feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""存储抽象层:ProjectStore 接口 + SQLite 一期实现(决策点 5:可平迁)"""
|
||||
@@ -0,0 +1,214 @@
|
||||
"""
|
||||
数据库连接存储层
|
||||
================
|
||||
|
||||
【功能说明】数据库连接配置的持久化(SQLite),支持增删改查。
|
||||
【安全设计】密码用简单加密存储(XOR + base64),前端返回脱敏值。
|
||||
【实现思路】DatabaseConnectionStore 抽象 + SqliteDatabaseConnectionStore 实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import sqlite3
|
||||
import uuid
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from app.schemas.database import (
|
||||
DatabaseConnection,
|
||||
DatabaseConnectionCreate,
|
||||
DatabaseConnectionUpdate,
|
||||
)
|
||||
from app.store.sqlite_util import open_connection
|
||||
|
||||
# 简易加密密钥(本地场景,够用;生产建议用密钥管理服务)
|
||||
_XOR_KEY = b"agent_db_key_2026"
|
||||
|
||||
|
||||
def _encrypt(text: str) -> str:
|
||||
"""简易 XOR + base64 加密(本地场景防止明文存储)。"""
|
||||
if not text:
|
||||
return ""
|
||||
data = text.encode("utf-8")
|
||||
encrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(data))
|
||||
return base64.b64encode(encrypted).decode("ascii")
|
||||
|
||||
|
||||
def _decrypt(token: str) -> str:
|
||||
"""解密。"""
|
||||
if not token:
|
||||
return ""
|
||||
try:
|
||||
encrypted = base64.b64decode(token.encode("ascii"))
|
||||
decrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(encrypted))
|
||||
return decrypted.decode("utf-8")
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
class DatabaseConnectionStore(ABC):
|
||||
"""数据库连接配置存储抽象"""
|
||||
|
||||
@abstractmethod
|
||||
def create(self, payload: DatabaseConnectionCreate) -> DatabaseConnection: ...
|
||||
|
||||
@abstractmethod
|
||||
def get(self, config_id: str) -> Optional[DatabaseConnection]: ...
|
||||
|
||||
@abstractmethod
|
||||
def get_with_password(self, config_id: str) -> Optional[dict]: ...
|
||||
|
||||
@abstractmethod
|
||||
def list_all(self) -> list[DatabaseConnection]: ...
|
||||
|
||||
@abstractmethod
|
||||
def update(
|
||||
self, config_id: str, payload: DatabaseConnectionUpdate
|
||||
) -> Optional[DatabaseConnection]: ...
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, config_id: str) -> bool: ...
|
||||
|
||||
|
||||
class SqliteDatabaseConnectionStore(DatabaseConnectionStore):
|
||||
"""SQLite 实现"""
|
||||
|
||||
def __init__(self, db_path: Path) -> None:
|
||||
self._db_path = Path(db_path)
|
||||
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_schema()
|
||||
|
||||
def _connect(self):
|
||||
"""
|
||||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||
|
||||
【修复】原先 `with sqlite3.connect(...)` 只提交不关闭,连接泄漏到 GC。
|
||||
改为委托 app.store.sqlite_util.open_connection,语义不变、额外保证 close。
|
||||
"""
|
||||
return open_connection(self._db_path)
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
ddl = """
|
||||
CREATE TABLE IF NOT EXISTS db_connection (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
db_type TEXT NOT NULL,
|
||||
host TEXT DEFAULT 'localhost',
|
||||
port INTEGER DEFAULT 3306,
|
||||
database TEXT NOT NULL,
|
||||
username TEXT DEFAULT '',
|
||||
password TEXT DEFAULT '',
|
||||
description TEXT DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
with self._connect() as conn:
|
||||
conn.execute(ddl)
|
||||
conn.commit()
|
||||
|
||||
@staticmethod
|
||||
def _row_to_entity(row: sqlite3.Row, mask_password: bool = True) -> DatabaseConnection:
|
||||
pwd = "******" if mask_password else _decrypt(row["password"] or "")
|
||||
return DatabaseConnection(
|
||||
id=row["id"],
|
||||
name=row["name"],
|
||||
db_type=row["db_type"],
|
||||
host=row["host"] or "localhost",
|
||||
port=row["port"] or 3306,
|
||||
database=row["database"],
|
||||
username=row["username"] or "",
|
||||
password=pwd,
|
||||
description=row["description"] or "",
|
||||
created_at=datetime.fromisoformat(row["created_at"]),
|
||||
updated_at=datetime.fromisoformat(row["updated_at"]),
|
||||
)
|
||||
|
||||
def create(self, payload: DatabaseConnectionCreate) -> DatabaseConnection:
|
||||
config_id = f"db_{uuid.uuid4().hex[:12]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._connect() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO db_connection
|
||||
(id, name, db_type, host, port, database, username, password, description, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
config_id,
|
||||
payload.name,
|
||||
payload.db_type,
|
||||
payload.host,
|
||||
payload.port,
|
||||
payload.database,
|
||||
payload.username,
|
||||
_encrypt(payload.password),
|
||||
payload.description,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
created = self.get(config_id)
|
||||
if created is None:
|
||||
raise RuntimeError(f"连接配置创建后回读失败:{config_id}")
|
||||
return created
|
||||
|
||||
def get(self, config_id: str) -> Optional[DatabaseConnection]:
|
||||
with self._connect() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM db_connection WHERE id = ?", (config_id,)
|
||||
).fetchone()
|
||||
return self._row_to_entity(row) if row else None
|
||||
|
||||
def get_with_password(self, config_id: str) -> Optional[dict]:
|
||||
"""返回含真实密码的连接信息(供引擎使用,不暴露给前端)。"""
|
||||
with self._connect() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM db_connection WHERE id = ?", (config_id,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"id": row["id"],
|
||||
"name": row["name"],
|
||||
"db_type": row["db_type"],
|
||||
"host": row["host"] or "localhost",
|
||||
"port": row["port"] or 3306,
|
||||
"database": row["database"],
|
||||
"username": row["username"] or "",
|
||||
"password": _decrypt(row["password"] or ""),
|
||||
}
|
||||
|
||||
def list_all(self) -> list[DatabaseConnection]:
|
||||
with self._connect() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM db_connection ORDER BY created_at DESC"
|
||||
).fetchall()
|
||||
return [self._row_to_entity(r) for r in rows]
|
||||
|
||||
def update(
|
||||
self, config_id: str, payload: DatabaseConnectionUpdate
|
||||
) -> Optional[DatabaseConnection]:
|
||||
existing = self.get(config_id)
|
||||
if existing is None:
|
||||
return None
|
||||
changes = payload.model_dump(exclude_none=True)
|
||||
if not changes:
|
||||
return existing
|
||||
if "password" in changes:
|
||||
changes["password"] = _encrypt(changes["password"])
|
||||
changes["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
set_clause = ", ".join(f"{k} = ?" for k in changes)
|
||||
values = list(changes.values()) + [config_id]
|
||||
with self._connect() as conn:
|
||||
conn.execute(f"UPDATE db_connection SET {set_clause} WHERE id = ?", values)
|
||||
conn.commit()
|
||||
return self.get(config_id)
|
||||
|
||||
def delete(self, config_id: str) -> bool:
|
||||
with self._connect() as conn:
|
||||
cursor = conn.execute("DELETE FROM db_connection WHERE id = ?", (config_id,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
@@ -0,0 +1,272 @@
|
||||
"""
|
||||
模型配置存储层
|
||||
==============
|
||||
|
||||
【功能说明】模型偏好配置的持久化(SQLite),支持增删改查。
|
||||
【技术选型理由】与 ProjectStore/TaskStore 同库同哲学(决策点 5 接口抽象 + SQLite)。
|
||||
【安全设计】API key 不入库,只存 provider_key 引用。
|
||||
【实现思路】ModelConfigStore 抽象 + SqliteModelConfigStore 实现,含默认数据初始化。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import uuid
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from app.schemas.model_config import ModelConfig, ModelConfigCreate, ModelConfigUpdate
|
||||
from app.store.sqlite_util import open_connection
|
||||
|
||||
# 默认模型配置(首次启动自动初始化,用户可增删改)
|
||||
DEFAULT_MODELS = [
|
||||
{
|
||||
"display_name": "GLM-5.3 — 强模型(代码/推理)",
|
||||
"model_id": "glm-5.3",
|
||||
"provider_key": "ccswitch",
|
||||
"model_role": "strong",
|
||||
"is_enabled": True,
|
||||
"sort_order": 10,
|
||||
"description": "via ccswitch,代码与推理能力强",
|
||||
},
|
||||
{
|
||||
"display_name": "GLM-5.3-Flash — 轻量快速",
|
||||
"model_id": "glm-5.3-flash",
|
||||
"provider_key": "ccswitch",
|
||||
"model_role": "weak",
|
||||
"is_enabled": True,
|
||||
"sort_order": 20,
|
||||
"description": "via ccswitch,速度快、成本低",
|
||||
},
|
||||
{
|
||||
"display_name": "Mimo-v2.6-Pro — 小米强模型",
|
||||
"model_id": "mimo-v2.6-pro",
|
||||
"provider_key": "ccswitch",
|
||||
"model_role": "strong",
|
||||
"is_enabled": True,
|
||||
"sort_order": 30,
|
||||
"description": "via ccswitch",
|
||||
},
|
||||
{
|
||||
"display_name": "DeepSeek-v4-Pro",
|
||||
"model_id": "deepseek-v4-pro",
|
||||
"provider_key": "ccswitch",
|
||||
"model_role": "strong",
|
||||
"is_enabled": True,
|
||||
"sort_order": 40,
|
||||
"description": "via ccswitch",
|
||||
},
|
||||
{
|
||||
"display_name": "MiniMax-Latest",
|
||||
"model_id": "minimax-latest",
|
||||
"provider_key": "ccswitch",
|
||||
"model_role": "general",
|
||||
"is_enabled": True,
|
||||
"sort_order": 50,
|
||||
"description": "via ccswitch",
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class ModelConfigStore(ABC):
|
||||
"""模型配置存储抽象接口"""
|
||||
|
||||
@abstractmethod
|
||||
def create(self, payload: ModelConfigCreate) -> ModelConfig: ...
|
||||
|
||||
@abstractmethod
|
||||
def get(self, config_id: str) -> Optional[ModelConfig]: ...
|
||||
|
||||
@abstractmethod
|
||||
def list_all(self, only_enabled: bool = False) -> list[ModelConfig]: ...
|
||||
|
||||
@abstractmethod
|
||||
def update(
|
||||
self, config_id: str, payload: ModelConfigUpdate
|
||||
) -> Optional[ModelConfig]: ...
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, config_id: str) -> bool: ...
|
||||
|
||||
|
||||
class SqliteModelConfigStore(ModelConfigStore):
|
||||
"""ModelConfigStore 的 SQLite 实现"""
|
||||
|
||||
def __init__(self, db_path: Path) -> None:
|
||||
self._db_path = Path(db_path)
|
||||
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_schema()
|
||||
self._seed_defaults()
|
||||
|
||||
def _connect(self):
|
||||
"""
|
||||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||
|
||||
【修复】原先 `with sqlite3.connect(...)` 只提交不关闭,连接泄漏到 GC。
|
||||
改为委托 app.store.sqlite_util.open_connection,语义不变、额外保证 close。
|
||||
"""
|
||||
return open_connection(self._db_path)
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
ddl = """
|
||||
CREATE TABLE IF NOT EXISTS model_config (
|
||||
id TEXT PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
model_id TEXT NOT NULL,
|
||||
provider_key TEXT NOT NULL DEFAULT 'ccswitch',
|
||||
model_role TEXT NOT NULL DEFAULT 'general',
|
||||
is_enabled INTEGER NOT NULL DEFAULT 1,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
fallback_order INTEGER NOT NULL DEFAULT 999,
|
||||
description TEXT DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
with self._connect() as conn:
|
||||
conn.execute(ddl)
|
||||
conn.commit()
|
||||
# 兼容旧表:补 fallback_order 列(幂等)
|
||||
try:
|
||||
conn.execute(
|
||||
"ALTER TABLE model_config ADD COLUMN fallback_order INTEGER NOT NULL DEFAULT 999"
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
pass # 列已存在
|
||||
# 数据迁移:fallback_order 全为 999 的旧数据按 sort_order 重排为 1,2,3...
|
||||
try:
|
||||
all_999 = conn.execute(
|
||||
"SELECT COUNT(*) FROM model_config WHERE fallback_order != 999"
|
||||
).fetchone()[0]
|
||||
total = conn.execute("SELECT COUNT(*) FROM model_config").fetchone()[0]
|
||||
if total > 0 and all_999 == 0:
|
||||
rows = conn.execute(
|
||||
"SELECT id FROM model_config ORDER BY sort_order ASC, created_at ASC"
|
||||
).fetchall()
|
||||
for i, row in enumerate(rows, start=1):
|
||||
conn.execute(
|
||||
"UPDATE model_config SET fallback_order = ? WHERE id = ?",
|
||||
(i, row["id"]),
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _seed_defaults(self) -> None:
|
||||
"""首次启动初始化默认模型配置(幂等:已有数据则跳过)。"""
|
||||
with self._connect() as conn:
|
||||
count = conn.execute("SELECT COUNT(*) FROM model_config").fetchone()[0]
|
||||
if count > 0:
|
||||
return
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
for idx, item in enumerate(DEFAULT_MODELS):
|
||||
conn.execute(
|
||||
"""INSERT INTO model_config
|
||||
(id, display_name, model_id, provider_key, model_role,
|
||||
is_enabled, sort_order, fallback_order, description, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
f"model_{uuid.uuid4().hex[:12]}",
|
||||
item["display_name"],
|
||||
item["model_id"],
|
||||
item["provider_key"],
|
||||
item["model_role"],
|
||||
1 if item["is_enabled"] else 0,
|
||||
item["sort_order"],
|
||||
idx + 1, # 默认降级链顺序按初始化顺序
|
||||
item["description"],
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
@staticmethod
|
||||
def _row_to_entity(row: sqlite3.Row) -> ModelConfig:
|
||||
return ModelConfig(
|
||||
id=row["id"],
|
||||
display_name=row["display_name"],
|
||||
model_id=row["model_id"],
|
||||
provider_key=row["provider_key"],
|
||||
model_role=row["model_role"],
|
||||
is_enabled=bool(row["is_enabled"]),
|
||||
sort_order=row["sort_order"],
|
||||
fallback_order=row["fallback_order"] if "fallback_order" in row.keys() else 999,
|
||||
description=row["description"] or "",
|
||||
created_at=datetime.fromisoformat(row["created_at"]),
|
||||
updated_at=datetime.fromisoformat(row["updated_at"]),
|
||||
)
|
||||
|
||||
def create(self, payload: ModelConfigCreate) -> ModelConfig:
|
||||
config_id = f"model_{uuid.uuid4().hex[:12]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._connect() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO model_config
|
||||
(id, display_name, model_id, provider_key, model_role,
|
||||
is_enabled, sort_order, fallback_order, description, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(
|
||||
config_id,
|
||||
payload.display_name,
|
||||
payload.model_id,
|
||||
payload.provider_key,
|
||||
payload.model_role,
|
||||
1 if payload.is_enabled else 0,
|
||||
payload.sort_order,
|
||||
payload.fallback_order,
|
||||
payload.description,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
created = self.get(config_id)
|
||||
if created is None:
|
||||
raise RuntimeError(f"模型配置创建后回读失败:{config_id}")
|
||||
return created
|
||||
|
||||
def get(self, config_id: str) -> Optional[ModelConfig]:
|
||||
with self._connect() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM model_config WHERE id = ?", (config_id,)
|
||||
).fetchone()
|
||||
return self._row_to_entity(row) if row else None
|
||||
|
||||
def list_all(self, only_enabled: bool = False) -> list[ModelConfig]:
|
||||
sql = "SELECT * FROM model_config"
|
||||
if only_enabled:
|
||||
sql += " WHERE is_enabled = 1"
|
||||
sql += " ORDER BY sort_order ASC, created_at ASC"
|
||||
with self._connect() as conn:
|
||||
rows = conn.execute(sql).fetchall()
|
||||
return [self._row_to_entity(r) for r in rows]
|
||||
|
||||
def update(
|
||||
self, config_id: str, payload: ModelConfigUpdate
|
||||
) -> Optional[ModelConfig]:
|
||||
existing = self.get(config_id)
|
||||
if existing is None:
|
||||
return None
|
||||
changes = payload.model_dump(exclude_none=True)
|
||||
if not changes:
|
||||
return existing
|
||||
# is_enabled 转 SQLite 整数
|
||||
if "is_enabled" in changes:
|
||||
changes["is_enabled"] = 1 if changes["is_enabled"] else 0
|
||||
changes["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
set_clause = ", ".join(f"{k} = ?" for k in changes)
|
||||
values = list(changes.values()) + [config_id]
|
||||
with self._connect() as conn:
|
||||
conn.execute(f"UPDATE model_config SET {set_clause} WHERE id = ?", values)
|
||||
conn.commit()
|
||||
return self.get(config_id)
|
||||
|
||||
def delete(self, config_id: str) -> bool:
|
||||
with self._connect() as conn:
|
||||
cursor = conn.execute("DELETE FROM model_config WHERE id = ?", (config_id,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
@@ -0,0 +1,428 @@
|
||||
"""
|
||||
平台账号存储
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
管理多个 AI 平台账号(品牌/账号名/套餐/控制台 URL/Cookie/用量快照)。
|
||||
同一品牌可有多个账号(多套餐并行)。
|
||||
|
||||
【技术选型理由】
|
||||
1. SQLite 存账号与 Cookie(JSON 序列化);
|
||||
2. 用量快照表记录每次抓取结果,支撑趋势分析;
|
||||
3. Cookie 加密存储(复用 Provider 的 XOR 加密)。
|
||||
|
||||
【安全设计】Cookie/凭证加密存储,前端脱敏展示。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from app.store.sqlite_util import open_connection
|
||||
|
||||
logger = logging.getLogger("agent.platform_store")
|
||||
|
||||
# 简易加密(与 provider_store 同款)
|
||||
_XOR_KEY = b"agent_platform_key_2026"
|
||||
|
||||
|
||||
def _encrypt(text: str) -> str:
|
||||
if not text:
|
||||
return ""
|
||||
data = text.encode("utf-8")
|
||||
encrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(data))
|
||||
return base64_encode(encrypted)
|
||||
|
||||
|
||||
def _decrypt(token: str) -> str:
|
||||
if not token:
|
||||
return ""
|
||||
try:
|
||||
import base64
|
||||
|
||||
encrypted = base64.b64decode(token.encode("ascii"))
|
||||
decrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(encrypted))
|
||||
return decrypted.decode("utf-8")
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
def base64_encode(data: bytes) -> str:
|
||||
import base64
|
||||
|
||||
return base64.b64encode(data).decode("ascii")
|
||||
|
||||
|
||||
class PlatformAccountStore:
|
||||
"""平台账号存储(SQLite)"""
|
||||
|
||||
def __init__(self, db_path: Path) -> None:
|
||||
self._db_path = Path(db_path)
|
||||
self._init_schema()
|
||||
self._seed_defaults()
|
||||
|
||||
def _conn(self):
|
||||
"""
|
||||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||
|
||||
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||
提交/回滚语义不变,额外保证 close。
|
||||
"""
|
||||
return open_connection(self._db_path)
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
ddl = """
|
||||
CREATE TABLE IF NOT EXISTS platform_account (
|
||||
id TEXT PRIMARY KEY,
|
||||
brand TEXT NOT NULL,
|
||||
account_name TEXT NOT NULL,
|
||||
plan_name TEXT DEFAULT '',
|
||||
console_url TEXT NOT NULL,
|
||||
cookies TEXT DEFAULT '',
|
||||
description TEXT DEFAULT '',
|
||||
is_active INTEGER DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS usage_snapshot (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL,
|
||||
captured_at TEXT NOT NULL,
|
||||
usage_percent REAL DEFAULT 0,
|
||||
used_amount TEXT DEFAULT '',
|
||||
total_amount TEXT DEFAULT '',
|
||||
remain_amount TEXT DEFAULT '',
|
||||
expire_date TEXT DEFAULT '',
|
||||
usage_5h TEXT DEFAULT '',
|
||||
usage_1w TEXT DEFAULT '',
|
||||
usage_1m TEXT DEFAULT '',
|
||||
reset_5h TEXT DEFAULT '',
|
||||
reset_1w TEXT DEFAULT '',
|
||||
reset_1m TEXT DEFAULT '',
|
||||
valid_until TEXT DEFAULT '',
|
||||
raw_data TEXT DEFAULT '',
|
||||
FOREIGN KEY (account_id) REFERENCES platform_account(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS scrape_schedule (
|
||||
id TEXT PRIMARY KEY,
|
||||
enabled INTEGER DEFAULT 0,
|
||||
interval_minutes INTEGER DEFAULT 360,
|
||||
account_ids TEXT DEFAULT '[]',
|
||||
last_run_at TEXT DEFAULT '',
|
||||
last_run_result TEXT DEFAULT '',
|
||||
login_detect_enabled INTEGER DEFAULT 1,
|
||||
login_detect_interval INTEGER DEFAULT 60,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
with self._conn() as conn:
|
||||
conn.executescript(ddl)
|
||||
conn.commit()
|
||||
for col_ddl in (
|
||||
"ALTER TABLE scrape_schedule ADD COLUMN login_detect_enabled INTEGER DEFAULT 1",
|
||||
"ALTER TABLE scrape_schedule ADD COLUMN login_detect_interval INTEGER DEFAULT 60",
|
||||
):
|
||||
try:
|
||||
conn.execute(col_ddl)
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
# 兼容旧表:补新列(幂等)
|
||||
for col_ddl in (
|
||||
"ALTER TABLE usage_snapshot ADD COLUMN usage_5h TEXT DEFAULT ''",
|
||||
"ALTER TABLE usage_snapshot ADD COLUMN usage_1w TEXT DEFAULT ''",
|
||||
"ALTER TABLE usage_snapshot ADD COLUMN usage_1m TEXT DEFAULT ''",
|
||||
"ALTER TABLE usage_snapshot ADD COLUMN reset_5h TEXT DEFAULT ''",
|
||||
"ALTER TABLE usage_snapshot ADD COLUMN reset_1w TEXT DEFAULT ''",
|
||||
"ALTER TABLE usage_snapshot ADD COLUMN reset_1m TEXT DEFAULT ''",
|
||||
"ALTER TABLE usage_snapshot ADD COLUMN valid_until TEXT DEFAULT ''",
|
||||
):
|
||||
try:
|
||||
conn.execute(col_ddl)
|
||||
conn.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
pass # 列已存在
|
||||
|
||||
def _seed_defaults(self) -> None:
|
||||
"""首次初始化:预置用户提到的两个平台控制台。"""
|
||||
with self._conn() as conn:
|
||||
count = conn.execute("SELECT COUNT(*) FROM platform_account").fetchone()[0]
|
||||
if count > 0:
|
||||
return
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
defaults = [
|
||||
{
|
||||
"brand": "小米",
|
||||
"account_name": "主力账号",
|
||||
"plan_name": "Coding 套餐",
|
||||
"console_url": "https://platform.xiaomimimo.com/console/plan-manage",
|
||||
"description": "小米 MiMo 平台用量页",
|
||||
},
|
||||
{
|
||||
"brand": "火山引擎",
|
||||
"account_name": "主力账号",
|
||||
"plan_name": "Coding 套餐",
|
||||
"console_url": "https://console.volcengine.com/ark/region:cn-beijing/subscription/coding-plan",
|
||||
"description": "火山方舟 Coding Plan 用量页",
|
||||
},
|
||||
]
|
||||
for item in defaults:
|
||||
conn.execute(
|
||||
"""INSERT INTO platform_account
|
||||
(id, brand, account_name, plan_name, console_url, description, is_active, created_at, updated_at)
|
||||
VALUES (?,?,?,?,?,?,1,?,?)""",
|
||||
(
|
||||
f"pa_{uuid.uuid4().hex[:8]}",
|
||||
item["brand"],
|
||||
item["account_name"],
|
||||
item["plan_name"],
|
||||
item["console_url"],
|
||||
item["description"],
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
logger.info("已预置平台账号:%d 个", len(defaults))
|
||||
|
||||
def _row_to_dict(self, row: sqlite3.Row) -> dict:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"brand": row["brand"],
|
||||
"account_name": row["account_name"],
|
||||
"plan_name": row["plan_name"],
|
||||
"console_url": row["console_url"],
|
||||
"description": row["description"] or "",
|
||||
"is_active": bool(row["is_active"]),
|
||||
"has_cookies": bool(row["cookies"]),
|
||||
"created_at": row["created_at"],
|
||||
"updated_at": row["updated_at"],
|
||||
}
|
||||
|
||||
def list_all(self) -> list[dict]:
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM platform_account ORDER BY brand, account_name"
|
||||
).fetchall()
|
||||
return [self._row_to_dict(r) for r in rows]
|
||||
|
||||
def get(self, account_id: str) -> Optional[dict]:
|
||||
with self._conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM platform_account WHERE id = ?", (account_id,)
|
||||
).fetchone()
|
||||
return self._row_to_dict(row) if row else None
|
||||
|
||||
def get_with_cookies(self, account_id: str) -> Optional[dict]:
|
||||
"""获取含真实 Cookie 的账号信息(供抓取用)。"""
|
||||
with self._conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM platform_account WHERE id = ?", (account_id,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
return {
|
||||
"id": row["id"],
|
||||
"brand": row["brand"],
|
||||
"account_name": row["account_name"],
|
||||
"plan_name": row["plan_name"],
|
||||
"console_url": row["console_url"],
|
||||
"cookies": _decrypt(row["cookies"] or ""),
|
||||
"is_active": bool(row["is_active"]),
|
||||
}
|
||||
|
||||
def create(self, brand: str, account_name: str, plan_name: str, console_url: str, description: str = "") -> dict:
|
||||
aid = f"pa_{uuid.uuid4().hex[:8]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._conn() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO platform_account
|
||||
(id, brand, account_name, plan_name, console_url, description, is_active, created_at, updated_at)
|
||||
VALUES (?,?,?,?,?,?,1,?,?)""",
|
||||
(aid, brand, account_name, plan_name, console_url, description, now, now),
|
||||
)
|
||||
conn.commit()
|
||||
return self.get(aid)
|
||||
|
||||
def update(self, account_id: str, **kwargs) -> Optional[dict]:
|
||||
allowed = {"brand", "account_name", "plan_name", "console_url", "description", "is_active"}
|
||||
updates = {k: v for k, v in kwargs.items() if k in allowed and v is not None}
|
||||
if "is_active" in updates:
|
||||
updates["is_enabled"] = 1 if updates["is_active"] else 0
|
||||
if not updates:
|
||||
return self.get(account_id)
|
||||
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||
values = list(updates.values()) + [account_id]
|
||||
with self._conn() as conn:
|
||||
conn.execute(f"UPDATE platform_account SET {set_clause} WHERE id = ?", values)
|
||||
conn.commit()
|
||||
return self.get(account_id)
|
||||
|
||||
def save_cookies(self, account_id: str, cookies_json: str) -> bool:
|
||||
"""保存登录 Cookie(JSON 序列化)。"""
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._conn() as conn:
|
||||
cursor = conn.execute(
|
||||
"UPDATE platform_account SET cookies = ?, updated_at = ? WHERE id = ?",
|
||||
(_encrypt(cookies_json), now, account_id),
|
||||
)
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
|
||||
def delete(self, account_id: str) -> bool:
|
||||
with self._conn() as conn:
|
||||
conn.execute("DELETE FROM usage_snapshot WHERE account_id = ?", (account_id,))
|
||||
cursor = conn.execute(
|
||||
"DELETE FROM platform_account WHERE id = ?", (account_id,)
|
||||
)
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
|
||||
# ---------- 用量快照 ----------
|
||||
|
||||
def save_snapshot(self, account_id: str, data: dict) -> dict:
|
||||
"""保存一次用量快照(含四指标 + 重置时间 + 有效期)。"""
|
||||
sid = f"us_{uuid.uuid4().hex[:8]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._conn() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO usage_snapshot
|
||||
(id, account_id, captured_at, usage_percent, used_amount, total_amount,
|
||||
remain_amount, expire_date, usage_5h, usage_1w, usage_1m,
|
||||
reset_5h, reset_1w, reset_1m, valid_until, raw_data)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(
|
||||
sid,
|
||||
account_id,
|
||||
now,
|
||||
data.get("usage_percent", 0),
|
||||
data.get("used_amount", ""),
|
||||
data.get("total_amount", ""),
|
||||
data.get("remain_amount", ""),
|
||||
data.get("expire_date", ""),
|
||||
data.get("usage_5h", ""),
|
||||
data.get("usage_1w", ""),
|
||||
data.get("usage_1m", ""),
|
||||
data.get("reset_5h", ""),
|
||||
data.get("reset_1w", ""),
|
||||
data.get("reset_1m", ""),
|
||||
data.get("valid_until", ""),
|
||||
json.dumps(data.get("raw_data", {}), ensure_ascii=False),
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return {"id": sid, "captured_at": now}
|
||||
|
||||
def get_latest_snapshot(self, account_id: str) -> Optional[dict]:
|
||||
"""获取最近一次用量快照。"""
|
||||
with self._conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM usage_snapshot WHERE account_id = ? ORDER BY captured_at DESC LIMIT 1",
|
||||
(account_id,),
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
def get_snapshots(self, account_id: str, limit: int = 30) -> list[dict]:
|
||||
"""获取用量快照历史(供趋势分析)。"""
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM usage_snapshot WHERE account_id = ? ORDER BY captured_at DESC LIMIT ?",
|
||||
(account_id, limit),
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
# ---------- 定时任务配置 ----------
|
||||
|
||||
def get_schedule(self) -> dict:
|
||||
"""获取定时抓取配置(不存在则创建默认)。"""
|
||||
with self._conn() as conn:
|
||||
row = conn.execute("SELECT * FROM scrape_schedule LIMIT 1").fetchone()
|
||||
if row is None:
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
conn.execute(
|
||||
"""INSERT INTO scrape_schedule
|
||||
(id, enabled, interval_minutes, account_ids,
|
||||
login_detect_enabled, login_detect_interval,
|
||||
created_at, updated_at)
|
||||
VALUES ('default', 0, 360, '[]', 1, 60, ?, ?)""",
|
||||
(now, now),
|
||||
)
|
||||
conn.commit()
|
||||
row = conn.execute("SELECT * FROM scrape_schedule WHERE id = 'default'").fetchone()
|
||||
|
||||
account_ids = []
|
||||
try:
|
||||
account_ids = json.loads(row["account_ids"] or "[]")
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return {
|
||||
"id": row["id"],
|
||||
"enabled": bool(row["enabled"]),
|
||||
"interval_minutes": row["interval_minutes"] or 360,
|
||||
"account_ids": account_ids,
|
||||
"last_run_at": row["last_run_at"] or "",
|
||||
"last_run_result": row["last_run_result"] or "",
|
||||
"login_detect_enabled": bool(row["login_detect_enabled"]) if "login_detect_enabled" in row.keys() else True,
|
||||
"login_detect_interval": row["login_detect_interval"] or 60 if "login_detect_interval" in row.keys() else 60,
|
||||
}
|
||||
|
||||
def update_schedule(
|
||||
self,
|
||||
enabled: bool | None = None,
|
||||
interval_minutes: int | None = None,
|
||||
account_ids: list[str] | None = None,
|
||||
login_detect_enabled: bool | None = None,
|
||||
login_detect_interval: int | None = None,
|
||||
) -> dict:
|
||||
"""更新定时抓取配置(含登录过期检测配置)。"""
|
||||
updates: dict[str, Any] = {"updated_at": datetime.now().astimezone().isoformat(timespec="seconds")}
|
||||
if enabled is not None:
|
||||
updates["enabled"] = 1 if enabled else 0
|
||||
if interval_minutes is not None:
|
||||
updates["interval_minutes"] = interval_minutes
|
||||
if account_ids is not None:
|
||||
updates["account_ids"] = json.dumps(account_ids, ensure_ascii=False)
|
||||
if login_detect_enabled is not None:
|
||||
updates["login_detect_enabled"] = 1 if login_detect_enabled else 0
|
||||
if login_detect_interval is not None:
|
||||
updates["login_detect_interval"] = login_detect_interval
|
||||
|
||||
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||
values = list(updates.values())
|
||||
with self._conn() as conn:
|
||||
conn.execute(f"UPDATE scrape_schedule SET {set_clause} WHERE id = 'default'", values)
|
||||
conn.commit()
|
||||
return self.get_schedule()
|
||||
|
||||
def record_schedule_run(self, result_summary: str) -> None:
|
||||
"""记录一次定时任务执行结果。"""
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._conn() as conn:
|
||||
conn.execute(
|
||||
"UPDATE scrape_schedule SET last_run_at = ?, last_run_result = ? WHERE id = 'default'",
|
||||
(now, result_summary[:500]),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
|
||||
# 全局单例
|
||||
_store: PlatformAccountStore | None = None
|
||||
|
||||
|
||||
def get_platform_store() -> PlatformAccountStore:
|
||||
global _store
|
||||
if _store is None:
|
||||
from app.config.settings import load_settings
|
||||
|
||||
s = load_settings()
|
||||
_store = PlatformAccountStore(s.sqlite_db_path)
|
||||
return _store
|
||||
@@ -0,0 +1,258 @@
|
||||
"""
|
||||
项目元数据存储抽象层
|
||||
====================
|
||||
|
||||
【功能说明】
|
||||
定义项目(Project)持久化的统一接口,并给出 SQLite 一期实现。
|
||||
业务层只依赖 ProjectStore 抽象,不感知底层是 SQLite / PostgreSQL / 还是内存。
|
||||
|
||||
【技术选型理由】
|
||||
1. 决策点 5 选了「C:接口抽象 + 一期 SQLite,预留平迁 Postgres」——
|
||||
本模块就是那个抽象边界,换实现时业务代码零改动。
|
||||
2. 选 SQLite 而非直接上 Postgres:硬约束 6 要求全落 D 盘本地,
|
||||
Windows 单机场景下 Docker 化 Postgres 是负资产。
|
||||
3. 用标准库 sqlite3 而非 ORM:项目表结构简单,ORM 反而引入额外
|
||||
学习成本与隐式行为;SQL 显式可读,便于教学与排错。
|
||||
|
||||
【实现思路】
|
||||
- ProjectStore(ABC):声明 CRUD + 查询接口;
|
||||
- SqliteProjectStore:用 sqlite3 实现,连接串落 D:\\Agent\\agent\\data\\agent.db;
|
||||
- 每次操作独立开连接(短连接),避免长连接在 Windows 下的文件锁问题;
|
||||
- 表创建幂等(IF NOT EXISTS),支持进程重复启动。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:SQLite 并发写冲突(多任务同时写)。
|
||||
应对:启用 WAL 模式 + busy_timeout=5000,短连接重试;一期单用户场景足够。
|
||||
风险2:datetime 字段时区不一致。
|
||||
应对:统一存 ISO8601 字符串(UTC+8 本地时区),读取时解析回 datetime。
|
||||
风险3:项目删除后孤儿数据(任务记录仍指向该项目)。
|
||||
应对:删除项目时级联清理关联任务(一期任务表后置,先预留注释与钩子)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
import uuid
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from app.schemas.project import Project, ProjectCreate, ProjectUpdate
|
||||
from app.store.sqlite_util import open_connection
|
||||
|
||||
|
||||
class ProjectStore(ABC):
|
||||
"""项目元数据存储抽象接口(决策点 5:存储可替换)"""
|
||||
|
||||
@abstractmethod
|
||||
def create(self, payload: ProjectCreate) -> Project:
|
||||
"""创建项目,返回带 id/时间戳的完整实体。"""
|
||||
|
||||
@abstractmethod
|
||||
def get(self, project_id: str) -> Optional[Project]:
|
||||
"""按 ID 查询项目,不存在返回 None。"""
|
||||
|
||||
@abstractmethod
|
||||
def list_all(self) -> list[Project]:
|
||||
"""查询全部项目(按创建时间倒序)。"""
|
||||
|
||||
@abstractmethod
|
||||
def update(self, project_id: str, payload: ProjectUpdate) -> Optional[Project]:
|
||||
"""按需更新项目字段,返回更新后的实体;不存在返回 None。"""
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, project_id: str) -> bool:
|
||||
"""删除项目,返回是否真正删除了记录。"""
|
||||
|
||||
|
||||
class SqliteProjectStore(ProjectStore):
|
||||
"""ProjectStore 的 SQLite 实现(一期默认实现)"""
|
||||
|
||||
def __init__(self, db_path: Path) -> None:
|
||||
self._db_path = Path(db_path)
|
||||
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._init_schema()
|
||||
|
||||
# ---------- 内部工具 ----------
|
||||
|
||||
def _connect(self):
|
||||
"""
|
||||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||
|
||||
【要点】
|
||||
- check_same_thread=False:FastAPI 线程池下跨线程安全(单机单用户场景);
|
||||
- WAL:读写并发更友好;busy_timeout:写锁冲突时等待而非直接报错。
|
||||
|
||||
【修复】原先 `with sqlite3.connect(...)` 只提交不关闭,连接泄漏到 GC。
|
||||
改为委托 app.store.sqlite_util.open_connection,语义不变、额外保证 close。
|
||||
"""
|
||||
return open_connection(self._db_path)
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
"""建表(幂等)。"""
|
||||
ddl = """
|
||||
CREATE TABLE IF NOT EXISTS project (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
code_root_path TEXT NOT NULL,
|
||||
backend_path TEXT NOT NULL DEFAULT 'backend',
|
||||
frontend_path TEXT NOT NULL DEFAULT 'frontend',
|
||||
backend_branch TEXT NOT NULL DEFAULT 'master',
|
||||
frontend_branch TEXT NOT NULL DEFAULT 'master',
|
||||
backends TEXT DEFAULT '[]',
|
||||
frontends TEXT DEFAULT '[]',
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
with self._connect() as conn:
|
||||
conn.execute(ddl)
|
||||
conn.commit()
|
||||
for col_ddl in (
|
||||
"ALTER TABLE project ADD COLUMN sort_order INTEGER NOT NULL DEFAULT 0",
|
||||
"ALTER TABLE project ADD COLUMN backends TEXT DEFAULT '[]'",
|
||||
"ALTER TABLE project ADD COLUMN frontends TEXT DEFAULT '[]'",
|
||||
):
|
||||
try:
|
||||
conn.execute(col_ddl)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
pass
|
||||
# 数据迁移:sort_order 全为 0 的旧数据按当前顺序重排为 1,2,3...
|
||||
# (上移/下移靠交换 sort_order 实现,全 0 时交换无效)
|
||||
try:
|
||||
zero_count = conn.execute(
|
||||
"SELECT COUNT(*) FROM project WHERE sort_order = 0"
|
||||
).fetchone()[0]
|
||||
total = conn.execute("SELECT COUNT(*) FROM project").fetchone()[0]
|
||||
if total > 0 and zero_count == total:
|
||||
rows = conn.execute(
|
||||
"SELECT id FROM project ORDER BY created_at DESC"
|
||||
).fetchall()
|
||||
for i, row in enumerate(rows, start=1):
|
||||
conn.execute(
|
||||
"UPDATE project SET sort_order = ? WHERE id = ?",
|
||||
(i, row["id"]),
|
||||
)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def _row_to_entity(row: sqlite3.Row) -> Project:
|
||||
import json as json_mod
|
||||
|
||||
backends = []
|
||||
frontends = []
|
||||
try:
|
||||
backends = json_mod.loads(row["backends"] or "[]") if "backends" in row.keys() else []
|
||||
frontends = json_mod.loads(row["frontends"] or "[]") if "frontends" in row.keys() else []
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return Project(
|
||||
id=row["id"],
|
||||
name=row["name"],
|
||||
code_root_path=row["code_root_path"],
|
||||
backend_path=row["backend_path"],
|
||||
frontend_path=row["frontend_path"],
|
||||
backend_branch=row["backend_branch"],
|
||||
frontend_branch=row["frontend_branch"],
|
||||
backends=backends,
|
||||
frontends=frontends,
|
||||
description=row["description"],
|
||||
sort_order=row["sort_order"] if "sort_order" in row.keys() else 0,
|
||||
created_at=datetime.fromisoformat(row["created_at"]),
|
||||
updated_at=datetime.fromisoformat(row["updated_at"]),
|
||||
)
|
||||
|
||||
# ---------- 接口实现 ----------
|
||||
|
||||
def create(self, payload: ProjectCreate) -> Project:
|
||||
import json as json_mod
|
||||
|
||||
project_id = f"proj_{uuid.uuid4().hex[:12]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._connect() as conn:
|
||||
# 新建项目排到第一位:现有项目 sort_order 整体 +1,新项目置 0
|
||||
conn.execute("UPDATE project SET sort_order = sort_order + 1")
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO project (
|
||||
id, name, code_root_path, backend_path, frontend_path,
|
||||
backend_branch, frontend_branch, backends, frontends,
|
||||
description, sort_order, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
project_id,
|
||||
payload.name,
|
||||
payload.code_root_path,
|
||||
payload.backend_path,
|
||||
payload.frontend_path,
|
||||
payload.backend_branch,
|
||||
payload.frontend_branch,
|
||||
json_mod.dumps([b.model_dump() for b in payload.backends], ensure_ascii=False),
|
||||
json_mod.dumps([f.model_dump() for f in payload.frontends], ensure_ascii=False),
|
||||
payload.description,
|
||||
0,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
created = self.get(project_id)
|
||||
if created is None: # 理论上不会发生,作为兜底防御
|
||||
raise RuntimeError(f"项目创建后回读失败,project_id={project_id}")
|
||||
return created
|
||||
|
||||
def get(self, project_id: str) -> Optional[Project]:
|
||||
with self._connect() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM project WHERE id = ?", (project_id,)
|
||||
).fetchone()
|
||||
return self._row_to_entity(row) if row else None
|
||||
|
||||
def list_all(self) -> list[Project]:
|
||||
with self._connect() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM project ORDER BY sort_order ASC, created_at DESC"
|
||||
).fetchall()
|
||||
return [self._row_to_entity(r) for r in rows]
|
||||
|
||||
def update(self, project_id: str, payload: ProjectUpdate) -> Optional[Project]:
|
||||
import json as json_mod
|
||||
|
||||
existing = self.get(project_id)
|
||||
if existing is None:
|
||||
return None
|
||||
changes = payload.model_dump(exclude_none=True)
|
||||
if not changes:
|
||||
return existing
|
||||
# JSON 字段序列化
|
||||
if "backends" in changes:
|
||||
changes["backends"] = json_mod.dumps(
|
||||
[b if isinstance(b, dict) else b.model_dump() for b in changes["backends"]],
|
||||
ensure_ascii=False,
|
||||
)
|
||||
if "frontends" in changes:
|
||||
changes["frontends"] = json_mod.dumps(
|
||||
[f if isinstance(f, dict) else f.model_dump() for f in changes["frontends"]],
|
||||
ensure_ascii=False,
|
||||
)
|
||||
changes["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
set_clause = ", ".join(f"{k} = ?" for k in changes.keys())
|
||||
values = list(changes.values()) + [project_id]
|
||||
with self._connect() as conn:
|
||||
conn.execute(f"UPDATE project SET {set_clause} WHERE id = ?", values)
|
||||
conn.commit()
|
||||
return self.get(project_id)
|
||||
|
||||
def delete(self, project_id: str) -> bool:
|
||||
with self._connect() as conn:
|
||||
cursor = conn.execute("DELETE FROM project WHERE id = ?", (project_id,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
@@ -0,0 +1,221 @@
|
||||
"""
|
||||
Provider 服务通道存储
|
||||
====================
|
||||
|
||||
【功能说明】
|
||||
管理多个 AI 模型服务通道(GLM/DeepSeek/Mimo 等平台)的地址与密钥。
|
||||
实现 ccswitch 的核心能力:统一管理多平台、按 model_id 路由。
|
||||
|
||||
【技术选型理由】
|
||||
1. 每个 Provider = 一个平台(base_url + api_key);
|
||||
2. 模型管理的 provider_key 引用 Provider 的 name;
|
||||
3. 模型路由按 provider_key 查 Provider 连接配置 → 直连调用。
|
||||
|
||||
【安全设计】API key 加密存储,前端返回脱敏值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import sqlite3
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from app.store.sqlite_util import open_connection
|
||||
|
||||
logger = logging.getLogger("agent.provider")
|
||||
|
||||
# 简易加密(与 db_connection_store 同款)
|
||||
_XOR_KEY = b"agent_provider_key_2026"
|
||||
|
||||
|
||||
def _encrypt(text: str) -> str:
|
||||
if not text:
|
||||
return ""
|
||||
data = text.encode("utf-8")
|
||||
encrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(data))
|
||||
return base64.b64encode(encrypted).decode("ascii")
|
||||
|
||||
|
||||
def _decrypt(token: str) -> str:
|
||||
if not token:
|
||||
return ""
|
||||
try:
|
||||
encrypted = base64.b64decode(token.encode("ascii"))
|
||||
decrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(encrypted))
|
||||
return decrypted.decode("utf-8")
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
|
||||
class ProviderStore:
|
||||
"""Provider 存储(SQLite)"""
|
||||
|
||||
def __init__(self, db_path: Path) -> None:
|
||||
self._db_path = Path(db_path)
|
||||
self._init_schema()
|
||||
self._seed_ccswitch()
|
||||
|
||||
def _conn(self):
|
||||
"""
|
||||
获取一个短连接(用完自动提交/回滚并关闭)。
|
||||
|
||||
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
||||
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
||||
提交/回滚语义不变,额外保证 close。
|
||||
"""
|
||||
return open_connection(self._db_path)
|
||||
|
||||
def _init_schema(self) -> None:
|
||||
ddl = """
|
||||
CREATE TABLE IF NOT EXISTS provider (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
base_url TEXT NOT NULL,
|
||||
api_key TEXT NOT NULL DEFAULT '',
|
||||
description TEXT DEFAULT '',
|
||||
is_enabled INTEGER DEFAULT 1,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
with self._conn() as conn:
|
||||
conn.execute(ddl)
|
||||
conn.commit()
|
||||
|
||||
def _seed_ccswitch(self) -> None:
|
||||
"""首次初始化:把 .env 里的 ccswitch 配置导入为默认 Provider(向后兼容)。"""
|
||||
with self._conn() as conn:
|
||||
count = conn.execute("SELECT COUNT(*) FROM provider").fetchone()[0]
|
||||
if count > 0:
|
||||
return
|
||||
try:
|
||||
from app.config.settings import load_settings
|
||||
|
||||
s = load_settings()
|
||||
if s.ccswitch_api_key and s.ccswitch_base_url:
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
conn.execute(
|
||||
"INSERT INTO provider (id, name, base_url, api_key, description, is_enabled, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
f"prov_{uuid.uuid4().hex[:8]}",
|
||||
"ccswitch",
|
||||
s.ccswitch_base_url,
|
||||
_encrypt(s.ccswitch_api_key),
|
||||
"ccswitch 本地代理(兼容旧配置)",
|
||||
1,
|
||||
now,
|
||||
now,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
logger.info("已导入 ccswitch 为默认 Provider")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("导入 ccswitch 失败:%s", exc)
|
||||
|
||||
def _row_to_dict(self, row: sqlite3.Row, mask_key: bool = False) -> dict:
|
||||
key = row["api_key"] or ""
|
||||
# 本地工具不脱敏,直接返回解密后的真实密钥(便于用户查看/编辑)
|
||||
display_key = _decrypt(key)
|
||||
return {
|
||||
"id": row["id"],
|
||||
"name": row["name"],
|
||||
"base_url": row["base_url"],
|
||||
"api_key": display_key,
|
||||
"description": row["description"] or "",
|
||||
"is_enabled": bool(row["is_enabled"]),
|
||||
"created_at": row["created_at"],
|
||||
"updated_at": row["updated_at"],
|
||||
}
|
||||
|
||||
def list_all(self, only_enabled: bool = False) -> list[dict]:
|
||||
sql = "SELECT * FROM provider"
|
||||
if only_enabled:
|
||||
sql += " WHERE is_enabled = 1"
|
||||
sql += " ORDER BY created_at"
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(sql).fetchall()
|
||||
return [self._row_to_dict(r) for r in rows]
|
||||
|
||||
def get(self, provider_id: str) -> Optional[dict]:
|
||||
with self._conn() as conn:
|
||||
row = conn.execute("SELECT * FROM provider WHERE id = ?", (provider_id,)).fetchone()
|
||||
return self._row_to_dict(row) if row else None
|
||||
|
||||
def get_by_name(self, name: str) -> Optional[dict]:
|
||||
with self._conn() as conn:
|
||||
row = conn.execute("SELECT * FROM provider WHERE name = ?", (name,)).fetchone()
|
||||
return self._row_to_dict(row) if row else None
|
||||
|
||||
def get_with_key(self, name: str) -> Optional[dict]:
|
||||
"""获取含真实 api_key 的连接信息(供模型路由用,不暴露给前端)。"""
|
||||
with self._conn() as conn:
|
||||
row = conn.execute("SELECT * FROM provider WHERE name = ?", (name,)).fetchone()
|
||||
return self._row_with_real_key(row) if row else None
|
||||
|
||||
def get_with_key_by_id(self, provider_id: str) -> Optional[dict]:
|
||||
"""按 ID 获取含真实 api_key 的连接信息(供测试连接用)。"""
|
||||
with self._conn() as conn:
|
||||
row = conn.execute("SELECT * FROM provider WHERE id = ?", (provider_id,)).fetchone()
|
||||
return self._row_with_real_key(row) if row else None
|
||||
|
||||
@staticmethod
|
||||
def _row_with_real_key(row: sqlite3.Row) -> dict:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"name": row["name"],
|
||||
"base_url": row["base_url"],
|
||||
"api_key": _decrypt(row["api_key"] or ""),
|
||||
"is_enabled": bool(row["is_enabled"]),
|
||||
}
|
||||
|
||||
def create(self, name: str, base_url: str, api_key: str = "", description: str = "") -> dict:
|
||||
pid = f"prov_{uuid.uuid4().hex[:8]}"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self._conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO provider (id, name, base_url, api_key, description, is_enabled, created_at, updated_at) VALUES (?,?,?,?,?,1,?,?)",
|
||||
(pid, name, base_url, _encrypt(api_key), description, now, now),
|
||||
)
|
||||
conn.commit()
|
||||
return self.get(pid)
|
||||
|
||||
def update(self, provider_id: str, **kwargs) -> Optional[dict]:
|
||||
allowed = {"name", "base_url", "api_key", "description", "is_enabled"}
|
||||
updates = {k: v for k, v in kwargs.items() if k in allowed and v is not None}
|
||||
if not updates:
|
||||
return self.get(provider_id)
|
||||
if "api_key" in updates:
|
||||
updates["api_key"] = _encrypt(updates["api_key"])
|
||||
if "is_enabled" in updates:
|
||||
updates["is_enabled"] = 1 if updates["is_enabled"] else 0
|
||||
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
||||
values = list(updates.values()) + [provider_id]
|
||||
with self._conn() as conn:
|
||||
conn.execute(f"UPDATE provider SET {set_clause} WHERE id = ?", values)
|
||||
conn.commit()
|
||||
return self.get(provider_id)
|
||||
|
||||
def delete(self, provider_id: str) -> bool:
|
||||
with self._conn() as conn:
|
||||
cursor = conn.execute("DELETE FROM provider WHERE id = ?", (provider_id,))
|
||||
conn.commit()
|
||||
return cursor.rowcount > 0
|
||||
|
||||
|
||||
# 全局单例
|
||||
_store: ProviderStore | None = None
|
||||
|
||||
|
||||
def get_provider_store() -> ProviderStore:
|
||||
global _store
|
||||
if _store is None:
|
||||
from app.config.settings import load_settings
|
||||
|
||||
s = load_settings()
|
||||
_store = ProviderStore(s.sqlite_db_path)
|
||||
return _store
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
SQLite 短连接上下文管理器
|
||||
========================
|
||||
|
||||
【功能说明】
|
||||
统一「开连接 → 用完提交/回滚 → 关闭」的生命周期,杜绝连接泄漏。
|
||||
|
||||
【为什么需要】
|
||||
Python 的 sqlite3.Connection 用在 with 里时:
|
||||
with sqlite3.connect(...) as conn: # 退出时 commit/rollback,但**不 close**
|
||||
...
|
||||
连接对象要等 GC 才释放。后果:
|
||||
- Windows:文件锁不释放 → PermissionError: [WinError 32]
|
||||
- 服务端高频调用:连接数持续增长,最终耗尽句柄
|
||||
测试 teardown 曾因此无法删除临时 db 文件。
|
||||
|
||||
【语义】与裸 `with sqlite3.connect()` **完全一致**,只多保证关闭:
|
||||
- 正常退出 → commit(与 Connection.__exit__ 的成功语义相同)
|
||||
- 异常退出 → rollback + 原样抛出
|
||||
- 无论何种情况 → finally 中 close
|
||||
|
||||
【设计取舍】
|
||||
用 @contextmanager 而不是包装类:调用点 `with self._connect() as conn`
|
||||
的写法完全不用改,属于零侵入修复。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Iterator
|
||||
|
||||
|
||||
@contextmanager
|
||||
def open_connection(
|
||||
db_path: Path | str, *, timeout: float = 5.0
|
||||
) -> Iterator[sqlite3.Connection]:
|
||||
"""
|
||||
打开一个短连接,用完自动提交/回滚并关闭。
|
||||
|
||||
【参数】
|
||||
db_path:SQLite 文件路径
|
||||
timeout:写锁冲突等待秒数(busy_timeout 同值)
|
||||
【返回】yield sqlite3.Connection(row_factory 已设为 sqlite3.Row)
|
||||
"""
|
||||
conn = sqlite3.connect(str(db_path), timeout=timeout, check_same_thread=False)
|
||||
try:
|
||||
conn.row_factory = sqlite3.Row
|
||||
# WAL:读写并发更友好;busy_timeout:写锁冲突时等待而非直接报错
|
||||
conn.execute("PRAGMA journal_mode=WAL;")
|
||||
conn.execute("PRAGMA busy_timeout=5000;")
|
||||
yield conn
|
||||
# 与 sqlite3.Connection.__exit__ 的成功语义保持一致(提交)
|
||||
conn.commit()
|
||||
except BaseException:
|
||||
# 与 sqlite3.Connection.__exit__ 的失败语义保持一致(回滚后抛出)
|
||||
try:
|
||||
conn.rollback()
|
||||
except Exception: # noqa: BLE001 - 回滚失败不掩盖原始异常
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
# 【本模块存在的唯一理由】确保连接一定被关闭
|
||||
conn.close()
|
||||
Reference in New Issue
Block a user