Merge pull request #433 from chenyme/migrated_config

chore: update dependencies and improve configuration handling
This commit is contained in:
Chenyme authored and GitHub committed 2026-04-10 15:43:31 +08:00
commit d82c5aef8d
17 files changed
+717 -66

No files matched your search

+1 -2
View File
@@ -11,7 +11,6 @@ TZ=Asia/Shanghai
LOG_LEVEL=INFO
# 写入本地文件日志
LOG_FILE_ENABLED=true
# 账号目录增量同步间隔(秒)
ACCOUNT_SYNC_INTERVAL=30
@@ -36,7 +35,7 @@ ACCOUNT_LOCAL_PATH=data/accounts.db
# ACCOUNT_REDIS_URL=redis://:password@host:6379/0
# mysql: SQLAlchemy DSN
# ACCOUNT_MYSQL_URL=mysql+asyncmy://user:password@127.0.0.1:3306/grok2api
# ACCOUNT_MYSQL_URL=mysql+aiomysql://user:password@127.0.0.1:3306/grok2api
# postgresql: SQLAlchemy DSN
# ACCOUNT_POSTGRESQL_URL=postgresql+asyncpg://user:password@127.0.0.1:5432/grok2api
+1 -1
View File
@@ -19,7 +19,7 @@ def create_repository() -> AccountRepository:
Supported values:
``local`` — SQLite (default, single-process)
``redis`` — Redis hash + sorted-set layout
``mysql`` — MySQL via asyncmy / SQLAlchemy
``mysql`` — MySQL via aiomysql / SQLAlchemy
``postgresql`` — PostgreSQL via asyncpg / SQLAlchemy
"""
backend = get_repository_backend()
+6 -5
View File
@@ -30,7 +30,7 @@ metadata = sa.MetaData()
accounts_table = sa.Table(
_TBL_ACCOUNTS,
metadata,
sa.Column("token", sa.Text, primary_key=True),
sa.Column("token", sa.String(512), primary_key=True),
sa.Column("pool", sa.Text, nullable=False, default="basic"),
sa.Column("status", sa.Text, nullable=False, default="active"),
sa.Column("created_at", sa.BigInteger, nullable=False),
@@ -57,7 +57,7 @@ accounts_table = sa.Table(
meta_table = sa.Table(
_TBL_META,
metadata,
sa.Column("key", sa.Text, primary_key=True),
sa.Column("key", sa.String(128), primary_key=True),
sa.Column("value", sa.Text, nullable=False),
)
@@ -143,10 +143,11 @@ class SqlAccountRepository:
.on_conflict_do_nothing()
)
else:
from sqlalchemy.dialects.mysql import insert as my_insert
await conn.execute(
sa.text(
"INSERT IGNORE INTO account_meta (key, value) VALUES ('revision', '0')"
)
my_insert(meta_table)
.values(key="revision", value="0")
.on_duplicate_key_update(value="0")
)
async def get_revision(self) -> int:
+10
View File
@@ -108,6 +108,16 @@ async def lifespan(app: FastAPI):
repo = create_repository()
await repo.initialize()
# 2a. First-boot migrations (config seed / account migration from SQLite).
from app.platform.startup import run_startup_migrations
await run_startup_migrations(
config_backend=_config._get_backend(),
account_repo=repo,
)
# Reload config in case it was just seeded/migrated into the backend.
await _config.load()
directory = await get_account_directory(repo)
# Expose repository on app.state for admin handlers.
+1 -1
View File
@@ -68,7 +68,7 @@ async def verify_api_key(
if token is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Missing or invalid Authorization header.")
if token not in allowed_keys:
if not any(hmac.compare_digest(token, k) for k in allowed_keys):
raise HTTPException(status.HTTP_403_FORBIDDEN, "Invalid API key.")
+5
View File
@@ -0,0 +1,5 @@
"""Config storage backends."""
from .base import ConfigBackend
from .factory import create_config_backend, get_config_backend_name
__all__ = ["ConfigBackend", "create_config_backend", "get_config_backend_name"]
+35
View File
@@ -0,0 +1,35 @@
"""Flatten / unflatten helpers shared by all backends."""
import json
import logging
from typing import Any
_log = logging.getLogger(__name__)
def flatten(nested: dict[str, Any], prefix: str = "") -> dict[str, str]:
"""Recursively flatten *nested* to ``{"section.key": json_value, ...}``."""
out: dict[str, str] = {}
for k, v in nested.items():
full = f"{prefix}.{k}" if prefix else k
if isinstance(v, dict):
out.update(flatten(v, full))
else:
out[full] = json.dumps(v, ensure_ascii=False)
return out
def unflatten(flat: dict[str, str]) -> dict[str, Any]:
"""Rebuild a nested dict from ``{"section.key": json_value, ...}``."""
result: dict[str, Any] = {}
for dotted, json_val in flat.items():
parts = dotted.split(".")
node = result
for part in parts[:-1]:
node = node.setdefault(part, {})
try:
node[parts[-1]] = json.loads(json_val)
except (json.JSONDecodeError, ValueError):
_log.warning("config: failed to deserialize key %r, treating as string", dotted)
node[parts[-1]] = json_val
return result
+28
View File
@@ -0,0 +1,28 @@
"""Abstract config backend interface."""
from abc import ABC, abstractmethod
from typing import Any
class ConfigBackend(ABC):
"""Persist and reload user config overrides.
Storage model: flat key-value pairs (dotted keys → JSON-serialised values).
``load()`` rebuilds the full nested dict from all stored pairs.
``apply_patch()`` writes *only* the changed keys, leaving the rest untouched.
"""
@abstractmethod
async def load(self) -> dict[str, Any]:
"""Return the full stored user-overrides as a nested dict."""
@abstractmethod
async def apply_patch(self, patch: dict[str, Any]) -> None:
"""Persist only the keys present in *patch* (nested dict)."""
@abstractmethod
async def version(self) -> object:
"""Return an opaque version token (cheap — called on every request)."""
async def close(self) -> None:
"""Release any resources held by the backend (optional)."""
+80
View File
@@ -0,0 +1,80 @@
"""Config backend factory — follows ACCOUNT_STORAGE automatically."""
import os
from pathlib import Path
from .base import ConfigBackend
_DEFAULT_USER_PATH = "data/config.toml"
def get_config_backend_name() -> str:
"""Return the active config backend name (mirrors ACCOUNT_STORAGE)."""
return os.getenv("ACCOUNT_STORAGE", "local").strip().lower()
def create_config_backend() -> ConfigBackend:
"""Instantiate the config backend that matches the account storage backend.
``ACCOUNT_STORAGE=local`` → TOML file (data/config.toml)
``ACCOUNT_STORAGE=redis`` → Redis (ACCOUNT_REDIS_URL)
``ACCOUNT_STORAGE=mysql`` → MySQL (ACCOUNT_MYSQL_URL)
``ACCOUNT_STORAGE=postgresql`` → PostgreSQL (ACCOUNT_POSTGRESQL_URL)
No extra env vars needed — reuses the same connection settings as accounts.
"""
backend = get_config_backend_name()
if backend == "local":
return _make_toml()
if backend == "redis":
return _make_redis()
if backend in ("mysql", "postgresql"):
return _make_sql(backend)
raise ValueError(f"Unknown account storage backend: {backend!r}")
def _make_toml() -> ConfigBackend:
from .toml import TomlConfigBackend
path_str = os.getenv("CONFIG_LOCAL_PATH", _DEFAULT_USER_PATH).strip()
path = Path(path_str)
if not path.is_absolute():
path = Path(__file__).resolve().parents[5] / path
return TomlConfigBackend(path)
def _make_redis() -> ConfigBackend:
from redis.asyncio import Redis
from .redis import RedisConfigBackend
url = os.getenv("ACCOUNT_REDIS_URL", "").strip()
if not url:
raise ValueError("Redis config backend requires ACCOUNT_REDIS_URL")
r = Redis.from_url(url, decode_responses=False)
return RedisConfigBackend(r)
def _make_sql(dialect: str) -> ConfigBackend:
from .sql import SqlConfigBackend
from app.control.account.backends.sql import (
create_mysql_engine,
create_pgsql_engine,
)
if dialect == "mysql":
url = os.getenv("ACCOUNT_MYSQL_URL", "").strip()
if not url:
raise ValueError("MySQL config backend requires ACCOUNT_MYSQL_URL")
engine = create_mysql_engine(url)
else:
url = os.getenv("ACCOUNT_POSTGRESQL_URL", "").strip()
if not url:
raise ValueError("PostgreSQL config backend requires ACCOUNT_POSTGRESQL_URL")
engine = create_pgsql_engine(url)
return SqlConfigBackend(engine, dialect=dialect)
__all__ = ["create_config_backend", "get_config_backend_name"]
+51
View File
@@ -0,0 +1,51 @@
"""Redis config backend (multi-replica / K8s)."""
from typing import Any
from .base import ConfigBackend
from ._serde import flatten, unflatten
_DEFAULT_HASH_KEY = "config:user"
_DEFAULT_VERSION_KEY = "config:version"
class RedisConfigBackend(ConfigBackend):
"""Flat key-value storage in a Redis Hash.
Each dotted config key is one Hash field (JSON-encoded value).
``apply_patch`` only writes the changed fields — all other fields
in the hash are untouched.
"""
def __init__(
self,
redis,
hash_key: str = _DEFAULT_HASH_KEY,
version_key: str = _DEFAULT_VERSION_KEY,
) -> None:
self._r = redis
self._hash_key = hash_key
self._version_key = version_key
async def load(self) -> dict[str, Any]:
raw: dict[bytes, bytes] = await self._r.hgetall(self._hash_key)
if not raw:
return {}
flat = {k.decode(): v.decode() for k, v in raw.items()}
return unflatten(flat)
async def apply_patch(self, patch: dict[str, Any]) -> None:
flat = flatten(patch)
if not flat:
return
async with self._r.pipeline(transaction=True) as pipe:
pipe.hset(self._hash_key, mapping=flat)
pipe.incr(self._version_key)
await pipe.execute()
async def version(self) -> object:
v = await self._r.get(self._version_key)
return int(v) if v else 0
async def close(self) -> None:
await self._r.aclose()
+120
View File
@@ -0,0 +1,120 @@
"""SQL config backend (MySQL / PostgreSQL)."""
from typing import Any
import sqlalchemy as sa
from sqlalchemy.ext.asyncio import AsyncEngine
from .base import ConfigBackend
from ._serde import flatten, unflatten
_TABLE = "config_store"
_VERSION_KEY = "__version__"
_metadata = sa.MetaData()
config_store_table = sa.Table(
_TABLE,
_metadata,
sa.Column("key", sa.String(255), primary_key=True),
sa.Column("value", sa.Text, nullable=False, default=""),
)
class SqlConfigBackend(ConfigBackend):
"""Flat key-value storage in a ``config_store`` table.
Each dotted config key is one row. ``apply_patch`` only UPSERTs the
changed rows — the rest of the table is untouched.
Version token is stored as the integer value of the ``__version__`` row.
"""
def __init__(self, engine: AsyncEngine, *, dialect: str = "postgresql") -> None:
self._engine = engine
self._dialect = dialect # "mysql" | "postgresql"
self._ready = False
async def _ensure_table(self) -> None:
if self._ready:
return
async with self._engine.begin() as conn:
await conn.run_sync(_metadata.create_all)
self._ready = True
async def load(self) -> dict[str, Any]:
await self._ensure_table()
async with self._engine.connect() as conn:
rows = await conn.execute(
sa.select(config_store_table)
.where(config_store_table.c.key != _VERSION_KEY)
)
flat = {row.key: row.value for row in rows}
return unflatten(flat)
async def apply_patch(self, patch: dict[str, Any]) -> None:
await self._ensure_table()
flat = flatten(patch)
if not flat:
return
async with self._engine.begin() as conn:
for k, v in flat.items():
await conn.execute(self._upsert(k, v))
# Atomically increment version counter (no read-modify-write race).
await conn.execute(self._upsert_incr_version())
async def version(self) -> object:
await self._ensure_table()
async with self._engine.connect() as conn:
row = await conn.execute(
sa.select(config_store_table.c.value)
.where(config_store_table.c.key == _VERSION_KEY)
)
val = row.scalar()
return int(val) if val else 0
def _upsert(self, key: str, value: str) -> sa.Insert:
if self._dialect == "postgresql":
from sqlalchemy.dialects.postgresql import insert
return (
insert(config_store_table)
.values(key=key, value=value)
.on_conflict_do_update(index_elements=["key"], set_={"value": value})
)
else: # mysql
from sqlalchemy.dialects.mysql import insert
return (
insert(config_store_table)
.values(key=key, value=value)
.on_duplicate_key_update(value=value)
)
def _upsert_incr_version(self) -> sa.Insert:
"""Atomically insert or increment the version counter row."""
if self._dialect == "postgresql":
from sqlalchemy.dialects.postgresql import insert
return (
insert(config_store_table)
.values(key=_VERSION_KEY, value="1")
.on_conflict_do_update(
index_elements=["key"],
set_={"value": sa.func.cast(
sa.func.cast(config_store_table.c.value, sa.Integer) + 1,
sa.Text,
)},
)
)
else: # mysql
from sqlalchemy.dialects.mysql import insert
return (
insert(config_store_table)
.values(key=_VERSION_KEY, value="1")
.on_duplicate_key_update(
value=sa.func.cast(
sa.func.cast(config_store_table.c.value, sa.Integer) + 1,
sa.Text,
)
)
)
async def close(self) -> None:
await self._engine.dispose()
+56
View File
@@ -0,0 +1,56 @@
"""TOML-file config backend (default, single-instance)."""
import asyncio
import os
from pathlib import Path
from typing import Any
import tomli_w
import tomllib
from .base import ConfigBackend
from ..loader import _deep_merge as deep_merge
class TomlConfigBackend(ConfigBackend):
"""Stores user overrides in a local TOML file.
Flat-key concern doesn't apply here: TOML is the native format and the
file is small enough that a full rewrite is negligible for local use.
Version token = file mtime.
"""
def __init__(self, path: Path) -> None:
self._path = path
async def load(self) -> dict[str, Any]:
if not self._path.exists():
return {}
return await asyncio.to_thread(self._read)
async def apply_patch(self, patch: dict[str, Any]) -> None:
await asyncio.to_thread(self._merge_write, patch)
async def version(self) -> object:
return _mtime(self._path)
def _read(self) -> dict[str, Any]:
with open(self._path, "rb") as fh:
return tomllib.load(fh)
def _merge_write(self, patch: dict[str, Any]) -> None:
existing = {}
if self._path.exists():
with open(self._path, "rb") as fh:
existing = tomllib.load(fh)
merged = deep_merge(existing, patch)
self._path.parent.mkdir(parents=True, exist_ok=True)
with open(self._path, "wb") as fh:
tomli_w.dump(merged, fh)
def _mtime(path: Path) -> float:
try:
return os.stat(path).st_mtime
except OSError:
return 0.0
+56 -55
View File
@@ -1,28 +1,21 @@
"""Typed configuration snapshot — built once at startup, read-only at runtime."""
"""Typed configuration snapshot — built once at startup, reloaded on change."""
import asyncio
import os
from pathlib import Path
from typing import Any
import tomli_w
from .loader import get_nested, load_config
from .loader import _deep_merge, get_nested, load_toml
from .backends import ConfigBackend, create_config_backend
_BASE_DIR = Path(__file__).resolve().parents[3] # project root
_DATA_DIR = _BASE_DIR / "data"
def _resolve_defaults_path() -> Path:
return _BASE_DIR / "config.defaults.toml"
def _resolve_user_path() -> Path:
return _DATA_DIR / "config.toml"
def _mtime(path: Path) -> float:
"""Return file mtime, or 0.0 if the file does not exist."""
try:
return os.stat(path).st_mtime
except OSError:
@@ -32,59 +25,67 @@ def _mtime(path: Path) -> float:
class ConfigSnapshot:
"""Immutable view over the loaded configuration dict.
Reloads from disk only when a config file's mtime changes, so the
per-request overhead is a pair of stat() syscalls rather than full
TOML parsing on every request.
Loading strategy (lowest → highest priority):
1. ``config.defaults.toml`` — shipped defaults (read-only, ConfigMap)
2. Backend user overrides — toml file or Redis (admin hot-update target)
3. ``GROK_*`` env vars — always win
Change detection is cheap: one stat() (toml) or one Redis GET (redis) per
request on the fast path.
"""
def __init__(self) -> None:
def __init__(self, backend: ConfigBackend | None = None) -> None:
self._data: dict[str, Any] = {}
self._loaded = False
self._lock = asyncio.Lock()
self._mtime_defaults: float = 0.0
self._mtime_user: float = 0.0
self._version: object = None
self._backend: ConfigBackend | None = backend
async def load(
self,
defaults_path: Path | None = None,
user_path: Path | None = None,
) -> None:
"""Reload config if any source file changed since last load.
def _get_backend(self) -> ConfigBackend:
if self._backend is None:
self._backend = create_config_backend()
return self._backend
Safe to call on every request — skips disk I/O when nothing changed.
Pass explicit paths only during testing; production uses the defaults.
async def load(self, defaults_path: Path | None = None) -> None:
"""Reload config if defaults or backend overrides changed.
Safe to call on every request — skips I/O when nothing changed.
Pass *defaults_path* only during testing.
"""
dp = defaults_path or _resolve_defaults_path()
up = user_path or _resolve_user_path()
backend = self._get_backend()
mt_dp = _mtime(dp)
mt_up = _mtime(up)
ver = await backend.version()
# Fast path: files unchanged — skip lock and disk I/O entirely.
if self._loaded and mt_dp == self._mtime_defaults and mt_up == self._mtime_user:
# Fast path: nothing changed.
if self._loaded and mt_dp == self._mtime_defaults and ver == self._version:
return
async with self._lock:
# Re-check under lock to avoid redundant reloads under concurrency.
mt_dp = _mtime(dp)
mt_up = _mtime(up)
if self._loaded and mt_dp == self._mtime_defaults and mt_up == self._mtime_user:
ver = await backend.version()
if self._loaded and mt_dp == self._mtime_defaults and ver == self._version:
return
if not dp.exists():
raise RuntimeError(f"Missing required defaults config: {dp}")
self._data = await asyncio.to_thread(load_config, dp, up)
defaults = await asyncio.to_thread(load_toml, dp)
user_overrides = await backend.load()
self._data = _deep_merge(defaults, user_overrides)
self._data = _apply_env(self._data)
self._loaded = True
self._mtime_defaults = mt_dp
self._mtime_user = mt_up
self._version = ver
async def ensure_loaded(self) -> None:
"""Load with defaults if not yet loaded."""
if not self._loaded:
await self.load()
def get(self, key: str, default: Any = None) -> Any:
"""Retrieve a value by dotted key (e.g. ``"account.refresh.enabled"``)."""
return get_nested(self._data, key, default)
def get_int(self, key: str, default: int = 0) -> int:
@@ -124,38 +125,38 @@ class ConfigSnapshot:
return [val]
async def update(self, patch: dict[str, Any]) -> None:
"""Merge *patch* into the current config and persist to user config file."""
"""Persist only the changed keys in *patch* via backend."""
backend = self._get_backend()
async with self._lock:
from .loader import _deep_merge
self._data = _deep_merge(self._data, patch)
user_path = _resolve_user_path()
await asyncio.to_thread(self._write_toml, user_path, self._data)
# Invalidate cached mtime so the next load() call re-reads the file
# and other workers pick up the change on their next request.
self._mtime_user = 0.0
@staticmethod
def _write_toml(path: Path, data: dict[str, Any]) -> None:
"""Write config dict to TOML file."""
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as fh:
tomli_w.dump(data, fh)
await backend.apply_patch(patch)
# Invalidate so next load() call pulls the new version.
self._version = None
def raw(self) -> dict[str, Any]:
"""Return a shallow copy of the underlying data dict."""
return dict(self._data)
# ---------------------------------------------------------------------------
# Env-var override layer (GROK_SECTION_KEY → section.key)
# ---------------------------------------------------------------------------
def _apply_env(data: dict[str, Any], prefix: str = "GROK_") -> dict[str, Any]:
prefix_len = len(prefix)
for env_key, env_val in os.environ.items():
if not env_key.startswith(prefix):
continue
parts = env_key[prefix_len:].lower().split("_", 1)
if len(parts) == 2:
section, key = parts
data.setdefault(section, {})[key] = env_val
return data
# Module-level singleton — imported everywhere.
config = ConfigSnapshot()
def get_config(key: str | None = None, default: Any = None) -> Any:
"""Convenience wrapper around the module-level ``config`` singleton.
Without arguments, returns the ``ConfigSnapshot`` instance itself.
With a *key*, returns the config value at that dotted path.
"""
if key is None:
return config
return config.get(key, default)
+4
View File
@@ -0,0 +1,4 @@
"""Startup utilities — migration, seeding, first-boot checks."""
from .migration import run_startup_migrations
__all__ = ["run_startup_migrations"]
+202
View File
@@ -0,0 +1,202 @@
"""First-boot data migration.
Config migration
----------------
local : seeds data/config.toml from config.defaults.toml if the file
does not exist yet — gives users an editable copy on first run.
redis / sql : if the backend is empty (version == 0) AND data/config.toml
exists, migrates the user overrides into the DB backend.
If data/config.toml does not exist either, nothing is written
(defaults are always loaded from config.defaults.toml at runtime).
Account migration
-----------------
Runs only when ACCOUNT_STORAGE != "local".
If data/accounts.db (the previous local SQLite store) exists AND the
target backend is empty (revision == 0), all accounts are copied into the
new backend — preserving pool, status, quota, usage stats, and timestamps.
After a successful migration the SQLite file is renamed to
data/accounts.db.migrated so the same migration is never re-run.
"""
from __future__ import annotations
import asyncio
import shutil
from pathlib import Path
from typing import TYPE_CHECKING
from loguru import logger
if TYPE_CHECKING:
from app.control.account.repository import AccountRepository
from app.platform.config.backends.base import ConfigBackend
_BASE_DIR = Path(__file__).resolve().parents[3]
_DATA_DIR = _BASE_DIR / "data"
_DEFAULTS_PATH = _BASE_DIR / "config.defaults.toml"
_USER_CFG_PATH = _DATA_DIR / "config.toml"
_LOCAL_DB_PATH = _DATA_DIR / "accounts.db"
_BATCH = 500 # accounts per upsert/patch batch
# ---------------------------------------------------------------------------
# Public entry point
# ---------------------------------------------------------------------------
async def run_startup_migrations(
config_backend: "ConfigBackend",
account_repo: "AccountRepository",
) -> None:
"""Run all first-boot migrations. Safe to call on every startup."""
await _migrate_config(config_backend)
await _migrate_accounts(account_repo)
# ---------------------------------------------------------------------------
# Config migration
# ---------------------------------------------------------------------------
async def _migrate_config(backend: "ConfigBackend") -> None:
from app.platform.config.backends.factory import get_config_backend_name
from app.platform.config.loader import load_toml
backend_name = get_config_backend_name()
if backend_name == "local":
# Seed data/config.toml from defaults so users have an editable file.
if not _USER_CFG_PATH.exists() and _DEFAULTS_PATH.exists():
await asyncio.to_thread(shutil.copy2, _DEFAULTS_PATH, _USER_CFG_PATH)
logger.info("config: seeded data/config.toml from config.defaults.toml")
return
# DB / Redis backends — migrate only if backend is empty.
if await backend.version() != 0:
return # already has data, skip
if _USER_CFG_PATH.exists():
user_data = await asyncio.to_thread(load_toml, _USER_CFG_PATH)
if user_data:
await backend.apply_patch(user_data)
logger.info(
"config: migrated data/config.toml → {} backend ({} keys)",
backend_name,
_count_keys(user_data),
)
return
logger.debug("config: {} backend is empty, no local overrides to migrate", backend_name)
# ---------------------------------------------------------------------------
# Account migration
# ---------------------------------------------------------------------------
async def _migrate_accounts(target_repo: "AccountRepository") -> None:
from app.control.account.backends.factory import get_repository_backend
if get_repository_backend() == "local":
return # already on local, nothing to migrate
sqlite_path = _LOCAL_DB_PATH
if not sqlite_path.exists():
return # no previous local data
# Check whether the target already has data.
snapshot = await target_repo.runtime_snapshot()
if snapshot.revision > 0 or snapshot.items:
logger.debug("account: target backend not empty (revision={}), skipping migration", snapshot.revision)
return
logger.info("account: migrating accounts from {} → {} backend", sqlite_path, get_repository_backend())
count = await _copy_accounts(sqlite_path, target_repo)
# Rename the SQLite file so this migration is never re-run.
done_path = sqlite_path.with_suffix(".db.migrated")
await asyncio.to_thread(sqlite_path.rename, done_path)
logger.info("account: migration complete ({} accounts), renamed {} → {}", count, sqlite_path.name, done_path.name)
async def _copy_accounts(sqlite_path: Path, target: "AccountRepository") -> int:
"""Read all accounts from the local SQLite file and write to *target*."""
from app.control.account.backends.local import LocalAccountRepository
from app.control.account.commands import AccountPatch, AccountUpsert, ListAccountsQuery
source = LocalAccountRepository(sqlite_path)
await source.initialize()
total = 0
page = 1
try:
while True:
result = await source.list_accounts(
ListAccountsQuery(page=page, page_size=_BATCH, include_deleted=True)
)
records = result.items
if not records:
break
# Step 1: upsert — creates records with token / pool / tags / ext.
upserts = [
AccountUpsert(token=r.token, pool=r.pool, tags=r.tags, ext=r.ext)
for r in records
]
await target.upsert_accounts(upserts)
# Step 2: patch — fills status, quota, usage counters, timestamps.
patches = [_record_to_patch(r) for r in records]
await target.patch_accounts(patches)
# Step 3: soft-delete records that were deleted in the source.
deleted_tokens = [r.token for r in records if r.deleted_at is not None]
if deleted_tokens:
await target.delete_accounts(deleted_tokens)
total += len(records)
if page >= result.total_pages:
break
page += 1
finally:
await source.close()
return total
def _record_to_patch(r) -> "AccountPatch":
from app.control.account.commands import AccountPatch
qs = r.quota_set()
return AccountPatch(
token=r.token,
status=r.status,
quota_auto=qs.auto.to_dict() if qs.auto else None,
quota_fast=qs.fast.to_dict() if qs.fast else None,
quota_expert=qs.expert.to_dict() if qs.expert else None,
quota_heavy=qs.heavy.to_dict() if qs.heavy else None,
# Usage counts — target starts at 0, so actual value == delta.
usage_use_delta=r.usage_use_count or None,
usage_fail_delta=r.usage_fail_count or None,
usage_sync_delta=r.usage_sync_count or None,
last_use_at=r.last_use_at,
last_fail_at=r.last_fail_at,
last_fail_reason=r.last_fail_reason,
last_sync_at=r.last_sync_at,
last_clear_at=r.last_clear_at,
state_reason=r.state_reason,
ext_merge=r.ext or None,
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _count_keys(nested: dict, prefix: str = "") -> int:
count = 0
for v in nested.values():
if isinstance(v, dict):
count += _count_keys(v)
else:
count += 1
return count
+3 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "grok2api"
version = "2.0.1"
version = "2.0.2"
description = "Grok2API rebuilt with FastAPI, fully aligned with the latest web call format. Supports streaming and non-streaming chat, image generation/editing, deep thinking, token pool concurrency, and automatic load balancing."
readme = "README.md"
requires-python = ">=3.13"
@@ -10,9 +10,11 @@ dependencies = [
"aiomysql>=0.2.0",
"asyncpg>=0.31.0",
"certifi>=2025.10.5",
"cryptography>=46.0.7",
"curl-cffi>=0.15.0",
"fastapi>=0.119.0",
"granian>=2.7.2",
"greenlet>=3.3.1",
"loguru>=0.7.3",
"orjson>=3.11.4",
"pydantic>=2.12.3",
Generated
+58 -1
View File
@@ -319,6 +319,59 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },
]
[[package]]
name = "cryptography"
version = "46.0.7"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cffi", marker = "platform_python_implementation != 'PyPy'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/47/93/ac8f3d5ff04d54bc814e961a43ae5b0b146154c89c61b47bb07557679b18/cryptography-46.0.7.tar.gz", hash = "sha256:e4cfd68c5f3e0bfdad0d38e023239b96a2fe84146481852dffbcca442c245aa5", size = 750652, upload-time = "2026-04-08T01:57:54.692Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0b/5d/4a8f770695d73be252331e60e526291e3df0c9b27556a90a6b47bccca4c2/cryptography-46.0.7-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:ea42cbe97209df307fdc3b155f1b6fa2577c0defa8f1f7d3be7d31d189108ad4", size = 7179869, upload-time = "2026-04-08T01:56:17.157Z" },
{ url = "https://files.pythonhosted.org/packages/5f/45/6d80dc379b0bbc1f9d1e429f42e4cb9e1d319c7a8201beffd967c516ea01/cryptography-46.0.7-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b36a4695e29fe69215d75960b22577197aca3f7a25b9cf9d165dcfe9d80bc325", size = 4275492, upload-time = "2026-04-08T01:56:19.36Z" },
{ url = "https://files.pythonhosted.org/packages/4a/9a/1765afe9f572e239c3469f2cb429f3ba7b31878c893b246b4b2994ffe2fe/cryptography-46.0.7-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5ad9ef796328c5e3c4ceed237a183f5d41d21150f972455a9d926593a1dcb308", size = 4426670, upload-time = "2026-04-08T01:56:21.415Z" },
{ url = "https://files.pythonhosted.org/packages/8f/3e/af9246aaf23cd4ee060699adab1e47ced3f5f7e7a8ffdd339f817b446462/cryptography-46.0.7-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:73510b83623e080a2c35c62c15298096e2a5dc8d51c3b4e1740211839d0dea77", size = 4280275, upload-time = "2026-04-08T01:56:23.539Z" },
{ url = "https://files.pythonhosted.org/packages/0f/54/6bbbfc5efe86f9d71041827b793c24811a017c6ac0fd12883e4caa86b8ed/cryptography-46.0.7-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:cbd5fb06b62bd0721e1170273d3f4d5a277044c47ca27ee257025146c34cbdd1", size = 4928402, upload-time = "2026-04-08T01:56:25.624Z" },
{ url = "https://files.pythonhosted.org/packages/2d/cf/054b9d8220f81509939599c8bdbc0c408dbd2bdd41688616a20731371fe0/cryptography-46.0.7-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:420b1e4109cc95f0e5700eed79908cef9268265c773d3a66f7af1eef53d409ef", size = 4459985, upload-time = "2026-04-08T01:56:27.309Z" },
{ url = "https://files.pythonhosted.org/packages/f9/46/4e4e9c6040fb01c7467d47217d2f882daddeb8828f7df800cb806d8a2288/cryptography-46.0.7-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:24402210aa54baae71d99441d15bb5a1919c195398a87b563df84468160a65de", size = 3990652, upload-time = "2026-04-08T01:56:29.095Z" },
{ url = "https://files.pythonhosted.org/packages/36/5f/313586c3be5a2fbe87e4c9a254207b860155a8e1f3cca99f9910008e7d08/cryptography-46.0.7-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:8a469028a86f12eb7d2fe97162d0634026d92a21f3ae0ac87ed1c4a447886c83", size = 4279805, upload-time = "2026-04-08T01:56:30.928Z" },
{ url = "https://files.pythonhosted.org/packages/69/33/60dfc4595f334a2082749673386a4d05e4f0cf4df8248e63b2c3437585f2/cryptography-46.0.7-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:9694078c5d44c157ef3162e3bf3946510b857df5a3955458381d1c7cfc143ddb", size = 4892883, upload-time = "2026-04-08T01:56:32.614Z" },
{ url = "https://files.pythonhosted.org/packages/c7/0b/333ddab4270c4f5b972f980adef4faa66951a4aaf646ca067af597f15563/cryptography-46.0.7-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:42a1e5f98abb6391717978baf9f90dc28a743b7d9be7f0751a6f56a75d14065b", size = 4459756, upload-time = "2026-04-08T01:56:34.306Z" },
{ url = "https://files.pythonhosted.org/packages/d2/14/633913398b43b75f1234834170947957c6b623d1701ffc7a9600da907e89/cryptography-46.0.7-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:91bbcb08347344f810cbe49065914fe048949648f6bd5c2519f34619142bbe85", size = 4410244, upload-time = "2026-04-08T01:56:35.977Z" },
{ url = "https://files.pythonhosted.org/packages/10/f2/19ceb3b3dc14009373432af0c13f46aa08e3ce334ec6eff13492e1812ccd/cryptography-46.0.7-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:5d1c02a14ceb9148cc7816249f64f623fbfee39e8c03b3650d842ad3f34d637e", size = 4674868, upload-time = "2026-04-08T01:56:38.034Z" },
{ url = "https://files.pythonhosted.org/packages/1a/bb/a5c213c19ee94b15dfccc48f363738633a493812687f5567addbcbba9f6f/cryptography-46.0.7-cp311-abi3-win32.whl", hash = "sha256:d23c8ca48e44ee015cd0a54aeccdf9f09004eba9fc96f38c911011d9ff1bd457", size = 3026504, upload-time = "2026-04-08T01:56:39.666Z" },
{ url = "https://files.pythonhosted.org/packages/2b/02/7788f9fefa1d060ca68717c3901ae7fffa21ee087a90b7f23c7a603c32ae/cryptography-46.0.7-cp311-abi3-win_amd64.whl", hash = "sha256:397655da831414d165029da9bc483bed2fe0e75dde6a1523ec2fe63f3c46046b", size = 3488363, upload-time = "2026-04-08T01:56:41.893Z" },
{ url = "https://files.pythonhosted.org/packages/7b/56/15619b210e689c5403bb0540e4cb7dbf11a6bf42e483b7644e471a2812b3/cryptography-46.0.7-cp314-cp314t-macosx_10_9_universal2.whl", hash = "sha256:d151173275e1728cf7839aaa80c34fe550c04ddb27b34f48c232193df8db5842", size = 7119671, upload-time = "2026-04-08T01:56:44Z" },
{ url = "https://files.pythonhosted.org/packages/74/66/e3ce040721b0b5599e175ba91ab08884c75928fbeb74597dd10ef13505d2/cryptography-46.0.7-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:db0f493b9181c7820c8134437eb8b0b4792085d37dbb24da050476ccb664e59c", size = 4268551, upload-time = "2026-04-08T01:56:46.071Z" },
{ url = "https://files.pythonhosted.org/packages/03/11/5e395f961d6868269835dee1bafec6a1ac176505a167f68b7d8818431068/cryptography-46.0.7-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ebd6daf519b9f189f85c479427bbd6e9c9037862cf8fe89ee35503bd209ed902", size = 4408887, upload-time = "2026-04-08T01:56:47.718Z" },
{ url = "https://files.pythonhosted.org/packages/40/53/8ed1cf4c3b9c8e611e7122fb56f1c32d09e1fff0f1d77e78d9ff7c82653e/cryptography-46.0.7-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:b7b412817be92117ec5ed95f880defe9cf18a832e8cafacf0a22337dc1981b4d", size = 4271354, upload-time = "2026-04-08T01:56:49.312Z" },
{ url = "https://files.pythonhosted.org/packages/50/46/cf71e26025c2e767c5609162c866a78e8a2915bbcfa408b7ca495c6140c4/cryptography-46.0.7-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:fbfd0e5f273877695cb93baf14b185f4878128b250cc9f8e617ea0c025dfb022", size = 4905845, upload-time = "2026-04-08T01:56:50.916Z" },
{ url = "https://files.pythonhosted.org/packages/c0/ea/01276740375bac6249d0a971ebdf6b4dc9ead0ee0a34ef3b5a88c1a9b0d4/cryptography-46.0.7-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:ffca7aa1d00cf7d6469b988c581598f2259e46215e0140af408966a24cf086ce", size = 4444641, upload-time = "2026-04-08T01:56:52.882Z" },
{ url = "https://files.pythonhosted.org/packages/3d/4c/7d258f169ae71230f25d9f3d06caabcff8c3baf0978e2b7d65e0acac3827/cryptography-46.0.7-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:60627cf07e0d9274338521205899337c5d18249db56865f943cbe753aa96f40f", size = 3967749, upload-time = "2026-04-08T01:56:54.597Z" },
{ url = "https://files.pythonhosted.org/packages/b5/2a/2ea0767cad19e71b3530e4cad9605d0b5e338b6a1e72c37c9c1ceb86c333/cryptography-46.0.7-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:80406c3065e2c55d7f49a9550fe0c49b3f12e5bfff5dedb727e319e1afb9bf99", size = 4270942, upload-time = "2026-04-08T01:56:56.416Z" },
{ url = "https://files.pythonhosted.org/packages/41/3d/fe14df95a83319af25717677e956567a105bb6ab25641acaa093db79975d/cryptography-46.0.7-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:c5b1ccd1239f48b7151a65bc6dd54bcfcc15e028c8ac126d3fada09db0e07ef1", size = 4871079, upload-time = "2026-04-08T01:56:58.31Z" },
{ url = "https://files.pythonhosted.org/packages/9c/59/4a479e0f36f8f378d397f4eab4c850b4ffb79a2f0d58704b8fa0703ddc11/cryptography-46.0.7-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:d5f7520159cd9c2154eb61eb67548ca05c5774d39e9c2c4339fd793fe7d097b2", size = 4443999, upload-time = "2026-04-08T01:57:00.508Z" },
{ url = "https://files.pythonhosted.org/packages/28/17/b59a741645822ec6d04732b43c5d35e4ef58be7bfa84a81e5ae6f05a1d33/cryptography-46.0.7-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fcd8eac50d9138c1d7fc53a653ba60a2bee81a505f9f8850b6b2888555a45d0e", size = 4399191, upload-time = "2026-04-08T01:57:02.654Z" },
{ url = "https://files.pythonhosted.org/packages/59/6a/bb2e166d6d0e0955f1e9ff70f10ec4b2824c9cfcdb4da772c7dd69cc7d80/cryptography-46.0.7-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:65814c60f8cc400c63131584e3e1fad01235edba2614b61fbfbfa954082db0ee", size = 4655782, upload-time = "2026-04-08T01:57:04.592Z" },
{ url = "https://files.pythonhosted.org/packages/95/b6/3da51d48415bcb63b00dc17c2eff3a651b7c4fed484308d0f19b30e8cb2c/cryptography-46.0.7-cp314-cp314t-win32.whl", hash = "sha256:fdd1736fed309b4300346f88f74cd120c27c56852c3838cab416e7a166f67298", size = 3002227, upload-time = "2026-04-08T01:57:06.91Z" },
{ url = "https://files.pythonhosted.org/packages/32/a8/9f0e4ed57ec9cebe506e58db11ae472972ecb0c659e4d52bbaee80ca340a/cryptography-46.0.7-cp314-cp314t-win_amd64.whl", hash = "sha256:e06acf3c99be55aa3b516397fe42f5855597f430add9c17fa46bf2e0fb34c9bb", size = 3475332, upload-time = "2026-04-08T01:57:08.807Z" },
{ url = "https://files.pythonhosted.org/packages/a7/7f/cd42fc3614386bc0c12f0cb3c4ae1fc2bbca5c9662dfed031514911d513d/cryptography-46.0.7-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:462ad5cb1c148a22b2e3bcc5ad52504dff325d17daf5df8d88c17dda1f75f2a4", size = 7165618, upload-time = "2026-04-08T01:57:10.645Z" },
{ url = "https://files.pythonhosted.org/packages/a5/d0/36a49f0262d2319139d2829f773f1b97ef8aef7f97e6e5bd21455e5a8fb5/cryptography-46.0.7-cp38-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:84d4cced91f0f159a7ddacad249cc077e63195c36aac40b4150e7a57e84fffe7", size = 4270628, upload-time = "2026-04-08T01:57:12.885Z" },
{ url = "https://files.pythonhosted.org/packages/8a/6c/1a42450f464dda6ffbe578a911f773e54dd48c10f9895a23a7e88b3e7db5/cryptography-46.0.7-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:128c5edfe5e5938b86b03941e94fac9ee793a94452ad1365c9fc3f4f62216832", size = 4415405, upload-time = "2026-04-08T01:57:14.923Z" },
{ url = "https://files.pythonhosted.org/packages/9a/92/4ed714dbe93a066dc1f4b4581a464d2d7dbec9046f7c8b7016f5286329e2/cryptography-46.0.7-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:5e51be372b26ef4ba3de3c167cd3d1022934bc838ae9eaad7e644986d2a3d163", size = 4272715, upload-time = "2026-04-08T01:57:16.638Z" },
{ url = "https://files.pythonhosted.org/packages/b7/e6/a26b84096eddd51494bba19111f8fffe976f6a09f132706f8f1bf03f51f7/cryptography-46.0.7-cp38-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:cdf1a610ef82abb396451862739e3fc93b071c844399e15b90726ef7470eeaf2", size = 4918400, upload-time = "2026-04-08T01:57:19.021Z" },
{ url = "https://files.pythonhosted.org/packages/c7/08/ffd537b605568a148543ac3c2b239708ae0bd635064bab41359252ef88ed/cryptography-46.0.7-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:1d25aee46d0c6f1a501adcddb2d2fee4b979381346a78558ed13e50aa8a59067", size = 4450634, upload-time = "2026-04-08T01:57:21.185Z" },
{ url = "https://files.pythonhosted.org/packages/16/01/0cd51dd86ab5b9befe0d031e276510491976c3a80e9f6e31810cce46c4ad/cryptography-46.0.7-cp38-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:cdfbe22376065ffcf8be74dc9a909f032df19bc58a699456a21712d6e5eabfd0", size = 3985233, upload-time = "2026-04-08T01:57:22.862Z" },
{ url = "https://files.pythonhosted.org/packages/92/49/819d6ed3a7d9349c2939f81b500a738cb733ab62fbecdbc1e38e83d45e12/cryptography-46.0.7-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:abad9dac36cbf55de6eb49badd4016806b3165d396f64925bf2999bcb67837ba", size = 4271955, upload-time = "2026-04-08T01:57:24.814Z" },
{ url = "https://files.pythonhosted.org/packages/80/07/ad9b3c56ebb95ed2473d46df0847357e01583f4c52a85754d1a55e29e4d0/cryptography-46.0.7-cp38-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:935ce7e3cfdb53e3536119a542b839bb94ec1ad081013e9ab9b7cfd478b05006", size = 4879888, upload-time = "2026-04-08T01:57:26.88Z" },
{ url = "https://files.pythonhosted.org/packages/b8/c7/201d3d58f30c4c2bdbe9b03844c291feb77c20511cc3586daf7edc12a47b/cryptography-46.0.7-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:35719dc79d4730d30f1c2b6474bd6acda36ae2dfae1e3c16f2051f215df33ce0", size = 4449961, upload-time = "2026-04-08T01:57:29.068Z" },
{ url = "https://files.pythonhosted.org/packages/a5/ef/649750cbf96f3033c3c976e112265c33906f8e462291a33d77f90356548c/cryptography-46.0.7-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7bbc6ccf49d05ac8f7d7b5e2e2c33830d4fe2061def88210a126d130d7f71a85", size = 4401696, upload-time = "2026-04-08T01:57:31.029Z" },
{ url = "https://files.pythonhosted.org/packages/41/52/a8908dcb1a389a459a29008c29966c1d552588d4ae6d43f3a1a4512e0ebe/cryptography-46.0.7-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a1529d614f44b863a7b480c6d000fe93b59acee9c82ffa027cfadc77521a9f5e", size = 4664256, upload-time = "2026-04-08T01:57:33.144Z" },
{ url = "https://files.pythonhosted.org/packages/4b/fa/f0ab06238e899cc3fb332623f337a7364f36f4bb3f2534c2bb95a35b132c/cryptography-46.0.7-cp38-abi3-win32.whl", hash = "sha256:f247c8c1a1fb45e12586afbb436ef21ff1e80670b2861a90353d9b025583d246", size = 3013001, upload-time = "2026-04-08T01:57:34.933Z" },
{ url = "https://files.pythonhosted.org/packages/d2/f1/00ce3bde3ca542d1acd8f8cfa38e446840945aa6363f9b74746394b14127/cryptography-46.0.7-cp38-abi3-win_amd64.whl", hash = "sha256:506c4ff91eff4f82bdac7633318a526b1d1309fc07ca76a3ad182cb5b686d6d3", size = 3472985, upload-time = "2026-04-08T01:57:36.714Z" },
]
[[package]]
name = "curl-cffi"
version = "0.15.0"
@@ -527,7 +580,7 @@ wheels = [
[[package]]
name = "grok2api"
version = "2.0.1"
version = "2.0.2"
source = { virtual = "." }
dependencies = [
{ name = "aiohttp" },
@@ -535,9 +588,11 @@ dependencies = [
{ name = "aiomysql" },
{ name = "asyncpg" },
{ name = "certifi" },
{ name = "cryptography" },
{ name = "curl-cffi" },
{ name = "fastapi" },
{ name = "granian" },
{ name = "greenlet" },
{ name = "loguru" },
{ name = "orjson" },
{ name = "pydantic" },
@@ -562,9 +617,11 @@ requires-dist = [
{ name = "aiomysql", specifier = ">=0.2.0" },
{ name = "asyncpg", specifier = ">=0.31.0" },
{ name = "certifi", specifier = ">=2025.10.5" },
{ name = "cryptography", specifier = ">=46.0.7" },
{ name = "curl-cffi", specifier = ">=0.15.0" },
{ name = "fastapi", specifier = ">=0.119.0" },
{ name = "granian", specifier = ">=2.7.2" },
{ name = "greenlet", specifier = ">=3.3.1" },
{ name = "loguru", specifier = ">=0.7.3" },
{ name = "orjson", specifier = ">=3.11.4" },
{ name = "pydantic", specifier = ">=2.12.3" },