Upload 201 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +16 -0
- .env.example +49 -0
- .github/ISSUE_TEMPLATE/bug_report.yml +39 -0
- .github/ISSUE_TEMPLATE/config.yml +5 -0
- .github/ISSUE_TEMPLATE/feature.yml +20 -0
- .github/ISSUE_TEMPLATE/question.yml +20 -0
- .github/pull_request_template.md +11 -0
- .github/workflows/docker.yml +63 -0
- .github/workflows/pr-meta.yml +16 -0
- .github/workflows/privoxy.yml +39 -0
- .github/workflows/security.yml +63 -0
- .gitignore +55 -0
- .python-version +1 -0
- Dockerfile +71 -38
- Dockerfile.privoxy +9 -0
- LICENSE +21 -0
- README.md +456 -8
- app/__init__.py +0 -0
- app/control/__init__.py +0 -0
- app/control/account/__init__.py +37 -0
- app/control/account/backends/__init__.py +0 -0
- app/control/account/backends/factory.py +138 -0
- app/control/account/backends/local.py +688 -0
- app/control/account/backends/redis.py +594 -0
- app/control/account/backends/sql.py +1094 -0
- app/control/account/commands.py +81 -0
- app/control/account/enums.py +39 -0
- app/control/account/invalid_credentials.py +82 -0
- app/control/account/models.py +347 -0
- app/control/account/quota_defaults.py +205 -0
- app/control/account/refresh.py +675 -0
- app/control/account/repository.py +102 -0
- app/control/account/runtime.py +102 -0
- app/control/account/scheduler.py +121 -0
- app/control/account/state_machine.py +333 -0
- app/control/admin/__init__.py +0 -0
- app/control/model/__init__.py +0 -0
- app/control/model/enums.py +77 -0
- app/control/model/registry.py +116 -0
- app/control/model/spec.py +98 -0
- app/control/proxy/__init__.py +431 -0
- app/control/proxy/config.py +56 -0
- app/control/proxy/feedback.py +39 -0
- app/control/proxy/models.py +109 -0
- app/control/proxy/providers/__init__.py +4 -0
- app/control/proxy/providers/flaresolverr.py +127 -0
- app/control/proxy/providers/manual.py +31 -0
- app/control/proxy/scheduler.py +83 -0
- app/dataplane/__init__.py +0 -0
- app/dataplane/account/__init__.py +360 -0
.dockerignore
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__
|
| 2 |
+
*.pyc
|
| 3 |
+
*.pyo
|
| 4 |
+
*.pyd
|
| 5 |
+
.Python
|
| 6 |
+
.env
|
| 7 |
+
.env.*
|
| 8 |
+
.git
|
| 9 |
+
.gitignore
|
| 10 |
+
.logs
|
| 11 |
+
logs
|
| 12 |
+
/data
|
| 13 |
+
/data/*
|
| 14 |
+
/data/tmp
|
| 15 |
+
/data/tmp/*
|
| 16 |
+
/tests
|
.env.example
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Grok2API environment example
|
| 2 |
+
#
|
| 3 |
+
# 用法:
|
| 4 |
+
# 1. 复制为 .env 后按需修改
|
| 5 |
+
# 2. 启动期 / 部署期变量放这里
|
| 6 |
+
# 3. 常规运行时配置优先改 ${DATA_DIR}/config.toml
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# ==================== 基础运行 ====================
|
| 10 |
+
TZ=Asia/Shanghai
|
| 11 |
+
LOG_LEVEL=INFO
|
| 12 |
+
# 写入本地文件日志
|
| 13 |
+
LOG_FILE_ENABLED=true
|
| 14 |
+
# 账号目录增量同步间隔(秒)
|
| 15 |
+
ACCOUNT_SYNC_INTERVAL=30
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# ==================== Web 服务 / Docker Compose ====================
|
| 19 |
+
SERVER_HOST=0.0.0.0
|
| 20 |
+
SERVER_PORT=8000
|
| 21 |
+
SERVER_WORKERS=1
|
| 22 |
+
|
| 23 |
+
# Docker Compose 宿主机映射端口
|
| 24 |
+
HOST_PORT=8000
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ==================== 账号存储(启动期) ====================
|
| 28 |
+
# 可选:local | redis | mysql | postgresql
|
| 29 |
+
ACCOUNT_STORAGE=local
|
| 30 |
+
|
| 31 |
+
# redis: Redis DSN(ACCOUNT_STORAGE=redis 时必填)
|
| 32 |
+
# ACCOUNT_REDIS_URL=redis://:password@host:6379/0
|
| 33 |
+
|
| 34 |
+
# mysql: SQLAlchemy DSN
|
| 35 |
+
# ACCOUNT_MYSQL_URL=mysql+aiomysql://user:password@127.0.0.1:3306/grok2api
|
| 36 |
+
|
| 37 |
+
# postgresql: SQLAlchemy DSN
|
| 38 |
+
# ACCOUNT_POSTGRESQL_URL=postgresql+asyncpg://user:password@127.0.0.1:5432/grok2api
|
| 39 |
+
|
| 40 |
+
# SQL 连接池(mysql / postgresql 模式,以下均为默认值,无需改动即可生效)
|
| 41 |
+
# ACCOUNT_SQL_POOL_SIZE=5
|
| 42 |
+
# ACCOUNT_SQL_MAX_OVERFLOW=10
|
| 43 |
+
# ACCOUNT_SQL_POOL_TIMEOUT=30
|
| 44 |
+
# ACCOUNT_SQL_POOL_RECYCLE=1800
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# ==================== 可选:本地数据 / 日志目录 ====================
|
| 48 |
+
DATA_DIR=./data
|
| 49 |
+
LOG_DIR=./logs
|
.github/ISSUE_TEMPLATE/bug_report.yml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Bug
|
| 2 |
+
description: 反馈缺陷或异常行为
|
| 3 |
+
title: "bug: "
|
| 4 |
+
labels: [bug]
|
| 5 |
+
body:
|
| 6 |
+
- type: textarea
|
| 7 |
+
id: description
|
| 8 |
+
attributes:
|
| 9 |
+
label: 问题描述
|
| 10 |
+
placeholder: 发生了什么,和预期行为有何不同?
|
| 11 |
+
validations:
|
| 12 |
+
required: true
|
| 13 |
+
|
| 14 |
+
- type: textarea
|
| 15 |
+
id: steps
|
| 16 |
+
attributes:
|
| 17 |
+
label: 复现步骤
|
| 18 |
+
placeholder: |
|
| 19 |
+
1. 启动服务,配置为 xxx
|
| 20 |
+
2. 调用 xxx 接口
|
| 21 |
+
3. 报错 / 出现异常行为
|
| 22 |
+
validations:
|
| 23 |
+
required: true
|
| 24 |
+
|
| 25 |
+
- type: input
|
| 26 |
+
id: version
|
| 27 |
+
attributes:
|
| 28 |
+
label: 版本
|
| 29 |
+
placeholder: v1.x.x 或 commit hash
|
| 30 |
+
validations:
|
| 31 |
+
required: true
|
| 32 |
+
|
| 33 |
+
- type: textarea
|
| 34 |
+
id: logs
|
| 35 |
+
attributes:
|
| 36 |
+
label: 相关日志
|
| 37 |
+
render: shell
|
| 38 |
+
validations:
|
| 39 |
+
required: true
|
.github/ISSUE_TEMPLATE/config.yml
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
blank_issues_enabled: false
|
| 2 |
+
contact_links:
|
| 3 |
+
- name: 文档与使用说明
|
| 4 |
+
url: https://blog.cheny.me/blog/posts/grok2api
|
| 5 |
+
about: 提交 Issue 前请先查看文档,很多常见问题已有说明。
|
.github/ISSUE_TEMPLATE/feature.yml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Feature
|
| 2 |
+
description: 新功能或现有功能增强建议
|
| 3 |
+
title: "feat: "
|
| 4 |
+
labels: [enhancement]
|
| 5 |
+
body:
|
| 6 |
+
- type: textarea
|
| 7 |
+
id: problem
|
| 8 |
+
attributes:
|
| 9 |
+
label: 背景 / 痛点
|
| 10 |
+
placeholder: 当前有什么不足?这个需求的使用场景是什么?
|
| 11 |
+
validations:
|
| 12 |
+
required: true
|
| 13 |
+
|
| 14 |
+
- type: textarea
|
| 15 |
+
id: solution
|
| 16 |
+
attributes:
|
| 17 |
+
label: 期望行为
|
| 18 |
+
placeholder: 希望如何工作?有没有参考实现?
|
| 19 |
+
validations:
|
| 20 |
+
required: true
|
.github/ISSUE_TEMPLATE/question.yml
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Question
|
| 2 |
+
description: 使用疑问或行为确认
|
| 3 |
+
title: "question: "
|
| 4 |
+
labels: [question]
|
| 5 |
+
body:
|
| 6 |
+
- type: textarea
|
| 7 |
+
id: question
|
| 8 |
+
attributes:
|
| 9 |
+
label: 问题
|
| 10 |
+
validations:
|
| 11 |
+
required: true
|
| 12 |
+
|
| 13 |
+
- type: textarea
|
| 14 |
+
id: context
|
| 15 |
+
attributes:
|
| 16 |
+
label: 上下文(配置 / 日志)
|
| 17 |
+
description: 相关配置请脱敏,日志请贴关键部分。
|
| 18 |
+
render: shell
|
| 19 |
+
validations:
|
| 20 |
+
required: false
|
.github/pull_request_template.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## Summary
|
| 2 |
+
|
| 3 |
+
<!-- 改动了什么,为什么改 -->
|
| 4 |
+
|
| 5 |
+
## Testing
|
| 6 |
+
|
| 7 |
+
<!-- 怎么验证:本地跑了什么、curl 结果、或"无需验证(仅文档/格式)" -->
|
| 8 |
+
|
| 9 |
+
## Related
|
| 10 |
+
|
| 11 |
+
<!-- Closes #... -->
|
.github/workflows/docker.yml
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Build Docker Image
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches:
|
| 6 |
+
- main
|
| 7 |
+
tags:
|
| 8 |
+
- 'v*'
|
| 9 |
+
pull_request:
|
| 10 |
+
branches:
|
| 11 |
+
- main
|
| 12 |
+
|
| 13 |
+
env:
|
| 14 |
+
REGISTRY: ghcr.io
|
| 15 |
+
IMAGE_NAME: ${{ github.repository }}
|
| 16 |
+
|
| 17 |
+
jobs:
|
| 18 |
+
build-and-push:
|
| 19 |
+
runs-on: ubuntu-latest
|
| 20 |
+
permissions:
|
| 21 |
+
contents: read
|
| 22 |
+
packages: write
|
| 23 |
+
id-token: write
|
| 24 |
+
|
| 25 |
+
steps:
|
| 26 |
+
- name: Checkout repository
|
| 27 |
+
uses: actions/checkout@v6
|
| 28 |
+
|
| 29 |
+
- name: Set up QEMU
|
| 30 |
+
uses: docker/setup-qemu-action@v3
|
| 31 |
+
|
| 32 |
+
- name: Set up Docker Buildx
|
| 33 |
+
uses: docker/setup-buildx-action@v3
|
| 34 |
+
|
| 35 |
+
- name: Log in to Container Registry
|
| 36 |
+
if: github.event_name != 'pull_request'
|
| 37 |
+
uses: docker/login-action@v3
|
| 38 |
+
with:
|
| 39 |
+
registry: ${{ env.REGISTRY }}
|
| 40 |
+
username: ${{ github.actor }}
|
| 41 |
+
password: ${{ secrets.GITHUB_TOKEN }}
|
| 42 |
+
|
| 43 |
+
- name: Extract metadata
|
| 44 |
+
id: meta
|
| 45 |
+
uses: docker/metadata-action@v5
|
| 46 |
+
with:
|
| 47 |
+
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
| 48 |
+
tags: |
|
| 49 |
+
type=raw,value=latest,enable=${{ github.ref_type == 'branch' }}
|
| 50 |
+
type=ref,event=tag
|
| 51 |
+
type=semver,pattern={{version}}
|
| 52 |
+
|
| 53 |
+
- name: Build and push Docker image
|
| 54 |
+
uses: docker/build-push-action@v6
|
| 55 |
+
with:
|
| 56 |
+
context: .
|
| 57 |
+
platforms: linux/amd64,linux/arm64
|
| 58 |
+
push: ${{ github.event_name != 'pull_request' }}
|
| 59 |
+
tags: ${{ steps.meta.outputs.tags }}
|
| 60 |
+
labels: ${{ steps.meta.outputs.labels }}
|
| 61 |
+
cache-from: type=gha
|
| 62 |
+
cache-to: type=gha,mode=max
|
| 63 |
+
pull: true
|
.github/workflows/pr-meta.yml
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: PR
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
pull_request:
|
| 5 |
+
types: [opened, edited, synchronize, reopened]
|
| 6 |
+
|
| 7 |
+
permissions:
|
| 8 |
+
pull-requests: read
|
| 9 |
+
|
| 10 |
+
jobs:
|
| 11 |
+
title:
|
| 12 |
+
runs-on: ubuntu-latest
|
| 13 |
+
steps:
|
| 14 |
+
- uses: amannn/action-semantic-pull-request@v5
|
| 15 |
+
env:
|
| 16 |
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
.github/workflows/privoxy.yml
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Build Privoxy-WARP Image
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [main]
|
| 6 |
+
paths:
|
| 7 |
+
- Dockerfile.privoxy
|
| 8 |
+
workflow_dispatch:
|
| 9 |
+
|
| 10 |
+
jobs:
|
| 11 |
+
build-and-push:
|
| 12 |
+
runs-on: ubuntu-latest
|
| 13 |
+
permissions:
|
| 14 |
+
contents: read
|
| 15 |
+
packages: write
|
| 16 |
+
steps:
|
| 17 |
+
- uses: actions/checkout@v4
|
| 18 |
+
|
| 19 |
+
- name: Set up QEMU
|
| 20 |
+
uses: docker/setup-qemu-action@v3
|
| 21 |
+
|
| 22 |
+
- name: Set up Docker Buildx
|
| 23 |
+
uses: docker/setup-buildx-action@v3
|
| 24 |
+
|
| 25 |
+
- name: Log in to GHCR
|
| 26 |
+
uses: docker/login-action@v3
|
| 27 |
+
with:
|
| 28 |
+
registry: ghcr.io
|
| 29 |
+
username: ${{ github.actor }}
|
| 30 |
+
password: ${{ secrets.GITHUB_TOKEN }}
|
| 31 |
+
|
| 32 |
+
- name: Build and push privoxy-warp
|
| 33 |
+
uses: docker/build-push-action@v6
|
| 34 |
+
with:
|
| 35 |
+
context: .
|
| 36 |
+
file: Dockerfile.privoxy
|
| 37 |
+
platforms: linux/amd64,linux/arm64
|
| 38 |
+
push: true
|
| 39 |
+
tags: ghcr.io/${{ github.repository_owner }}/privoxy-warp:latest
|
.github/workflows/security.yml
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Security
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [main]
|
| 6 |
+
pull_request:
|
| 7 |
+
branches: [main]
|
| 8 |
+
schedule:
|
| 9 |
+
- cron: "0 3 * * 1"
|
| 10 |
+
|
| 11 |
+
permissions:
|
| 12 |
+
contents: read
|
| 13 |
+
|
| 14 |
+
jobs:
|
| 15 |
+
gitleaks:
|
| 16 |
+
name: Gitleaks Secret Scanner
|
| 17 |
+
runs-on: ubuntu-latest
|
| 18 |
+
steps:
|
| 19 |
+
- uses: actions/checkout@v4
|
| 20 |
+
with:
|
| 21 |
+
fetch-depth: 0
|
| 22 |
+
|
| 23 |
+
# 针对 PR:使用原生逻辑
|
| 24 |
+
- name: Setup PR commits & Run Gitleaks
|
| 25 |
+
if: github.event_name == 'pull_request'
|
| 26 |
+
run: |
|
| 27 |
+
git fetch --no-tags --prune --depth=1 origin \
|
| 28 |
+
"+${{ github.event.pull_request.base.sha }}:refs/remotes/origin/pr-base"
|
| 29 |
+
git remote add pr-head "https://github.com/${{ github.event.pull_request.head.repo.full_name }}.git"
|
| 30 |
+
git fetch --no-tags --prune --depth=1 pr-head \
|
| 31 |
+
"+${{ github.event.pull_request.head.sha }}:refs/remotes/pr-head/current"
|
| 32 |
+
|
| 33 |
+
docker run --rm \
|
| 34 |
+
-v "$PWD:/repo" \
|
| 35 |
+
-w /repo \
|
| 36 |
+
zricethezav/gitleaks:v8.24.3 \
|
| 37 |
+
detect --source . --redact -v --exit-code=2 \
|
| 38 |
+
--log-opts="--no-merges refs/remotes/origin/pr-base..refs/remotes/pr-head/current"
|
| 39 |
+
|
| 40 |
+
# 针对 Push 和 Schedule:使用官方 Action
|
| 41 |
+
- name: Run Gitleaks Action
|
| 42 |
+
if: github.event_name != 'pull_request'
|
| 43 |
+
uses: gitleaks/gitleaks-action@v2
|
| 44 |
+
env:
|
| 45 |
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
| 46 |
+
GITLEAKS_ENABLE_UPLOAD_ARTIFACT: true
|
| 47 |
+
GITLEAKS_ENABLE_SUMMARY: true
|
| 48 |
+
continue-on-error: true
|
| 49 |
+
|
| 50 |
+
pip-audit:
|
| 51 |
+
name: Python Dependency Audit
|
| 52 |
+
runs-on: ubuntu-latest
|
| 53 |
+
steps:
|
| 54 |
+
- uses: actions/checkout@v4
|
| 55 |
+
- name: Install uv
|
| 56 |
+
uses: astral-sh/setup-uv@v3
|
| 57 |
+
- name: Export requirements
|
| 58 |
+
run: uv export --frozen --no-dev --format requirements-txt -o /tmp/req.txt
|
| 59 |
+
- name: Run pip-audit
|
| 60 |
+
run: |
|
| 61 |
+
uvx pip-audit -r /tmp/req.txt --progress-spinner off \
|
| 62 |
+
--ignore-vuln PYSEC-2026-161
|
| 63 |
+
echo "Dependency audit passed"
|
.gitignore
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
*.so
|
| 6 |
+
.Python
|
| 7 |
+
build/
|
| 8 |
+
develop-eggs/
|
| 9 |
+
dist/
|
| 10 |
+
downloads/
|
| 11 |
+
eggs/
|
| 12 |
+
.eggs/
|
| 13 |
+
lib/
|
| 14 |
+
lib64/
|
| 15 |
+
parts/
|
| 16 |
+
sdist/
|
| 17 |
+
var/
|
| 18 |
+
wheels/
|
| 19 |
+
*.egg-info/
|
| 20 |
+
.installed.cfg
|
| 21 |
+
*.egg
|
| 22 |
+
MANIFEST
|
| 23 |
+
|
| 24 |
+
# Virtual Environment
|
| 25 |
+
.venv/
|
| 26 |
+
venv/
|
| 27 |
+
ENV/
|
| 28 |
+
env/
|
| 29 |
+
|
| 30 |
+
# IDE
|
| 31 |
+
.vscode/
|
| 32 |
+
.idea/
|
| 33 |
+
*.swp
|
| 34 |
+
*.swo
|
| 35 |
+
*~
|
| 36 |
+
.DS_Store
|
| 37 |
+
|
| 38 |
+
# Environment Variables
|
| 39 |
+
.env
|
| 40 |
+
|
| 41 |
+
# Logs
|
| 42 |
+
logs/
|
| 43 |
+
*.log
|
| 44 |
+
|
| 45 |
+
# Data
|
| 46 |
+
data/
|
| 47 |
+
app/data/
|
| 48 |
+
|
| 49 |
+
# Testing
|
| 50 |
+
.pytest_cache/
|
| 51 |
+
.coverage
|
| 52 |
+
htmlcov/
|
| 53 |
+
|
| 54 |
+
# Project specific
|
| 55 |
+
.ace-tool/
|
.python-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
3.13
|
Dockerfile
CHANGED
|
@@ -1,44 +1,77 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
ca-certificates \
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
|
| 37 |
-
|
| 38 |
-
RUN mkdir -p /app/grok2api/logs && chmod -R 777 /app/grok2api
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
|
| 43 |
-
|
| 44 |
-
CMD ["
|
|
|
|
| 1 |
+
# ── Builder ───────────────────────────────────────────────────────────────────
|
| 2 |
+
FROM python:3.13-alpine AS builder
|
| 3 |
+
|
| 4 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 5 |
+
PYTHONUNBUFFERED=1 \
|
| 6 |
+
UV_PROJECT_ENVIRONMENT=/opt/venv
|
| 7 |
+
|
| 8 |
+
ENV PATH="$UV_PROJECT_ENVIRONMENT/bin:$PATH"
|
| 9 |
+
|
| 10 |
+
# Rust/Cargo are required to compile curl-cffi wheels on musl/Alpine.
|
| 11 |
+
# If upstream ever ships musl wheels, remove cargo + rust to speed up builds.
|
| 12 |
+
RUN apk add --no-cache \
|
| 13 |
+
ca-certificates \
|
| 14 |
+
build-base \
|
| 15 |
+
linux-headers \
|
| 16 |
+
libffi-dev \
|
| 17 |
+
openssl-dev \
|
| 18 |
+
curl-dev \
|
| 19 |
+
cargo \
|
| 20 |
+
rust
|
| 21 |
+
|
| 22 |
+
WORKDIR /app
|
| 23 |
+
|
| 24 |
+
# Pin uv to a minor version for reproducible builds.
|
| 25 |
+
# Bump manually when you want to pick up a newer uv release.
|
| 26 |
+
COPY --from=ghcr.io/astral-sh/uv:0.6 /uv /uvx /bin/
|
| 27 |
+
|
| 28 |
+
COPY pyproject.toml uv.lock ./
|
| 29 |
+
|
| 30 |
+
RUN uv sync --frozen --no-dev --no-install-project \
|
| 31 |
+
&& find /opt/venv -type d \
|
| 32 |
+
\( -name "__pycache__" -o -name "tests" -o -name "test" -o -name "testing" \) \
|
| 33 |
+
-prune -exec rm -rf {} + \
|
| 34 |
+
&& find /opt/venv -type f -name "*.pyc" -delete \
|
| 35 |
+
&& find /opt/venv -type f -name "*.so" -exec strip --strip-unneeded {} + 2>/dev/null; true \
|
| 36 |
+
&& rm -rf /root/.cache /tmp/uv-cache
|
| 37 |
+
|
| 38 |
+
# ── Runtime ───────────────────────────────────────────────────────────────────
|
| 39 |
+
FROM python:3.13-alpine
|
| 40 |
+
|
| 41 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 42 |
+
PYTHONUNBUFFERED=1 \
|
| 43 |
+
TZ=Asia/Shanghai \
|
| 44 |
+
VIRTUAL_ENV=/opt/venv \
|
| 45 |
+
SERVER_HOST=0.0.0.0 \
|
| 46 |
+
SERVER_PORT=8000 \
|
| 47 |
+
SERVER_WORKERS=1
|
| 48 |
+
|
| 49 |
+
ENV PATH="$VIRTUAL_ENV/bin:$PATH"
|
| 50 |
+
|
| 51 |
+
RUN apk add --no-cache \
|
| 52 |
+
tzdata \
|
| 53 |
ca-certificates \
|
| 54 |
+
libffi \
|
| 55 |
+
openssl \
|
| 56 |
+
libgcc \
|
| 57 |
+
libstdc++ \
|
| 58 |
+
libcurl
|
| 59 |
+
|
| 60 |
+
WORKDIR /app
|
| 61 |
+
|
| 62 |
+
COPY --from=builder /opt/venv /opt/venv
|
| 63 |
|
| 64 |
+
COPY pyproject.toml config.defaults.toml ./
|
| 65 |
+
COPY app ./app
|
| 66 |
+
COPY scripts ./scripts
|
| 67 |
|
| 68 |
+
RUN mkdir -p /app/data /app/logs \
|
| 69 |
+
&& chmod +x /app/scripts/entrypoint.sh /app/scripts/init_storage.sh
|
| 70 |
|
| 71 |
+
EXPOSE 8000
|
|
|
|
| 72 |
|
| 73 |
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
|
| 74 |
+
CMD ["sh", "-c", "wget -qO /dev/null http://127.0.0.1:${SERVER_PORT}/health || exit 1"]
|
| 75 |
|
| 76 |
+
ENTRYPOINT ["/app/scripts/entrypoint.sh"]
|
| 77 |
+
CMD ["sh", "-c", "exec granian --interface asgi --host ${SERVER_HOST} --port ${SERVER_PORT} --workers ${SERVER_WORKERS} app.main:app"]
|
Dockerfile.privoxy
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM alpine:latest
|
| 2 |
+
|
| 3 |
+
RUN apk add --no-cache privoxy && \
|
| 4 |
+
echo "listen-address 0.0.0.0:8118" >> /etc/privoxy/config && \
|
| 5 |
+
echo "forward-socks5 / warp-proxy:1080 ." >> /etc/privoxy/config
|
| 6 |
+
|
| 7 |
+
EXPOSE 8118
|
| 8 |
+
|
| 9 |
+
CMD ["privoxy", "--no-daemon", "--user", "privoxy", "/etc/privoxy/config"]
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Chenyme
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19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 5 |
+
<h1>Grok Web 能力的 OpenAI 兼容网关</h1>
|
| 6 |
+
|
| 7 |
+
<h3>多账号池、智能选号、自动维护</h3>
|
| 8 |
+
|
| 9 |
+
<p>
|
| 10 |
+
将 grok.com 与 console.x.ai 的聊天、图像、视频能力,<br>
|
| 11 |
+
以 <strong>OpenAI / Anthropic 兼容 API</strong> 统一对外提供。
|
| 12 |
+
</p>
|
| 13 |
+
|
| 14 |
+
<p>
|
| 15 |
+
<a href="https://www.python.org/"><img alt="Python" src="https://img.shields.io/badge/python-3.13%2B-3776AB?logo=python&logoColor=white"></a>
|
| 16 |
+
<a href="https://fastapi.tiangolo.com/"><img alt="FastAPI" src="https://img.shields.io/badge/FastAPI-0.119%2B-009688?logo=fastapi&logoColor=white"></a>
|
| 17 |
+
<a href="https://github.com/jiujiu532/grok2api/pkgs/container/grok2api"><img alt="Docker" src="https://img.shields.io/badge/ghcr.io-jiujiu532%2Fgrok2api-2496ED?logo=docker&logoColor=white"></a>
|
| 18 |
+
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-MIT-16a34a"></a>
|
| 19 |
+
</p>
|
| 20 |
+
|
| 21 |
+
<p>
|
| 22 |
+
<a href="#核心特性">核心特性</a> ·
|
| 23 |
+
<a href="#部署指南">部署指南</a> ·
|
| 24 |
+
<a href="#模型列表">模型列表</a> ·
|
| 25 |
+
<a href="#账号配置">账号配置</a> ·
|
| 26 |
+
<a href="#api-端点">API 端点</a> ·
|
| 27 |
+
<a href="#常见问题">常见问题</a>
|
| 28 |
+
</p>
|
| 29 |
+
|
| 30 |
+
</div>
|
| 31 |
+
|
| 32 |
+
> [!NOTE]
|
| 33 |
+
> 本项目仅供学习与研究交流。请务必遵守 Grok 的使用条款及当地法律法规,不得用于非法用途。
|
| 34 |
+
|
| 35 |
+
本仓库基于上游 [chenyme/grok2api](https://github.com/chenyme/grok2api) 二次开发,新增多账号池管理、Console 免费模型、配额轮换、防封部署等能力。欢迎 PR 和 Fork,二开请保留原作者与前端标识。
|
| 36 |
+
|
| 37 |
+
---
|
| 38 |
+
|
| 39 |
+
## 核心特性
|
| 40 |
+
|
| 41 |
+
| 能力 | 说明 |
|
| 42 |
+
| :-- | :-- |
|
| 43 |
+
| OpenAI 兼容 | `/v1/chat/completions`、`/v1/responses`、`/v1/images/generations`、`/v1/videos` |
|
| 44 |
+
| Anthropic 兼容 | `/v1/messages`(Claude SDK 直接对接) |
|
| 45 |
+
| 多账号池 | basic / super / heavy 三级池,自动负载均衡与配额同步 |
|
| 46 |
+
| 免费账号 | 支持 `console.x.ai` SSO Token,`*-console` 模型零成本使用 |
|
| 47 |
+
| 媒体生成 | 文生图、图像编辑、文生视频、图生视频,本地缓存与代理链接 |
|
| 48 |
+
| 防封内置 | `x-statsig-id` 兼容修复,WARP + FlareSolverr 一键部署 |
|
| 49 |
+
| 管理后台 | Admin 配置、账号管理、Web Chat、Masonry 画廊、ChatKit 语音 |
|
| 50 |
+
|
| 51 |
+
---
|
| 52 |
+
|
| 53 |
+
## 部署指南
|
| 54 |
+
|
| 55 |
+
本项目提供两种部署方式:
|
| 56 |
+
|
| 57 |
+
| 方式 | 说明 | 适用场景 |
|
| 58 |
+
| :-- | :-- | :-- |
|
| 59 |
+
| **标准版** | 仅 grok2api,直连 Grok | IP 干净、无 Cloudflare 拦截 |
|
| 60 |
+
| **防封版** | grok2api + WARP + Privoxy + FlareSolverr | IP 被 Cloudflare 拦截、需要稳定访问 |
|
| 61 |
+
|
| 62 |
+
> [!TIP]
|
| 63 |
+
> 当前版本已内置 403 兼容修复,标准版可直接验证。仍遇 403 时再切防封版。
|
| 64 |
+
|
| 65 |
+
---
|
| 66 |
+
|
| 67 |
+
### 标准版部署
|
| 68 |
+
|
| 69 |
+
**Docker Compose(推荐):**
|
| 70 |
+
|
| 71 |
+
```bash
|
| 72 |
+
git clone https://github.com/jiujiu532/grok2api
|
| 73 |
+
cd grok2api/grok2api-main/grok2api-main
|
| 74 |
+
cp .env.example .env
|
| 75 |
+
docker compose up -d
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
查看日志:
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
docker compose logs -f grok2api
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
**Docker 单容器:**
|
| 85 |
+
|
| 86 |
+
```bash
|
| 87 |
+
docker run -d --name grok2api \
|
| 88 |
+
-p 8000:8000 \
|
| 89 |
+
-e TZ=Asia/Shanghai \
|
| 90 |
+
-e LOG_LEVEL=INFO \
|
| 91 |
+
-e ACCOUNT_STORAGE=local \
|
| 92 |
+
-v $(pwd)/data:/app/data \
|
| 93 |
+
-v $(pwd)/logs:/app/logs \
|
| 94 |
+
--restart unless-stopped \
|
| 95 |
+
ghcr.io/jiujiu532/grok2api:latest
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
Windows PowerShell:
|
| 99 |
+
|
| 100 |
+
```powershell
|
| 101 |
+
docker run -d `
|
| 102 |
+
--name grok2api `
|
| 103 |
+
-p 8000:8000 `
|
| 104 |
+
-e TZ=Asia/Shanghai `
|
| 105 |
+
-e LOG_LEVEL=INFO `
|
| 106 |
+
-e ACCOUNT_STORAGE=local `
|
| 107 |
+
-v ${PWD}/data:/app/data `
|
| 108 |
+
-v ${PWD}/logs:/app/logs `
|
| 109 |
+
--restart unless-stopped `
|
| 110 |
+
ghcr.io/jiujiu532/grok2api:latest
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
---
|
| 114 |
+
|
| 115 |
+
### 防封版部署
|
| 116 |
+
|
| 117 |
+
> **前置要求**:服务器需支持 `NET_ADMIN` + `SYS_MODULE` 权限(KVM/XEN 虚拟化均支持,OpenVZ/LXC 不支持)。
|
| 118 |
+
|
| 119 |
+
```bash
|
| 120 |
+
git clone https://github.com/jiujiu532/grok2api
|
| 121 |
+
cd grok2api/grok2api-main/grok2api-main
|
| 122 |
+
docker compose -f docker-compose.warp.yml up -d
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
防封版自动启动以下服务:
|
| 126 |
+
|
| 127 |
+
| 服务 | 说明 |
|
| 128 |
+
| :-- | :-- |
|
| 129 |
+
| `warp-proxy` | Cloudflare WARP 出口代理,提供干净 IP |
|
| 130 |
+
| `privoxy` | HTTP 代理,将流量转发到 WARP |
|
| 131 |
+
| `flaresolverr` | 自动解 Cloudflare 挑战,获取 cf_clearance |
|
| 132 |
+
| `init-config` | 初始化容器,自动写入代理配置 |
|
| 133 |
+
| `grok2api` | 主服务 |
|
| 134 |
+
|
| 135 |
+
启动后代理配置已自动完成,进入 Admin 后台添加账号即可使用。
|
| 136 |
+
|
| 137 |
---
|
| 138 |
+
|
| 139 |
+
<details>
|
| 140 |
+
<summary><strong>升级 / 回滚 / 卸载 / 迁移</strong></summary>
|
| 141 |
+
|
| 142 |
+
### 升级
|
| 143 |
+
|
| 144 |
+
无论标准版还是防封版,升级时只需更新 `grok2api` 主镜像,防封组件不需要更新。
|
| 145 |
+
|
| 146 |
+
**标准版升级:**
|
| 147 |
+
|
| 148 |
+
```bash
|
| 149 |
+
docker pull ghcr.io/jiujiu532/grok2api:latest
|
| 150 |
+
docker compose up -d --no-deps grok2api
|
| 151 |
+
```
|
| 152 |
+
|
| 153 |
+
**防封版升级(只更新主服务,不动 WARP/FlareSolverr):**
|
| 154 |
+
|
| 155 |
+
```bash
|
| 156 |
+
docker pull ghcr.io/jiujiu532/grok2api:latest
|
| 157 |
+
docker compose -f docker-compose.warp.yml up -d --no-deps grok2api
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
> `--no-deps` 确保只重启 grok2api,WARP/Privoxy/FlareSolverr 继续运行不中断。
|
| 161 |
+
>
|
| 162 |
+
> `./data/` 中的配置(`config.toml`)和数据库(`accounts.db`)挂载在 volume 中,升级不会覆盖。
|
| 163 |
+
|
| 164 |
+
### 回滚
|
| 165 |
+
|
| 166 |
+
```bash
|
| 167 |
+
# 查看可用版本:https://github.com/jiujiu532/grok2api/pkgs/container/grok2api
|
| 168 |
+
docker pull ghcr.io/jiujiu532/grok2api:<tag>
|
| 169 |
+
|
| 170 |
+
# 标准版回滚
|
| 171 |
+
docker compose up -d --no-deps grok2api
|
| 172 |
+
|
| 173 |
+
# 防封版回滚
|
| 174 |
+
docker compose -f docker-compose.warp.yml up -d --no-deps grok2api
|
| 175 |
+
```
|
| 176 |
+
|
| 177 |
+
### 卸载
|
| 178 |
+
|
| 179 |
+
**标准版卸载:**
|
| 180 |
+
|
| 181 |
+
```bash
|
| 182 |
+
cd grok2api/grok2api-main/grok2api-main
|
| 183 |
+
docker compose down
|
| 184 |
+
# 如需删除数据(不可恢复):
|
| 185 |
+
rm -rf ./data ./logs
|
| 186 |
+
```
|
| 187 |
+
|
| 188 |
+
**防封版卸载:**
|
| 189 |
+
|
| 190 |
+
```bash
|
| 191 |
+
cd grok2api/grok2api-main/grok2api-main
|
| 192 |
+
docker compose -f docker-compose.warp.yml down
|
| 193 |
+
# 如需删除数据(不可恢复):
|
| 194 |
+
rm -rf ./data ./logs
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
### 从标准版迁移到防封版
|
| 198 |
+
|
| 199 |
+
数据完全保留,无需重新配置:
|
| 200 |
+
|
| 201 |
+
```bash
|
| 202 |
+
# 停止标准版
|
| 203 |
+
docker compose down
|
| 204 |
+
|
| 205 |
+
# 用防封版启动(自动检测已有配置,不覆盖)
|
| 206 |
+
docker compose -f docker-compose.warp.yml up -d
|
| 207 |
+
```
|
| 208 |
+
|
| 209 |
+
</details>
|
| 210 |
+
|
| 211 |
---
|
| 212 |
|
| 213 |
+
### 本地源码部署
|
| 214 |
+
|
| 215 |
+
前置:Python 3.13+、[uv](https://docs.astral.sh/uv/getting-started/installation/)
|
| 216 |
+
|
| 217 |
+
```bash
|
| 218 |
+
git clone https://github.com/jiujiu532/grok2api
|
| 219 |
+
cd grok2api/grok2api-main/grok2api-main
|
| 220 |
+
cp .env.example .env && uv sync
|
| 221 |
+
uv run granian --interface asgi --host 0.0.0.0 --port 8000 --workers 1 app.main:app
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
---
|
| 225 |
+
|
| 226 |
+
### 首次启动
|
| 227 |
+
|
| 228 |
+
访问 `http://localhost:8000/admin/login`,默认密码 `grok2api`,进入后设置:
|
| 229 |
+
|
| 230 |
+
1. `app.app_key` — Admin 密码
|
| 231 |
+
2. `app.api_key` — API 鉴权密钥(留空不鉴权)
|
| 232 |
+
3. `app.app_url` — 公网地址(图片/视频链接需要)
|
| 233 |
+
|
| 234 |
+
> 配置保存即时生效,无需重启。
|
| 235 |
+
|
| 236 |
+
---
|
| 237 |
+
|
| 238 |
+
## 模型列表
|
| 239 |
+
|
| 240 |
+
### Chat( grok.com)
|
| 241 |
+
|
| 242 |
+
basic表示free账号,spuer和heavy 为付费
|
| 243 |
+
|
| 244 |
+
| 模型名 | mode | 账号等级 | 备注 |
|
| 245 |
+
| :-- | :-- | :-- | :-- |
|
| 246 |
+
| `grok-4.20-fast` / `grok-4.3-fast` | fast | basic(优先高等级) |
|
| 247 |
+
| `grok-4.20-auto` | auto | super |
|
| 248 |
+
| `grok-4.20-expert` | expert | super |
|
| 249 |
+
| `grok-4.20-heavy` | heavy | heavy | |
|
| 250 |
+
| `grok-4.3-beta` | grok-420-computer-use-sa | super |
|
| 251 |
+
| `grok-4.20-multi-agent-0309` | heavy | heavy |
|
| 252 |
+
| `grok-4.20-0309-non-reasoning` | fast | basic |
|
| 253 |
+
| `grok-4.20-0309` | auto | super |
|
| 254 |
+
| `grok-4.20-0309-reasoning` | expert | super |
|
| 255 |
+
| `grok-4.20-0309-non-reasoning-super` | fast | super |
|
| 256 |
+
| `grok-4.20-0309-super` | auto | super |
|
| 257 |
+
| `grok-4.20-0309-reasoning-super` | expert | super |
|
| 258 |
+
| `grok-4.20-0309-non-reasoning-heavy` | fast | heavy |
|
| 259 |
+
| `grok-4.20-0309-heavy` | auto | heavy |
|
| 260 |
+
| `grok-4.20-0309-reasoning-heavy` | expert | heavy |
|
| 261 |
+
|
| 262 |
+
### Chat( console.x.ai)
|
| 263 |
+
|
| 264 |
+
通过 SSO Token 免费访问,不消耗付费额度。所有免费模型使用 **basic** 等级账号。
|
| 265 |
+
|
| 266 |
+
| 模型名 | reasoning effort | 账号等级 |
|
| 267 |
+
| :-- | :-- | :-- |
|
| 268 |
+
| `grok-4.3-console` | 用户传入(默认 medium) | basic |
|
| 269 |
+
| `grok-4.3-low` | low(固定) | basic |
|
| 270 |
+
| `grok-4.3-medium` | medium(固定) | basic |
|
| 271 |
+
| `grok-4.3-high` | high(固定) | basic |
|
| 272 |
+
| `grok-4.20-0309-console` | 默认 | basic |
|
| 273 |
+
| `grok-4.20-0309-reasoning-console` | 固定 reasoning | basic |
|
| 274 |
+
| `grok-4.20-0309-non-reasoning-console` | 无 reasoning | basic |
|
| 275 |
+
| `grok-4.20-multi-agent-console` | 用户传入(默认 medium) | basic|
|
| 276 |
+
| `grok-4.20-multi-agent-low` | low(固定)→ 4 agents | basic|
|
| 277 |
+
| `grok-4.20-multi-agent-medium` | medium(固定)→ 4 agents | basic|
|
| 278 |
+
| `grok-4.20-multi-agent-high` | high(固定)→ 16 agents | basic |
|
| 279 |
+
| `grok-4.20-multi-agent-xhigh` | xhigh(固定)→ 16 agents | basic|
|
| 280 |
+
| `grok-build-console` | 默认 | basic |
|
| 281 |
+
|
| 282 |
+
**Console 配额**:30 次 / 15 分钟窗口,采用延迟恢复轮换策略(消耗至剩余 15 次时启动计时器,评分机制自动轮换到其他账号)。后台每 30 秒巡检并自动重置过期配额。
|
| 283 |
+
|
| 284 |
+
### Image / Video( grok.com)
|
| 285 |
+
|
| 286 |
+
| 模型名 | 能力 | 账号等级 |
|
| 287 |
+
| :-- | :-- | :-- |
|
| 288 |
+
| `grok-imagine-image-lite` | 文生图 | basic |
|
| 289 |
+
| `grok-imagine-image` / `image-pro` | 文生图 | super |
|
| 290 |
+
| `grok-imagine-image-edit` | 图像编辑 | super |
|
| 291 |
+
| `grok-imagine-video` | 文生视频 | super |
|
| 292 |
+
|
| 293 |
+
---
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
## 账号配置
|
| 298 |
+
|
| 299 |
+
| 类型 | 等级 | 适用模型 |
|
| 300 |
+
| :-- | :-- | :-- |
|
| 301 |
+
| 付费账号(x.ai 官方) | super / heavy | `grok-4.20-*`、`grok-4.3-beta`、`grok-4.3-fast` |
|
| 302 |
+
| 免费账号(console.x.ai SSO) | basic | 所有 `*-console` / `*-low` / `*-medium` / `*-high` / `*-xhigh` |
|
| 303 |
+
|
| 304 |
+
**免费账号获取方式**:
|
| 305 |
+
|
| 306 |
+
1. 浏览器 F12 打开开发者工具
|
| 307 |
+
2. 访问 `https://console.x.ai/`
|
| 308 |
+
3. Network 面板找任意请求,Cookie 中复制 `sso` 值
|
| 309 |
+
4. Admin 后台 → 账号管理 → 添加账号,粘贴 token
|
| 310 |
+
|
| 311 |
+
> SSO Token 属于敏感凭证,请勿写入代码或提交到版本库。
|
| 312 |
+
|
| 313 |
+
---
|
| 314 |
+
|
| 315 |
+
## API 端点
|
| 316 |
+
|
| 317 |
+
| 端点 | 说明 |
|
| 318 |
+
| :-- | :-- |
|
| 319 |
+
| `GET /v1/models` | 列出可用模型 |
|
| 320 |
+
| `POST /v1/chat/completions` | 聊天 / 图像 / 视频统一入口 |
|
| 321 |
+
| `POST /v1/responses` | OpenAI Responses API |
|
| 322 |
+
| `POST /v1/messages` | Anthropic Messages API |
|
| 323 |
+
| `POST /v1/images/generations` | 图像生成 |
|
| 324 |
+
| `POST /v1/images/edits` | 图像编辑 |
|
| 325 |
+
| `POST /v1/videos` | 异步视频任务 |
|
| 326 |
+
| `GET /v1/videos/{id}` / `{id}/content` | 查询 / 下载视频 |
|
| 327 |
+
|
| 328 |
+
---
|
| 329 |
+
|
| 330 |
+
## 环境变量
|
| 331 |
+
|
| 332 |
+
| 变量名 | 说明 | 默认值 |
|
| 333 |
+
| :-- | :-- | :-- |
|
| 334 |
+
| `TZ` | 时区 | `Asia/Shanghai` |
|
| 335 |
+
| `LOG_LEVEL` | 日志级别 | `INFO` |
|
| 336 |
+
| `LOG_FILE_ENABLED` | 写入本地文件日志 | `true` |
|
| 337 |
+
| `SERVER_HOST` | 监听地址 | `0.0.0.0` |
|
| 338 |
+
| `SERVER_PORT` | 监听端口 | `8000` |
|
| 339 |
+
| `SERVER_WORKERS` | Granian worker 数量 | `1` |
|
| 340 |
+
| `HOST_PORT` | Compose 宿主机映射端口 | `8000` |
|
| 341 |
+
| `DATA_DIR` | 本地数据根目录 | `./data` |
|
| 342 |
+
| `LOG_DIR` | 本地日志目录 | `./logs` |
|
| 343 |
+
| `ACCOUNT_STORAGE` | 存储后端:`local` / `redis` / `mysql` / `postgresql` | `local` |
|
| 344 |
+
| `ACCOUNT_SYNC_INTERVAL` | 增量同步间隔(秒) | `30` |
|
| 345 |
+
| `ACCOUNT_SYNC_ACTIVE_INTERVAL` | 活跃同步间隔(秒) | `3` |
|
| 346 |
+
| `ACCOUNT_LOCAL_PATH` | SQLite 路径 | `${DATA_DIR}/accounts.db` |
|
| 347 |
+
| `ACCOUNT_REDIS_URL` | Redis DSN | `""` |
|
| 348 |
+
| `ACCOUNT_MYSQL_URL` | MySQL DSN | `""` |
|
| 349 |
+
| `ACCOUNT_POSTGRESQL_URL` | PostgreSQL DSN | `""` |
|
| 350 |
+
| `ACCOUNT_SQL_POOL_SIZE` | 连接池核心连接数 | `5` |
|
| 351 |
+
| `ACCOUNT_SQL_MAX_OVERFLOW` | 连接池最大溢出 | `10` |
|
| 352 |
+
| `ACCOUNT_SQL_POOL_TIMEOUT` | 等待空闲连接超时(秒) | `30` |
|
| 353 |
+
| `ACCOUNT_SQL_POOL_RECYCLE` | 连接最大复用时间(秒) | `1800` |
|
| 354 |
+
|
| 355 |
+
运行时配置支持 `GROK_` 前缀覆盖,如 `GROK_APP_API_KEY` 覆盖 `app.api_key`。
|
| 356 |
+
|
| 357 |
+
---
|
| 358 |
+
|
| 359 |
+
## 调用示例
|
| 360 |
+
|
| 361 |
+
```bash
|
| 362 |
+
# 付费账号对话
|
| 363 |
+
curl http://localhost:8000/v1/chat/completions \
|
| 364 |
+
-H "Authorization: Bearer $API_KEY" \
|
| 365 |
+
-H "Content-Type: application/json" \
|
| 366 |
+
-d '{"model":"grok-4.20-auto","stream":true,"messages":[{"role":"user","content":"你好"}]}'
|
| 367 |
+
|
| 368 |
+
# 免费账号对话
|
| 369 |
+
curl http://localhost:8000/v1/chat/completions \
|
| 370 |
+
-H "Authorization: Bearer $API_KEY" \
|
| 371 |
+
-H "Content-Type: application/json" \
|
| 372 |
+
-d '{"model":"grok-4.3-console","stream":true,"messages":[{"role":"user","content":"你好"}]}'
|
| 373 |
+
```
|
| 374 |
+
|
| 375 |
+
---
|
| 376 |
+
|
| 377 |
+
## 常见问题
|
| 378 |
+
|
| 379 |
+
| 问题 | 解决方案 |
|
| 380 |
+
| :-- | :-- |
|
| 381 |
+
| Admin 打不开 | 确认端口映射和防火墙:`docker compose ps` |
|
| 382 |
+
| 图片/视频链接 403 | 设置 `app.app_url` 为公网地址(含 `https://`) |
|
| 383 |
+
| Cloudflare 拦截 | 更换代理,或者切换防封版部署,再或者手动配置 `proxy.clearance.mode` |
|
| 384 |
+
| 多 Worker 冲突 | 无冲突,调度器通过文件锁选举 leader |
|
| 385 |
+
|
| 386 |
+
---
|
| 387 |
+
|
| 388 |
+
## 更新日志
|
| 389 |
+
|
| 390 |
+
### v0.1.7
|
| 391 |
+
|
| 392 |
+
**新功能**
|
| 393 |
+
|
| 394 |
+
- 🔌 **Console 原生工具调用支持**([PR#24](https://github.com/jiujiu532/grok2api/pull/24),感谢 @daoguademeng)
|
| 395 |
+
- Console 模型支持 OpenAI 兼容的 `tools` / `tool_choice` 参数
|
| 396 |
+
- 客户端 function tools(如 bash、read)可稳定产出 `tool_calls`
|
| 397 |
+
- Grok 内置工具(web_search、x_search 等 19 个)保持内部语义,不泄露为客户端 tool_calls
|
| 398 |
+
- 支持多轮 tool-call 上下文(assistant tool_calls + tool result 正确转换)
|
| 399 |
+
- 新增 738 行回归测试覆盖核心逻辑
|
| 400 |
+
|
| 401 |
+
**优化**
|
| 402 |
+
|
| 403 |
+
- 🔧 **Console 配额参数调整**:恢复周期从 15 分钟改为 30 分钟,轮换阈值从 15 改为 20,降低单号负载
|
| 404 |
+
- 💓 **SSE 心跳保活**:所有流式接口在数据开始前发送心跳注释,防止思考期间连接超时
|
| 405 |
+
- ⚡ **TXT 导入异步化**:大批量导入不再阻塞,接口立即返回,刷新在后台进行
|
| 406 |
+
- 🔒 **依赖安全升级**:cryptography 48.0.1+、starlette 1.1.0+、python-multipart 0.0.31+
|
| 407 |
+
|
| 408 |
+
**修复**
|
| 409 |
+
|
| 410 |
+
- 🐛 修复 NSFW 初始化时生日已锁定的 429 报错([PR#25](https://github.com/jiujiu532/grok2api/pull/25),感谢 @Xaihi-nun)
|
| 411 |
+
- 🐛 修复批量刷新结果未区分异常与临时失败的问题
|
| 412 |
+
|
| 413 |
+
### v0.1.5 (2025-06-13)
|
| 414 |
+
|
| 415 |
+
**优化**
|
| 416 |
+
|
| 417 |
+
- 🔧 **批量刷新结果优化**:刷新账户时区分"凭证失效(异常)"和"临时失败(网络波动)"两种状态
|
| 418 |
+
- 前端提示更清晰:`刷新完成:成功 906,异常 40,临时失败 54`
|
| 419 |
+
- 后端性能优化:批量查询失败账户状态(从 N 次数据库查询降为 1 次)
|
| 420 |
+
- 异常账户自动进入"异常"筛选组,临时失败不影响账户状态
|
| 421 |
+
|
| 422 |
+
- 🎯 **导入账户交互改进**(基于 [PR#13](https://github.com/jiujiu532/grok2api/pull/13))
|
| 423 |
+
- 新增/导入弹窗中加入"导入后自动开启 NSFW"复选框(默认不勾选)
|
| 424 |
+
- 工具栏按钮互斥显示:勾选账号时显示批量操作按钮,未勾选显示全局按钮
|
| 425 |
+
- 去除全局配置 `account.auto_nsfw_on_import`,改为每次导入时手动选择
|
| 426 |
+
|
| 427 |
+
- ⚙️ **并发数限制调整**
|
| 428 |
+
- 批量操作硬限制从 50 调整为 80
|
| 429 |
+
- 配置页并发数输入框添加 `min: 1, max: 80` 强制限制
|
| 430 |
+
- 防止用户输入���出范围的并发值导致后端压力过大
|
| 431 |
+
|
| 432 |
+
**修复**
|
| 433 |
+
|
| 434 |
+
- 🐛 修复配置页数字输入框 `min/max` 属性未生效的问题
|
| 435 |
+
- 🐛 补充 `tokens.py` 缺失的 `Query` 导入(导致服务启动失败)
|
| 436 |
+
- 🐛 补充翻译文件中缺失的 `autoNsfwOnImport` 和 `autoNsfwHint` 键
|
| 437 |
+
|
| 438 |
+
---
|
| 439 |
+
|
| 440 |
+
## 致谢
|
| 441 |
+
|
| 442 |
+
- 上游:[chenyme/grok2api](https://github.com/chenyme/grok2api)
|
| 443 |
+
- DeepWiki:[chenyme/grok2api](https://deepwiki.com/chenyme/grok2api)
|
| 444 |
+
- 项目文档:[blog.cheny.me](https://blog.cheny.me/blog/posts/grok2api)
|
| 445 |
+
- 社区:[Linux.do](https://linux.do)
|
| 446 |
+
|
| 447 |
+
---
|
| 448 |
+
|
| 449 |
+
## Star History
|
| 450 |
+
|
| 451 |
+
[](https://star-history.com/#jiujiu532/grok2api&Date)
|
| 452 |
+
|
| 453 |
+
---
|
| 454 |
+
|
| 455 |
+
<div align="center">
|
| 456 |
+
|
| 457 |
+
**MIT License**
|
| 458 |
+
|
| 459 |
+
</div>
|
app/__init__.py
ADDED
|
File without changes
|
app/control/__init__.py
ADDED
|
File without changes
|
app/control/account/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Account control-plane domain — public exports."""
|
| 2 |
+
|
| 3 |
+
from .enums import AccountStatus, FeedbackKind, QuotaSource
|
| 4 |
+
from .models import (
|
| 5 |
+
AccountChangeSet,
|
| 6 |
+
AccountMutationResult,
|
| 7 |
+
AccountPage,
|
| 8 |
+
AccountQuotaSet,
|
| 9 |
+
AccountRecord,
|
| 10 |
+
AccountUsageStats,
|
| 11 |
+
QuotaWindow,
|
| 12 |
+
RuntimeSnapshot,
|
| 13 |
+
)
|
| 14 |
+
from .commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery
|
| 15 |
+
from .repository import AccountRepository
|
| 16 |
+
from .state_machine import AccountFeedback, StatePolicy, apply_feedback, clear_failures, derive_status, is_selectable, is_manageable
|
| 17 |
+
from .quota_defaults import BASIC_QUOTA_DEFAULTS, SUPER_QUOTA_DEFAULTS, default_quota_set
|
| 18 |
+
from .refresh import AccountRefreshService, RefreshResult
|
| 19 |
+
from .runtime import get_refresh_service, set_refresh_service
|
| 20 |
+
from .scheduler import AccountRefreshScheduler, get_account_refresh_scheduler
|
| 21 |
+
from .backends.factory import create_repository
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
"AccountStatus", "FeedbackKind", "QuotaSource",
|
| 25 |
+
"QuotaWindow", "AccountQuotaSet", "AccountUsageStats",
|
| 26 |
+
"AccountRecord", "AccountMutationResult", "AccountPage",
|
| 27 |
+
"AccountChangeSet", "RuntimeSnapshot",
|
| 28 |
+
"AccountUpsert", "AccountPatch", "ListAccountsQuery", "BulkReplacePoolCommand",
|
| 29 |
+
"AccountRepository",
|
| 30 |
+
"AccountFeedback", "StatePolicy", "apply_feedback", "clear_failures",
|
| 31 |
+
"derive_status", "is_selectable", "is_manageable",
|
| 32 |
+
"BASIC_QUOTA_DEFAULTS", "SUPER_QUOTA_DEFAULTS", "default_quota_set",
|
| 33 |
+
"AccountRefreshService", "RefreshResult",
|
| 34 |
+
"get_refresh_service", "set_refresh_service",
|
| 35 |
+
"AccountRefreshScheduler", "get_account_refresh_scheduler",
|
| 36 |
+
"create_repository",
|
| 37 |
+
]
|
app/control/account/backends/__init__.py
ADDED
|
File without changes
|
app/control/account/backends/factory.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Account repository factory — selects the backend from startup env."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any
|
| 6 |
+
from urllib.parse import urlsplit, urlunsplit
|
| 7 |
+
|
| 8 |
+
from app.platform.paths import data_path
|
| 9 |
+
from ..repository import AccountRepository
|
| 10 |
+
|
| 11 |
+
_SUPPORTED_BACKENDS = {"local", "redis", "mysql", "postgresql"}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def create_repository() -> AccountRepository:
|
| 15 |
+
"""Instantiate the configured account storage backend.
|
| 16 |
+
|
| 17 |
+
Startup env: ``ACCOUNT_STORAGE`` (default: ``"local"``)
|
| 18 |
+
|
| 19 |
+
Supported values:
|
| 20 |
+
``local`` — SQLite (default, single-process)
|
| 21 |
+
``redis`` — Redis hash + sorted-set layout
|
| 22 |
+
``mysql`` — MySQL via aiomysql / SQLAlchemy
|
| 23 |
+
``postgresql`` — PostgreSQL via asyncpg / SQLAlchemy
|
| 24 |
+
"""
|
| 25 |
+
backend = get_repository_backend()
|
| 26 |
+
|
| 27 |
+
if backend == "local":
|
| 28 |
+
return _make_local()
|
| 29 |
+
if backend == "redis":
|
| 30 |
+
return _make_redis()
|
| 31 |
+
if backend == "mysql":
|
| 32 |
+
return _make_sql("mysql")
|
| 33 |
+
if backend == "postgresql":
|
| 34 |
+
return _make_sql("postgresql")
|
| 35 |
+
|
| 36 |
+
raise ValueError(f"Unknown account storage backend: {backend!r}")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def describe_repository_target() -> tuple[str, str]:
|
| 40 |
+
"""Return current storage backend and a log-safe target description."""
|
| 41 |
+
backend = get_repository_backend()
|
| 42 |
+
|
| 43 |
+
if backend == "local":
|
| 44 |
+
return "local", str(_resolve_local_db_path())
|
| 45 |
+
if backend == "redis":
|
| 46 |
+
return "redis", _redact_url(_get_required_env("ACCOUNT_REDIS_URL"))
|
| 47 |
+
if backend == "mysql":
|
| 48 |
+
return "mysql", _redact_url(_get_env("ACCOUNT_MYSQL_URL"))
|
| 49 |
+
if backend == "postgresql":
|
| 50 |
+
return "postgresql", _redact_url(_get_env("ACCOUNT_POSTGRESQL_URL"))
|
| 51 |
+
return backend, "<unknown>"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# ---------------------------------------------------------------------------
|
| 55 |
+
# Backend constructors
|
| 56 |
+
# ---------------------------------------------------------------------------
|
| 57 |
+
|
| 58 |
+
def get_repository_backend() -> str:
|
| 59 |
+
"""Return the configured account storage backend from startup env."""
|
| 60 |
+
backend = _get_env("ACCOUNT_STORAGE", "local").lower()
|
| 61 |
+
if backend not in _SUPPORTED_BACKENDS:
|
| 62 |
+
raise ValueError(f"Unknown account storage backend: {backend!r}")
|
| 63 |
+
return backend
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _get_env(name: str, default: str = "") -> str:
|
| 67 |
+
value = os.getenv(name)
|
| 68 |
+
if value is None:
|
| 69 |
+
return default
|
| 70 |
+
value = value.strip()
|
| 71 |
+
return value or default
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _get_required_env(name: str) -> str:
|
| 75 |
+
value = _get_env(name)
|
| 76 |
+
if not value:
|
| 77 |
+
raise ValueError(f"Missing required env: {name}")
|
| 78 |
+
return value
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _resolve_local_db_path() -> Path:
|
| 82 |
+
path_str = _get_env("ACCOUNT_LOCAL_PATH", str(data_path("accounts.db")))
|
| 83 |
+
db_path = Path(path_str)
|
| 84 |
+
if not db_path.is_absolute():
|
| 85 |
+
db_path = Path(__file__).resolve().parents[4] / db_path
|
| 86 |
+
return db_path
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _redact_url(url: Any) -> str:
|
| 90 |
+
raw = str(url or "").strip()
|
| 91 |
+
if not raw:
|
| 92 |
+
return "<empty>"
|
| 93 |
+
try:
|
| 94 |
+
parts = urlsplit(raw)
|
| 95 |
+
except Exception:
|
| 96 |
+
return raw
|
| 97 |
+
if not parts.scheme:
|
| 98 |
+
return raw
|
| 99 |
+
hostname = parts.hostname or ""
|
| 100 |
+
if parts.port:
|
| 101 |
+
hostname = f"{hostname}:{parts.port}"
|
| 102 |
+
if parts.username:
|
| 103 |
+
auth = f"{parts.username}:***@"
|
| 104 |
+
elif parts.password:
|
| 105 |
+
auth = "***@"
|
| 106 |
+
else:
|
| 107 |
+
auth = ""
|
| 108 |
+
return urlunsplit((parts.scheme, f"{auth}{hostname}", parts.path, parts.query, parts.fragment))
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _make_local() -> AccountRepository:
|
| 112 |
+
from .local import LocalAccountRepository
|
| 113 |
+
|
| 114 |
+
return LocalAccountRepository(_resolve_local_db_path())
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _make_redis() -> AccountRepository:
|
| 118 |
+
from redis.asyncio import Redis
|
| 119 |
+
from .redis import RedisAccountRepository
|
| 120 |
+
|
| 121 |
+
url = _get_required_env("ACCOUNT_REDIS_URL")
|
| 122 |
+
r = Redis.from_url(url, decode_responses=False)
|
| 123 |
+
return RedisAccountRepository(r)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _make_sql(dialect: str) -> AccountRepository:
|
| 127 |
+
from .sql import SqlAccountRepository, create_mysql_engine, create_pgsql_engine
|
| 128 |
+
|
| 129 |
+
if dialect == "mysql":
|
| 130 |
+
url = _get_env("ACCOUNT_MYSQL_URL")
|
| 131 |
+
engine = create_mysql_engine(url)
|
| 132 |
+
else:
|
| 133 |
+
url = _get_env("ACCOUNT_POSTGRESQL_URL")
|
| 134 |
+
engine = create_pgsql_engine(url)
|
| 135 |
+
return SqlAccountRepository(engine, dialect=dialect, dispose_engine=False)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
__all__ = ["create_repository", "describe_repository_target", "get_repository_backend"]
|
app/control/account/backends/local.py
ADDED
|
@@ -0,0 +1,688 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 5 |
+
import sqlite3
|
| 6 |
+
from contextlib import closing
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from app.platform.runtime.clock import now_ms
|
| 11 |
+
from ..commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery
|
| 12 |
+
from ..enums import AccountStatus
|
| 13 |
+
from ..models import (
|
| 14 |
+
AccountChangeSet,
|
| 15 |
+
AccountMutationResult,
|
| 16 |
+
AccountPage,
|
| 17 |
+
AccountRecord,
|
| 18 |
+
RuntimeSnapshot,
|
| 19 |
+
)
|
| 20 |
+
from ..quota_defaults import default_quota_set, BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_WINDOW_SECONDS
|
| 21 |
+
|
| 22 |
+
_TBL = "accounts"
|
| 23 |
+
_META = "account_meta"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class LocalAccountRepository:
|
| 27 |
+
"""SQLite-backed account repository."""
|
| 28 |
+
|
| 29 |
+
def __init__(self, db_path: Path) -> None:
|
| 30 |
+
self._path = Path(db_path)
|
| 31 |
+
self._lock = asyncio.Lock()
|
| 32 |
+
|
| 33 |
+
# ------------------------------------------------------------------
|
| 34 |
+
# Internal helpers
|
| 35 |
+
# ------------------------------------------------------------------
|
| 36 |
+
|
| 37 |
+
def _connect(self) -> sqlite3.Connection:
|
| 38 |
+
conn = sqlite3.connect(self._path, check_same_thread=False)
|
| 39 |
+
conn.row_factory = sqlite3.Row
|
| 40 |
+
conn.execute("PRAGMA journal_mode=WAL")
|
| 41 |
+
conn.execute("PRAGMA synchronous=NORMAL")
|
| 42 |
+
conn.execute("PRAGMA busy_timeout=5000")
|
| 43 |
+
conn.execute("PRAGMA foreign_keys=ON")
|
| 44 |
+
return conn
|
| 45 |
+
|
| 46 |
+
def _init_sync(self) -> None:
|
| 47 |
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
| 48 |
+
with closing(self._connect()) as conn:
|
| 49 |
+
conn.executescript(f"""
|
| 50 |
+
CREATE TABLE IF NOT EXISTS {_META} (
|
| 51 |
+
key TEXT PRIMARY KEY,
|
| 52 |
+
value TEXT NOT NULL
|
| 53 |
+
);
|
| 54 |
+
INSERT OR IGNORE INTO {_META} VALUES ('revision', '0');
|
| 55 |
+
|
| 56 |
+
CREATE TABLE IF NOT EXISTS {_TBL} (
|
| 57 |
+
token TEXT NOT NULL PRIMARY KEY,
|
| 58 |
+
pool TEXT NOT NULL DEFAULT 'basic',
|
| 59 |
+
status TEXT NOT NULL DEFAULT 'active',
|
| 60 |
+
created_at INTEGER NOT NULL,
|
| 61 |
+
updated_at INTEGER NOT NULL,
|
| 62 |
+
tags TEXT NOT NULL DEFAULT '[]',
|
| 63 |
+
quota_auto TEXT NOT NULL DEFAULT '{{}}',
|
| 64 |
+
quota_fast TEXT NOT NULL DEFAULT '{{}}',
|
| 65 |
+
quota_expert TEXT NOT NULL DEFAULT '{{}}',
|
| 66 |
+
quota_heavy TEXT NOT NULL DEFAULT '{{}}',
|
| 67 |
+
quota_grok_4_3 TEXT NOT NULL DEFAULT '{{}}',
|
| 68 |
+
quota_console TEXT NOT NULL DEFAULT '{{}}',
|
| 69 |
+
usage_use_count INTEGER NOT NULL DEFAULT 0,
|
| 70 |
+
usage_fail_count INTEGER NOT NULL DEFAULT 0,
|
| 71 |
+
usage_sync_count INTEGER NOT NULL DEFAULT 0,
|
| 72 |
+
last_use_at INTEGER,
|
| 73 |
+
last_fail_at INTEGER,
|
| 74 |
+
last_fail_reason TEXT,
|
| 75 |
+
last_sync_at INTEGER,
|
| 76 |
+
last_clear_at INTEGER,
|
| 77 |
+
state_reason TEXT,
|
| 78 |
+
deleted_at INTEGER,
|
| 79 |
+
ext TEXT NOT NULL DEFAULT '{{}}',
|
| 80 |
+
revision INTEGER NOT NULL DEFAULT 0
|
| 81 |
+
);
|
| 82 |
+
CREATE INDEX IF NOT EXISTS idx_acc_revision
|
| 83 |
+
ON {_TBL} (revision);
|
| 84 |
+
CREATE INDEX IF NOT EXISTS idx_acc_pool_status
|
| 85 |
+
ON {_TBL} (pool, status);
|
| 86 |
+
CREATE INDEX IF NOT EXISTS idx_acc_deleted
|
| 87 |
+
ON {_TBL} (deleted_at) WHERE deleted_at IS NOT NULL;
|
| 88 |
+
""")
|
| 89 |
+
self._ensure_column_sync(conn, "quota_grok_4_3", "TEXT NOT NULL DEFAULT '{}'")
|
| 90 |
+
self._ensure_column_sync(conn, "quota_console", "TEXT NOT NULL DEFAULT '{}'")
|
| 91 |
+
conn.commit()
|
| 92 |
+
|
| 93 |
+
@staticmethod
|
| 94 |
+
def _ensure_column_sync(conn: sqlite3.Connection, name: str, ddl: str) -> None:
|
| 95 |
+
cols = {row[1] for row in conn.execute(f"PRAGMA table_info({_TBL})").fetchall()}
|
| 96 |
+
if name not in cols:
|
| 97 |
+
conn.execute(f"ALTER TABLE {_TBL} ADD COLUMN {name} {ddl}")
|
| 98 |
+
|
| 99 |
+
def _bump_revision(self, conn: sqlite3.Connection) -> int:
|
| 100 |
+
conn.execute(
|
| 101 |
+
f"UPDATE {_META} SET value = CAST(value AS INTEGER) + 1 WHERE key = 'revision'"
|
| 102 |
+
)
|
| 103 |
+
row = conn.execute(
|
| 104 |
+
f"SELECT CAST(value AS INTEGER) FROM {_META} WHERE key = 'revision'"
|
| 105 |
+
).fetchone()
|
| 106 |
+
return int(row[0])
|
| 107 |
+
|
| 108 |
+
def _get_revision_sync(self, conn: sqlite3.Connection) -> int:
|
| 109 |
+
row = conn.execute(
|
| 110 |
+
f"SELECT CAST(value AS INTEGER) FROM {_META} WHERE key = 'revision'"
|
| 111 |
+
).fetchone()
|
| 112 |
+
return int(row[0]) if row else 0
|
| 113 |
+
|
| 114 |
+
@staticmethod
|
| 115 |
+
def _row_to_record(row: sqlite3.Row) -> AccountRecord:
|
| 116 |
+
d = dict(row)
|
| 117 |
+
d["tags"] = json.loads(d.get("tags") or "[]")
|
| 118 |
+
heavy_raw = d.pop("quota_heavy", "{}") or "{}"
|
| 119 |
+
grok_4_3_raw = d.pop("quota_grok_4_3", "{}") or "{}"
|
| 120 |
+
console_raw = d.pop("quota_console", "{}") or "{}"
|
| 121 |
+
heavy_dict = json.loads(heavy_raw)
|
| 122 |
+
grok_4_3_dict = json.loads(grok_4_3_raw)
|
| 123 |
+
console_dict = json.loads(console_raw)
|
| 124 |
+
d["quota"] = {
|
| 125 |
+
"auto": json.loads(d.pop("quota_auto", "{}") or "{}"),
|
| 126 |
+
"fast": json.loads(d.pop("quota_fast", "{}") or "{}"),
|
| 127 |
+
"expert": json.loads(d.pop("quota_expert", "{}") or "{}"),
|
| 128 |
+
**({"heavy": heavy_dict} if heavy_dict else {}),
|
| 129 |
+
**({"grok_4_3": grok_4_3_dict} if grok_4_3_dict else {}),
|
| 130 |
+
**({"console": console_dict} if console_dict else {}),
|
| 131 |
+
}
|
| 132 |
+
d["ext"] = json.loads(d.get("ext") or "{}")
|
| 133 |
+
return AccountRecord.model_validate(d)
|
| 134 |
+
|
| 135 |
+
@staticmethod
|
| 136 |
+
def _record_to_row(record: AccountRecord, revision: int) -> dict[str, Any]:
|
| 137 |
+
qs = record.quota_set()
|
| 138 |
+
return {
|
| 139 |
+
"token": record.token,
|
| 140 |
+
"pool": record.pool,
|
| 141 |
+
"status": record.status.value,
|
| 142 |
+
"created_at": record.created_at,
|
| 143 |
+
"updated_at": record.updated_at,
|
| 144 |
+
"tags": json.dumps(record.tags),
|
| 145 |
+
"quota_auto": json.dumps(qs.auto.to_dict()),
|
| 146 |
+
"quota_fast": json.dumps(qs.fast.to_dict()),
|
| 147 |
+
"quota_expert": json.dumps(qs.expert.to_dict()),
|
| 148 |
+
"quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}",
|
| 149 |
+
"quota_grok_4_3": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}",
|
| 150 |
+
"quota_console": json.dumps(qs.console.to_dict()) if qs.console else "{}",
|
| 151 |
+
"usage_use_count": record.usage_use_count,
|
| 152 |
+
"usage_fail_count": record.usage_fail_count,
|
| 153 |
+
"usage_sync_count": record.usage_sync_count,
|
| 154 |
+
"last_use_at": record.last_use_at,
|
| 155 |
+
"last_fail_at": record.last_fail_at,
|
| 156 |
+
"last_fail_reason": record.last_fail_reason,
|
| 157 |
+
"last_sync_at": record.last_sync_at,
|
| 158 |
+
"last_clear_at": record.last_clear_at,
|
| 159 |
+
"state_reason": record.state_reason,
|
| 160 |
+
"deleted_at": record.deleted_at,
|
| 161 |
+
"ext": json.dumps(record.ext),
|
| 162 |
+
"revision": revision,
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
def _upsert_sync(
|
| 166 |
+
self,
|
| 167 |
+
conn: sqlite3.Connection,
|
| 168 |
+
items: list[AccountUpsert],
|
| 169 |
+
revision: int,
|
| 170 |
+
) -> int:
|
| 171 |
+
ts = now_ms()
|
| 172 |
+
|
| 173 |
+
# 按 pool 缓存配额 JSON,避免重复计算(同一 pool 的配额完全相同)
|
| 174 |
+
_quota_json_cache: dict[str, dict[str, str]] = {}
|
| 175 |
+
|
| 176 |
+
def _get_quota_json(pool: str) -> dict[str, str]:
|
| 177 |
+
cached = _quota_json_cache.get(pool)
|
| 178 |
+
if cached is not None:
|
| 179 |
+
return cached
|
| 180 |
+
qs = default_quota_set(pool)
|
| 181 |
+
result = {
|
| 182 |
+
"qa": json.dumps(qs.auto.to_dict()),
|
| 183 |
+
"qf": json.dumps(qs.fast.to_dict()),
|
| 184 |
+
"qe": json.dumps(qs.expert.to_dict()),
|
| 185 |
+
"qh": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}",
|
| 186 |
+
"qg": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}",
|
| 187 |
+
"qc": json.dumps(qs.console.to_dict()) if qs.console else "{}",
|
| 188 |
+
}
|
| 189 |
+
_quota_json_cache[pool] = result
|
| 190 |
+
return result
|
| 191 |
+
|
| 192 |
+
# 批量准备参数
|
| 193 |
+
rows: list[tuple] = []
|
| 194 |
+
for item in items:
|
| 195 |
+
# 轻量 token 清洗(API 层 _sanitize 已做过完整清洗,此处仅做安全兜底)
|
| 196 |
+
token = str(item.token or "").strip()
|
| 197 |
+
if token.startswith("sso="):
|
| 198 |
+
token = token[4:]
|
| 199 |
+
token = token.encode("ascii", errors="ignore").decode("ascii").strip()
|
| 200 |
+
if not token:
|
| 201 |
+
continue
|
| 202 |
+
pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic"
|
| 203 |
+
q = _get_quota_json(pool)
|
| 204 |
+
rows.append((
|
| 205 |
+
token, pool, ts, ts,
|
| 206 |
+
json.dumps(item.tags),
|
| 207 |
+
q["qa"], q["qf"], q["qe"], q["qh"], q["qg"], q["qc"],
|
| 208 |
+
json.dumps(item.ext),
|
| 209 |
+
revision,
|
| 210 |
+
))
|
| 211 |
+
|
| 212 |
+
if not rows:
|
| 213 |
+
return 0
|
| 214 |
+
|
| 215 |
+
# 批量插入(1 次 executemany 代替 N 次 execute)
|
| 216 |
+
conn.executemany(
|
| 217 |
+
f"""
|
| 218 |
+
INSERT INTO {_TBL} (
|
| 219 |
+
token, pool, status, created_at, updated_at,
|
| 220 |
+
tags, quota_auto, quota_fast, quota_expert, quota_heavy, quota_grok_4_3, quota_console,
|
| 221 |
+
usage_use_count, usage_fail_count, usage_sync_count,
|
| 222 |
+
ext, revision
|
| 223 |
+
) VALUES (
|
| 224 |
+
?, ?, 'active', ?, ?,
|
| 225 |
+
?, ?, ?, ?, ?, ?, ?,
|
| 226 |
+
0, 0, 0, ?, ?
|
| 227 |
+
)
|
| 228 |
+
ON CONFLICT(token) DO UPDATE SET
|
| 229 |
+
pool = excluded.pool,
|
| 230 |
+
status = 'active',
|
| 231 |
+
deleted_at = NULL,
|
| 232 |
+
updated_at = excluded.updated_at,
|
| 233 |
+
tags = excluded.tags,
|
| 234 |
+
quota_console = excluded.quota_console,
|
| 235 |
+
ext = excluded.ext,
|
| 236 |
+
revision = excluded.revision
|
| 237 |
+
""",
|
| 238 |
+
rows,
|
| 239 |
+
)
|
| 240 |
+
return len(rows)
|
| 241 |
+
|
| 242 |
+
def _patch_sync(
|
| 243 |
+
self,
|
| 244 |
+
conn: sqlite3.Connection,
|
| 245 |
+
patches: list[AccountPatch],
|
| 246 |
+
revision: int,
|
| 247 |
+
) -> int:
|
| 248 |
+
ts = now_ms()
|
| 249 |
+
count = 0
|
| 250 |
+
for patch in patches:
|
| 251 |
+
# Fetch current record.
|
| 252 |
+
row = conn.execute(
|
| 253 |
+
f"SELECT * FROM {_TBL} WHERE token = ?", (patch.token,)
|
| 254 |
+
).fetchone()
|
| 255 |
+
if row is None:
|
| 256 |
+
continue
|
| 257 |
+
record = self._row_to_record(row)
|
| 258 |
+
qs = record.quota_set()
|
| 259 |
+
|
| 260 |
+
sets: dict[str, Any] = {"updated_at": ts, "revision": revision}
|
| 261 |
+
|
| 262 |
+
if patch.pool is not None:
|
| 263 |
+
sets["pool"] = patch.pool
|
| 264 |
+
if patch.status is not None:
|
| 265 |
+
sets["status"] = patch.status.value
|
| 266 |
+
if patch.state_reason is not None:
|
| 267 |
+
sets["state_reason"] = patch.state_reason
|
| 268 |
+
if patch.last_use_at is not None:
|
| 269 |
+
sets["last_use_at"] = patch.last_use_at
|
| 270 |
+
if patch.last_fail_at is not None:
|
| 271 |
+
sets["last_fail_at"] = patch.last_fail_at
|
| 272 |
+
if patch.last_fail_reason is not None:
|
| 273 |
+
sets["last_fail_reason"] = patch.last_fail_reason
|
| 274 |
+
if patch.last_sync_at is not None:
|
| 275 |
+
sets["last_sync_at"] = patch.last_sync_at
|
| 276 |
+
if patch.last_clear_at is not None:
|
| 277 |
+
sets["last_clear_at"] = patch.last_clear_at
|
| 278 |
+
|
| 279 |
+
# Usage counters (delta).
|
| 280 |
+
if patch.usage_use_delta is not None:
|
| 281 |
+
sets["usage_use_count"] = max(0, record.usage_use_count + patch.usage_use_delta)
|
| 282 |
+
if patch.usage_fail_delta is not None:
|
| 283 |
+
sets["usage_fail_count"] = max(0, record.usage_fail_count + patch.usage_fail_delta)
|
| 284 |
+
if patch.usage_sync_delta is not None:
|
| 285 |
+
sets["usage_sync_count"] = max(0, record.usage_sync_count + patch.usage_sync_delta)
|
| 286 |
+
|
| 287 |
+
# Quota windows.
|
| 288 |
+
if patch.quota_auto is not None:
|
| 289 |
+
sets["quota_auto"] = json.dumps(patch.quota_auto)
|
| 290 |
+
if patch.quota_fast is not None:
|
| 291 |
+
sets["quota_fast"] = json.dumps(patch.quota_fast)
|
| 292 |
+
if patch.quota_expert is not None:
|
| 293 |
+
sets["quota_expert"] = json.dumps(patch.quota_expert)
|
| 294 |
+
if patch.quota_heavy is not None:
|
| 295 |
+
sets["quota_heavy"] = json.dumps(patch.quota_heavy)
|
| 296 |
+
if patch.quota_grok_4_3 is not None:
|
| 297 |
+
sets["quota_grok_4_3"] = json.dumps(patch.quota_grok_4_3)
|
| 298 |
+
if patch.quota_console is not None:
|
| 299 |
+
sets["quota_console"] = json.dumps(patch.quota_console)
|
| 300 |
+
|
| 301 |
+
# Tags — use set arithmetic to avoid O(n×m) membership tests.
|
| 302 |
+
tag_set: set[str] = set(record.tags)
|
| 303 |
+
if patch.tags is not None:
|
| 304 |
+
tag_set = set(patch.tags)
|
| 305 |
+
if patch.add_tags:
|
| 306 |
+
tag_set.update(patch.add_tags)
|
| 307 |
+
if patch.remove_tags:
|
| 308 |
+
tag_set.difference_update(patch.remove_tags)
|
| 309 |
+
sets["tags"] = json.dumps(sorted(tag_set))
|
| 310 |
+
|
| 311 |
+
# ext merge.
|
| 312 |
+
ext = dict(record.ext)
|
| 313 |
+
if patch.ext_merge:
|
| 314 |
+
ext.update(patch.ext_merge)
|
| 315 |
+
if patch.clear_failures:
|
| 316 |
+
for k in ("cooldown_until", "cooldown_reason", "disabled_at",
|
| 317 |
+
"disabled_reason", "expired_at", "expired_reason",
|
| 318 |
+
"forbidden_strikes", "console_429_count"):
|
| 319 |
+
ext.pop(k, None)
|
| 320 |
+
sets["status"] = AccountStatus.ACTIVE.value
|
| 321 |
+
sets["usage_fail_count"] = 0
|
| 322 |
+
sets["last_fail_at"] = None
|
| 323 |
+
sets["last_fail_reason"] = None
|
| 324 |
+
sets["state_reason"] = None
|
| 325 |
+
sets["ext"] = json.dumps(ext)
|
| 326 |
+
|
| 327 |
+
col_sql = ", ".join(f"{k} = :{k}" for k in sets)
|
| 328 |
+
conn.execute(
|
| 329 |
+
f"UPDATE {_TBL} SET {col_sql} WHERE token = :_token",
|
| 330 |
+
{**sets, "_token": patch.token},
|
| 331 |
+
)
|
| 332 |
+
count += conn.execute("SELECT changes()").fetchone()[0]
|
| 333 |
+
return count
|
| 334 |
+
|
| 335 |
+
# ------------------------------------------------------------------
|
| 336 |
+
# Public API
|
| 337 |
+
# ------------------------------------------------------------------
|
| 338 |
+
|
| 339 |
+
async def initialize(self) -> None:
|
| 340 |
+
async with self._lock:
|
| 341 |
+
await asyncio.to_thread(self._init_sync)
|
| 342 |
+
|
| 343 |
+
async def get_revision(self) -> int:
|
| 344 |
+
def _sync() -> int:
|
| 345 |
+
with closing(self._connect()) as conn:
|
| 346 |
+
return self._get_revision_sync(conn)
|
| 347 |
+
return await asyncio.to_thread(_sync)
|
| 348 |
+
|
| 349 |
+
async def runtime_snapshot(self) -> RuntimeSnapshot:
|
| 350 |
+
def _sync() -> RuntimeSnapshot:
|
| 351 |
+
with closing(self._connect()) as conn:
|
| 352 |
+
rev = self._get_revision_sync(conn)
|
| 353 |
+
rows = conn.execute(
|
| 354 |
+
f"SELECT * FROM {_TBL} WHERE deleted_at IS NULL"
|
| 355 |
+
).fetchall()
|
| 356 |
+
return RuntimeSnapshot(
|
| 357 |
+
revision=rev,
|
| 358 |
+
items=[self._row_to_record(r) for r in rows],
|
| 359 |
+
)
|
| 360 |
+
return await asyncio.to_thread(_sync)
|
| 361 |
+
|
| 362 |
+
async def scan_changes(
|
| 363 |
+
self,
|
| 364 |
+
since_revision: int,
|
| 365 |
+
*,
|
| 366 |
+
limit: int = 5000,
|
| 367 |
+
) -> AccountChangeSet:
|
| 368 |
+
def _sync() -> AccountChangeSet:
|
| 369 |
+
with closing(self._connect()) as conn:
|
| 370 |
+
rev = self._get_revision_sync(conn)
|
| 371 |
+
rows = conn.execute(
|
| 372 |
+
f"SELECT * FROM {_TBL} WHERE revision > ? ORDER BY revision LIMIT ?",
|
| 373 |
+
(since_revision, limit),
|
| 374 |
+
).fetchall()
|
| 375 |
+
items: list[AccountRecord] = []
|
| 376 |
+
deleted: list[str] = []
|
| 377 |
+
batch_max_rev = 0
|
| 378 |
+
for row in rows:
|
| 379 |
+
r = self._row_to_record(row)
|
| 380 |
+
if r.revision > batch_max_rev:
|
| 381 |
+
batch_max_rev = r.revision
|
| 382 |
+
if r.is_deleted():
|
| 383 |
+
deleted.append(r.token)
|
| 384 |
+
else:
|
| 385 |
+
items.append(r)
|
| 386 |
+
has_more = len(rows) == limit
|
| 387 |
+
return AccountChangeSet(
|
| 388 |
+
revision=rev,
|
| 389 |
+
batch_max_revision=batch_max_rev,
|
| 390 |
+
items=items,
|
| 391 |
+
deleted_tokens=deleted,
|
| 392 |
+
has_more=has_more,
|
| 393 |
+
)
|
| 394 |
+
return await asyncio.to_thread(_sync)
|
| 395 |
+
|
| 396 |
+
async def upsert_accounts(
|
| 397 |
+
self,
|
| 398 |
+
items: list[AccountUpsert],
|
| 399 |
+
) -> AccountMutationResult:
|
| 400 |
+
if not items:
|
| 401 |
+
return AccountMutationResult()
|
| 402 |
+
|
| 403 |
+
def _sync() -> AccountMutationResult:
|
| 404 |
+
with closing(self._connect()) as conn:
|
| 405 |
+
rev = self._bump_revision(conn)
|
| 406 |
+
count = self._upsert_sync(conn, items, rev)
|
| 407 |
+
conn.commit()
|
| 408 |
+
return AccountMutationResult(upserted=count, revision=rev)
|
| 409 |
+
|
| 410 |
+
async with self._lock:
|
| 411 |
+
return await asyncio.to_thread(_sync)
|
| 412 |
+
|
| 413 |
+
async def patch_accounts(
|
| 414 |
+
self,
|
| 415 |
+
patches: list[AccountPatch],
|
| 416 |
+
) -> AccountMutationResult:
|
| 417 |
+
if not patches:
|
| 418 |
+
return AccountMutationResult()
|
| 419 |
+
|
| 420 |
+
def _sync() -> AccountMutationResult:
|
| 421 |
+
with closing(self._connect()) as conn:
|
| 422 |
+
rev = self._bump_revision(conn)
|
| 423 |
+
count = self._patch_sync(conn, patches, rev)
|
| 424 |
+
conn.commit()
|
| 425 |
+
return AccountMutationResult(patched=count, revision=rev)
|
| 426 |
+
|
| 427 |
+
async with self._lock:
|
| 428 |
+
return await asyncio.to_thread(_sync)
|
| 429 |
+
|
| 430 |
+
async def delete_accounts(
|
| 431 |
+
self,
|
| 432 |
+
tokens: list[str],
|
| 433 |
+
) -> AccountMutationResult:
|
| 434 |
+
if not tokens:
|
| 435 |
+
return AccountMutationResult()
|
| 436 |
+
|
| 437 |
+
def _sync() -> AccountMutationResult:
|
| 438 |
+
ts = now_ms()
|
| 439 |
+
with closing(self._connect()) as conn:
|
| 440 |
+
rev = self._bump_revision(conn)
|
| 441 |
+
conn.executemany(
|
| 442 |
+
f"UPDATE {_TBL} SET deleted_at = ?, updated_at = ?, revision = ? "
|
| 443 |
+
f"WHERE token = ? AND deleted_at IS NULL",
|
| 444 |
+
[(ts, ts, rev, t) for t in tokens],
|
| 445 |
+
)
|
| 446 |
+
count = conn.execute("SELECT changes()").fetchone()[0]
|
| 447 |
+
conn.commit()
|
| 448 |
+
return AccountMutationResult(deleted=count, revision=rev)
|
| 449 |
+
|
| 450 |
+
async with self._lock:
|
| 451 |
+
return await asyncio.to_thread(_sync)
|
| 452 |
+
|
| 453 |
+
async def get_accounts(
|
| 454 |
+
self,
|
| 455 |
+
tokens: list[str],
|
| 456 |
+
) -> list[AccountRecord]:
|
| 457 |
+
if not tokens:
|
| 458 |
+
return []
|
| 459 |
+
|
| 460 |
+
def _sync() -> list[AccountRecord]:
|
| 461 |
+
with closing(self._connect()) as conn:
|
| 462 |
+
placeholders = ",".join("?" * len(tokens))
|
| 463 |
+
rows = conn.execute(
|
| 464 |
+
f"SELECT * FROM {_TBL} WHERE token IN ({placeholders})",
|
| 465 |
+
tokens,
|
| 466 |
+
).fetchall()
|
| 467 |
+
return [self._row_to_record(r) for r in rows]
|
| 468 |
+
|
| 469 |
+
return await asyncio.to_thread(_sync)
|
| 470 |
+
|
| 471 |
+
async def list_accounts(
|
| 472 |
+
self,
|
| 473 |
+
query: ListAccountsQuery,
|
| 474 |
+
) -> AccountPage:
|
| 475 |
+
def _sync() -> AccountPage:
|
| 476 |
+
with closing(self._connect()) as conn:
|
| 477 |
+
where_parts: list[str] = []
|
| 478 |
+
params: list[Any] = []
|
| 479 |
+
|
| 480 |
+
if not query.include_deleted:
|
| 481 |
+
where_parts.append("deleted_at IS NULL")
|
| 482 |
+
if query.pool:
|
| 483 |
+
where_parts.append("pool = ?")
|
| 484 |
+
params.append(query.pool)
|
| 485 |
+
if query.status:
|
| 486 |
+
where_parts.append("status = ?")
|
| 487 |
+
params.append(query.status.value)
|
| 488 |
+
|
| 489 |
+
where_sql = ("WHERE " + " AND ".join(where_parts)) if where_parts else ""
|
| 490 |
+
order_dir = "DESC" if query.sort_desc else "ASC"
|
| 491 |
+
# Allow only known column names to prevent injection.
|
| 492 |
+
safe_sort = query.sort_by if query.sort_by in {
|
| 493 |
+
"updated_at", "created_at", "last_use_at", "token",
|
| 494 |
+
"usage_use_count", "usage_fail_count",
|
| 495 |
+
} else "updated_at"
|
| 496 |
+
order_sql = f"ORDER BY {safe_sort} {order_dir}"
|
| 497 |
+
|
| 498 |
+
total = conn.execute(
|
| 499 |
+
f"SELECT COUNT(*) FROM {_TBL} {where_sql}", params
|
| 500 |
+
).fetchone()[0]
|
| 501 |
+
|
| 502 |
+
offset = (query.page - 1) * query.page_size
|
| 503 |
+
rows = conn.execute(
|
| 504 |
+
f"SELECT * FROM {_TBL} {where_sql} {order_sql} "
|
| 505 |
+
f"LIMIT ? OFFSET ?",
|
| 506 |
+
params + [query.page_size, offset],
|
| 507 |
+
).fetchall()
|
| 508 |
+
items = [self._row_to_record(r) for r in rows]
|
| 509 |
+
total_pages = max(1, (total + query.page_size - 1) // query.page_size)
|
| 510 |
+
rev = self._get_revision_sync(conn)
|
| 511 |
+
return AccountPage(
|
| 512 |
+
items=items,
|
| 513 |
+
total=total,
|
| 514 |
+
page=query.page,
|
| 515 |
+
page_size=query.page_size,
|
| 516 |
+
total_pages=total_pages,
|
| 517 |
+
revision=rev,
|
| 518 |
+
)
|
| 519 |
+
|
| 520 |
+
return await asyncio.to_thread(_sync)
|
| 521 |
+
|
| 522 |
+
async def replace_pool(
|
| 523 |
+
self,
|
| 524 |
+
command: BulkReplacePoolCommand,
|
| 525 |
+
) -> AccountMutationResult:
|
| 526 |
+
def _sync() -> AccountMutationResult:
|
| 527 |
+
ts = now_ms()
|
| 528 |
+
with closing(self._connect()) as conn:
|
| 529 |
+
rev = self._bump_revision(conn)
|
| 530 |
+
# Soft-delete all existing accounts in the pool.
|
| 531 |
+
conn.execute(
|
| 532 |
+
f"UPDATE {_TBL} SET deleted_at = ?, updated_at = ?, revision = ? "
|
| 533 |
+
f"WHERE pool = ? AND deleted_at IS NULL",
|
| 534 |
+
(ts, ts, rev, command.pool),
|
| 535 |
+
)
|
| 536 |
+
deleted = conn.execute("SELECT changes()").fetchone()[0]
|
| 537 |
+
# Bump revision again for upserts.
|
| 538 |
+
rev = self._bump_revision(conn)
|
| 539 |
+
upserted = self._upsert_sync(conn, command.upserts, rev)
|
| 540 |
+
conn.commit()
|
| 541 |
+
return AccountMutationResult(
|
| 542 |
+
upserted=upserted, deleted=deleted, revision=rev
|
| 543 |
+
)
|
| 544 |
+
|
| 545 |
+
async with self._lock:
|
| 546 |
+
return await asyncio.to_thread(_sync)
|
| 547 |
+
|
| 548 |
+
async def reset_expired_console_windows(self) -> int:
|
| 549 |
+
"""Batch-reset exhausted + expired console quotas via direct SQL.
|
| 550 |
+
|
| 551 |
+
处理两种异常情况:
|
| 552 |
+
1. 老条件:remaining<=0 且 (reset_at IS NULL 或已过期) → 正常配额耗尽恢复
|
| 553 |
+
2. 新条件 (M6):reset_at 已过期(即使 remaining>0)→ 异常数据归位
|
| 554 |
+
(来源:人工 patch、迁移数据、M1 历史副作用等)
|
| 555 |
+
"""
|
| 556 |
+
def _sync() -> int:
|
| 557 |
+
with closing(self._connect()) as conn:
|
| 558 |
+
now = now_ms()
|
| 559 |
+
# 先查有多少需要重置的
|
| 560 |
+
count = conn.execute(
|
| 561 |
+
f"""
|
| 562 |
+
SELECT COUNT(*) FROM {_TBL}
|
| 563 |
+
WHERE status = 'active'
|
| 564 |
+
AND deleted_at IS NULL
|
| 565 |
+
AND (
|
| 566 |
+
(
|
| 567 |
+
CAST(json_extract(quota_console, '$.remaining') AS INTEGER) <= 0
|
| 568 |
+
AND (
|
| 569 |
+
json_extract(quota_console, '$.reset_at') IS NULL
|
| 570 |
+
OR CAST(json_extract(quota_console, '$.reset_at') AS INTEGER) < ?
|
| 571 |
+
)
|
| 572 |
+
)
|
| 573 |
+
OR
|
| 574 |
+
(
|
| 575 |
+
json_extract(quota_console, '$.reset_at') IS NOT NULL
|
| 576 |
+
AND CAST(json_extract(quota_console, '$.reset_at') AS INTEGER) < ?
|
| 577 |
+
)
|
| 578 |
+
)
|
| 579 |
+
""",
|
| 580 |
+
(now, now),
|
| 581 |
+
).fetchone()[0]
|
| 582 |
+
if count == 0:
|
| 583 |
+
return 0
|
| 584 |
+
|
| 585 |
+
# 从 quota_defaults.py 动态读取,不硬编码
|
| 586 |
+
reset_json = json.dumps({
|
| 587 |
+
"remaining": BASIC_CONSOLE_LIMIT,
|
| 588 |
+
"total": BASIC_CONSOLE_LIMIT,
|
| 589 |
+
"window_seconds": BASIC_CONSOLE_WINDOW_SECONDS,
|
| 590 |
+
"reset_at": None,
|
| 591 |
+
"synced_at": now,
|
| 592 |
+
"source": 0,
|
| 593 |
+
})
|
| 594 |
+
rev = self._bump_revision(conn)
|
| 595 |
+
conn.execute(
|
| 596 |
+
f"""
|
| 597 |
+
UPDATE {_TBL}
|
| 598 |
+
SET quota_console = ?, revision = ?, updated_at = ?
|
| 599 |
+
WHERE status = 'active'
|
| 600 |
+
AND deleted_at IS NULL
|
| 601 |
+
AND (
|
| 602 |
+
(
|
| 603 |
+
CAST(json_extract(quota_console, '$.remaining') AS INTEGER) <= 0
|
| 604 |
+
AND (
|
| 605 |
+
json_extract(quota_console, '$.reset_at') IS NULL
|
| 606 |
+
OR CAST(json_extract(quota_console, '$.reset_at') AS INTEGER) < ?
|
| 607 |
+
)
|
| 608 |
+
)
|
| 609 |
+
OR
|
| 610 |
+
(
|
| 611 |
+
json_extract(quota_console, '$.reset_at') IS NOT NULL
|
| 612 |
+
AND CAST(json_extract(quota_console, '$.reset_at') AS INTEGER) < ?
|
| 613 |
+
)
|
| 614 |
+
)
|
| 615 |
+
""",
|
| 616 |
+
(reset_json, rev, now, now, now),
|
| 617 |
+
)
|
| 618 |
+
affected = conn.execute("SELECT changes()").fetchone()[0]
|
| 619 |
+
conn.commit()
|
| 620 |
+
return affected
|
| 621 |
+
|
| 622 |
+
async with self._lock:
|
| 623 |
+
return await asyncio.to_thread(_sync)
|
| 624 |
+
|
| 625 |
+
async def recover_console_expired_accounts(self) -> int:
|
| 626 |
+
"""Auto-recover console 429 EXPIRED accounts with successful history.
|
| 627 |
+
|
| 628 |
+
Conditions:
|
| 629 |
+
- status = 'expired'
|
| 630 |
+
- state_reason = 'console_429_threshold_exceeded'
|
| 631 |
+
- usage_use_count > 5
|
| 632 |
+
- ext.expired_at <= now - 1 hour
|
| 633 |
+
"""
|
| 634 |
+
def _sync() -> int:
|
| 635 |
+
with closing(self._connect()) as conn:
|
| 636 |
+
now = now_ms()
|
| 637 |
+
recovery_threshold = now - 3600 * 1000
|
| 638 |
+
|
| 639 |
+
# 查询符合条件的账号 token 和 ext
|
| 640 |
+
rows = conn.execute(
|
| 641 |
+
f"""
|
| 642 |
+
SELECT token, ext FROM {_TBL}
|
| 643 |
+
WHERE status = 'expired'
|
| 644 |
+
AND deleted_at IS NULL
|
| 645 |
+
AND state_reason = 'console_429_threshold_exceeded'
|
| 646 |
+
AND usage_use_count > 5
|
| 647 |
+
AND CAST(json_extract(ext, '$.expired_at') AS INTEGER) <= ?
|
| 648 |
+
""",
|
| 649 |
+
(recovery_threshold,),
|
| 650 |
+
).fetchall()
|
| 651 |
+
|
| 652 |
+
if not rows:
|
| 653 |
+
return 0
|
| 654 |
+
|
| 655 |
+
rev = self._bump_revision(conn)
|
| 656 |
+
for row in rows:
|
| 657 |
+
token, ext_raw = row
|
| 658 |
+
try:
|
| 659 |
+
ext = json.loads(ext_raw) if ext_raw else {}
|
| 660 |
+
except (ValueError, TypeError):
|
| 661 |
+
ext = {}
|
| 662 |
+
# 清理 EXPIRED 相关字段
|
| 663 |
+
for k in ("expired_at", "expired_reason",
|
| 664 |
+
"console_429_count", "console_429_last_at"):
|
| 665 |
+
ext.pop(k, None)
|
| 666 |
+
conn.execute(
|
| 667 |
+
f"""
|
| 668 |
+
UPDATE {_TBL}
|
| 669 |
+
SET status = 'active',
|
| 670 |
+
state_reason = NULL,
|
| 671 |
+
ext = ?,
|
| 672 |
+
revision = ?,
|
| 673 |
+
updated_at = ?
|
| 674 |
+
WHERE token = ?
|
| 675 |
+
""",
|
| 676 |
+
(json.dumps(ext), rev, now, token),
|
| 677 |
+
)
|
| 678 |
+
conn.commit()
|
| 679 |
+
return len(rows)
|
| 680 |
+
|
| 681 |
+
async with self._lock:
|
| 682 |
+
return await asyncio.to_thread(_sync)
|
| 683 |
+
|
| 684 |
+
async def close(self) -> None:
|
| 685 |
+
"""No-op for SQLite — connections are opened and closed per operation."""
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
__all__ = ["LocalAccountRepository"]
|
app/control/account/backends/redis.py
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Redis account repository.
|
| 2 |
+
|
| 3 |
+
Layout:
|
| 4 |
+
accounts:rev — STRING global revision counter
|
| 5 |
+
accounts:record:<token> — HASH flattened AccountRecord fields
|
| 6 |
+
accounts:pool:<pool> — SET token members per pool (live)
|
| 7 |
+
accounts:revision_log — ZSET token → revision (for scan_changes)
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
from app.platform.runtime.clock import now_ms
|
| 14 |
+
from ..commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery
|
| 15 |
+
from ..enums import AccountStatus
|
| 16 |
+
from ..models import (
|
| 17 |
+
AccountChangeSet,
|
| 18 |
+
AccountMutationResult,
|
| 19 |
+
AccountPage,
|
| 20 |
+
AccountRecord,
|
| 21 |
+
RuntimeSnapshot,
|
| 22 |
+
)
|
| 23 |
+
from redis.asyncio import Redis
|
| 24 |
+
|
| 25 |
+
from ..quota_defaults import default_quota_set
|
| 26 |
+
|
| 27 |
+
_KEY_REV = "accounts:rev"
|
| 28 |
+
_KEY_RECORD = "accounts:record:{token}"
|
| 29 |
+
_KEY_POOL = "accounts:pool:{pool}"
|
| 30 |
+
_KEY_REV_LOG = "accounts:revision_log"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _record_key(token: str) -> str:
|
| 34 |
+
return f"accounts:record:{token}"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _pool_key(pool: str) -> str:
|
| 38 |
+
return f"accounts:pool:{pool}"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class RedisAccountRepository:
|
| 42 |
+
"""Redis-backed account repository.
|
| 43 |
+
|
| 44 |
+
Requires redis-py >= 5 with async support.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(self, redis: "Redis") -> None:
|
| 48 |
+
self._r = redis
|
| 49 |
+
|
| 50 |
+
# ------------------------------------------------------------------
|
| 51 |
+
# Serialisation helpers
|
| 52 |
+
# ------------------------------------------------------------------
|
| 53 |
+
|
| 54 |
+
@staticmethod
|
| 55 |
+
def _to_hash(record: AccountRecord, revision: int) -> dict[str, str]:
|
| 56 |
+
qs = record.quota_set()
|
| 57 |
+
return {
|
| 58 |
+
"pool": record.pool,
|
| 59 |
+
"status": record.status.value,
|
| 60 |
+
"created_at": str(record.created_at),
|
| 61 |
+
"updated_at": str(record.updated_at),
|
| 62 |
+
"tags": json.dumps(record.tags),
|
| 63 |
+
"quota_auto": json.dumps(qs.auto.to_dict()),
|
| 64 |
+
"quota_fast": json.dumps(qs.fast.to_dict()),
|
| 65 |
+
"quota_expert": json.dumps(qs.expert.to_dict()),
|
| 66 |
+
"quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}",
|
| 67 |
+
"quota_grok_4_3": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}",
|
| 68 |
+
"quota_console": json.dumps(qs.console.to_dict()) if qs.console else "{}",
|
| 69 |
+
"usage_use_count": str(record.usage_use_count),
|
| 70 |
+
"usage_fail_count": str(record.usage_fail_count),
|
| 71 |
+
"usage_sync_count": str(record.usage_sync_count),
|
| 72 |
+
"last_use_at": str(record.last_use_at or ""),
|
| 73 |
+
"last_fail_at": str(record.last_fail_at or ""),
|
| 74 |
+
"last_fail_reason": record.last_fail_reason or "",
|
| 75 |
+
"last_sync_at": str(record.last_sync_at or ""),
|
| 76 |
+
"last_clear_at": str(record.last_clear_at or ""),
|
| 77 |
+
"state_reason": record.state_reason or "",
|
| 78 |
+
"deleted_at": str(record.deleted_at or ""),
|
| 79 |
+
"ext": json.dumps(record.ext),
|
| 80 |
+
"revision": str(revision),
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
@staticmethod
|
| 84 |
+
def _from_hash(token: str, h: dict[bytes | str, bytes | str]) -> AccountRecord:
|
| 85 |
+
def _s(k: str) -> str:
|
| 86 |
+
v = h.get(k) or h.get(k.encode())
|
| 87 |
+
return v.decode() if isinstance(v, bytes) else (v or "")
|
| 88 |
+
|
| 89 |
+
def _i(k: str) -> int | None:
|
| 90 |
+
v = _s(k)
|
| 91 |
+
return int(v) if v else None
|
| 92 |
+
|
| 93 |
+
return AccountRecord.model_validate({
|
| 94 |
+
"token": token,
|
| 95 |
+
"pool": _s("pool") or "basic",
|
| 96 |
+
"status": _s("status") or "active",
|
| 97 |
+
"created_at": _i("created_at") or now_ms(),
|
| 98 |
+
"updated_at": _i("updated_at") or now_ms(),
|
| 99 |
+
"tags": json.loads(_s("tags") or "[]"),
|
| 100 |
+
"quota": {
|
| 101 |
+
"auto": json.loads(_s("quota_auto") or "{}"),
|
| 102 |
+
"fast": json.loads(_s("quota_fast") or "{}"),
|
| 103 |
+
"expert": json.loads(_s("quota_expert") or "{}"),
|
| 104 |
+
**({
|
| 105 |
+
"heavy": json.loads(_s("quota_heavy"))
|
| 106 |
+
} if _s("quota_heavy") and _s("quota_heavy") != "{}" else {}),
|
| 107 |
+
**({
|
| 108 |
+
"grok_4_3": json.loads(_s("quota_grok_4_3"))
|
| 109 |
+
} if _s("quota_grok_4_3") and _s("quota_grok_4_3") != "{}" else {}),
|
| 110 |
+
**({
|
| 111 |
+
"console": json.loads(_s("quota_console"))
|
| 112 |
+
} if _s("quota_console") and _s("quota_console") != "{}" else {}),
|
| 113 |
+
},
|
| 114 |
+
"usage_use_count": int(_s("usage_use_count") or 0),
|
| 115 |
+
"usage_fail_count": int(_s("usage_fail_count") or 0),
|
| 116 |
+
"usage_sync_count": int(_s("usage_sync_count") or 0),
|
| 117 |
+
"last_use_at": _i("last_use_at"),
|
| 118 |
+
"last_fail_at": _i("last_fail_at"),
|
| 119 |
+
"last_fail_reason": _s("last_fail_reason") or None,
|
| 120 |
+
"last_sync_at": _i("last_sync_at"),
|
| 121 |
+
"last_clear_at": _i("last_clear_at"),
|
| 122 |
+
"state_reason": _s("state_reason") or None,
|
| 123 |
+
"deleted_at": _i("deleted_at"),
|
| 124 |
+
"ext": json.loads(_s("ext") or "{}"),
|
| 125 |
+
"revision": int(_s("revision") or 0),
|
| 126 |
+
})
|
| 127 |
+
|
| 128 |
+
# ------------------------------------------------------------------
|
| 129 |
+
# Revision management
|
| 130 |
+
# ------------------------------------------------------------------
|
| 131 |
+
|
| 132 |
+
async def _bump_revision(self) -> int:
|
| 133 |
+
return int(await self._r.incr(_KEY_REV))
|
| 134 |
+
|
| 135 |
+
# ------------------------------------------------------------------
|
| 136 |
+
# Public API
|
| 137 |
+
# ------------------------------------------------------------------
|
| 138 |
+
|
| 139 |
+
async def initialize(self) -> None:
|
| 140 |
+
await self._r.setnx(_KEY_REV, "0")
|
| 141 |
+
|
| 142 |
+
async def get_revision(self) -> int:
|
| 143 |
+
v = await self._r.get(_KEY_REV)
|
| 144 |
+
return int(v) if v else 0
|
| 145 |
+
|
| 146 |
+
async def runtime_snapshot(self) -> RuntimeSnapshot:
|
| 147 |
+
rev = await self.get_revision()
|
| 148 |
+
# Scan all record keys.
|
| 149 |
+
keys: list[str] = []
|
| 150 |
+
async for k in self._r.scan_iter("accounts:record:*"):
|
| 151 |
+
keys.append(k.decode() if isinstance(k, bytes) else k)
|
| 152 |
+
|
| 153 |
+
items: list[AccountRecord] = []
|
| 154 |
+
for key in keys:
|
| 155 |
+
token = key.split(":", 2)[-1]
|
| 156 |
+
h = await self._r.hgetall(key)
|
| 157 |
+
if not h:
|
| 158 |
+
continue
|
| 159 |
+
record = self._from_hash(token, h)
|
| 160 |
+
if not record.is_deleted():
|
| 161 |
+
items.append(record)
|
| 162 |
+
return RuntimeSnapshot(revision=rev, items=items)
|
| 163 |
+
|
| 164 |
+
async def scan_changes(
|
| 165 |
+
self,
|
| 166 |
+
since_revision: int,
|
| 167 |
+
*,
|
| 168 |
+
limit: int = 5000,
|
| 169 |
+
) -> AccountChangeSet:
|
| 170 |
+
rev = await self.get_revision()
|
| 171 |
+
# Tokens whose revision > since_revision; 带分数以便提取本批最大 revision。
|
| 172 |
+
entries = await self._r.zrangebyscore(
|
| 173 |
+
_KEY_REV_LOG,
|
| 174 |
+
since_revision + 1,
|
| 175 |
+
"+inf",
|
| 176 |
+
withscores=True,
|
| 177 |
+
start=0,
|
| 178 |
+
num=limit,
|
| 179 |
+
)
|
| 180 |
+
tokens: list[tuple[str, int]] = []
|
| 181 |
+
batch_max_rev = 0
|
| 182 |
+
for entry in entries:
|
| 183 |
+
tok, score = entry
|
| 184 |
+
tok_s = tok.decode() if isinstance(tok, bytes) else tok
|
| 185 |
+
score_i = int(score)
|
| 186 |
+
if score_i > batch_max_rev:
|
| 187 |
+
batch_max_rev = score_i
|
| 188 |
+
tokens.append((tok_s, score_i))
|
| 189 |
+
items: list[AccountRecord] = []
|
| 190 |
+
deleted: list[str] = []
|
| 191 |
+
for token, _score in tokens:
|
| 192 |
+
h = await self._r.hgetall(_record_key(token))
|
| 193 |
+
if not h:
|
| 194 |
+
deleted.append(token)
|
| 195 |
+
continue
|
| 196 |
+
record = self._from_hash(token, h)
|
| 197 |
+
if record.is_deleted():
|
| 198 |
+
deleted.append(token)
|
| 199 |
+
else:
|
| 200 |
+
items.append(record)
|
| 201 |
+
return AccountChangeSet(
|
| 202 |
+
revision=rev,
|
| 203 |
+
batch_max_revision=batch_max_rev,
|
| 204 |
+
items=items,
|
| 205 |
+
deleted_tokens=deleted,
|
| 206 |
+
has_more=len(entries) == limit,
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
async def upsert_accounts(
|
| 210 |
+
self,
|
| 211 |
+
items: list[AccountUpsert],
|
| 212 |
+
) -> AccountMutationResult:
|
| 213 |
+
if not items:
|
| 214 |
+
return AccountMutationResult()
|
| 215 |
+
rev = await self._bump_revision()
|
| 216 |
+
count = 0
|
| 217 |
+
for item in items:
|
| 218 |
+
try:
|
| 219 |
+
token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token
|
| 220 |
+
except ValueError:
|
| 221 |
+
continue
|
| 222 |
+
pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic"
|
| 223 |
+
qs = default_quota_set(pool)
|
| 224 |
+
ts = now_ms()
|
| 225 |
+
record = AccountRecord(
|
| 226 |
+
token = token,
|
| 227 |
+
pool = pool,
|
| 228 |
+
tags = item.tags,
|
| 229 |
+
ext = item.ext,
|
| 230 |
+
quota = qs.to_dict(),
|
| 231 |
+
created_at = ts,
|
| 232 |
+
updated_at = ts,
|
| 233 |
+
)
|
| 234 |
+
key = _record_key(token)
|
| 235 |
+
await self._r.hset(key, mapping=self._to_hash(record, rev))
|
| 236 |
+
await self._r.sadd(_pool_key(pool), token)
|
| 237 |
+
await self._r.zadd(_KEY_REV_LOG, {token: rev})
|
| 238 |
+
count += 1
|
| 239 |
+
return AccountMutationResult(upserted=count, revision=rev)
|
| 240 |
+
|
| 241 |
+
async def patch_accounts(
|
| 242 |
+
self,
|
| 243 |
+
patches: list[AccountPatch],
|
| 244 |
+
) -> AccountMutationResult:
|
| 245 |
+
if not patches:
|
| 246 |
+
return AccountMutationResult()
|
| 247 |
+
rev = await self._bump_revision()
|
| 248 |
+
count = 0
|
| 249 |
+
ts = now_ms()
|
| 250 |
+
for patch in patches:
|
| 251 |
+
key = _record_key(patch.token)
|
| 252 |
+
h = await self._r.hgetall(key)
|
| 253 |
+
if not h:
|
| 254 |
+
continue
|
| 255 |
+
record = self._from_hash(patch.token, h)
|
| 256 |
+
qs = record.quota_set()
|
| 257 |
+
|
| 258 |
+
updates: dict[str, str] = {
|
| 259 |
+
"updated_at": str(ts),
|
| 260 |
+
"revision": str(rev),
|
| 261 |
+
}
|
| 262 |
+
if patch.status is not None:
|
| 263 |
+
updates["status"] = patch.status.value
|
| 264 |
+
if patch.state_reason is not None:
|
| 265 |
+
updates["state_reason"] = patch.state_reason
|
| 266 |
+
if patch.last_use_at is not None:
|
| 267 |
+
updates["last_use_at"] = str(patch.last_use_at)
|
| 268 |
+
if patch.last_fail_at is not None:
|
| 269 |
+
updates["last_fail_at"] = str(patch.last_fail_at)
|
| 270 |
+
if patch.last_fail_reason is not None:
|
| 271 |
+
updates["last_fail_reason"] = patch.last_fail_reason
|
| 272 |
+
if patch.last_sync_at is not None:
|
| 273 |
+
updates["last_sync_at"] = str(patch.last_sync_at)
|
| 274 |
+
if patch.last_clear_at is not None:
|
| 275 |
+
updates["last_clear_at"] = str(patch.last_clear_at)
|
| 276 |
+
if patch.pool is not None:
|
| 277 |
+
updates["pool"] = patch.pool
|
| 278 |
+
if patch.quota_auto is not None:
|
| 279 |
+
updates["quota_auto"] = json.dumps(patch.quota_auto)
|
| 280 |
+
if patch.quota_fast is not None:
|
| 281 |
+
updates["quota_fast"] = json.dumps(patch.quota_fast)
|
| 282 |
+
if patch.quota_expert is not None:
|
| 283 |
+
updates["quota_expert"] = json.dumps(patch.quota_expert)
|
| 284 |
+
if patch.quota_heavy is not None:
|
| 285 |
+
updates["quota_heavy"] = json.dumps(patch.quota_heavy)
|
| 286 |
+
if patch.quota_grok_4_3 is not None:
|
| 287 |
+
updates["quota_grok_4_3"] = json.dumps(patch.quota_grok_4_3)
|
| 288 |
+
if patch.quota_console is not None:
|
| 289 |
+
updates["quota_console"] = json.dumps(patch.quota_console)
|
| 290 |
+
|
| 291 |
+
# Usage counters.
|
| 292 |
+
if patch.usage_use_delta is not None:
|
| 293 |
+
updates["usage_use_count"] = str(max(0, record.usage_use_count + patch.usage_use_delta))
|
| 294 |
+
if patch.usage_fail_delta is not None:
|
| 295 |
+
updates["usage_fail_count"] = str(max(0, record.usage_fail_count + patch.usage_fail_delta))
|
| 296 |
+
if patch.usage_sync_delta is not None:
|
| 297 |
+
updates["usage_sync_count"] = str(max(0, record.usage_sync_count + patch.usage_sync_delta))
|
| 298 |
+
|
| 299 |
+
# Tags.
|
| 300 |
+
tags = list(record.tags)
|
| 301 |
+
if patch.tags is not None:
|
| 302 |
+
tags = patch.tags
|
| 303 |
+
if patch.add_tags:
|
| 304 |
+
for t in patch.add_tags:
|
| 305 |
+
if t not in tags:
|
| 306 |
+
tags.append(t)
|
| 307 |
+
if patch.remove_tags:
|
| 308 |
+
tags = [t for t in tags if t not in patch.remove_tags]
|
| 309 |
+
updates["tags"] = json.dumps(tags)
|
| 310 |
+
|
| 311 |
+
# ext.
|
| 312 |
+
ext = dict(record.ext)
|
| 313 |
+
if patch.ext_merge:
|
| 314 |
+
ext.update(patch.ext_merge)
|
| 315 |
+
if patch.clear_failures:
|
| 316 |
+
for k in ("cooldown_until", "cooldown_reason", "disabled_at",
|
| 317 |
+
"disabled_reason", "expired_at", "expired_reason",
|
| 318 |
+
"forbidden_strikes", "console_429_count"):
|
| 319 |
+
ext.pop(k, None)
|
| 320 |
+
updates["status"] = AccountStatus.ACTIVE.value
|
| 321 |
+
updates["usage_fail_count"] = "0"
|
| 322 |
+
updates["last_fail_at"] = ""
|
| 323 |
+
updates["last_fail_reason"] = ""
|
| 324 |
+
updates["state_reason"] = ""
|
| 325 |
+
updates["ext"] = json.dumps(ext)
|
| 326 |
+
|
| 327 |
+
await self._r.hset(key, mapping=updates)
|
| 328 |
+
await self._r.zadd(_KEY_REV_LOG, {patch.token: rev})
|
| 329 |
+
count += 1
|
| 330 |
+
return AccountMutationResult(patched=count, revision=rev)
|
| 331 |
+
|
| 332 |
+
async def delete_accounts(
|
| 333 |
+
self,
|
| 334 |
+
tokens: list[str],
|
| 335 |
+
) -> AccountMutationResult:
|
| 336 |
+
if not tokens:
|
| 337 |
+
return AccountMutationResult()
|
| 338 |
+
rev = await self._bump_revision()
|
| 339 |
+
ts = now_ms()
|
| 340 |
+
count = 0
|
| 341 |
+
for token in tokens:
|
| 342 |
+
key = _record_key(token)
|
| 343 |
+
exists = await self._r.hget(key, "deleted_at")
|
| 344 |
+
if exists and exists not in (b"", b"None", None):
|
| 345 |
+
continue # Already deleted.
|
| 346 |
+
h = await self._r.hgetall(key)
|
| 347 |
+
if not h:
|
| 348 |
+
continue
|
| 349 |
+
pool = (h.get(b"pool") or h.get("pool") or b"basic")
|
| 350 |
+
if isinstance(pool, bytes):
|
| 351 |
+
pool = pool.decode()
|
| 352 |
+
await self._r.hset(key, mapping={
|
| 353 |
+
"deleted_at": str(ts),
|
| 354 |
+
"updated_at": str(ts),
|
| 355 |
+
"revision": str(rev),
|
| 356 |
+
})
|
| 357 |
+
await self._r.srem(_pool_key(pool), token)
|
| 358 |
+
await self._r.zadd(_KEY_REV_LOG, {token: rev})
|
| 359 |
+
count += 1
|
| 360 |
+
return AccountMutationResult(deleted=count, revision=rev)
|
| 361 |
+
|
| 362 |
+
async def get_accounts(
|
| 363 |
+
self,
|
| 364 |
+
tokens: list[str],
|
| 365 |
+
) -> list[AccountRecord]:
|
| 366 |
+
if not tokens:
|
| 367 |
+
return []
|
| 368 |
+
results: list[AccountRecord] = []
|
| 369 |
+
# Pipeline keeps batch maintenance from doing one network round trip per token.
|
| 370 |
+
async with self._r.pipeline() as pipe:
|
| 371 |
+
for token in tokens:
|
| 372 |
+
pipe.hgetall(_record_key(token))
|
| 373 |
+
hashes = await pipe.execute()
|
| 374 |
+
for token, h in zip(tokens, hashes, strict=True):
|
| 375 |
+
if h:
|
| 376 |
+
results.append(self._from_hash(token, h))
|
| 377 |
+
return results
|
| 378 |
+
|
| 379 |
+
async def list_accounts(
|
| 380 |
+
self,
|
| 381 |
+
query: ListAccountsQuery,
|
| 382 |
+
) -> AccountPage:
|
| 383 |
+
# Full scan — Redis is not optimised for filtered listing.
|
| 384 |
+
all_records: list[AccountRecord] = []
|
| 385 |
+
async for key in self._r.scan_iter("accounts:record:*"):
|
| 386 |
+
token = (key.decode() if isinstance(key, bytes) else key).split(":", 2)[-1]
|
| 387 |
+
h = await self._r.hgetall(key)
|
| 388 |
+
if not h:
|
| 389 |
+
continue
|
| 390 |
+
r = self._from_hash(token, h)
|
| 391 |
+
if not query.include_deleted and r.is_deleted():
|
| 392 |
+
continue
|
| 393 |
+
if query.pool and r.pool != query.pool:
|
| 394 |
+
continue
|
| 395 |
+
if query.status and r.status != query.status:
|
| 396 |
+
continue
|
| 397 |
+
all_records.append(r)
|
| 398 |
+
|
| 399 |
+
# Sort.
|
| 400 |
+
sort_key = query.sort_by
|
| 401 |
+
all_records.sort(
|
| 402 |
+
key=lambda r: getattr(r, sort_key, 0) or 0,
|
| 403 |
+
reverse=query.sort_desc,
|
| 404 |
+
)
|
| 405 |
+
total = len(all_records)
|
| 406 |
+
start = (query.page - 1) * query.page_size
|
| 407 |
+
items = all_records[start : start + query.page_size]
|
| 408 |
+
total_pages = max(1, (total + query.page_size - 1) // query.page_size)
|
| 409 |
+
rev = await self.get_revision()
|
| 410 |
+
return AccountPage(
|
| 411 |
+
items=items,
|
| 412 |
+
total=total,
|
| 413 |
+
page=query.page,
|
| 414 |
+
page_size=query.page_size,
|
| 415 |
+
total_pages=total_pages,
|
| 416 |
+
revision=rev,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
async def replace_pool(
|
| 420 |
+
self,
|
| 421 |
+
command: BulkReplacePoolCommand,
|
| 422 |
+
) -> AccountMutationResult:
|
| 423 |
+
existing = await self._r.smembers(_pool_key(command.pool))
|
| 424 |
+
tokens = [
|
| 425 |
+
(t.decode() if isinstance(t, bytes) else t) for t in existing
|
| 426 |
+
]
|
| 427 |
+
deleted_result = await self.delete_accounts(tokens)
|
| 428 |
+
upserted_result = await self.upsert_accounts(command.upserts)
|
| 429 |
+
return AccountMutationResult(
|
| 430 |
+
upserted=upserted_result.upserted,
|
| 431 |
+
deleted=deleted_result.deleted,
|
| 432 |
+
revision=upserted_result.revision,
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
async def reset_expired_console_windows(self) -> int:
|
| 436 |
+
"""Python 实现 console 窗口过期重置(Redis 无 SQL)。
|
| 437 |
+
|
| 438 |
+
与 SQL 后端 (local.py / sql.py) 语义一致:
|
| 439 |
+
1. 老条件:remaining<=0 且 (reset_at IS NULL 或已过期) → 配额耗尽恢复
|
| 440 |
+
2. 新条件 (M6):reset_at 已过期(即使 remaining>0)→ 异常数据归位
|
| 441 |
+
仅处理 status='active' 且未删除的账号。
|
| 442 |
+
"""
|
| 443 |
+
from ..quota_defaults import BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_WINDOW_SECONDS
|
| 444 |
+
|
| 445 |
+
now = now_ms()
|
| 446 |
+
reset_payload = {
|
| 447 |
+
"remaining": BASIC_CONSOLE_LIMIT,
|
| 448 |
+
"total": BASIC_CONSOLE_LIMIT,
|
| 449 |
+
"window_seconds": BASIC_CONSOLE_WINDOW_SECONDS,
|
| 450 |
+
"reset_at": None,
|
| 451 |
+
"synced_at": now,
|
| 452 |
+
"source": 0,
|
| 453 |
+
}
|
| 454 |
+
reset_json = json.dumps(reset_payload)
|
| 455 |
+
|
| 456 |
+
# 扫描所有账号 hash key
|
| 457 |
+
keys: list[str] = []
|
| 458 |
+
async for k in self._r.scan_iter("accounts:record:*"):
|
| 459 |
+
keys.append(k.decode() if isinstance(k, bytes) else k)
|
| 460 |
+
if not keys:
|
| 461 |
+
return 0
|
| 462 |
+
|
| 463 |
+
# 找出符合重置条件的账号
|
| 464 |
+
to_reset: list[str] = []
|
| 465 |
+
for key in keys:
|
| 466 |
+
h = await self._r.hgetall(key)
|
| 467 |
+
if not h:
|
| 468 |
+
continue
|
| 469 |
+
|
| 470 |
+
def _bget(k: str) -> str:
|
| 471 |
+
v = h.get(k) or h.get(k.encode())
|
| 472 |
+
return v.decode() if isinstance(v, bytes) else (v or "")
|
| 473 |
+
|
| 474 |
+
status = _bget("status")
|
| 475 |
+
deleted = _bget("deleted_at")
|
| 476 |
+
if status != "active" or deleted:
|
| 477 |
+
continue
|
| 478 |
+
qc_raw = _bget("quota_console")
|
| 479 |
+
if not qc_raw or qc_raw == "{}":
|
| 480 |
+
continue
|
| 481 |
+
try:
|
| 482 |
+
qc = json.loads(qc_raw)
|
| 483 |
+
except (ValueError, TypeError):
|
| 484 |
+
continue
|
| 485 |
+
remaining = int(qc.get("remaining") or 0)
|
| 486 |
+
reset_at = qc.get("reset_at")
|
| 487 |
+
reset_at_int = int(reset_at) if reset_at is not None else None
|
| 488 |
+
|
| 489 |
+
cond_old = remaining <= 0 and (reset_at_int is None or reset_at_int < now)
|
| 490 |
+
cond_new = reset_at_int is not None and reset_at_int < now
|
| 491 |
+
if cond_old or cond_new:
|
| 492 |
+
token = key.split(":", 2)[-1]
|
| 493 |
+
to_reset.append(token)
|
| 494 |
+
|
| 495 |
+
if not to_reset:
|
| 496 |
+
return 0
|
| 497 |
+
|
| 498 |
+
# 批量写入 + 记录 revision
|
| 499 |
+
rev = await self._bump_revision()
|
| 500 |
+
for token in to_reset:
|
| 501 |
+
await self._r.hset(_record_key(token), mapping={
|
| 502 |
+
"quota_console": reset_json,
|
| 503 |
+
"revision": str(rev),
|
| 504 |
+
"updated_at": str(now),
|
| 505 |
+
})
|
| 506 |
+
await self._r.zadd(_KEY_REV_LOG, {token: rev})
|
| 507 |
+
return len(to_reset)
|
| 508 |
+
|
| 509 |
+
async def recover_console_expired_accounts(self) -> int:
|
| 510 |
+
"""Auto-recover console 429 EXPIRED accounts with successful history.
|
| 511 |
+
|
| 512 |
+
Conditions:
|
| 513 |
+
- status = 'expired'
|
| 514 |
+
- state_reason = 'console_429_threshold_exceeded'
|
| 515 |
+
- usage_use_count > 5
|
| 516 |
+
- ext.expired_at <= now - 1 hour
|
| 517 |
+
"""
|
| 518 |
+
now = now_ms()
|
| 519 |
+
recovery_threshold = now - 3600 * 1000
|
| 520 |
+
|
| 521 |
+
# 扫描所有账号
|
| 522 |
+
keys: list[str] = []
|
| 523 |
+
async for k in self._r.scan_iter("accounts:record:*"):
|
| 524 |
+
keys.append(k.decode() if isinstance(k, bytes) else k)
|
| 525 |
+
if not keys:
|
| 526 |
+
return 0
|
| 527 |
+
|
| 528 |
+
to_recover: list[tuple[str, dict]] = []
|
| 529 |
+
for key in keys:
|
| 530 |
+
h = await self._r.hgetall(key)
|
| 531 |
+
if not h:
|
| 532 |
+
continue
|
| 533 |
+
|
| 534 |
+
def _bget(k: str) -> str:
|
| 535 |
+
v = h.get(k) or h.get(k.encode())
|
| 536 |
+
return v.decode() if isinstance(v, bytes) else (v or "")
|
| 537 |
+
|
| 538 |
+
status = _bget("status")
|
| 539 |
+
deleted = _bget("deleted_at")
|
| 540 |
+
state_reason = _bget("state_reason")
|
| 541 |
+
if (
|
| 542 |
+
status != "expired"
|
| 543 |
+
or deleted
|
| 544 |
+
or state_reason != "console_429_threshold_exceeded"
|
| 545 |
+
):
|
| 546 |
+
continue
|
| 547 |
+
try:
|
| 548 |
+
use_count = int(_bget("usage_use_count") or 0)
|
| 549 |
+
except (ValueError, TypeError):
|
| 550 |
+
continue
|
| 551 |
+
if use_count <= 5:
|
| 552 |
+
continue
|
| 553 |
+
ext_raw = _bget("ext")
|
| 554 |
+
try:
|
| 555 |
+
ext = json.loads(ext_raw) if ext_raw else {}
|
| 556 |
+
except (ValueError, TypeError):
|
| 557 |
+
ext = {}
|
| 558 |
+
expired_at = ext.get("expired_at")
|
| 559 |
+
if expired_at is None:
|
| 560 |
+
continue
|
| 561 |
+
try:
|
| 562 |
+
expired_at_int = int(expired_at)
|
| 563 |
+
except (ValueError, TypeError):
|
| 564 |
+
continue
|
| 565 |
+
if expired_at_int > recovery_threshold:
|
| 566 |
+
continue
|
| 567 |
+
# 清理 EXPIRED 相关字段
|
| 568 |
+
for k in ("expired_at", "expired_reason",
|
| 569 |
+
"console_429_count", "console_429_last_at"):
|
| 570 |
+
ext.pop(k, None)
|
| 571 |
+
token = key.split(":", 2)[-1]
|
| 572 |
+
to_recover.append((token, ext))
|
| 573 |
+
|
| 574 |
+
if not to_recover:
|
| 575 |
+
return 0
|
| 576 |
+
|
| 577 |
+
rev = await self._bump_revision()
|
| 578 |
+
for token, ext in to_recover:
|
| 579 |
+
await self._r.hset(_record_key(token), mapping={
|
| 580 |
+
"status": "active",
|
| 581 |
+
"state_reason": "",
|
| 582 |
+
"ext": json.dumps(ext),
|
| 583 |
+
"revision": str(rev),
|
| 584 |
+
"updated_at": str(now),
|
| 585 |
+
})
|
| 586 |
+
await self._r.zadd(_KEY_REV_LOG, {token: rev})
|
| 587 |
+
return len(to_recover)
|
| 588 |
+
|
| 589 |
+
async def close(self) -> None:
|
| 590 |
+
"""Close the underlying Redis connection pool."""
|
| 591 |
+
await self._r.aclose()
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
__all__ = ["RedisAccountRepository"]
|
app/control/account/backends/sql.py
ADDED
|
@@ -0,0 +1,1094 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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emy-based backend for MySQL and PostgreSQL.
|
| 2 |
+
|
| 3 |
+
Both dialects share the same table schema and query logic;
|
| 4 |
+
only the DDL fragments and upsert syntax differ.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import ssl
|
| 10 |
+
from threading import Lock
|
| 11 |
+
from typing import Any
|
| 12 |
+
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
|
| 13 |
+
|
| 14 |
+
import asyncio
|
| 15 |
+
|
| 16 |
+
import sqlalchemy as sa
|
| 17 |
+
from sqlalchemy.ext.asyncio import AsyncEngine, async_sessionmaker, create_async_engine
|
| 18 |
+
|
| 19 |
+
from app.platform.runtime.clock import now_ms
|
| 20 |
+
from ..commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery
|
| 21 |
+
from ..enums import AccountStatus
|
| 22 |
+
from ..models import (
|
| 23 |
+
AccountChangeSet,
|
| 24 |
+
AccountMutationResult,
|
| 25 |
+
AccountPage,
|
| 26 |
+
AccountRecord,
|
| 27 |
+
RuntimeSnapshot,
|
| 28 |
+
)
|
| 29 |
+
from ..quota_defaults import default_quota_set, BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_WINDOW_SECONDS
|
| 30 |
+
|
| 31 |
+
_TBL_ACCOUNTS = "accounts"
|
| 32 |
+
_TBL_META = "account_meta"
|
| 33 |
+
|
| 34 |
+
metadata = sa.MetaData()
|
| 35 |
+
|
| 36 |
+
accounts_table = sa.Table(
|
| 37 |
+
_TBL_ACCOUNTS,
|
| 38 |
+
metadata,
|
| 39 |
+
sa.Column("token", sa.String(512), primary_key=True),
|
| 40 |
+
sa.Column("pool", sa.Text, nullable=False, default="basic"),
|
| 41 |
+
sa.Column("status", sa.Text, nullable=False, default="active"),
|
| 42 |
+
sa.Column("created_at", sa.BigInteger, nullable=False),
|
| 43 |
+
sa.Column("updated_at", sa.BigInteger, nullable=False),
|
| 44 |
+
sa.Column("tags", sa.Text, nullable=False, default="[]"),
|
| 45 |
+
sa.Column("quota_auto", sa.Text, nullable=False, default="{}"),
|
| 46 |
+
sa.Column("quota_fast", sa.Text, nullable=False, default="{}"),
|
| 47 |
+
sa.Column("quota_expert", sa.Text, nullable=False, default="{}"),
|
| 48 |
+
sa.Column("quota_heavy", sa.Text, nullable=False, default="{}"),
|
| 49 |
+
sa.Column("quota_grok_4_3", sa.Text, nullable=False, default="{}"),
|
| 50 |
+
sa.Column("quota_console", sa.Text, nullable=False, default="{}"),
|
| 51 |
+
sa.Column("usage_use_count", sa.Integer, nullable=False, default=0),
|
| 52 |
+
sa.Column("usage_fail_count", sa.Integer, nullable=False, default=0),
|
| 53 |
+
sa.Column("usage_sync_count", sa.Integer, nullable=False, default=0),
|
| 54 |
+
sa.Column("last_use_at", sa.BigInteger),
|
| 55 |
+
sa.Column("last_fail_at", sa.BigInteger),
|
| 56 |
+
sa.Column("last_fail_reason", sa.Text),
|
| 57 |
+
sa.Column("last_sync_at", sa.BigInteger),
|
| 58 |
+
sa.Column("last_clear_at", sa.BigInteger),
|
| 59 |
+
sa.Column("state_reason", sa.Text),
|
| 60 |
+
sa.Column("deleted_at", sa.BigInteger),
|
| 61 |
+
sa.Column("ext", sa.Text, nullable=False, default="{}"),
|
| 62 |
+
sa.Column("revision", sa.BigInteger, nullable=False, default=0),
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
meta_table = sa.Table(
|
| 66 |
+
_TBL_META,
|
| 67 |
+
metadata,
|
| 68 |
+
sa.Column("key", sa.String(128), primary_key=True),
|
| 69 |
+
sa.Column("value", sa.Text, nullable=False),
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
_SQL_SSL_MODE_PARAM_KEYS = ("sslmode", "ssl-mode", "ssl")
|
| 73 |
+
_PG_SSL_CERT_PARAM_KEYS = ("sslrootcert", "sslcert", "sslkey")
|
| 74 |
+
_PG_SSL_UNSUPPORTED_PARAM_KEYS = (
|
| 75 |
+
"sslcrl",
|
| 76 |
+
"sslpassword",
|
| 77 |
+
"sslnegotiation",
|
| 78 |
+
"ssl_min_protocol_version",
|
| 79 |
+
"ssl_max_protocol_version",
|
| 80 |
+
)
|
| 81 |
+
_PG_SSL_QUERY_PARAM_KEYS = (
|
| 82 |
+
*_SQL_SSL_MODE_PARAM_KEYS,
|
| 83 |
+
*_PG_SSL_CERT_PARAM_KEYS,
|
| 84 |
+
*_PG_SSL_UNSUPPORTED_PARAM_KEYS,
|
| 85 |
+
)
|
| 86 |
+
_MYSQL_SSL_CERT_PARAM_KEYS = ("ssl-ca", "ssl-capath", "ssl-cert", "ssl-key")
|
| 87 |
+
_MYSQL_SSL_OPTIONAL_PARAM_KEYS = ("ssl-check-hostname", "ssl-cipher")
|
| 88 |
+
_MYSQL_SSL_QUERY_PARAM_KEYS = (
|
| 89 |
+
*_SQL_SSL_MODE_PARAM_KEYS,
|
| 90 |
+
*_MYSQL_SSL_CERT_PARAM_KEYS,
|
| 91 |
+
*_MYSQL_SSL_OPTIONAL_PARAM_KEYS,
|
| 92 |
+
)
|
| 93 |
+
_SSL_BOOL_TRUE = {"1", "true", "yes", "on"}
|
| 94 |
+
_SSL_BOOL_FALSE = {"0", "false", "no", "off"}
|
| 95 |
+
|
| 96 |
+
_PG_SSL_MODE_ALIASES: dict[str, str] = {
|
| 97 |
+
"disable": "disable",
|
| 98 |
+
"disabled": "disable",
|
| 99 |
+
"false": "disable",
|
| 100 |
+
"0": "disable",
|
| 101 |
+
"no": "disable",
|
| 102 |
+
"off": "disable",
|
| 103 |
+
"prefer": "prefer",
|
| 104 |
+
"preferred": "prefer",
|
| 105 |
+
"allow": "allow",
|
| 106 |
+
"require": "require",
|
| 107 |
+
"required": "require",
|
| 108 |
+
"true": "require",
|
| 109 |
+
"1": "require",
|
| 110 |
+
"yes": "require",
|
| 111 |
+
"on": "require",
|
| 112 |
+
"verify-ca": "verify-ca",
|
| 113 |
+
"verify_ca": "verify-ca",
|
| 114 |
+
"verify-full": "verify-full",
|
| 115 |
+
"verify_full": "verify-full",
|
| 116 |
+
"verify-identity": "verify-full",
|
| 117 |
+
"verify_identity": "verify-full",
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
_MYSQL_SSL_MODE_ALIASES: dict[str, str] = {
|
| 121 |
+
"disable": "disabled",
|
| 122 |
+
"disabled": "disabled",
|
| 123 |
+
"false": "disabled",
|
| 124 |
+
"0": "disabled",
|
| 125 |
+
"no": "disabled",
|
| 126 |
+
"off": "disabled",
|
| 127 |
+
"prefer": "preferred",
|
| 128 |
+
"preferred": "preferred",
|
| 129 |
+
"allow": "preferred",
|
| 130 |
+
"require": "required",
|
| 131 |
+
"required": "required",
|
| 132 |
+
"true": "required",
|
| 133 |
+
"1": "required",
|
| 134 |
+
"yes": "required",
|
| 135 |
+
"on": "required",
|
| 136 |
+
"verify-ca": "verify_ca",
|
| 137 |
+
"verify_ca": "verify_ca",
|
| 138 |
+
"verify-full": "verify_identity",
|
| 139 |
+
"verify_full": "verify_identity",
|
| 140 |
+
"verify-identity": "verify_identity",
|
| 141 |
+
"verify_identity": "verify_identity",
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
_ENGINE_CACHE_LOCK = Lock()
|
| 145 |
+
_ENGINE_CACHE: dict[tuple[str, str, str], AsyncEngine] = {}
|
| 146 |
+
_ENGINE_KEYS_BY_ID: dict[int, set[tuple[str, str, str]]] = {}
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _normalize_sql_url(dialect: str, url: str) -> str:
|
| 150 |
+
"""Rewrite SQL URLs to the async SQLAlchemy dialect form."""
|
| 151 |
+
if not url or "://" not in url:
|
| 152 |
+
return url
|
| 153 |
+
if dialect == "mysql":
|
| 154 |
+
if url.startswith("mysql://"):
|
| 155 |
+
return f"mysql+aiomysql://{url[len('mysql://') :]}"
|
| 156 |
+
if url.startswith("mariadb://"):
|
| 157 |
+
return f"mysql+aiomysql://{url[len('mariadb://') :]}"
|
| 158 |
+
if url.startswith("mariadb+aiomysql://"):
|
| 159 |
+
return f"mysql+aiomysql://{url[len('mariadb+aiomysql://') :]}"
|
| 160 |
+
return url
|
| 161 |
+
if url.startswith("postgres://"):
|
| 162 |
+
return f"postgresql+asyncpg://{url[len('postgres://') :]}"
|
| 163 |
+
if url.startswith("postgresql://"):
|
| 164 |
+
return f"postgresql+asyncpg://{url[len('postgresql://') :]}"
|
| 165 |
+
if url.startswith("pgsql://"):
|
| 166 |
+
return f"postgresql+asyncpg://{url[len('pgsql://') :]}"
|
| 167 |
+
return url
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _get_env_int(name: str, default: int, *, minimum: int = 0) -> int:
|
| 171 |
+
raw = os.getenv(name, "").strip()
|
| 172 |
+
if not raw:
|
| 173 |
+
return default
|
| 174 |
+
try:
|
| 175 |
+
return max(minimum, int(raw))
|
| 176 |
+
except ValueError:
|
| 177 |
+
return default
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _normalize_ssl_mode(dialect: str, raw_mode: str) -> str:
|
| 181 |
+
if not raw_mode:
|
| 182 |
+
raise ValueError("SSL mode cannot be empty")
|
| 183 |
+
|
| 184 |
+
mode = raw_mode.strip().lower().replace(" ", "")
|
| 185 |
+
if dialect == "mysql":
|
| 186 |
+
canonical = _MYSQL_SSL_MODE_ALIASES.get(mode)
|
| 187 |
+
else:
|
| 188 |
+
canonical = _PG_SSL_MODE_ALIASES.get(mode)
|
| 189 |
+
if not canonical:
|
| 190 |
+
raise ValueError(f"Unsupported SSL mode {raw_mode!r} for SQL dialect {dialect!r}")
|
| 191 |
+
return canonical
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def _has_ssl_options(options: dict[str, str], keys: tuple[str, ...]) -> bool:
|
| 195 |
+
return any(options.get(key) for key in keys)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _parse_ssl_bool(name: str, raw_value: str | None) -> bool | None:
|
| 199 |
+
if raw_value is None:
|
| 200 |
+
return None
|
| 201 |
+
|
| 202 |
+
value = raw_value.strip().lower()
|
| 203 |
+
if not value:
|
| 204 |
+
return None
|
| 205 |
+
if value in _SSL_BOOL_TRUE:
|
| 206 |
+
return True
|
| 207 |
+
if value in _SSL_BOOL_FALSE:
|
| 208 |
+
return False
|
| 209 |
+
raise ValueError(f"Unsupported boolean value {raw_value!r} for SQL SSL option {name!r}")
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _extract_sql_ssl_options(
|
| 213 |
+
dialect: str,
|
| 214 |
+
url: str,
|
| 215 |
+
) -> tuple[str, dict[str, str]]:
|
| 216 |
+
parsed = urlparse(url)
|
| 217 |
+
ssl_query_keys = _PG_SSL_QUERY_PARAM_KEYS if dialect == "postgresql" else _MYSQL_SSL_QUERY_PARAM_KEYS
|
| 218 |
+
ssl_options: dict[str, str] = {}
|
| 219 |
+
filtered_query_items: list[tuple[str, str]] = []
|
| 220 |
+
ssl_param_keys = {key.lower() for key in ssl_query_keys}
|
| 221 |
+
for key, value in parse_qsl(parsed.query, keep_blank_values=True):
|
| 222 |
+
key_lower = key.lower()
|
| 223 |
+
if key_lower in ssl_param_keys:
|
| 224 |
+
normalized_value = value.strip()
|
| 225 |
+
if key_lower not in ssl_options:
|
| 226 |
+
ssl_options[key_lower] = normalized_value
|
| 227 |
+
continue
|
| 228 |
+
filtered_query_items.append((key, value))
|
| 229 |
+
|
| 230 |
+
cleaned_url = urlunparse(
|
| 231 |
+
parsed._replace(query=urlencode(filtered_query_items, doseq=True))
|
| 232 |
+
)
|
| 233 |
+
return cleaned_url, ssl_options
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _resolve_ssl_mode(dialect: str, ssl_options: dict[str, str]) -> str | None:
|
| 237 |
+
raw_ssl_mode = next(
|
| 238 |
+
(ssl_options.get(key) for key in _SQL_SSL_MODE_PARAM_KEYS if ssl_options.get(key)),
|
| 239 |
+
None,
|
| 240 |
+
)
|
| 241 |
+
if raw_ssl_mode:
|
| 242 |
+
return _normalize_ssl_mode(dialect, raw_ssl_mode)
|
| 243 |
+
|
| 244 |
+
if ssl_options:
|
| 245 |
+
if dialect == "postgresql":
|
| 246 |
+
raise ValueError("PostgreSQL SSL URL parameters require sslmode to be set explicitly")
|
| 247 |
+
raise ValueError("MySQL SSL URL parameters require ssl-mode to be set explicitly")
|
| 248 |
+
return None
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def _validate_pg_ssl_options(mode: str | None, ssl_options: dict[str, str]) -> None:
|
| 252 |
+
unsupported = [
|
| 253 |
+
key for key in _PG_SSL_UNSUPPORTED_PARAM_KEYS
|
| 254 |
+
if ssl_options.get(key)
|
| 255 |
+
]
|
| 256 |
+
if unsupported:
|
| 257 |
+
joined = ", ".join(sorted(unsupported))
|
| 258 |
+
raise ValueError(f"Unsupported PostgreSQL SSL URL parameter(s): {joined}")
|
| 259 |
+
if mode == "disable" and _has_ssl_options(ssl_options, _PG_SSL_CERT_PARAM_KEYS):
|
| 260 |
+
raise ValueError("PostgreSQL SSL certificate parameters cannot be used with sslmode=disable")
|
| 261 |
+
if mode in {"allow", "prefer"} and _has_ssl_options(ssl_options, _PG_SSL_CERT_PARAM_KEYS):
|
| 262 |
+
raise ValueError("PostgreSQL sslmode=allow/prefer is not supported with certificate URL parameters")
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _build_pg_ssl_context(mode: str, ssl_options: dict[str, str]) -> ssl.SSLContext:
|
| 266 |
+
sslrootcert = ssl_options.get("sslrootcert") or None
|
| 267 |
+
sslcert = ssl_options.get("sslcert") or None
|
| 268 |
+
sslkey = ssl_options.get("sslkey") or None
|
| 269 |
+
|
| 270 |
+
ctx = ssl.create_default_context(cafile=sslrootcert)
|
| 271 |
+
if mode == "require":
|
| 272 |
+
ctx.check_hostname = False
|
| 273 |
+
if not sslrootcert:
|
| 274 |
+
ctx.verify_mode = ssl.CERT_NONE
|
| 275 |
+
elif mode == "verify-ca":
|
| 276 |
+
ctx.check_hostname = False
|
| 277 |
+
else:
|
| 278 |
+
ctx.check_hostname = True
|
| 279 |
+
|
| 280 |
+
if sslcert:
|
| 281 |
+
ctx.load_cert_chain(certfile=sslcert, keyfile=sslkey or None)
|
| 282 |
+
elif sslkey:
|
| 283 |
+
raise ValueError("PostgreSQL sslkey requires sslcert")
|
| 284 |
+
return ctx
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _build_mysql_ssl_context(mode: str, ssl_options: dict[str, str]) -> ssl.SSLContext | None:
|
| 288 |
+
if mode == "disabled":
|
| 289 |
+
if _has_ssl_options(ssl_options, _MYSQL_SSL_CERT_PARAM_KEYS):
|
| 290 |
+
raise ValueError("MySQL SSL certificate parameters cannot be used with ssl-mode=disabled")
|
| 291 |
+
return None
|
| 292 |
+
if mode == "preferred":
|
| 293 |
+
raise ValueError("MySQL ssl-mode=allow/prefer is not supported by aiomysql")
|
| 294 |
+
|
| 295 |
+
ssl_ca = ssl_options.get("ssl-ca") or None
|
| 296 |
+
ssl_capath = ssl_options.get("ssl-capath") or None
|
| 297 |
+
ssl_cert = ssl_options.get("ssl-cert") or None
|
| 298 |
+
ssl_key = ssl_options.get("ssl-key") or None
|
| 299 |
+
ssl_check_hostname = _parse_ssl_bool("ssl-check-hostname", ssl_options.get("ssl-check-hostname"))
|
| 300 |
+
ssl_cipher = ssl_options.get("ssl-cipher") or None
|
| 301 |
+
|
| 302 |
+
ctx = ssl.create_default_context(cafile=ssl_ca, capath=ssl_capath)
|
| 303 |
+
if mode in ("preferred", "required"):
|
| 304 |
+
ctx.check_hostname = False
|
| 305 |
+
ctx.verify_mode = ssl.CERT_NONE
|
| 306 |
+
elif mode == "verify_ca":
|
| 307 |
+
ctx.check_hostname = False
|
| 308 |
+
else:
|
| 309 |
+
ctx.check_hostname = True
|
| 310 |
+
|
| 311 |
+
if ssl_check_hostname is not None:
|
| 312 |
+
if mode == "required" and ssl_check_hostname:
|
| 313 |
+
raise ValueError("MySQL ssl-check-hostname=true requires ssl-mode=verify_identity")
|
| 314 |
+
ctx.check_hostname = ssl_check_hostname
|
| 315 |
+
if ssl_cipher:
|
| 316 |
+
ctx.set_ciphers(ssl_cipher)
|
| 317 |
+
if ssl_cert:
|
| 318 |
+
ctx.load_cert_chain(certfile=ssl_cert, keyfile=ssl_key or None)
|
| 319 |
+
elif ssl_key:
|
| 320 |
+
raise ValueError("MySQL ssl-key requires ssl-cert")
|
| 321 |
+
return ctx
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _build_sql_connect_args(
|
| 325 |
+
dialect: str,
|
| 326 |
+
ssl_options: dict[str, str],
|
| 327 |
+
) -> dict[str, Any] | None:
|
| 328 |
+
mode = _resolve_ssl_mode(dialect, ssl_options)
|
| 329 |
+
if not mode:
|
| 330 |
+
return None
|
| 331 |
+
|
| 332 |
+
if dialect == "mysql":
|
| 333 |
+
ctx = _build_mysql_ssl_context(mode, ssl_options)
|
| 334 |
+
return {"ssl": ctx} if ctx is not None else None
|
| 335 |
+
|
| 336 |
+
_validate_pg_ssl_options(mode, ssl_options)
|
| 337 |
+
if mode == "disable":
|
| 338 |
+
return None
|
| 339 |
+
# asyncpg does not accept ssl= as a plain string (e.g. "require").
|
| 340 |
+
# Always build a proper ssl.SSLContext so the driver can use it directly.
|
| 341 |
+
return {"ssl": _build_pg_ssl_context(mode, ssl_options)}
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def _prepare_sql_url_and_connect_args(
|
| 345 |
+
dialect: str,
|
| 346 |
+
url: str,
|
| 347 |
+
) -> tuple[str, dict[str, Any] | None]:
|
| 348 |
+
"""Strip SSL query params from the URL and translate them to connect_args."""
|
| 349 |
+
normalized_url = _normalize_sql_url(dialect, url)
|
| 350 |
+
if "://" not in normalized_url:
|
| 351 |
+
return normalized_url, None
|
| 352 |
+
|
| 353 |
+
cleaned_url, ssl_options = _extract_sql_ssl_options(dialect, normalized_url)
|
| 354 |
+
return cleaned_url, _build_sql_connect_args(dialect, ssl_options)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def _is_serverless() -> bool:
|
| 358 |
+
"""Detect common serverless environments (Vercel, AWS Lambda, etc.)."""
|
| 359 |
+
return bool(
|
| 360 |
+
os.getenv("VERCEL")
|
| 361 |
+
or os.getenv("AWS_LAMBDA_FUNCTION_NAME")
|
| 362 |
+
or os.getenv("FUNCTIONS_WORKER_RUNTIME") # Azure Functions
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _sql_engine_kwargs(connect_args: dict[str, Any] | None) -> dict[str, Any]:
|
| 367 |
+
# In serverless environments each function instance is short-lived and may
|
| 368 |
+
# run concurrently. Keep pools small to avoid exhausting DB connections.
|
| 369 |
+
serverless = _is_serverless()
|
| 370 |
+
kwargs: dict[str, Any] = {
|
| 371 |
+
"pool_size": _get_env_int("ACCOUNT_SQL_POOL_SIZE", 1 if serverless else 5, minimum=1),
|
| 372 |
+
"max_overflow": _get_env_int("ACCOUNT_SQL_MAX_OVERFLOW", 2 if serverless else 10, minimum=0),
|
| 373 |
+
"pool_timeout": _get_env_int("ACCOUNT_SQL_POOL_TIMEOUT", 30, minimum=1),
|
| 374 |
+
"pool_recycle": _get_env_int("ACCOUNT_SQL_POOL_RECYCLE", 1800, minimum=0),
|
| 375 |
+
"pool_pre_ping": True,
|
| 376 |
+
"pool_use_lifo": True,
|
| 377 |
+
}
|
| 378 |
+
if connect_args:
|
| 379 |
+
kwargs["connect_args"] = connect_args
|
| 380 |
+
return kwargs
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _get_or_create_engine(
|
| 384 |
+
cache_key: tuple[str, str, str],
|
| 385 |
+
normalized_url: str,
|
| 386 |
+
connect_args: dict[str, Any] | None,
|
| 387 |
+
) -> AsyncEngine:
|
| 388 |
+
with _ENGINE_CACHE_LOCK:
|
| 389 |
+
engine = _ENGINE_CACHE.get(cache_key)
|
| 390 |
+
if engine is not None:
|
| 391 |
+
return engine
|
| 392 |
+
|
| 393 |
+
engine = create_async_engine(normalized_url, **_sql_engine_kwargs(connect_args))
|
| 394 |
+
_ENGINE_CACHE[cache_key] = engine
|
| 395 |
+
_ENGINE_KEYS_BY_ID.setdefault(id(engine), set()).add(cache_key)
|
| 396 |
+
return engine
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def _evict_cached_engine(engine: AsyncEngine) -> None:
|
| 400 |
+
with _ENGINE_CACHE_LOCK:
|
| 401 |
+
for key in _ENGINE_KEYS_BY_ID.pop(id(engine), set()):
|
| 402 |
+
if _ENGINE_CACHE.get(key) is engine:
|
| 403 |
+
_ENGINE_CACHE.pop(key, None)
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def _row_to_record(row: Any) -> AccountRecord:
|
| 407 |
+
d = dict(row._mapping)
|
| 408 |
+
d["tags"] = json.loads(d.get("tags") or "[]")
|
| 409 |
+
heavy_raw = d.pop("quota_heavy", "{}") or "{}"
|
| 410 |
+
grok_4_3_raw = d.pop("quota_grok_4_3", "{}") or "{}"
|
| 411 |
+
console_raw = d.pop("quota_console", "{}") or "{}"
|
| 412 |
+
heavy_dict = json.loads(heavy_raw)
|
| 413 |
+
grok_4_3_dict = json.loads(grok_4_3_raw)
|
| 414 |
+
console_dict = json.loads(console_raw)
|
| 415 |
+
d["quota"] = {
|
| 416 |
+
"auto": json.loads(d.pop("quota_auto", "{}") or "{}"),
|
| 417 |
+
"fast": json.loads(d.pop("quota_fast", "{}") or "{}"),
|
| 418 |
+
"expert": json.loads(d.pop("quota_expert", "{}") or "{}"),
|
| 419 |
+
**({"heavy": heavy_dict} if heavy_dict else {}),
|
| 420 |
+
**({"grok_4_3": grok_4_3_dict} if grok_4_3_dict else {}),
|
| 421 |
+
**({"console": console_dict} if console_dict else {}),
|
| 422 |
+
}
|
| 423 |
+
d["ext"] = json.loads(d.get("ext") or "{}")
|
| 424 |
+
return AccountRecord.model_validate(d)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class SqlAccountRepository:
|
| 428 |
+
"""Async SQLAlchemy-based repository for MySQL / PostgreSQL."""
|
| 429 |
+
|
| 430 |
+
def __init__(
|
| 431 |
+
self,
|
| 432 |
+
engine: AsyncEngine,
|
| 433 |
+
*,
|
| 434 |
+
dialect: str = "mysql",
|
| 435 |
+
dispose_engine: bool = True,
|
| 436 |
+
) -> None:
|
| 437 |
+
self._engine = engine
|
| 438 |
+
self._dialect = dialect # "mysql" | "postgresql"
|
| 439 |
+
self._session = async_sessionmaker(engine, expire_on_commit=False)
|
| 440 |
+
self._dispose_engine = dispose_engine
|
| 441 |
+
self._initialized = False
|
| 442 |
+
self._init_lock = asyncio.Lock()
|
| 443 |
+
|
| 444 |
+
# ------------------------------------------------------------------
|
| 445 |
+
# Revision helpers (run inside a transaction)
|
| 446 |
+
# ------------------------------------------------------------------
|
| 447 |
+
|
| 448 |
+
async def _bump_revision(self, conn: Any) -> int:
|
| 449 |
+
await conn.execute(
|
| 450 |
+
meta_table.update()
|
| 451 |
+
.where(meta_table.c.key == "revision")
|
| 452 |
+
.values(value=sa.cast(
|
| 453 |
+
sa.cast(meta_table.c.value, sa.BigInteger) + 1, sa.Text
|
| 454 |
+
))
|
| 455 |
+
)
|
| 456 |
+
row = await conn.execute(
|
| 457 |
+
sa.select(meta_table.c.value).where(meta_table.c.key == "revision")
|
| 458 |
+
)
|
| 459 |
+
return int(row.scalar())
|
| 460 |
+
|
| 461 |
+
async def _get_revision(self, conn: Any) -> int:
|
| 462 |
+
row = await conn.execute(
|
| 463 |
+
sa.select(meta_table.c.value).where(meta_table.c.key == "revision")
|
| 464 |
+
)
|
| 465 |
+
v = row.scalar()
|
| 466 |
+
return int(v) if v else 0
|
| 467 |
+
|
| 468 |
+
# ------------------------------------------------------------------
|
| 469 |
+
# Upsert — dialect-specific
|
| 470 |
+
# ------------------------------------------------------------------
|
| 471 |
+
|
| 472 |
+
def _build_upsert(self, row: dict[str, Any]):
|
| 473 |
+
if self._dialect == "postgresql":
|
| 474 |
+
from sqlalchemy.dialects.postgresql import insert
|
| 475 |
+
stmt = insert(accounts_table).values(**row)
|
| 476 |
+
# On conflict, update all columns except token and created_at.
|
| 477 |
+
update_cols = {k: stmt.excluded[k] for k in row if k not in ("token", "created_at")}
|
| 478 |
+
return stmt.on_conflict_do_update(index_elements=["token"], set_=update_cols)
|
| 479 |
+
else:
|
| 480 |
+
# MySQL
|
| 481 |
+
from sqlalchemy.dialects.mysql import insert
|
| 482 |
+
stmt = insert(accounts_table).values(**row)
|
| 483 |
+
update_cols = {k: stmt.inserted[k] for k in row if k not in ("token", "created_at")}
|
| 484 |
+
return stmt.on_duplicate_key_update(**update_cols)
|
| 485 |
+
|
| 486 |
+
# ------------------------------------------------------------------
|
| 487 |
+
# Public API
|
| 488 |
+
# ------------------------------------------------------------------
|
| 489 |
+
|
| 490 |
+
async def _ensure_initialized(self) -> None:
|
| 491 |
+
"""Idempotent: create tables + seed revision row if not already done.
|
| 492 |
+
|
| 493 |
+
Safe to call on every request — short-circuits after first success so
|
| 494 |
+
repeated calls cost only an asyncio lock check. This allows the
|
| 495 |
+
repository to self-initialise even when the ASGI lifespan is not
|
| 496 |
+
executed (e.g. Vercel serverless cold-starts).
|
| 497 |
+
"""
|
| 498 |
+
if self._initialized:
|
| 499 |
+
return
|
| 500 |
+
async with self._init_lock:
|
| 501 |
+
if self._initialized:
|
| 502 |
+
return
|
| 503 |
+
await self._do_initialize()
|
| 504 |
+
self._initialized = True
|
| 505 |
+
|
| 506 |
+
async def _do_initialize(self) -> None:
|
| 507 |
+
async with self._engine.begin() as conn:
|
| 508 |
+
await conn.run_sync(metadata.create_all)
|
| 509 |
+
await self._ensure_columns(conn)
|
| 510 |
+
# Seed revision row.
|
| 511 |
+
if self._dialect == "postgresql":
|
| 512 |
+
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
| 513 |
+
await conn.execute(
|
| 514 |
+
pg_insert(meta_table)
|
| 515 |
+
.values(key="revision", value="0")
|
| 516 |
+
.on_conflict_do_nothing()
|
| 517 |
+
)
|
| 518 |
+
else:
|
| 519 |
+
from sqlalchemy.dialects.mysql import insert as my_insert
|
| 520 |
+
await conn.execute(
|
| 521 |
+
my_insert(meta_table)
|
| 522 |
+
.values(key="revision", value="0")
|
| 523 |
+
.on_duplicate_key_update(value="0")
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
async def _ensure_columns(self, conn: Any) -> None:
|
| 527 |
+
"""Idempotent ALTER TABLE migrations for columns added after the initial schema."""
|
| 528 |
+
existing = await self._table_columns(conn, _TBL_ACCOUNTS)
|
| 529 |
+
if "quota_grok_4_3" not in existing:
|
| 530 |
+
if self._dialect == "mysql":
|
| 531 |
+
await conn.exec_driver_sql(
|
| 532 |
+
f"ALTER TABLE {_TBL_ACCOUNTS} "
|
| 533 |
+
f"ADD COLUMN quota_grok_4_3 TEXT"
|
| 534 |
+
)
|
| 535 |
+
await conn.exec_driver_sql(
|
| 536 |
+
f"UPDATE {_TBL_ACCOUNTS} "
|
| 537 |
+
f"SET quota_grok_4_3 = '{{}}' "
|
| 538 |
+
f"WHERE quota_grok_4_3 IS NULL"
|
| 539 |
+
)
|
| 540 |
+
await conn.exec_driver_sql(
|
| 541 |
+
f"ALTER TABLE {_TBL_ACCOUNTS} "
|
| 542 |
+
f"MODIFY COLUMN quota_grok_4_3 TEXT NOT NULL"
|
| 543 |
+
)
|
| 544 |
+
else:
|
| 545 |
+
await conn.exec_driver_sql(
|
| 546 |
+
f"ALTER TABLE {_TBL_ACCOUNTS} "
|
| 547 |
+
f"ADD COLUMN quota_grok_4_3 TEXT NOT NULL DEFAULT '{{}}'"
|
| 548 |
+
)
|
| 549 |
+
if "quota_console" not in existing:
|
| 550 |
+
if self._dialect == "mysql":
|
| 551 |
+
await conn.exec_driver_sql(
|
| 552 |
+
f"ALTER TABLE {_TBL_ACCOUNTS} "
|
| 553 |
+
f"ADD COLUMN quota_console TEXT"
|
| 554 |
+
)
|
| 555 |
+
await conn.exec_driver_sql(
|
| 556 |
+
f"UPDATE {_TBL_ACCOUNTS} "
|
| 557 |
+
f"SET quota_console = '{{}}' "
|
| 558 |
+
f"WHERE quota_console IS NULL"
|
| 559 |
+
)
|
| 560 |
+
await conn.exec_driver_sql(
|
| 561 |
+
f"ALTER TABLE {_TBL_ACCOUNTS} "
|
| 562 |
+
f"MODIFY COLUMN quota_console TEXT NOT NULL"
|
| 563 |
+
)
|
| 564 |
+
else:
|
| 565 |
+
await conn.exec_driver_sql(
|
| 566 |
+
f"ALTER TABLE {_TBL_ACCOUNTS} "
|
| 567 |
+
f"ADD COLUMN quota_console TEXT NOT NULL DEFAULT '{{}}'"
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
async def _table_columns(self, conn: Any, table: str) -> set[str]:
|
| 571 |
+
if self._dialect == "postgresql":
|
| 572 |
+
rows = await conn.execute(
|
| 573 |
+
sa.text(
|
| 574 |
+
"SELECT column_name FROM information_schema.columns "
|
| 575 |
+
"WHERE table_name = :t"
|
| 576 |
+
),
|
| 577 |
+
{"t": table},
|
| 578 |
+
)
|
| 579 |
+
else:
|
| 580 |
+
rows = await conn.execute(
|
| 581 |
+
sa.text(
|
| 582 |
+
"SELECT COLUMN_NAME FROM information_schema.columns "
|
| 583 |
+
"WHERE table_schema = DATABASE() AND table_name = :t"
|
| 584 |
+
),
|
| 585 |
+
{"t": table},
|
| 586 |
+
)
|
| 587 |
+
return {str(r[0]).lower() for r in rows.fetchall()}
|
| 588 |
+
|
| 589 |
+
async def initialize(self) -> None:
|
| 590 |
+
await self._ensure_initialized()
|
| 591 |
+
|
| 592 |
+
async def get_revision(self) -> int:
|
| 593 |
+
await self._ensure_initialized()
|
| 594 |
+
async with self._engine.connect() as conn:
|
| 595 |
+
return await self._get_revision(conn)
|
| 596 |
+
|
| 597 |
+
async def runtime_snapshot(self) -> RuntimeSnapshot:
|
| 598 |
+
await self._ensure_initialized()
|
| 599 |
+
async with self._engine.connect() as conn:
|
| 600 |
+
rev = await self._get_revision(conn)
|
| 601 |
+
rows = (await conn.execute(
|
| 602 |
+
sa.select(accounts_table).where(accounts_table.c.deleted_at.is_(None))
|
| 603 |
+
)).fetchall()
|
| 604 |
+
return RuntimeSnapshot(revision=rev, items=[_row_to_record(r) for r in rows])
|
| 605 |
+
|
| 606 |
+
async def scan_changes(
|
| 607 |
+
self,
|
| 608 |
+
since_revision: int,
|
| 609 |
+
*,
|
| 610 |
+
limit: int = 5000,
|
| 611 |
+
) -> AccountChangeSet:
|
| 612 |
+
await self._ensure_initialized()
|
| 613 |
+
async with self._engine.connect() as conn:
|
| 614 |
+
rev = await self._get_revision(conn)
|
| 615 |
+
rows = (await conn.execute(
|
| 616 |
+
sa.select(accounts_table)
|
| 617 |
+
.where(accounts_table.c.revision > since_revision)
|
| 618 |
+
.order_by(accounts_table.c.revision)
|
| 619 |
+
.limit(limit)
|
| 620 |
+
)).fetchall()
|
| 621 |
+
items: list[AccountRecord] = []
|
| 622 |
+
deleted: list[str] = []
|
| 623 |
+
batch_max_rev = 0
|
| 624 |
+
for row in rows:
|
| 625 |
+
r = _row_to_record(row)
|
| 626 |
+
if r.revision > batch_max_rev:
|
| 627 |
+
batch_max_rev = r.revision
|
| 628 |
+
if r.is_deleted():
|
| 629 |
+
deleted.append(r.token)
|
| 630 |
+
else:
|
| 631 |
+
items.append(r)
|
| 632 |
+
return AccountChangeSet(
|
| 633 |
+
revision=rev,
|
| 634 |
+
batch_max_revision=batch_max_rev,
|
| 635 |
+
items=items,
|
| 636 |
+
deleted_tokens=deleted,
|
| 637 |
+
has_more=len(rows) == limit,
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
async def upsert_accounts(
|
| 641 |
+
self,
|
| 642 |
+
items: list[AccountUpsert],
|
| 643 |
+
) -> AccountMutationResult:
|
| 644 |
+
if not items:
|
| 645 |
+
return AccountMutationResult()
|
| 646 |
+
await self._ensure_initialized()
|
| 647 |
+
async with self._engine.begin() as conn:
|
| 648 |
+
rev = await self._bump_revision(conn)
|
| 649 |
+
ts = now_ms()
|
| 650 |
+
count = 0
|
| 651 |
+
for item in items:
|
| 652 |
+
try:
|
| 653 |
+
token = AccountRecord.model_validate({"token": item.token, "pool": item.pool}).token
|
| 654 |
+
except Exception:
|
| 655 |
+
continue
|
| 656 |
+
pool = item.pool if item.pool in ("basic", "super", "heavy") else "basic"
|
| 657 |
+
qs = default_quota_set(pool)
|
| 658 |
+
row = {
|
| 659 |
+
"token": token,
|
| 660 |
+
"pool": pool,
|
| 661 |
+
"status": "active",
|
| 662 |
+
"created_at": ts,
|
| 663 |
+
"updated_at": ts,
|
| 664 |
+
"deleted_at": None, # clear soft-delete on re-import
|
| 665 |
+
"tags": json.dumps(item.tags),
|
| 666 |
+
"quota_auto": json.dumps(qs.auto.to_dict()),
|
| 667 |
+
"quota_fast": json.dumps(qs.fast.to_dict()),
|
| 668 |
+
"quota_expert": json.dumps(qs.expert.to_dict()),
|
| 669 |
+
"quota_heavy": json.dumps(qs.heavy.to_dict()) if qs.heavy else "{}",
|
| 670 |
+
"quota_grok_4_3": json.dumps(qs.grok_4_3.to_dict()) if qs.grok_4_3 else "{}",
|
| 671 |
+
"quota_console": json.dumps(qs.console.to_dict()) if qs.console else "{}",
|
| 672 |
+
"usage_use_count": 0,
|
| 673 |
+
"usage_fail_count": 0,
|
| 674 |
+
"usage_sync_count": 0,
|
| 675 |
+
"ext": json.dumps(item.ext),
|
| 676 |
+
"revision": rev,
|
| 677 |
+
}
|
| 678 |
+
await conn.execute(self._build_upsert(row))
|
| 679 |
+
count += 1
|
| 680 |
+
return AccountMutationResult(upserted=count, revision=rev)
|
| 681 |
+
|
| 682 |
+
async def patch_accounts(
|
| 683 |
+
self,
|
| 684 |
+
patches: list[AccountPatch],
|
| 685 |
+
) -> AccountMutationResult:
|
| 686 |
+
if not patches:
|
| 687 |
+
return AccountMutationResult()
|
| 688 |
+
await self._ensure_initialized()
|
| 689 |
+
async with self._engine.begin() as conn:
|
| 690 |
+
rev = await self._bump_revision(conn)
|
| 691 |
+
ts = now_ms()
|
| 692 |
+
count = 0
|
| 693 |
+
for patch in patches:
|
| 694 |
+
# S3 修复:SELECT FOR UPDATE 锁行,避免多个并发 patch_accounts
|
| 695 |
+
# 在 read-modify-write 期间互相覆盖(JSON 列 / tags / ext 的 lost-update)。
|
| 696 |
+
# 数值列改用原子表达式 col=col+delta,无需依赖 Python 端计算。
|
| 697 |
+
# SQLite 在 SQL 后端不走这条路径(用 local.py 的 asyncio.Lock 串行化)。
|
| 698 |
+
row = (await conn.execute(
|
| 699 |
+
sa.select(accounts_table)
|
| 700 |
+
.where(accounts_table.c.token == patch.token)
|
| 701 |
+
.with_for_update()
|
| 702 |
+
)).fetchone()
|
| 703 |
+
if row is None:
|
| 704 |
+
continue
|
| 705 |
+
record = _row_to_record(row)
|
| 706 |
+
|
| 707 |
+
updates: dict[str, Any] = {"updated_at": ts, "revision": rev}
|
| 708 |
+
if patch.pool is not None:
|
| 709 |
+
updates["pool"] = patch.pool
|
| 710 |
+
if patch.status is not None:
|
| 711 |
+
updates["status"] = patch.status.value
|
| 712 |
+
if patch.state_reason is not None:
|
| 713 |
+
updates["state_reason"] = patch.state_reason
|
| 714 |
+
if patch.last_use_at is not None:
|
| 715 |
+
updates["last_use_at"] = patch.last_use_at
|
| 716 |
+
if patch.last_fail_at is not None:
|
| 717 |
+
updates["last_fail_at"] = patch.last_fail_at
|
| 718 |
+
if patch.last_fail_reason is not None:
|
| 719 |
+
updates["last_fail_reason"] = patch.last_fail_reason
|
| 720 |
+
if patch.last_sync_at is not None:
|
| 721 |
+
updates["last_sync_at"] = patch.last_sync_at
|
| 722 |
+
if patch.last_clear_at is not None:
|
| 723 |
+
updates["last_clear_at"] = patch.last_clear_at
|
| 724 |
+
if patch.quota_auto is not None:
|
| 725 |
+
updates["quota_auto"] = json.dumps(patch.quota_auto)
|
| 726 |
+
if patch.quota_fast is not None:
|
| 727 |
+
updates["quota_fast"] = json.dumps(patch.quota_fast)
|
| 728 |
+
if patch.quota_expert is not None:
|
| 729 |
+
updates["quota_expert"] = json.dumps(patch.quota_expert)
|
| 730 |
+
if patch.quota_heavy is not None:
|
| 731 |
+
updates["quota_heavy"] = json.dumps(patch.quota_heavy)
|
| 732 |
+
if patch.quota_grok_4_3 is not None:
|
| 733 |
+
updates["quota_grok_4_3"] = json.dumps(patch.quota_grok_4_3)
|
| 734 |
+
if patch.quota_console is not None:
|
| 735 |
+
updates["quota_console"] = json.dumps(patch.quota_console)
|
| 736 |
+
# S3 修复:数值列使用原子表达式 GREATEST(0, col+delta),
|
| 737 |
+
# 而不是基于 SELECT 出的旧值在 Python 中算新值。
|
| 738 |
+
# GREATEST 在 MySQL/PostgreSQL 上均原生支持。
|
| 739 |
+
if patch.usage_use_delta is not None:
|
| 740 |
+
delta = int(patch.usage_use_delta)
|
| 741 |
+
updates["usage_use_count"] = sa.text(
|
| 742 |
+
f"GREATEST(0, usage_use_count + {delta})"
|
| 743 |
+
)
|
| 744 |
+
if patch.usage_fail_delta is not None:
|
| 745 |
+
delta = int(patch.usage_fail_delta)
|
| 746 |
+
updates["usage_fail_count"] = sa.text(
|
| 747 |
+
f"GREATEST(0, usage_fail_count + {delta})"
|
| 748 |
+
)
|
| 749 |
+
if patch.usage_sync_delta is not None:
|
| 750 |
+
delta = int(patch.usage_sync_delta)
|
| 751 |
+
updates["usage_sync_count"] = sa.text(
|
| 752 |
+
f"GREATEST(0, usage_sync_count + {delta})"
|
| 753 |
+
)
|
| 754 |
+
|
| 755 |
+
tags = list(record.tags)
|
| 756 |
+
if patch.tags is not None:
|
| 757 |
+
tags = patch.tags
|
| 758 |
+
if patch.add_tags:
|
| 759 |
+
for t in patch.add_tags:
|
| 760 |
+
if t not in tags:
|
| 761 |
+
tags.append(t)
|
| 762 |
+
if patch.remove_tags:
|
| 763 |
+
tags = [t for t in tags if t not in patch.remove_tags]
|
| 764 |
+
updates["tags"] = json.dumps(tags)
|
| 765 |
+
|
| 766 |
+
ext = dict(record.ext)
|
| 767 |
+
if patch.ext_merge:
|
| 768 |
+
ext.update(patch.ext_merge)
|
| 769 |
+
if patch.clear_failures:
|
| 770 |
+
for k in ("cooldown_until", "cooldown_reason", "disabled_at",
|
| 771 |
+
"disabled_reason", "expired_at", "expired_reason",
|
| 772 |
+
"forbidden_strikes", "console_429_count"):
|
| 773 |
+
ext.pop(k, None)
|
| 774 |
+
updates["status"] = AccountStatus.ACTIVE.value
|
| 775 |
+
updates["usage_fail_count"] = 0
|
| 776 |
+
updates["last_fail_at"] = None
|
| 777 |
+
updates["last_fail_reason"] = None
|
| 778 |
+
updates["state_reason"] = None
|
| 779 |
+
updates["ext"] = json.dumps(ext)
|
| 780 |
+
|
| 781 |
+
await conn.execute(
|
| 782 |
+
accounts_table.update()
|
| 783 |
+
.where(accounts_table.c.token == patch.token)
|
| 784 |
+
.values(**updates)
|
| 785 |
+
)
|
| 786 |
+
count += 1
|
| 787 |
+
return AccountMutationResult(patched=count, revision=rev)
|
| 788 |
+
|
| 789 |
+
async def delete_accounts(
|
| 790 |
+
self,
|
| 791 |
+
tokens: list[str],
|
| 792 |
+
) -> AccountMutationResult:
|
| 793 |
+
if not tokens:
|
| 794 |
+
return AccountMutationResult()
|
| 795 |
+
await self._ensure_initialized()
|
| 796 |
+
async with self._engine.begin() as conn:
|
| 797 |
+
rev = await self._bump_revision(conn)
|
| 798 |
+
ts = now_ms()
|
| 799 |
+
result = await conn.execute(
|
| 800 |
+
accounts_table.update()
|
| 801 |
+
.where(
|
| 802 |
+
accounts_table.c.token.in_(tokens),
|
| 803 |
+
accounts_table.c.deleted_at.is_(None),
|
| 804 |
+
)
|
| 805 |
+
.values(deleted_at=ts, updated_at=ts, revision=rev)
|
| 806 |
+
)
|
| 807 |
+
return AccountMutationResult(deleted=result.rowcount, revision=rev)
|
| 808 |
+
|
| 809 |
+
async def get_accounts(
|
| 810 |
+
self,
|
| 811 |
+
tokens: list[str],
|
| 812 |
+
) -> list[AccountRecord]:
|
| 813 |
+
if not tokens:
|
| 814 |
+
return []
|
| 815 |
+
await self._ensure_initialized()
|
| 816 |
+
async with self._engine.connect() as conn:
|
| 817 |
+
rows = (await conn.execute(
|
| 818 |
+
sa.select(accounts_table).where(accounts_table.c.token.in_(tokens))
|
| 819 |
+
)).fetchall()
|
| 820 |
+
return [_row_to_record(r) for r in rows]
|
| 821 |
+
|
| 822 |
+
async def list_accounts(
|
| 823 |
+
self,
|
| 824 |
+
query: ListAccountsQuery,
|
| 825 |
+
) -> AccountPage:
|
| 826 |
+
await self._ensure_initialized()
|
| 827 |
+
async with self._engine.connect() as conn:
|
| 828 |
+
stmt = sa.select(accounts_table)
|
| 829 |
+
if not query.include_deleted:
|
| 830 |
+
stmt = stmt.where(accounts_table.c.deleted_at.is_(None))
|
| 831 |
+
if query.pool:
|
| 832 |
+
stmt = stmt.where(accounts_table.c.pool == query.pool)
|
| 833 |
+
if query.status:
|
| 834 |
+
stmt = stmt.where(accounts_table.c.status == query.status.value)
|
| 835 |
+
|
| 836 |
+
total_row = (await conn.execute(
|
| 837 |
+
sa.select(sa.func.count()).select_from(stmt.subquery())
|
| 838 |
+
)).scalar()
|
| 839 |
+
total = int(total_row or 0)
|
| 840 |
+
|
| 841 |
+
sort_col = getattr(accounts_table.c, query.sort_by, accounts_table.c.updated_at)
|
| 842 |
+
if query.sort_desc:
|
| 843 |
+
stmt = stmt.order_by(sort_col.desc())
|
| 844 |
+
else:
|
| 845 |
+
stmt = stmt.order_by(sort_col.asc())
|
| 846 |
+
offset = (query.page - 1) * query.page_size
|
| 847 |
+
stmt = stmt.limit(query.page_size).offset(offset)
|
| 848 |
+
|
| 849 |
+
rows = (await conn.execute(stmt)).fetchall()
|
| 850 |
+
rev = await self._get_revision(conn)
|
| 851 |
+
return AccountPage(
|
| 852 |
+
items=[_row_to_record(r) for r in rows],
|
| 853 |
+
total=total,
|
| 854 |
+
page=query.page,
|
| 855 |
+
page_size=query.page_size,
|
| 856 |
+
total_pages=max(1, (total + query.page_size - 1) // query.page_size),
|
| 857 |
+
revision=rev,
|
| 858 |
+
)
|
| 859 |
+
|
| 860 |
+
async def replace_pool(
|
| 861 |
+
self,
|
| 862 |
+
command: BulkReplacePoolCommand,
|
| 863 |
+
) -> AccountMutationResult:
|
| 864 |
+
await self._ensure_initialized()
|
| 865 |
+
async with self._engine.begin() as conn:
|
| 866 |
+
rev = await self._bump_revision(conn)
|
| 867 |
+
ts = now_ms()
|
| 868 |
+
del_result = await conn.execute(
|
| 869 |
+
accounts_table.update()
|
| 870 |
+
.where(
|
| 871 |
+
accounts_table.c.pool == command.pool,
|
| 872 |
+
accounts_table.c.deleted_at.is_(None),
|
| 873 |
+
)
|
| 874 |
+
.values(deleted_at=ts, updated_at=ts, revision=rev)
|
| 875 |
+
)
|
| 876 |
+
deleted = del_result.rowcount
|
| 877 |
+
|
| 878 |
+
upserted_result = await self.upsert_accounts(command.upserts)
|
| 879 |
+
return AccountMutationResult(
|
| 880 |
+
upserted=upserted_result.upserted,
|
| 881 |
+
deleted=deleted,
|
| 882 |
+
revision=upserted_result.revision,
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
async def reset_expired_console_windows(self) -> int:
|
| 886 |
+
"""Batch-reset exhausted + expired console quotas via direct SQL.
|
| 887 |
+
|
| 888 |
+
处理两种异常情况:
|
| 889 |
+
1. 老条件:remaining<=0 且 (reset_at IS NULL 或已过期) → 正常配额耗尽恢复
|
| 890 |
+
2. 新条件 (M6):reset_at 已过期(即使 remaining>0)→ 异常数据归位
|
| 891 |
+
"""
|
| 892 |
+
import json as _json
|
| 893 |
+
now = now_ms()
|
| 894 |
+
|
| 895 |
+
if self._dialect == "postgresql":
|
| 896 |
+
count_sql = sa.text(
|
| 897 |
+
"SELECT COUNT(*) FROM accounts"
|
| 898 |
+
" WHERE status = 'active'"
|
| 899 |
+
" AND deleted_at IS NULL"
|
| 900 |
+
" AND ("
|
| 901 |
+
" ("
|
| 902 |
+
" (quota_console->>'remaining')::int <= 0"
|
| 903 |
+
" AND ("
|
| 904 |
+
" quota_console->>'reset_at' IS NULL"
|
| 905 |
+
" OR (quota_console->>'reset_at')::bigint < :now"
|
| 906 |
+
" )"
|
| 907 |
+
" )"
|
| 908 |
+
" OR ("
|
| 909 |
+
" quota_console->>'reset_at' IS NOT NULL"
|
| 910 |
+
" AND (quota_console->>'reset_at')::bigint < :now"
|
| 911 |
+
" )"
|
| 912 |
+
" )"
|
| 913 |
+
)
|
| 914 |
+
update_sql = sa.text(
|
| 915 |
+
"UPDATE accounts"
|
| 916 |
+
" SET quota_console = :reset_json, revision = :rev, updated_at = :now"
|
| 917 |
+
" WHERE status = 'active'"
|
| 918 |
+
" AND deleted_at IS NULL"
|
| 919 |
+
" AND ("
|
| 920 |
+
" ("
|
| 921 |
+
" (quota_console->>'remaining')::int <= 0"
|
| 922 |
+
" AND ("
|
| 923 |
+
" quota_console->>'reset_at' IS NULL"
|
| 924 |
+
" OR (quota_console->>'reset_at')::bigint < :now"
|
| 925 |
+
" )"
|
| 926 |
+
" )"
|
| 927 |
+
" OR ("
|
| 928 |
+
" quota_console->>'reset_at' IS NOT NULL"
|
| 929 |
+
" AND (quota_console->>'reset_at')::bigint < :now"
|
| 930 |
+
" )"
|
| 931 |
+
" )"
|
| 932 |
+
)
|
| 933 |
+
else:
|
| 934 |
+
# MySQL
|
| 935 |
+
count_sql = sa.text(
|
| 936 |
+
"SELECT COUNT(*) FROM accounts"
|
| 937 |
+
" WHERE status = 'active'"
|
| 938 |
+
" AND deleted_at IS NULL"
|
| 939 |
+
" AND ("
|
| 940 |
+
" ("
|
| 941 |
+
" CAST(JSON_EXTRACT(quota_console, '$.remaining') AS SIGNED) <= 0"
|
| 942 |
+
" AND ("
|
| 943 |
+
" JSON_EXTRACT(quota_console, '$.reset_at') IS NULL"
|
| 944 |
+
" OR CAST(JSON_EXTRACT(quota_console, '$.reset_at') AS SIGNED) < :now"
|
| 945 |
+
" )"
|
| 946 |
+
" )"
|
| 947 |
+
" OR ("
|
| 948 |
+
" JSON_EXTRACT(quota_console, '$.reset_at') IS NOT NULL"
|
| 949 |
+
" AND CAST(JSON_EXTRACT(quota_console, '$.reset_at') AS SIGNED) < :now"
|
| 950 |
+
" )"
|
| 951 |
+
" )"
|
| 952 |
+
)
|
| 953 |
+
update_sql = sa.text(
|
| 954 |
+
"UPDATE accounts"
|
| 955 |
+
" SET quota_console = :reset_json, revision = :rev, updated_at = :now"
|
| 956 |
+
" WHERE status = 'active'"
|
| 957 |
+
" AND deleted_at IS NULL"
|
| 958 |
+
" AND ("
|
| 959 |
+
" ("
|
| 960 |
+
" CAST(JSON_EXTRACT(quota_console, '$.remaining') AS SIGNED) <= 0"
|
| 961 |
+
" AND ("
|
| 962 |
+
" JSON_EXTRACT(quota_console, '$.reset_at') IS NULL"
|
| 963 |
+
" OR CAST(JSON_EXTRACT(quota_console, '$.reset_at') AS SIGNED) < :now"
|
| 964 |
+
" )"
|
| 965 |
+
" )"
|
| 966 |
+
" OR ("
|
| 967 |
+
" JSON_EXTRACT(quota_console, '$.reset_at') IS NOT NULL"
|
| 968 |
+
" AND CAST(JSON_EXTRACT(quota_console, '$.reset_at') AS SIGNED) < :now"
|
| 969 |
+
" )"
|
| 970 |
+
" )"
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
async with self._session() as session:
|
| 974 |
+
async with session.begin():
|
| 975 |
+
result = await session.execute(count_sql, {"now": now})
|
| 976 |
+
count = result.scalar() or 0
|
| 977 |
+
if count == 0:
|
| 978 |
+
return 0
|
| 979 |
+
|
| 980 |
+
reset_json = _json.dumps({
|
| 981 |
+
"remaining": BASIC_CONSOLE_LIMIT,
|
| 982 |
+
"total": BASIC_CONSOLE_LIMIT,
|
| 983 |
+
"window_seconds": BASIC_CONSOLE_WINDOW_SECONDS,
|
| 984 |
+
"reset_at": None,
|
| 985 |
+
"synced_at": now,
|
| 986 |
+
"source": 0,
|
| 987 |
+
})
|
| 988 |
+
rev = await self._bump_revision(session)
|
| 989 |
+
result = await session.execute(update_sql, {
|
| 990 |
+
"reset_json": reset_json,
|
| 991 |
+
"rev": rev,
|
| 992 |
+
"now": now,
|
| 993 |
+
})
|
| 994 |
+
return result.rowcount or count
|
| 995 |
+
|
| 996 |
+
async def recover_console_expired_accounts(self) -> int:
|
| 997 |
+
"""Auto-recover console 429 EXPIRED accounts with successful history.
|
| 998 |
+
|
| 999 |
+
Conditions:
|
| 1000 |
+
- status = 'expired'
|
| 1001 |
+
- state_reason = 'console_429_threshold_exceeded'
|
| 1002 |
+
- usage_use_count > 5
|
| 1003 |
+
- ext.expired_at <= now - 1 hour
|
| 1004 |
+
"""
|
| 1005 |
+
import json as _json
|
| 1006 |
+
now = now_ms()
|
| 1007 |
+
recovery_threshold = now - 3600 * 1000
|
| 1008 |
+
|
| 1009 |
+
if self._dialect == "postgresql":
|
| 1010 |
+
select_sql = sa.text(
|
| 1011 |
+
"SELECT token, ext FROM accounts"
|
| 1012 |
+
" WHERE status = 'expired'"
|
| 1013 |
+
" AND deleted_at IS NULL"
|
| 1014 |
+
" AND state_reason = 'console_429_threshold_exceeded'"
|
| 1015 |
+
" AND usage_use_count > 5"
|
| 1016 |
+
" AND (ext->>'expired_at')::bigint <= :threshold"
|
| 1017 |
+
)
|
| 1018 |
+
else:
|
| 1019 |
+
# MySQL
|
| 1020 |
+
select_sql = sa.text(
|
| 1021 |
+
"SELECT token, ext FROM accounts"
|
| 1022 |
+
" WHERE status = 'expired'"
|
| 1023 |
+
" AND deleted_at IS NULL"
|
| 1024 |
+
" AND state_reason = 'console_429_threshold_exceeded'"
|
| 1025 |
+
" AND usage_use_count > 5"
|
| 1026 |
+
" AND CAST(JSON_EXTRACT(ext, '$.expired_at') AS SIGNED) <= :threshold"
|
| 1027 |
+
)
|
| 1028 |
+
|
| 1029 |
+
update_sql = sa.text(
|
| 1030 |
+
"UPDATE accounts"
|
| 1031 |
+
" SET status = 'active',"
|
| 1032 |
+
" state_reason = NULL,"
|
| 1033 |
+
" ext = :ext_json,"
|
| 1034 |
+
" revision = :rev,"
|
| 1035 |
+
" updated_at = :now"
|
| 1036 |
+
" WHERE token = :token"
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
async with self._session() as session:
|
| 1040 |
+
async with session.begin():
|
| 1041 |
+
rows = (await session.execute(
|
| 1042 |
+
select_sql, {"threshold": recovery_threshold}
|
| 1043 |
+
)).fetchall()
|
| 1044 |
+
|
| 1045 |
+
if not rows:
|
| 1046 |
+
return 0
|
| 1047 |
+
|
| 1048 |
+
rev = await self._bump_revision(session)
|
| 1049 |
+
count = 0
|
| 1050 |
+
for row in rows:
|
| 1051 |
+
token = row[0]
|
| 1052 |
+
ext_raw = row[1]
|
| 1053 |
+
try:
|
| 1054 |
+
ext = _json.loads(ext_raw) if ext_raw else {}
|
| 1055 |
+
except (ValueError, TypeError):
|
| 1056 |
+
ext = {}
|
| 1057 |
+
for k in ("expired_at", "expired_reason",
|
| 1058 |
+
"console_429_count", "console_429_last_at"):
|
| 1059 |
+
ext.pop(k, None)
|
| 1060 |
+
await session.execute(update_sql, {
|
| 1061 |
+
"ext_json": _json.dumps(ext),
|
| 1062 |
+
"rev": rev,
|
| 1063 |
+
"now": now,
|
| 1064 |
+
"token": token,
|
| 1065 |
+
})
|
| 1066 |
+
count += 1
|
| 1067 |
+
return count
|
| 1068 |
+
|
| 1069 |
+
async def close(self) -> None:
|
| 1070 |
+
"""Dispose the SQLAlchemy connection pool."""
|
| 1071 |
+
if self._dispose_engine:
|
| 1072 |
+
_evict_cached_engine(self._engine)
|
| 1073 |
+
await self._engine.dispose()
|
| 1074 |
+
|
| 1075 |
+
|
| 1076 |
+
def _engine_cache_key(dialect: str, normalized_url: str, connect_args: dict[str, Any] | None) -> tuple[str, str, str]:
|
| 1077 |
+
"""Build a stable cache key from the normalized URL and connect args."""
|
| 1078 |
+
args_key = str(sorted(connect_args.items(), key=lambda kv: kv[0])) if connect_args else ""
|
| 1079 |
+
return (dialect, normalized_url, args_key)
|
| 1080 |
+
|
| 1081 |
+
|
| 1082 |
+
def create_mysql_engine(url: str) -> AsyncEngine:
|
| 1083 |
+
"""Create an async SQLAlchemy engine for MySQL."""
|
| 1084 |
+
normalized_url, connect_args = _prepare_sql_url_and_connect_args("mysql", (url or "").strip())
|
| 1085 |
+
return _get_or_create_engine(_engine_cache_key("mysql", normalized_url, connect_args), normalized_url, connect_args)
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
def create_pgsql_engine(url: str) -> AsyncEngine:
|
| 1089 |
+
"""Create an async SQLAlchemy engine for PostgreSQL."""
|
| 1090 |
+
normalized_url, connect_args = _prepare_sql_url_and_connect_args("postgresql", (url or "").strip())
|
| 1091 |
+
return _get_or_create_engine(_engine_cache_key("postgresql", normalized_url, connect_args), normalized_url, connect_args)
|
| 1092 |
+
|
| 1093 |
+
|
| 1094 |
+
__all__ = ["SqlAccountRepository", "create_mysql_engine", "create_pgsql_engine"]
|
app/control/account/commands.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Command / query objects for the account control plane."""
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
from pydantic import BaseModel, Field
|
| 6 |
+
|
| 7 |
+
from .enums import AccountStatus
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class AccountUpsert(BaseModel):
|
| 11 |
+
"""Create-or-replace command for a single account.
|
| 12 |
+
|
| 13 |
+
Only ``token`` is required; all other fields use safe defaults.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
token: str
|
| 17 |
+
pool: str = "basic"
|
| 18 |
+
tags: list[str] = Field(default_factory=list)
|
| 19 |
+
ext: dict[str, Any] = Field(default_factory=dict)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class AccountPatch(BaseModel):
|
| 23 |
+
"""Partial update — only supplied fields are written.
|
| 24 |
+
|
| 25 |
+
Fields left as ``None`` are **not** modified in the backend.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
token: str
|
| 29 |
+
pool: str | None = None # update pool type when inferred
|
| 30 |
+
status: AccountStatus | None = None
|
| 31 |
+
tags: list[str] | None = None
|
| 32 |
+
add_tags: list[str] | None = None
|
| 33 |
+
remove_tags: list[str] | None = None
|
| 34 |
+
# Per-mode quota patches (raw dicts matching QuotaWindow.to_dict()).
|
| 35 |
+
quota_auto: dict[str, Any] | None = None
|
| 36 |
+
quota_fast: dict[str, Any] | None = None
|
| 37 |
+
quota_expert: dict[str, Any] | None = None
|
| 38 |
+
quota_heavy: dict[str, Any] | None = None
|
| 39 |
+
quota_grok_4_3: dict[str, Any] | None = None
|
| 40 |
+
quota_console: dict[str, Any] | None = None
|
| 41 |
+
# Usage counters — delta values (added to existing counts).
|
| 42 |
+
usage_use_delta: int | None = None
|
| 43 |
+
usage_fail_delta: int | None = None
|
| 44 |
+
usage_sync_delta: int | None = None
|
| 45 |
+
# Timestamp overrides (set absolute values).
|
| 46 |
+
last_use_at: int | None = None
|
| 47 |
+
last_fail_at: int | None = None
|
| 48 |
+
last_fail_reason: str | None = None
|
| 49 |
+
last_sync_at: int | None = None
|
| 50 |
+
last_clear_at: int | None = None
|
| 51 |
+
state_reason: str | None = None
|
| 52 |
+
ext_merge: dict[str, Any] | None = None
|
| 53 |
+
clear_failures: bool = False
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ListAccountsQuery(BaseModel):
|
| 57 |
+
"""Query parameters for paginated account listing."""
|
| 58 |
+
|
| 59 |
+
page: int = Field(default=1, ge=1)
|
| 60 |
+
page_size: int = Field(default=50, ge=1, le=2000)
|
| 61 |
+
pool: str | None = None
|
| 62 |
+
status: AccountStatus | None = None
|
| 63 |
+
tags: list[str] = Field(default_factory=list)
|
| 64 |
+
include_deleted: bool = False
|
| 65 |
+
sort_by: str = "updated_at" # field name
|
| 66 |
+
sort_desc: bool = True
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class BulkReplacePoolCommand(BaseModel):
|
| 70 |
+
"""Replace all accounts in a pool atomically."""
|
| 71 |
+
|
| 72 |
+
pool: str
|
| 73 |
+
upserts: list[AccountUpsert] = Field(default_factory=list)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
__all__ = [
|
| 77 |
+
"AccountUpsert",
|
| 78 |
+
"AccountPatch",
|
| 79 |
+
"ListAccountsQuery",
|
| 80 |
+
"BulkReplacePoolCommand",
|
| 81 |
+
]
|
app/control/account/enums.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Control-plane account enumerations."""
|
| 2 |
+
|
| 3 |
+
from enum import IntEnum, StrEnum
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class AccountStatus(StrEnum):
|
| 7 |
+
"""Persistent lifecycle status of an account record."""
|
| 8 |
+
|
| 9 |
+
ACTIVE = "active"
|
| 10 |
+
COOLING = "cooling"
|
| 11 |
+
EXPIRED = "expired"
|
| 12 |
+
DISABLED = "disabled"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class QuotaSource(IntEnum):
|
| 16 |
+
"""Reliability of a stored QuotaWindow value.
|
| 17 |
+
|
| 18 |
+
Integer values are stored in the quota JSON payload.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
DEFAULT = 0 # Never synced; using built-in default.
|
| 22 |
+
REAL = 1 # Retrieved from upstream rate-limits API.
|
| 23 |
+
ESTIMATED = 2 # Locally decremented after a failed API call.
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class FeedbackKind(StrEnum):
|
| 27 |
+
"""Classification of the outcome of a single upstream request."""
|
| 28 |
+
|
| 29 |
+
SUCCESS = "success"
|
| 30 |
+
UNAUTHORIZED = "unauthorized" # 401 — token invalid / expired
|
| 31 |
+
FORBIDDEN = "forbidden" # 403 — account suspended / CF challenge
|
| 32 |
+
RATE_LIMITED = "rate_limited" # 429 — quota exhausted
|
| 33 |
+
SERVER_ERROR = "server_error" # 5xx — upstream fault
|
| 34 |
+
DISABLE = "disable" # operator-initiated disable
|
| 35 |
+
DELETE = "delete" # operator-initiated delete
|
| 36 |
+
RESTORE = "restore" # operator-initiated restore
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
__all__ = ["AccountStatus", "QuotaSource", "FeedbackKind"]
|
app/control/account/invalid_credentials.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared handling for upstream invalid-credential failures."""
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING
|
| 4 |
+
|
| 5 |
+
from app.platform.errors import UpstreamError
|
| 6 |
+
from app.platform.logging.logger import logger
|
| 7 |
+
from app.platform.runtime.clock import now_ms
|
| 8 |
+
|
| 9 |
+
from .commands import AccountPatch
|
| 10 |
+
from .enums import AccountStatus, FeedbackKind
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from .repository import AccountRepository
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
async def mark_account_invalid_credentials(
|
| 17 |
+
repo: "AccountRepository",
|
| 18 |
+
token: str,
|
| 19 |
+
exc: BaseException,
|
| 20 |
+
*,
|
| 21 |
+
source: str,
|
| 22 |
+
) -> bool:
|
| 23 |
+
"""Mark *token* as invalid when *exc* matches Grok invalid credentials."""
|
| 24 |
+
from app.dataplane.reverse.protocol.xai_usage import is_invalid_credentials_error
|
| 25 |
+
|
| 26 |
+
if not is_invalid_credentials_error(exc):
|
| 27 |
+
return False
|
| 28 |
+
|
| 29 |
+
record = next(iter(await repo.get_accounts([token])), None)
|
| 30 |
+
reason = "invalid_credentials"
|
| 31 |
+
ts = now_ms()
|
| 32 |
+
ext = record.ext if record is not None else {}
|
| 33 |
+
|
| 34 |
+
await repo.patch_accounts(
|
| 35 |
+
[
|
| 36 |
+
AccountPatch(
|
| 37 |
+
token=token,
|
| 38 |
+
status=AccountStatus.EXPIRED,
|
| 39 |
+
last_fail_at=ts,
|
| 40 |
+
last_fail_reason=reason,
|
| 41 |
+
state_reason=reason,
|
| 42 |
+
ext_merge={
|
| 43 |
+
**ext,
|
| 44 |
+
"expired_at": ts,
|
| 45 |
+
"expired_reason": reason,
|
| 46 |
+
},
|
| 47 |
+
)
|
| 48 |
+
]
|
| 49 |
+
)
|
| 50 |
+
logger.info(
|
| 51 |
+
"account expired from {}: token={}... status={} upstream_status={}",
|
| 52 |
+
source,
|
| 53 |
+
token[:10],
|
| 54 |
+
AccountStatus.EXPIRED,
|
| 55 |
+
getattr(exc, "status", None) if isinstance(exc, UpstreamError) else None,
|
| 56 |
+
)
|
| 57 |
+
return True
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def feedback_kind_for_error(exc: BaseException | None) -> FeedbackKind:
|
| 61 |
+
"""Map an upstream exception to the appropriate account feedback kind."""
|
| 62 |
+
if exc is None:
|
| 63 |
+
return FeedbackKind.SERVER_ERROR
|
| 64 |
+
# Check for known blocked/invalid body markers first — these override
|
| 65 |
+
# the generic status-code mapping so that e.g. a 403 with "blocked-user"
|
| 66 |
+
# body is treated as an account-level credential failure, not a generic
|
| 67 |
+
# FORBIDDEN that only lowers health.
|
| 68 |
+
from app.dataplane.reverse.protocol.xai_usage import is_invalid_credentials_error
|
| 69 |
+
|
| 70 |
+
if is_invalid_credentials_error(exc):
|
| 71 |
+
return FeedbackKind.UNAUTHORIZED
|
| 72 |
+
status = getattr(exc, "status", 0)
|
| 73 |
+
if status == 429:
|
| 74 |
+
return FeedbackKind.RATE_LIMITED
|
| 75 |
+
if status == 401:
|
| 76 |
+
return FeedbackKind.UNAUTHORIZED
|
| 77 |
+
if status == 403:
|
| 78 |
+
return FeedbackKind.FORBIDDEN
|
| 79 |
+
return FeedbackKind.SERVER_ERROR
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
__all__ = ["mark_account_invalid_credentials", "feedback_kind_for_error"]
|
app/control/account/models.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from pydantic import BaseModel, Field, field_validator
|
| 7 |
+
|
| 8 |
+
from app.platform.runtime.clock import now_ms
|
| 9 |
+
from .enums import AccountStatus, QuotaSource
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# ---------------------------------------------------------------------------
|
| 13 |
+
# QuotaWindow
|
| 14 |
+
# ---------------------------------------------------------------------------
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass(slots=True)
|
| 18 |
+
class QuotaWindow:
|
| 19 |
+
"""Rate-limit window for one mode (auto / fast / expert).
|
| 20 |
+
|
| 21 |
+
``remaining`` — queries remaining in the current window.
|
| 22 |
+
``total`` — total queries per window.
|
| 23 |
+
``window_seconds`` — window duration in seconds.
|
| 24 |
+
``reset_at`` — ms timestamp when the window resets; None = unknown.
|
| 25 |
+
``synced_at`` — ms timestamp of last upstream sync; None = never.
|
| 26 |
+
``source`` — reliability of this value.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
remaining: int
|
| 30 |
+
total: int
|
| 31 |
+
window_seconds: int
|
| 32 |
+
reset_at: int | None
|
| 33 |
+
synced_at: int | None
|
| 34 |
+
source: QuotaSource
|
| 35 |
+
|
| 36 |
+
def is_exhausted(self) -> bool:
|
| 37 |
+
return self.remaining <= 0
|
| 38 |
+
|
| 39 |
+
def is_window_expired(self, now: int) -> bool:
|
| 40 |
+
"""Return True if the reset timestamp has passed."""
|
| 41 |
+
return self.reset_at is not None and now >= self.reset_at
|
| 42 |
+
|
| 43 |
+
def to_dict(self) -> dict[str, Any]:
|
| 44 |
+
return {
|
| 45 |
+
"remaining": self.remaining,
|
| 46 |
+
"total": self.total,
|
| 47 |
+
"window_seconds": self.window_seconds,
|
| 48 |
+
"reset_at": self.reset_at,
|
| 49 |
+
"synced_at": self.synced_at,
|
| 50 |
+
"source": int(self.source),
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
@classmethod
|
| 54 |
+
def from_dict(cls, d: dict[str, Any]) -> "QuotaWindow":
|
| 55 |
+
return cls(
|
| 56 |
+
remaining=int(d.get("remaining", 0)),
|
| 57 |
+
total=int(d.get("total", 0)),
|
| 58 |
+
window_seconds=int(d.get("window_seconds", 0)),
|
| 59 |
+
reset_at=d.get("reset_at"),
|
| 60 |
+
synced_at=d.get("synced_at"),
|
| 61 |
+
source=QuotaSource(int(d.get("source", 0))),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ---------------------------------------------------------------------------
|
| 66 |
+
# AccountQuotaSet
|
| 67 |
+
# ---------------------------------------------------------------------------
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass(slots=True)
|
| 71 |
+
class AccountQuotaSet:
|
| 72 |
+
"""Quota set — one window per mode (auto / fast / expert / heavy / grok_4_3).
|
| 73 |
+
|
| 74 |
+
``heavy`` is ``None`` for basic and super accounts.
|
| 75 |
+
``grok_4_3`` is ``None`` for basic accounts (super/heavy only).
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
auto: QuotaWindow
|
| 79 |
+
fast: QuotaWindow
|
| 80 |
+
expert: QuotaWindow
|
| 81 |
+
heavy: QuotaWindow | None = None # heavy-pool accounts only
|
| 82 |
+
grok_4_3: QuotaWindow | None = None # super/heavy accounts only
|
| 83 |
+
console: QuotaWindow | None = None # basic pool console models (console.x.ai)
|
| 84 |
+
|
| 85 |
+
def get(self, mode_id: int) -> QuotaWindow | None:
|
| 86 |
+
"""Return the quota window for *mode_id* (0=auto, 1=fast, 2=expert, 3=heavy, 4=grok_4_3, 5=console)."""
|
| 87 |
+
if mode_id == 0:
|
| 88 |
+
return self.auto
|
| 89 |
+
if mode_id == 1:
|
| 90 |
+
return self.fast
|
| 91 |
+
if mode_id == 2:
|
| 92 |
+
return self.expert
|
| 93 |
+
if mode_id == 3:
|
| 94 |
+
return self.heavy
|
| 95 |
+
if mode_id == 4:
|
| 96 |
+
return self.grok_4_3
|
| 97 |
+
if mode_id == 5:
|
| 98 |
+
return self.console
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
def set(self, mode_id: int, window: QuotaWindow) -> None:
|
| 102 |
+
"""Replace the quota window for *mode_id*."""
|
| 103 |
+
if mode_id == 0:
|
| 104 |
+
self.auto = window
|
| 105 |
+
elif mode_id == 1:
|
| 106 |
+
self.fast = window
|
| 107 |
+
elif mode_id == 2:
|
| 108 |
+
self.expert = window
|
| 109 |
+
elif mode_id == 3:
|
| 110 |
+
self.heavy = window
|
| 111 |
+
elif mode_id == 4:
|
| 112 |
+
self.grok_4_3 = window
|
| 113 |
+
else:
|
| 114 |
+
self.console = window # mode_id == 5
|
| 115 |
+
|
| 116 |
+
def to_dict(self) -> dict[str, dict[str, Any]]:
|
| 117 |
+
d: dict[str, dict[str, Any]] = {
|
| 118 |
+
"auto": self.auto.to_dict(),
|
| 119 |
+
"fast": self.fast.to_dict(),
|
| 120 |
+
"expert": self.expert.to_dict(),
|
| 121 |
+
}
|
| 122 |
+
if self.heavy is not None:
|
| 123 |
+
d["heavy"] = self.heavy.to_dict()
|
| 124 |
+
if self.grok_4_3 is not None:
|
| 125 |
+
d["grok_4_3"] = self.grok_4_3.to_dict()
|
| 126 |
+
if self.console is not None:
|
| 127 |
+
d["console"] = self.console.to_dict()
|
| 128 |
+
return d
|
| 129 |
+
|
| 130 |
+
@classmethod
|
| 131 |
+
def from_dict(cls, d: dict[str, Any]) -> "AccountQuotaSet":
|
| 132 |
+
heavy_d = d.get("heavy")
|
| 133 |
+
grok_4_3_d = d.get("grok_4_3")
|
| 134 |
+
console_d = d.get("console")
|
| 135 |
+
return cls(
|
| 136 |
+
auto=QuotaWindow.from_dict(d.get("auto", {})),
|
| 137 |
+
fast=QuotaWindow.from_dict(d.get("fast", {})),
|
| 138 |
+
expert=QuotaWindow.from_dict(d.get("expert", {})),
|
| 139 |
+
heavy=QuotaWindow.from_dict(heavy_d) if heavy_d else None,
|
| 140 |
+
grok_4_3=QuotaWindow.from_dict(grok_4_3_d) if grok_4_3_d else None,
|
| 141 |
+
console=QuotaWindow.from_dict(console_d) if console_d else None,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# ---------------------------------------------------------------------------
|
| 146 |
+
# AccountUsageStats
|
| 147 |
+
# ---------------------------------------------------------------------------
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@dataclass(slots=True)
|
| 151 |
+
class AccountUsageStats:
|
| 152 |
+
"""Cumulative usage counters for an account."""
|
| 153 |
+
|
| 154 |
+
use_count: int = 0 # Successful calls (SUCCESS feedback)
|
| 155 |
+
fail_count: int = 0 # Failed calls (non-success feedback)
|
| 156 |
+
sync_count: int = 0 # Usage API sync calls
|
| 157 |
+
|
| 158 |
+
def to_dict(self) -> dict[str, int]:
|
| 159 |
+
return {
|
| 160 |
+
"use_count": self.use_count,
|
| 161 |
+
"fail_count": self.fail_count,
|
| 162 |
+
"sync_count": self.sync_count,
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
@classmethod
|
| 166 |
+
def from_dict(cls, d: dict[str, Any]) -> "AccountUsageStats":
|
| 167 |
+
return cls(
|
| 168 |
+
use_count=int(d.get("use_count", 0)),
|
| 169 |
+
fail_count=int(d.get("fail_count", 0)),
|
| 170 |
+
sync_count=int(d.get("sync_count", 0)),
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# ---------------------------------------------------------------------------
|
| 175 |
+
# AccountRecord (Pydantic — control plane only)
|
| 176 |
+
# ---------------------------------------------------------------------------
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class AccountRecord(BaseModel):
|
| 180 |
+
"""Persistent account record — single source of truth for all backends.
|
| 181 |
+
|
| 182 |
+
``pool`` values: ``"basic"`` | ``"super"`` | ``"heavy"``
|
| 183 |
+
All timestamps are milliseconds since epoch.
|
| 184 |
+
``ext`` carries non-core extension data only.
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
token: str
|
| 188 |
+
pool: str = "basic"
|
| 189 |
+
status: AccountStatus = AccountStatus.ACTIVE
|
| 190 |
+
created_at: int = Field(default_factory=now_ms)
|
| 191 |
+
updated_at: int = Field(default_factory=now_ms)
|
| 192 |
+
tags: list[str] = Field(default_factory=list)
|
| 193 |
+
# Serialised form of AccountQuotaSet. Stored as dict for Pydantic
|
| 194 |
+
# round-tripping; use .quota_set() to deserialise, .with_quota_set()
|
| 195 |
+
# to produce an updated copy.
|
| 196 |
+
quota: dict[str, Any] = Field(default_factory=dict)
|
| 197 |
+
usage_use_count: int = 0
|
| 198 |
+
usage_fail_count: int = 0
|
| 199 |
+
usage_sync_count: int = 0
|
| 200 |
+
last_use_at: int | None = None
|
| 201 |
+
last_fail_at: int | None = None
|
| 202 |
+
last_fail_reason: str | None = None
|
| 203 |
+
last_sync_at: int | None = None
|
| 204 |
+
last_clear_at: int | None = None
|
| 205 |
+
state_reason: str | None = None
|
| 206 |
+
deleted_at: int | None = None
|
| 207 |
+
ext: dict[str, Any] = Field(default_factory=dict)
|
| 208 |
+
revision: int = 0
|
| 209 |
+
|
| 210 |
+
# --- computed properties ---
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def is_nsfw(self) -> bool:
|
| 214 |
+
return "nsfw" in self.tags
|
| 215 |
+
|
| 216 |
+
@property
|
| 217 |
+
def is_super(self) -> bool:
|
| 218 |
+
return self.pool == "super"
|
| 219 |
+
|
| 220 |
+
@property
|
| 221 |
+
def is_heavy(self) -> bool:
|
| 222 |
+
return self.pool == "heavy"
|
| 223 |
+
|
| 224 |
+
def is_deleted(self) -> bool:
|
| 225 |
+
return self.deleted_at is not None
|
| 226 |
+
|
| 227 |
+
def quota_set(self) -> AccountQuotaSet:
|
| 228 |
+
"""Deserialise the stored quota dict into an AccountQuotaSet."""
|
| 229 |
+
return AccountQuotaSet.from_dict(self.quota)
|
| 230 |
+
|
| 231 |
+
def with_quota_set(self, qs: AccountQuotaSet) -> "AccountRecord":
|
| 232 |
+
"""Return a copy of this record with the given quota set serialised."""
|
| 233 |
+
return self.model_copy(update={"quota": qs.to_dict()})
|
| 234 |
+
|
| 235 |
+
# --- validators ---
|
| 236 |
+
|
| 237 |
+
@field_validator("token", mode="before")
|
| 238 |
+
@classmethod
|
| 239 |
+
def _normalize_token(cls, v: Any) -> str:
|
| 240 |
+
if v is None:
|
| 241 |
+
raise ValueError("token cannot be None")
|
| 242 |
+
token = str(v)
|
| 243 |
+
# Normalise Unicode dash / space variants and strip zero-width chars.
|
| 244 |
+
token = token.translate(
|
| 245 |
+
str.maketrans(
|
| 246 |
+
{
|
| 247 |
+
"\u2010": "-",
|
| 248 |
+
"\u2011": "-",
|
| 249 |
+
"\u2012": "-",
|
| 250 |
+
"\u2013": "-",
|
| 251 |
+
"\u2014": "-",
|
| 252 |
+
"\u2212": "-",
|
| 253 |
+
"\u00a0": " ",
|
| 254 |
+
"\u2007": " ",
|
| 255 |
+
"\u202f": " ",
|
| 256 |
+
"\u200b": "",
|
| 257 |
+
"\u200c": "",
|
| 258 |
+
"\u200d": "",
|
| 259 |
+
"\ufeff": "",
|
| 260 |
+
}
|
| 261 |
+
)
|
| 262 |
+
)
|
| 263 |
+
token = "".join(token.split())
|
| 264 |
+
if token.startswith("sso="):
|
| 265 |
+
token = token[4:]
|
| 266 |
+
token = token.encode("ascii", errors="ignore").decode("ascii")
|
| 267 |
+
if not token:
|
| 268 |
+
raise ValueError("token is empty after normalisation")
|
| 269 |
+
return token
|
| 270 |
+
|
| 271 |
+
@field_validator("pool", mode="before")
|
| 272 |
+
@classmethod
|
| 273 |
+
def _normalize_pool(cls, v: Any) -> str:
|
| 274 |
+
val = str(v or "").strip().lower()
|
| 275 |
+
if val in ("super"):
|
| 276 |
+
return "super"
|
| 277 |
+
if val in ("heavy",):
|
| 278 |
+
return "heavy"
|
| 279 |
+
if val in ("ssobasic", "basic", "", "auto"):
|
| 280 |
+
# "auto" is a UI alias meaning "let quota sync decide";
|
| 281 |
+
# save as basic for now — refresh will correct to the real type.
|
| 282 |
+
return "basic"
|
| 283 |
+
raise ValueError(f"Unknown pool: {v!r}")
|
| 284 |
+
|
| 285 |
+
@field_validator("tags", mode="before")
|
| 286 |
+
@classmethod
|
| 287 |
+
def _normalize_tags(cls, v: Any) -> list[str]:
|
| 288 |
+
if not v:
|
| 289 |
+
return []
|
| 290 |
+
if isinstance(v, str):
|
| 291 |
+
v = [p.strip() for p in v.split(",")]
|
| 292 |
+
seen: list[str] = []
|
| 293 |
+
for item in v:
|
| 294 |
+
tag = str(item).strip()
|
| 295 |
+
if tag and tag not in seen:
|
| 296 |
+
seen.append(tag)
|
| 297 |
+
return seen
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# ---------------------------------------------------------------------------
|
| 301 |
+
# Lightweight result types
|
| 302 |
+
# ---------------------------------------------------------------------------
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class AccountMutationResult(BaseModel):
|
| 306 |
+
upserted: int = 0
|
| 307 |
+
patched: int = 0
|
| 308 |
+
deleted: int = 0
|
| 309 |
+
revision: int = 0
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class AccountPage(BaseModel):
|
| 313 |
+
items: list[AccountRecord] = Field(default_factory=list)
|
| 314 |
+
total: int = 0
|
| 315 |
+
page: int = 1
|
| 316 |
+
page_size: int = 50
|
| 317 |
+
total_pages: int = 1
|
| 318 |
+
revision: int = 0
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class AccountChangeSet(BaseModel):
|
| 322 |
+
revision: int = 0
|
| 323 |
+
# 本批返回行中观察到的最大 revision。
|
| 324 |
+
# 当 has_more=True 时,调用方应只推进到 batch_max_revision,
|
| 325 |
+
# 避免跳过尚未返回的中间行(参见 S2 修复)。
|
| 326 |
+
# 若本批为空则为 0。
|
| 327 |
+
batch_max_revision: int = 0
|
| 328 |
+
items: list[AccountRecord] = Field(default_factory=list)
|
| 329 |
+
deleted_tokens: list[str] = Field(default_factory=list)
|
| 330 |
+
has_more: bool = False
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class RuntimeSnapshot(BaseModel):
|
| 334 |
+
revision: int = 0
|
| 335 |
+
items: list[AccountRecord] = Field(default_factory=list)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
__all__ = [
|
| 339 |
+
"QuotaWindow",
|
| 340 |
+
"AccountQuotaSet",
|
| 341 |
+
"AccountUsageStats",
|
| 342 |
+
"AccountRecord",
|
| 343 |
+
"AccountMutationResult",
|
| 344 |
+
"AccountPage",
|
| 345 |
+
"AccountChangeSet",
|
| 346 |
+
"RuntimeSnapshot",
|
| 347 |
+
]
|
app/control/account/quota_defaults.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Default quota windows and pool inference logic.
|
| 2 |
+
|
| 3 |
+
Canonical quota totals per pool type (from upstream rate-limits API):
|
| 4 |
+
|
| 5 |
+
auto fast expert heavy grok_4_3
|
| 6 |
+
basic — 30 — — — window: 86400 s
|
| 7 |
+
super 50 140 50 — 50 window: 7200 s
|
| 8 |
+
heavy 150 400 150 20 150 window: 7200 s
|
| 9 |
+
|
| 10 |
+
Pool inference uses ``auto.total`` as the primary signal for super/heavy
|
| 11 |
+
accounts; basic accounts no longer expose auto/expert windows locally.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from typing import TYPE_CHECKING
|
| 15 |
+
|
| 16 |
+
from .enums import QuotaSource
|
| 17 |
+
from .models import AccountQuotaSet, QuotaWindow
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ---------------------------------------------------------------------------
|
| 24 |
+
# Helpers
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _w(remaining: int, total: int, window_seconds: int) -> QuotaWindow:
|
| 29 |
+
return QuotaWindow(
|
| 30 |
+
remaining=remaining,
|
| 31 |
+
total=total,
|
| 32 |
+
window_seconds=window_seconds,
|
| 33 |
+
reset_at=None,
|
| 34 |
+
synced_at=None,
|
| 35 |
+
source=QuotaSource.DEFAULT,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ---------------------------------------------------------------------------
|
| 40 |
+
# Per-pool default quota sets
|
| 41 |
+
# ---------------------------------------------------------------------------
|
| 42 |
+
|
| 43 |
+
BASIC_FAST_LIMIT = 30
|
| 44 |
+
BASIC_FAST_WINDOW_SECONDS = 86_400
|
| 45 |
+
|
| 46 |
+
BASIC_CONSOLE_LIMIT = 20
|
| 47 |
+
BASIC_CONSOLE_WINDOW_SECONDS = 3600
|
| 48 |
+
|
| 49 |
+
BASIC_QUOTA_DEFAULTS = AccountQuotaSet(
|
| 50 |
+
auto=_w(0, 0, 0), # unsupported on basic accounts
|
| 51 |
+
fast=_w(BASIC_FAST_LIMIT, BASIC_FAST_LIMIT, BASIC_FAST_WINDOW_SECONDS),
|
| 52 |
+
expert=_w(0, 0, 0), # unsupported on basic accounts
|
| 53 |
+
console=_w(BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_LIMIT, BASIC_CONSOLE_WINDOW_SECONDS),
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
SUPER_QUOTA_DEFAULTS = AccountQuotaSet(
|
| 57 |
+
auto=_w(50, 50, 7_200), # 50 queries / 2 h
|
| 58 |
+
fast=_w(140, 140, 7_200), # 140 queries / 2 h
|
| 59 |
+
expert=_w(50, 50, 7_200), # 50 queries / 2 h
|
| 60 |
+
grok_4_3=_w(50, 50, 7_200), # 50 queries / 2 h
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
HEAVY_QUOTA_DEFAULTS = AccountQuotaSet(
|
| 64 |
+
auto=_w(150, 150, 7_200), # 150 queries / 2 h
|
| 65 |
+
fast=_w(400, 400, 7_200), # 400 queries / 2 h
|
| 66 |
+
expert=_w(150, 150, 7_200), # 150 queries / 2 h
|
| 67 |
+
heavy=_w(20, 20, 7_200), # 20 queries / 2 h
|
| 68 |
+
grok_4_3=_w(150, 150, 7_200), # 150 queries / 2 h
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# Map pool name → defaults object (used by backends on upsert).
|
| 72 |
+
_POOL_DEFAULTS: dict[str, AccountQuotaSet] = {
|
| 73 |
+
"basic": BASIC_QUOTA_DEFAULTS,
|
| 74 |
+
"super": SUPER_QUOTA_DEFAULTS,
|
| 75 |
+
"heavy": HEAVY_QUOTA_DEFAULTS,
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
_SUPPORTED_MODE_IDS_BY_POOL: dict[str, frozenset[int]] = {
|
| 79 |
+
"basic": frozenset((1, 5)),
|
| 80 |
+
"super": frozenset((0, 1, 2, 4, 5)),
|
| 81 |
+
"heavy": frozenset((0, 1, 2, 3, 4, 5)),
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
# ---------------------------------------------------------------------------
|
| 85 |
+
# Pool inference — keyed on auto.total (unique across pool types)
|
| 86 |
+
# ---------------------------------------------------------------------------
|
| 87 |
+
|
| 88 |
+
_AUTO_TOTAL_TO_POOL: dict[int, str] = {
|
| 89 |
+
20: "basic",
|
| 90 |
+
50: "super",
|
| 91 |
+
150: "heavy",
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def default_quota_set(pool: str) -> AccountQuotaSet:
|
| 96 |
+
"""Return a fresh copy of the default quota set for *pool*."""
|
| 97 |
+
src = _POOL_DEFAULTS.get(pool, BASIC_QUOTA_DEFAULTS)
|
| 98 |
+
qs = AccountQuotaSet(
|
| 99 |
+
auto=_w(src.auto.remaining, src.auto.total, src.auto.window_seconds),
|
| 100 |
+
fast=_w(src.fast.remaining, src.fast.total, src.fast.window_seconds),
|
| 101 |
+
expert=_w(src.expert.remaining, src.expert.total, src.expert.window_seconds),
|
| 102 |
+
)
|
| 103 |
+
if src.heavy is not None:
|
| 104 |
+
qs.heavy = _w(src.heavy.remaining, src.heavy.total, src.heavy.window_seconds)
|
| 105 |
+
if src.grok_4_3 is not None:
|
| 106 |
+
qs.grok_4_3 = _w(
|
| 107 |
+
src.grok_4_3.remaining, src.grok_4_3.total, src.grok_4_3.window_seconds
|
| 108 |
+
)
|
| 109 |
+
if src.console is not None:
|
| 110 |
+
qs.console = _w(
|
| 111 |
+
src.console.remaining, src.console.total, src.console.window_seconds
|
| 112 |
+
)
|
| 113 |
+
return qs
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def supports_mode(pool: str, mode_id: int) -> bool:
|
| 117 |
+
"""Return whether *pool* has a default quota window for *mode_id*."""
|
| 118 |
+
return mode_id in _SUPPORTED_MODE_IDS_BY_POOL.get(
|
| 119 |
+
pool, _SUPPORTED_MODE_IDS_BY_POOL["basic"]
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def supported_mode_ids(pool: str) -> tuple[int, ...]:
|
| 124 |
+
"""Return the supported mode IDs for *pool* in stable request order."""
|
| 125 |
+
supported = _SUPPORTED_MODE_IDS_BY_POOL.get(
|
| 126 |
+
pool, _SUPPORTED_MODE_IDS_BY_POOL["basic"]
|
| 127 |
+
)
|
| 128 |
+
return tuple(mode_id for mode_id in (0, 1, 2, 3, 4, 5) if mode_id in supported)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def default_quota_window(pool: str, mode_id: int) -> QuotaWindow | None:
|
| 132 |
+
"""Return the default quota window for *(pool, mode_id)*, if supported."""
|
| 133 |
+
if not supports_mode(pool, mode_id):
|
| 134 |
+
return None
|
| 135 |
+
return default_quota_set(pool).get(mode_id)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def normalize_quota_window(
|
| 139 |
+
pool: str, mode_id: int, window: QuotaWindow | None
|
| 140 |
+
) -> QuotaWindow | None:
|
| 141 |
+
"""Apply product-level quota policy for one pool/mode window."""
|
| 142 |
+
if window is None or not supports_mode(pool, mode_id):
|
| 143 |
+
return None
|
| 144 |
+
if pool == "basic" and mode_id == 1:
|
| 145 |
+
return QuotaWindow(
|
| 146 |
+
remaining=max(0, min(int(window.remaining), BASIC_FAST_LIMIT)),
|
| 147 |
+
total=BASIC_FAST_LIMIT,
|
| 148 |
+
window_seconds=BASIC_FAST_WINDOW_SECONDS,
|
| 149 |
+
reset_at=window.reset_at,
|
| 150 |
+
synced_at=window.synced_at,
|
| 151 |
+
source=window.source,
|
| 152 |
+
)
|
| 153 |
+
if pool == "basic" and mode_id == 5:
|
| 154 |
+
# L1 修复:矫正历史 console 配额数据到当前常量值
|
| 155 |
+
# 历史值如 200/24h、70/5min、100/1min、30/15min、30/30min 等均归一到 20/60min
|
| 156 |
+
return QuotaWindow(
|
| 157 |
+
remaining=max(0, min(int(window.remaining), BASIC_CONSOLE_LIMIT)),
|
| 158 |
+
total=BASIC_CONSOLE_LIMIT,
|
| 159 |
+
window_seconds=BASIC_CONSOLE_WINDOW_SECONDS,
|
| 160 |
+
reset_at=window.reset_at,
|
| 161 |
+
synced_at=window.synced_at,
|
| 162 |
+
source=window.source,
|
| 163 |
+
)
|
| 164 |
+
return window
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def normalize_quota_set(pool: str, quota_set: AccountQuotaSet) -> AccountQuotaSet:
|
| 168 |
+
"""Return a quota set normalized to the supported modes for *pool*."""
|
| 169 |
+
defaults = default_quota_set(pool)
|
| 170 |
+
|
| 171 |
+
auto = normalize_quota_window(pool, 0, quota_set.auto) or defaults.auto
|
| 172 |
+
fast = normalize_quota_window(pool, 1, quota_set.fast) or defaults.fast
|
| 173 |
+
expert = normalize_quota_window(pool, 2, quota_set.expert) or defaults.expert
|
| 174 |
+
|
| 175 |
+
qs = AccountQuotaSet(auto=auto, fast=fast, expert=expert)
|
| 176 |
+
qs.heavy = normalize_quota_window(pool, 3, quota_set.heavy)
|
| 177 |
+
qs.grok_4_3 = normalize_quota_window(pool, 4, quota_set.grok_4_3)
|
| 178 |
+
qs.console = normalize_quota_window(pool, 5, quota_set.console) or defaults.console
|
| 179 |
+
return qs
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def infer_pool(windows: dict[int, QuotaWindow]) -> str:
|
| 183 |
+
"""Infer pool type from live quota windows returned by the rate-limits API.
|
| 184 |
+
|
| 185 |
+
Uses ``auto.total`` (mode_id=0) as the discriminating signal.
|
| 186 |
+
Falls back to ``"basic"`` when the value is absent or unrecognised.
|
| 187 |
+
"""
|
| 188 |
+
auto_win = windows.get(0)
|
| 189 |
+
if auto_win is None:
|
| 190 |
+
return "basic"
|
| 191 |
+
return _AUTO_TOTAL_TO_POOL.get(auto_win.total, "basic")
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
__all__ = [
|
| 195 |
+
"BASIC_QUOTA_DEFAULTS",
|
| 196 |
+
"SUPER_QUOTA_DEFAULTS",
|
| 197 |
+
"HEAVY_QUOTA_DEFAULTS",
|
| 198 |
+
"default_quota_set",
|
| 199 |
+
"default_quota_window",
|
| 200 |
+
"infer_pool",
|
| 201 |
+
"normalize_quota_set",
|
| 202 |
+
"normalize_quota_window",
|
| 203 |
+
"supported_mode_ids",
|
| 204 |
+
"supports_mode",
|
| 205 |
+
]
|
app/control/account/refresh.py
ADDED
|
@@ -0,0 +1,675 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Account refresh service — mode-aware usage synchronisation."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import TYPE_CHECKING
|
| 6 |
+
|
| 7 |
+
from app.platform.errors import UpstreamError
|
| 8 |
+
from app.platform.config.snapshot import get_config
|
| 9 |
+
from app.platform.logging.logger import logger
|
| 10 |
+
from app.platform.runtime.clock import now_ms
|
| 11 |
+
from app.platform.runtime.batch import run_batch
|
| 12 |
+
from app.control.model.enums import ALL_MODES_FULL
|
| 13 |
+
from .enums import AccountStatus, QuotaSource
|
| 14 |
+
from .models import AccountRecord, QuotaWindow
|
| 15 |
+
from .quota_defaults import (
|
| 16 |
+
default_quota_window,
|
| 17 |
+
infer_pool,
|
| 18 |
+
normalize_quota_window,
|
| 19 |
+
supported_mode_ids,
|
| 20 |
+
supports_mode,
|
| 21 |
+
)
|
| 22 |
+
from .state_machine import is_manageable
|
| 23 |
+
|
| 24 |
+
if TYPE_CHECKING:
|
| 25 |
+
from .repository import AccountRepository
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass
|
| 29 |
+
class RefreshResult:
|
| 30 |
+
checked: int = 0
|
| 31 |
+
refreshed: int = 0
|
| 32 |
+
recovered: int = 0
|
| 33 |
+
expired: int = 0
|
| 34 |
+
disabled: int = 0
|
| 35 |
+
rate_limited: int = 0
|
| 36 |
+
failed: int = 0
|
| 37 |
+
|
| 38 |
+
def merge(self, other: "RefreshResult") -> None:
|
| 39 |
+
self.checked += other.checked
|
| 40 |
+
self.refreshed += other.refreshed
|
| 41 |
+
self.recovered += other.recovered
|
| 42 |
+
self.expired += other.expired
|
| 43 |
+
self.disabled += other.disabled
|
| 44 |
+
self.rate_limited += other.rate_limited
|
| 45 |
+
self.failed += other.failed
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
_MODE_KEYS = {
|
| 49 |
+
0: "quota_auto",
|
| 50 |
+
1: "quota_fast",
|
| 51 |
+
2: "quota_expert",
|
| 52 |
+
3: "quota_heavy",
|
| 53 |
+
4: "quota_grok_4_3",
|
| 54 |
+
5: "quota_console", # console.x.ai 独立配额
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _infer_pool_from_live_windows(windows: dict[int, QuotaWindow]) -> str | None:
|
| 59 |
+
"""Infer pool only from quota totals that identify an entitlement tier."""
|
| 60 |
+
auto_win = windows.get(0)
|
| 61 |
+
if auto_win is not None:
|
| 62 |
+
inferred = infer_pool(windows) # type: ignore[arg-type]
|
| 63 |
+
if inferred != "basic" or auto_win.total == 20:
|
| 64 |
+
return inferred
|
| 65 |
+
|
| 66 |
+
for mode_id in (2, 4):
|
| 67 |
+
win = windows.get(mode_id)
|
| 68 |
+
if win is None:
|
| 69 |
+
continue
|
| 70 |
+
if win.total == 150:
|
| 71 |
+
return "heavy"
|
| 72 |
+
if win.total == 50:
|
| 73 |
+
return "super"
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class AccountRefreshService:
|
| 78 |
+
"""Fetches real quota data from the upstream usage API and persists it.
|
| 79 |
+
|
| 80 |
+
Triggers:
|
| 81 |
+
1. Import — fetch all modes supported by the account's pool.
|
| 82 |
+
2. Call — fetch the called mode only (async, non-blocking).
|
| 83 |
+
3. Schedule — refresh one pool per loop using that pool's supported modes.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, repository: "AccountRepository") -> None:
|
| 87 |
+
self._repo = repository
|
| 88 |
+
self._lock = asyncio.Lock()
|
| 89 |
+
self._od_lock = asyncio.Lock()
|
| 90 |
+
self._od_last = 0.0
|
| 91 |
+
|
| 92 |
+
# ------------------------------------------------------------------
|
| 93 |
+
# Usage API fetch (delegates to dataplane reverse protocol)
|
| 94 |
+
# ------------------------------------------------------------------
|
| 95 |
+
|
| 96 |
+
async def _fetch_all_quotas(
|
| 97 |
+
self, token: str, pool: str, *, bootstrap: bool = False
|
| 98 |
+
) -> dict[int, QuotaWindow] | None:
|
| 99 |
+
"""Fetch quota windows for every mode supported by *pool*.
|
| 100 |
+
|
| 101 |
+
Examples:
|
| 102 |
+
- basic -> fast
|
| 103 |
+
- super -> auto / fast / expert / grok_4_3
|
| 104 |
+
- heavy -> auto / fast / expert / heavy / grok_4_3
|
| 105 |
+
"""
|
| 106 |
+
try:
|
| 107 |
+
from app.dataplane.reverse.protocol.xai_usage import fetch_all_quotas
|
| 108 |
+
|
| 109 |
+
mode_ids = supported_mode_ids(pool)
|
| 110 |
+
if bootstrap:
|
| 111 |
+
# Bootstrap refreshes need entitlement probes even when the
|
| 112 |
+
# current local image is basic. If auto is flaky, expert/heavy
|
| 113 |
+
# windows still provide enough signal to avoid a sticky
|
| 114 |
+
# misclassification.
|
| 115 |
+
mode_ids = tuple(dict.fromkeys((0, 2, 3, 4, *mode_ids)))
|
| 116 |
+
return await fetch_all_quotas(token, mode_ids)
|
| 117 |
+
except UpstreamError:
|
| 118 |
+
raise
|
| 119 |
+
except Exception as exc:
|
| 120 |
+
logger.debug(
|
| 121 |
+
"account quota fetch failed: token={}... pool={} error={}",
|
| 122 |
+
token[:10],
|
| 123 |
+
pool,
|
| 124 |
+
exc,
|
| 125 |
+
)
|
| 126 |
+
return None
|
| 127 |
+
|
| 128 |
+
async def _fetch_mode_quota(
|
| 129 |
+
self, token: str, pool: str, mode_id: int
|
| 130 |
+
) -> QuotaWindow | None:
|
| 131 |
+
"""Fetch a single mode quota window."""
|
| 132 |
+
if not supports_mode(pool, mode_id):
|
| 133 |
+
logger.debug(
|
| 134 |
+
"account mode quota fetch skipped: token={}... pool={} mode_id={} reason=unsupported_mode",
|
| 135 |
+
token[:10],
|
| 136 |
+
pool,
|
| 137 |
+
mode_id,
|
| 138 |
+
)
|
| 139 |
+
return None
|
| 140 |
+
try:
|
| 141 |
+
from app.dataplane.reverse.protocol.xai_usage import fetch_mode_quota
|
| 142 |
+
|
| 143 |
+
return await fetch_mode_quota(token, mode_id)
|
| 144 |
+
except UpstreamError:
|
| 145 |
+
raise
|
| 146 |
+
except Exception as exc:
|
| 147 |
+
logger.debug(
|
| 148 |
+
"account mode quota fetch failed: token={}... pool={} mode_id={} error={}",
|
| 149 |
+
token[:10],
|
| 150 |
+
pool,
|
| 151 |
+
mode_id,
|
| 152 |
+
exc,
|
| 153 |
+
)
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
# ------------------------------------------------------------------
|
| 157 |
+
# Core refresh logic
|
| 158 |
+
# ------------------------------------------------------------------
|
| 159 |
+
|
| 160 |
+
async def refresh_on_import(self, tokens: list[str]) -> RefreshResult:
|
| 161 |
+
"""Called after bulk import — sync real quotas for all accounts."""
|
| 162 |
+
records = await self._repo.get_accounts(tokens)
|
| 163 |
+
active = [r for r in records if is_manageable(r)]
|
| 164 |
+
if not active:
|
| 165 |
+
return RefreshResult(checked=len(records))
|
| 166 |
+
|
| 167 |
+
concurrency = get_config("account.refresh.usage_concurrency", 15)
|
| 168 |
+
results = await run_batch(
|
| 169 |
+
active,
|
| 170 |
+
lambda r: self._refresh_one(r, apply_fallback=True, bootstrap=True),
|
| 171 |
+
concurrency=concurrency,
|
| 172 |
+
)
|
| 173 |
+
agg = RefreshResult(checked=len(records))
|
| 174 |
+
for r in results:
|
| 175 |
+
agg.merge(r)
|
| 176 |
+
return agg
|
| 177 |
+
|
| 178 |
+
async def refresh_call_async(self, token: str, mode_id: int) -> None:
|
| 179 |
+
"""Fire-and-forget single-mode quota sync after a successful call."""
|
| 180 |
+
record = (await self._repo.get_accounts([token]) or [None])[0]
|
| 181 |
+
if record is None or record.is_deleted():
|
| 182 |
+
return
|
| 183 |
+
|
| 184 |
+
# mode_id=5 (CONSOLE) 是本地管理的配额,不需要请求 xai usage API
|
| 185 |
+
# 直接做本地扣减并更新 usage_use_count
|
| 186 |
+
if mode_id == 5:
|
| 187 |
+
await self._apply_single_mode(
|
| 188 |
+
record, mode_id, window=None, is_use=True, use_at_ms=now_ms()
|
| 189 |
+
)
|
| 190 |
+
return
|
| 191 |
+
|
| 192 |
+
try:
|
| 193 |
+
window = await self._fetch_mode_quota(token, record.pool, mode_id)
|
| 194 |
+
except UpstreamError as exc:
|
| 195 |
+
if await self._expire_invalid_credentials(record, exc):
|
| 196 |
+
return
|
| 197 |
+
raise
|
| 198 |
+
await self._apply_single_mode(
|
| 199 |
+
record, mode_id, window, is_use=True, use_at_ms=now_ms()
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
async def refresh_scheduled(self, pool: str | None = None) -> RefreshResult:
|
| 203 |
+
"""Periodic refresh — fetch real quotas for all (or one pool's) accounts.
|
| 204 |
+
|
| 205 |
+
Args:
|
| 206 |
+
pool: When set, only refreshes accounts belonging to that pool.
|
| 207 |
+
When ``None``, refreshes all pools.
|
| 208 |
+
"""
|
| 209 |
+
snapshot = await self._repo.runtime_snapshot()
|
| 210 |
+
records = [r for r in snapshot.items if is_manageable(r)]
|
| 211 |
+
if pool is not None:
|
| 212 |
+
records = [r for r in records if r.pool == pool]
|
| 213 |
+
|
| 214 |
+
concurrency = get_config("account.refresh.usage_concurrency", 15)
|
| 215 |
+
results = await run_batch(
|
| 216 |
+
records,
|
| 217 |
+
lambda r: self._refresh_one(r, apply_fallback=True),
|
| 218 |
+
concurrency=concurrency,
|
| 219 |
+
)
|
| 220 |
+
agg = RefreshResult()
|
| 221 |
+
for r in results:
|
| 222 |
+
agg.merge(r)
|
| 223 |
+
return agg
|
| 224 |
+
|
| 225 |
+
async def refresh_on_demand(self) -> RefreshResult:
|
| 226 |
+
"""Throttled on-demand refresh triggered by request path."""
|
| 227 |
+
min_interval = float(
|
| 228 |
+
get_config("account.refresh.on_demand_min_interval_sec", 300)
|
| 229 |
+
)
|
| 230 |
+
import time
|
| 231 |
+
|
| 232 |
+
now = time.monotonic()
|
| 233 |
+
if now - self._od_last < min_interval:
|
| 234 |
+
return RefreshResult()
|
| 235 |
+
if self._od_lock.locked():
|
| 236 |
+
return RefreshResult()
|
| 237 |
+
async with self._od_lock:
|
| 238 |
+
now = time.monotonic()
|
| 239 |
+
if now - self._od_last < min_interval:
|
| 240 |
+
return RefreshResult()
|
| 241 |
+
result = await self.refresh_scheduled()
|
| 242 |
+
self._od_last = time.monotonic()
|
| 243 |
+
return result
|
| 244 |
+
|
| 245 |
+
async def refresh_tokens(self, tokens: list[str]) -> RefreshResult:
|
| 246 |
+
"""Explicit refresh for a list of tokens (admin / manual trigger)."""
|
| 247 |
+
records = [r for r in await self._repo.get_accounts(tokens) if is_manageable(r)]
|
| 248 |
+
concurrency = get_config("account.refresh.usage_concurrency", 15)
|
| 249 |
+
results = await run_batch(
|
| 250 |
+
records,
|
| 251 |
+
lambda r: self._refresh_one(r, bootstrap=True),
|
| 252 |
+
concurrency=concurrency,
|
| 253 |
+
)
|
| 254 |
+
agg = RefreshResult()
|
| 255 |
+
for r in results:
|
| 256 |
+
agg.merge(r)
|
| 257 |
+
return agg
|
| 258 |
+
|
| 259 |
+
# ------------------------------------------------------------------
|
| 260 |
+
# Per-account refresh
|
| 261 |
+
# ------------------------------------------------------------------
|
| 262 |
+
|
| 263 |
+
async def _refresh_one(
|
| 264 |
+
self,
|
| 265 |
+
record: AccountRecord,
|
| 266 |
+
*,
|
| 267 |
+
apply_fallback: bool = False,
|
| 268 |
+
bootstrap: bool = False,
|
| 269 |
+
) -> RefreshResult:
|
| 270 |
+
"""Fetch all pool-supported modes from the usage API and persist them.
|
| 271 |
+
|
| 272 |
+
apply_fallback=True — used by scheduled/import paths: when API fails,
|
| 273 |
+
decrement REAL quotas or reset expired DEFAULT windows.
|
| 274 |
+
apply_fallback=False — used by manual/on-demand paths: if API fails, return
|
| 275 |
+
failed=1 immediately without touching stored data.
|
| 276 |
+
"""
|
| 277 |
+
if record.is_deleted():
|
| 278 |
+
return RefreshResult()
|
| 279 |
+
|
| 280 |
+
try:
|
| 281 |
+
windows = await self._fetch_all_quotas(
|
| 282 |
+
record.token, record.pool, bootstrap=bootstrap
|
| 283 |
+
)
|
| 284 |
+
except UpstreamError as exc:
|
| 285 |
+
if await self._expire_invalid_credentials(record, exc):
|
| 286 |
+
return RefreshResult(checked=1, expired=1, failed=0)
|
| 287 |
+
raise
|
| 288 |
+
|
| 289 |
+
# API call completely failed — no real data available.
|
| 290 |
+
if windows is None:
|
| 291 |
+
if not apply_fallback:
|
| 292 |
+
return RefreshResult(checked=1, failed=1)
|
| 293 |
+
# Scheduled/import path: apply conservative fallback.
|
| 294 |
+
return await self._apply_fallback(record)
|
| 295 |
+
|
| 296 |
+
# We got at least a response — apply real data per mode.
|
| 297 |
+
qs = record.quota_set()
|
| 298 |
+
now = now_ms()
|
| 299 |
+
patches: dict[str, dict] = {}
|
| 300 |
+
refreshed = False
|
| 301 |
+
inferred = _infer_pool_from_live_windows(windows)
|
| 302 |
+
effective_pool = inferred if (bootstrap and inferred) else record.pool
|
| 303 |
+
|
| 304 |
+
for mode in ALL_MODES_FULL:
|
| 305 |
+
mode_id = int(mode)
|
| 306 |
+
if mode_id in windows:
|
| 307 |
+
window = normalize_quota_window(
|
| 308 |
+
effective_pool, mode_id, windows[mode_id]
|
| 309 |
+
)
|
| 310 |
+
if window is None:
|
| 311 |
+
continue
|
| 312 |
+
patches[_MODE_KEYS[mode_id]] = window.to_dict()
|
| 313 |
+
refreshed = True
|
| 314 |
+
elif apply_fallback:
|
| 315 |
+
existing = qs.get(mode_id)
|
| 316 |
+
if existing is None:
|
| 317 |
+
continue
|
| 318 |
+
if existing.source == QuotaSource.REAL:
|
| 319 |
+
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
| 320 |
+
remaining=max(0, existing.remaining - 1),
|
| 321 |
+
total=existing.total,
|
| 322 |
+
window_seconds=existing.window_seconds,
|
| 323 |
+
reset_at=existing.reset_at,
|
| 324 |
+
synced_at=existing.synced_at,
|
| 325 |
+
source=QuotaSource.ESTIMATED,
|
| 326 |
+
).to_dict()
|
| 327 |
+
elif existing.is_window_expired(now):
|
| 328 |
+
default = default_quota_window(effective_pool, mode_id)
|
| 329 |
+
if default is None:
|
| 330 |
+
continue
|
| 331 |
+
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
| 332 |
+
remaining=default.total,
|
| 333 |
+
total=default.total,
|
| 334 |
+
window_seconds=default.window_seconds,
|
| 335 |
+
reset_at=now + default.window_seconds * 1000,
|
| 336 |
+
synced_at=now,
|
| 337 |
+
source=QuotaSource.DEFAULT,
|
| 338 |
+
).to_dict()
|
| 339 |
+
|
| 340 |
+
if not patches:
|
| 341 |
+
return RefreshResult(checked=1, failed=0 if refreshed else 1)
|
| 342 |
+
|
| 343 |
+
# Infer pool type from live quota data and patch if it changed.
|
| 344 |
+
pool_patch = inferred if inferred is not None and inferred != record.pool else None
|
| 345 |
+
if pool_patch:
|
| 346 |
+
logger.info(
|
| 347 |
+
"account pool updated from live quota: token={}... previous_pool={} current_pool={}",
|
| 348 |
+
record.token[:10],
|
| 349 |
+
record.pool,
|
| 350 |
+
inferred,
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
from .commands import AccountPatch
|
| 354 |
+
|
| 355 |
+
await self._repo.patch_accounts(
|
| 356 |
+
[
|
| 357 |
+
AccountPatch(
|
| 358 |
+
token=record.token,
|
| 359 |
+
pool=pool_patch,
|
| 360 |
+
last_sync_at=now_ms() if refreshed else None,
|
| 361 |
+
usage_sync_delta=1 if refreshed else None,
|
| 362 |
+
**patches, # type: ignore[arg-type]
|
| 363 |
+
)
|
| 364 |
+
]
|
| 365 |
+
)
|
| 366 |
+
was_cooling = record.status == AccountStatus.COOLING
|
| 367 |
+
return RefreshResult(
|
| 368 |
+
checked=1,
|
| 369 |
+
refreshed=1 if refreshed else 0,
|
| 370 |
+
failed=0 if refreshed else 1,
|
| 371 |
+
recovered=1 if (was_cooling and refreshed) else 0,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
async def _apply_fallback(self, record: AccountRecord) -> RefreshResult:
|
| 375 |
+
"""Conservative fallback when API is unreachable (scheduled/import path only)."""
|
| 376 |
+
qs = record.quota_set()
|
| 377 |
+
now = now_ms()
|
| 378 |
+
patches: dict[str, dict] = {}
|
| 379 |
+
|
| 380 |
+
for mode in ALL_MODES_FULL:
|
| 381 |
+
mode_id = int(mode)
|
| 382 |
+
existing = qs.get(mode_id)
|
| 383 |
+
if existing is None:
|
| 384 |
+
continue
|
| 385 |
+
if existing.source == QuotaSource.REAL:
|
| 386 |
+
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
| 387 |
+
remaining=max(0, existing.remaining - 1),
|
| 388 |
+
total=existing.total,
|
| 389 |
+
window_seconds=existing.window_seconds,
|
| 390 |
+
reset_at=existing.reset_at,
|
| 391 |
+
synced_at=existing.synced_at,
|
| 392 |
+
source=QuotaSource.ESTIMATED,
|
| 393 |
+
).to_dict()
|
| 394 |
+
elif existing.is_window_expired(now):
|
| 395 |
+
default = default_quota_window(record.pool, mode_id)
|
| 396 |
+
if default is None:
|
| 397 |
+
continue
|
| 398 |
+
patches[_MODE_KEYS[mode_id]] = QuotaWindow(
|
| 399 |
+
remaining=default.total,
|
| 400 |
+
total=default.total,
|
| 401 |
+
window_seconds=default.window_seconds,
|
| 402 |
+
reset_at=now + default.window_seconds * 1000,
|
| 403 |
+
synced_at=now,
|
| 404 |
+
source=QuotaSource.DEFAULT,
|
| 405 |
+
).to_dict()
|
| 406 |
+
|
| 407 |
+
if patches:
|
| 408 |
+
from .commands import AccountPatch
|
| 409 |
+
|
| 410 |
+
await self._repo.patch_accounts(
|
| 411 |
+
[AccountPatch(token=record.token, **patches)]
|
| 412 |
+
) # type: ignore[arg-type]
|
| 413 |
+
|
| 414 |
+
return RefreshResult(checked=1, failed=1)
|
| 415 |
+
|
| 416 |
+
async def record_failure_async(
|
| 417 |
+
self, token: str, mode_id: int, exc: BaseException | None = None
|
| 418 |
+
) -> None:
|
| 419 |
+
"""Fire-and-forget: persist failure counter and timestamp after a failed call."""
|
| 420 |
+
from .commands import AccountPatch
|
| 421 |
+
|
| 422 |
+
try:
|
| 423 |
+
if exc is not None:
|
| 424 |
+
record = next(iter(await self._repo.get_accounts([token])), None)
|
| 425 |
+
if record is not None and await self._expire_invalid_credentials(
|
| 426 |
+
record, exc
|
| 427 |
+
):
|
| 428 |
+
return
|
| 429 |
+
if (
|
| 430 |
+
record is not None
|
| 431 |
+
and getattr(exc, "status", None) == 429
|
| 432 |
+
and mode_id in _MODE_KEYS
|
| 433 |
+
):
|
| 434 |
+
now = now_ms()
|
| 435 |
+
quota_patch: dict[str, dict] = {}
|
| 436 |
+
window = record.quota_set().get(mode_id)
|
| 437 |
+
extra_patch: dict = {}
|
| 438 |
+
if window is not None:
|
| 439 |
+
if mode_id == 5:
|
| 440 |
+
# Console 429: 一次直接清零(扣 20),账号当前窗口不再可用
|
| 441 |
+
# 立即启动恢复计时器,窗口结束后由巡检任务重置
|
| 442 |
+
new_remaining = 0
|
| 443 |
+
reset_at = window.reset_at
|
| 444 |
+
if reset_at is None and window.window_seconds > 0:
|
| 445 |
+
reset_at = now + window.window_seconds * 1000
|
| 446 |
+
quota_patch[_MODE_KEYS[mode_id]] = QuotaWindow(
|
| 447 |
+
remaining=new_remaining,
|
| 448 |
+
total=window.total,
|
| 449 |
+
window_seconds=window.window_seconds,
|
| 450 |
+
reset_at=reset_at,
|
| 451 |
+
synced_at=window.synced_at,
|
| 452 |
+
source=QuotaSource.ESTIMATED,
|
| 453 |
+
).to_dict()
|
| 454 |
+
# Console 专属 429 计数器(独立于 usage_fail_count,
|
| 455 |
+
# 避免被 500/网络超时等其他失败干扰)。
|
| 456 |
+
# 12 小时滑动窗口:距离上次 429 超过 12 小时 → 计数重置为 0
|
| 457 |
+
ext_data = record.ext or {}
|
| 458 |
+
last_429_at = int(ext_data.get("console_429_last_at", 0))
|
| 459 |
+
sliding_window_ms = 12 * 3600 * 1000
|
| 460 |
+
if last_429_at > 0 and (now - last_429_at) > sliding_window_ms:
|
| 461 |
+
console_429_count = 0
|
| 462 |
+
else:
|
| 463 |
+
console_429_count = int(ext_data.get("console_429_count", 0))
|
| 464 |
+
new_429_count = console_429_count + 1
|
| 465 |
+
ext_merge: dict = {
|
| 466 |
+
**ext_data,
|
| 467 |
+
"console_429_count": new_429_count,
|
| 468 |
+
"console_429_last_at": now,
|
| 469 |
+
}
|
| 470 |
+
# 12 小时内累计 3 次 429 标记为 EXPIRED 异常组
|
| 471 |
+
if new_429_count >= 3:
|
| 472 |
+
extra_patch["status"] = AccountStatus.EXPIRED
|
| 473 |
+
extra_patch["state_reason"] = "console_429_threshold_exceeded"
|
| 474 |
+
ext_merge["expired_at"] = now
|
| 475 |
+
ext_merge["expired_reason"] = "console_429_threshold_exceeded"
|
| 476 |
+
logger.info(
|
| 477 |
+
"account marked expired due to repeated 429: token={}... count={}",
|
| 478 |
+
token[:10],
|
| 479 |
+
new_429_count,
|
| 480 |
+
)
|
| 481 |
+
extra_patch["ext_merge"] = ext_merge
|
| 482 |
+
else:
|
| 483 |
+
# 非 console 模式保持原有清零逻辑
|
| 484 |
+
reset_at = (
|
| 485 |
+
window.reset_at
|
| 486 |
+
if window.reset_at is not None and window.reset_at > now
|
| 487 |
+
else now + max(window.window_seconds, 1) * 1000
|
| 488 |
+
)
|
| 489 |
+
quota_patch[_MODE_KEYS[mode_id]] = QuotaWindow(
|
| 490 |
+
remaining=0,
|
| 491 |
+
total=window.total,
|
| 492 |
+
window_seconds=window.window_seconds,
|
| 493 |
+
reset_at=reset_at,
|
| 494 |
+
synced_at=window.synced_at,
|
| 495 |
+
source=QuotaSource.ESTIMATED,
|
| 496 |
+
).to_dict()
|
| 497 |
+
await self._repo.patch_accounts(
|
| 498 |
+
[
|
| 499 |
+
AccountPatch(
|
| 500 |
+
token=token,
|
| 501 |
+
usage_fail_delta=1,
|
| 502 |
+
last_fail_at=now,
|
| 503 |
+
last_fail_reason="rate_limited",
|
| 504 |
+
**extra_patch,
|
| 505 |
+
**quota_patch,
|
| 506 |
+
)
|
| 507 |
+
]
|
| 508 |
+
)
|
| 509 |
+
return
|
| 510 |
+
await self._repo.patch_accounts(
|
| 511 |
+
[
|
| 512 |
+
AccountPatch(
|
| 513 |
+
token=token,
|
| 514 |
+
usage_fail_delta=1,
|
| 515 |
+
last_fail_at=now_ms(),
|
| 516 |
+
)
|
| 517 |
+
]
|
| 518 |
+
)
|
| 519 |
+
except Exception as exc:
|
| 520 |
+
logger.debug(
|
| 521 |
+
"account failure record update failed: token={}... error={}",
|
| 522 |
+
token[:10],
|
| 523 |
+
exc,
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
async def _apply_single_mode(
|
| 527 |
+
self,
|
| 528 |
+
record: AccountRecord,
|
| 529 |
+
mode_id: int,
|
| 530 |
+
window: QuotaWindow | None,
|
| 531 |
+
*,
|
| 532 |
+
is_use: bool = False,
|
| 533 |
+
use_at_ms: int | None = None,
|
| 534 |
+
) -> None:
|
| 535 |
+
qs = record.quota_set()
|
| 536 |
+
mode_key = _MODE_KEYS.get(mode_id)
|
| 537 |
+
if mode_key is None:
|
| 538 |
+
logger.warning(
|
| 539 |
+
"account single-mode sync skipped: token={}... pool={} mode_id={} reason=unknown_mode",
|
| 540 |
+
record.token[:10],
|
| 541 |
+
record.pool,
|
| 542 |
+
mode_id,
|
| 543 |
+
)
|
| 544 |
+
return
|
| 545 |
+
|
| 546 |
+
quota_patch: dict[str, dict] = {}
|
| 547 |
+
if window is not None:
|
| 548 |
+
normalized = normalize_quota_window(record.pool, mode_id, window)
|
| 549 |
+
if normalized is None:
|
| 550 |
+
logger.debug(
|
| 551 |
+
"account single-mode quota patch skipped: token={}... pool={} mode_id={} reason=unsupported_mode",
|
| 552 |
+
record.token[:10],
|
| 553 |
+
record.pool,
|
| 554 |
+
mode_id,
|
| 555 |
+
)
|
| 556 |
+
return
|
| 557 |
+
quota_patch[mode_key] = normalized.to_dict()
|
| 558 |
+
else:
|
| 559 |
+
existing = qs.get(mode_id)
|
| 560 |
+
if existing is not None:
|
| 561 |
+
now = now_ms()
|
| 562 |
+
# 如果窗口已过期,重置为默认值(适用于本地管理的配额,如 console)
|
| 563 |
+
if existing.is_window_expired(now):
|
| 564 |
+
default = default_quota_window(record.pool, mode_id)
|
| 565 |
+
if default is not None:
|
| 566 |
+
new_remaining = max(0, default.total - 1) # 本次调用消耗1次
|
| 567 |
+
# console (mode_id=5) 阈值轮换策略:reset_at=None,
|
| 568 |
+
# 让后续扣减在 remaining<=12 时再启动计时器,与 else 分支一致;
|
| 569 |
+
# 非 console 模式保持原行为:首次使用即启动计时器
|
| 570 |
+
if mode_id == 5:
|
| 571 |
+
reset_at = None
|
| 572 |
+
else:
|
| 573 |
+
reset_at = now + default.window_seconds * 1000
|
| 574 |
+
quota_patch[mode_key] = QuotaWindow(
|
| 575 |
+
remaining=new_remaining,
|
| 576 |
+
total=default.total,
|
| 577 |
+
window_seconds=default.window_seconds,
|
| 578 |
+
reset_at=reset_at,
|
| 579 |
+
synced_at=now,
|
| 580 |
+
source=QuotaSource.DEFAULT,
|
| 581 |
+
).to_dict()
|
| 582 |
+
else:
|
| 583 |
+
# Console 配额轮换策略:remaining 降到阈值时才启动恢复计时器,
|
| 584 |
+
# 避免同一批账号被反复选中(评分机制会优先选配额充足的账号)。
|
| 585 |
+
new_remaining = max(0, existing.remaining - 1)
|
| 586 |
+
reset_at = existing.reset_at
|
| 587 |
+
if mode_id == 5:
|
| 588 |
+
# console 配额:remaining <= 12 时才启动恢复计时器
|
| 589 |
+
if reset_at is None and new_remaining <= 12 and existing.window_seconds > 0:
|
| 590 |
+
reset_at = now + existing.window_seconds * 1000
|
| 591 |
+
else:
|
| 592 |
+
# 非 console 模式保持原有逻辑:首次使用即启动计时器
|
| 593 |
+
if reset_at is None and existing.window_seconds > 0:
|
| 594 |
+
reset_at = now + existing.window_seconds * 1000
|
| 595 |
+
quota_patch[mode_key] = QuotaWindow(
|
| 596 |
+
remaining=new_remaining,
|
| 597 |
+
total=existing.total,
|
| 598 |
+
window_seconds=existing.window_seconds,
|
| 599 |
+
reset_at=reset_at,
|
| 600 |
+
synced_at=existing.synced_at,
|
| 601 |
+
source=QuotaSource.ESTIMATED,
|
| 602 |
+
).to_dict()
|
| 603 |
+
else:
|
| 604 |
+
logger.debug(
|
| 605 |
+
"account single-mode quota patch skipped: token={}... pool={} mode_id={} reason=unsupported_mode",
|
| 606 |
+
record.token[:10],
|
| 607 |
+
record.pool,
|
| 608 |
+
mode_id,
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
from .commands import AccountPatch
|
| 612 |
+
|
| 613 |
+
await self._repo.patch_accounts(
|
| 614 |
+
[
|
| 615 |
+
AccountPatch(
|
| 616 |
+
token=record.token,
|
| 617 |
+
last_sync_at=now_ms() if window is not None else None,
|
| 618 |
+
usage_sync_delta=1 if window is not None else None,
|
| 619 |
+
usage_use_delta=1 if is_use else None,
|
| 620 |
+
last_use_at=use_at_ms if is_use else None,
|
| 621 |
+
**quota_patch, # type: ignore[arg-type]
|
| 622 |
+
)
|
| 623 |
+
]
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
async def _expire_invalid_credentials(
|
| 627 |
+
self, record: AccountRecord, exc: UpstreamError
|
| 628 |
+
) -> bool:
|
| 629 |
+
from .invalid_credentials import mark_account_invalid_credentials
|
| 630 |
+
|
| 631 |
+
return await mark_account_invalid_credentials(
|
| 632 |
+
self._repo,
|
| 633 |
+
record.token,
|
| 634 |
+
exc,
|
| 635 |
+
source="usage refresh",
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
# ------------------------------------------------------------------
|
| 639 |
+
# Console 配额窗口自动重置(后台定时巡检)
|
| 640 |
+
# ------------------------------------------------------------------
|
| 641 |
+
|
| 642 |
+
async def reset_expired_console_windows(self) -> int:
|
| 643 |
+
"""批量重置过期/卡死的 console 配额(委托给存储后端的 SQL 优化)。
|
| 644 |
+
|
| 645 |
+
Returns:
|
| 646 |
+
重置的账号数量。
|
| 647 |
+
"""
|
| 648 |
+
count = await self._repo.reset_expired_console_windows()
|
| 649 |
+
if count > 0:
|
| 650 |
+
logger.debug("console quota windows auto-reset: count={}", count)
|
| 651 |
+
return count
|
| 652 |
+
|
| 653 |
+
async def recover_console_expired_accounts(self) -> int:
|
| 654 |
+
"""自动恢复 console 429 EXPIRED 账号(满足条件)。
|
| 655 |
+
|
| 656 |
+
恢复条件(AND):
|
| 657 |
+
- status = EXPIRED
|
| 658 |
+
- state_reason = console_429_threshold_exceeded
|
| 659 |
+
- usage_use_count > 5(有成功调用历史)
|
| 660 |
+
- expired_at <= now - 1 小时(等待时间够了)
|
| 661 |
+
|
| 662 |
+
恢复操作:
|
| 663 |
+
- status: EXPIRED → ACTIVE
|
| 664 |
+
- 清理 ext 中的 expired_at / expired_reason / console_429_count / console_429_last_at
|
| 665 |
+
|
| 666 |
+
Returns:
|
| 667 |
+
恢复的账号数量。
|
| 668 |
+
"""
|
| 669 |
+
count = await self._repo.recover_console_expired_accounts()
|
| 670 |
+
if count > 0:
|
| 671 |
+
logger.info("console expired accounts auto-recovered: count={}", count)
|
| 672 |
+
return count
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
__all__ = ["AccountRefreshService", "RefreshResult"]
|
app/control/account/repository.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Account repository protocol — the contract every backend must satisfy."""
|
| 2 |
+
|
| 3 |
+
from typing import Protocol, runtime_checkable
|
| 4 |
+
|
| 5 |
+
from .commands import AccountPatch, AccountUpsert, BulkReplacePoolCommand, ListAccountsQuery
|
| 6 |
+
from .models import (
|
| 7 |
+
AccountChangeSet,
|
| 8 |
+
AccountMutationResult,
|
| 9 |
+
AccountPage,
|
| 10 |
+
AccountRecord,
|
| 11 |
+
RuntimeSnapshot,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@runtime_checkable
|
| 16 |
+
class AccountRepository(Protocol):
|
| 17 |
+
"""Storage contract shared by all account backends."""
|
| 18 |
+
|
| 19 |
+
async def initialize(self) -> None:
|
| 20 |
+
"""Create schema / tables / indices if they do not exist."""
|
| 21 |
+
...
|
| 22 |
+
|
| 23 |
+
async def get_revision(self) -> int:
|
| 24 |
+
"""Return the current global revision counter."""
|
| 25 |
+
...
|
| 26 |
+
|
| 27 |
+
async def runtime_snapshot(self) -> RuntimeSnapshot:
|
| 28 |
+
"""Return all non-deleted accounts for hot-path bootstrap."""
|
| 29 |
+
...
|
| 30 |
+
|
| 31 |
+
async def scan_changes(
|
| 32 |
+
self,
|
| 33 |
+
since_revision: int,
|
| 34 |
+
*,
|
| 35 |
+
limit: int = 5000,
|
| 36 |
+
) -> AccountChangeSet:
|
| 37 |
+
"""Return records modified after *since_revision* (inclusive)."""
|
| 38 |
+
...
|
| 39 |
+
|
| 40 |
+
async def upsert_accounts(
|
| 41 |
+
self,
|
| 42 |
+
items: list[AccountUpsert],
|
| 43 |
+
) -> AccountMutationResult:
|
| 44 |
+
"""Insert or replace accounts. Pushes revision."""
|
| 45 |
+
...
|
| 46 |
+
|
| 47 |
+
async def patch_accounts(
|
| 48 |
+
self,
|
| 49 |
+
patches: list[AccountPatch],
|
| 50 |
+
) -> AccountMutationResult:
|
| 51 |
+
"""Apply partial updates to existing accounts. Pushes revision."""
|
| 52 |
+
...
|
| 53 |
+
|
| 54 |
+
async def delete_accounts(
|
| 55 |
+
self,
|
| 56 |
+
tokens: list[str],
|
| 57 |
+
) -> AccountMutationResult:
|
| 58 |
+
"""Soft-delete accounts (set deleted_at). Pushes revision."""
|
| 59 |
+
...
|
| 60 |
+
|
| 61 |
+
async def get_accounts(
|
| 62 |
+
self,
|
| 63 |
+
tokens: list[str],
|
| 64 |
+
) -> list[AccountRecord]:
|
| 65 |
+
"""Fetch accounts by token list."""
|
| 66 |
+
...
|
| 67 |
+
|
| 68 |
+
async def list_accounts(
|
| 69 |
+
self,
|
| 70 |
+
query: ListAccountsQuery,
|
| 71 |
+
) -> AccountPage:
|
| 72 |
+
"""Return a paginated, filtered, sorted account list."""
|
| 73 |
+
...
|
| 74 |
+
|
| 75 |
+
async def replace_pool(
|
| 76 |
+
self,
|
| 77 |
+
command: BulkReplacePoolCommand,
|
| 78 |
+
) -> AccountMutationResult:
|
| 79 |
+
"""Atomically replace all accounts in a pool."""
|
| 80 |
+
...
|
| 81 |
+
|
| 82 |
+
async def reset_expired_console_windows(self) -> int:
|
| 83 |
+
"""Batch-reset console quotas that are exhausted and expired. Pushes revision."""
|
| 84 |
+
...
|
| 85 |
+
|
| 86 |
+
async def recover_console_expired_accounts(self) -> int:
|
| 87 |
+
"""Auto-recover console 429 EXPIRED accounts with successful history.
|
| 88 |
+
|
| 89 |
+
Recovery conditions (AND):
|
| 90 |
+
- status = EXPIRED
|
| 91 |
+
- state_reason = 'console_429_threshold_exceeded'
|
| 92 |
+
- usage_use_count > 5
|
| 93 |
+
- ext.expired_at <= now - 1 hour
|
| 94 |
+
"""
|
| 95 |
+
...
|
| 96 |
+
|
| 97 |
+
async def close(self) -> None:
|
| 98 |
+
"""Release database connections / file handles."""
|
| 99 |
+
...
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
__all__ = ["AccountRepository"]
|
app/control/account/runtime.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Account runtime singletons and hot-apply helpers.
|
| 2 |
+
|
| 3 |
+
These helpers expose the process-local account refresh runtime without making
|
| 4 |
+
callers import ``app.main``. Admin handlers use them to reconcile strategy and
|
| 5 |
+
scheduler state after hot config updates.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import TYPE_CHECKING, Literal
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from .refresh import AccountRefreshService
|
| 12 |
+
from .scheduler import AccountRefreshScheduler
|
| 13 |
+
|
| 14 |
+
_refresh_service: "AccountRefreshService | None" = None
|
| 15 |
+
_refresh_scheduler: "AccountRefreshScheduler | None" = None
|
| 16 |
+
_refresh_scheduler_leader = False
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def set_refresh_service(service: "AccountRefreshService | None") -> None:
|
| 20 |
+
"""Register the process-global account refresh service."""
|
| 21 |
+
global _refresh_service
|
| 22 |
+
_refresh_service = service
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_refresh_service() -> "AccountRefreshService | None":
|
| 26 |
+
"""Return the registered account refresh service, if any."""
|
| 27 |
+
return _refresh_service
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def set_refresh_scheduler(scheduler: "AccountRefreshScheduler | None") -> None:
|
| 31 |
+
"""Register the process-global account refresh scheduler."""
|
| 32 |
+
global _refresh_scheduler
|
| 33 |
+
_refresh_scheduler = scheduler
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_refresh_scheduler() -> "AccountRefreshScheduler | None":
|
| 37 |
+
"""Return the registered account refresh scheduler, if any."""
|
| 38 |
+
return _refresh_scheduler
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def set_refresh_scheduler_leader(is_leader: bool) -> None:
|
| 42 |
+
"""Record whether this worker currently owns the refresh scheduler lock."""
|
| 43 |
+
global _refresh_scheduler_leader
|
| 44 |
+
_refresh_scheduler_leader = bool(is_leader)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def is_refresh_scheduler_leader() -> bool:
|
| 48 |
+
"""Return True when this worker is the active refresh-scheduler leader."""
|
| 49 |
+
return _refresh_scheduler_leader
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def reconcile_refresh_runtime(
|
| 53 |
+
enabled: bool | None = None,
|
| 54 |
+
) -> Literal["quota", "random"]:
|
| 55 |
+
"""Hot-apply refresh strategy and scheduler state for the current worker."""
|
| 56 |
+
from app.dataplane.account.selector import current_strategy, set_strategy
|
| 57 |
+
from app.platform.config.snapshot import config
|
| 58 |
+
from app.platform.logging.logger import logger
|
| 59 |
+
|
| 60 |
+
refresh_enabled = (
|
| 61 |
+
config.get_bool("account.refresh.enabled", False)
|
| 62 |
+
if enabled is None
|
| 63 |
+
else bool(enabled)
|
| 64 |
+
)
|
| 65 |
+
target_strategy: Literal["quota", "random"] = (
|
| 66 |
+
"quota" if refresh_enabled else "random"
|
| 67 |
+
)
|
| 68 |
+
previous_strategy = current_strategy()
|
| 69 |
+
if previous_strategy != target_strategy:
|
| 70 |
+
set_strategy(target_strategy)
|
| 71 |
+
|
| 72 |
+
scheduler_action = "unchanged"
|
| 73 |
+
scheduler = _refresh_scheduler
|
| 74 |
+
if scheduler is not None and _refresh_scheduler_leader:
|
| 75 |
+
if refresh_enabled:
|
| 76 |
+
if not scheduler.is_running():
|
| 77 |
+
scheduler.start()
|
| 78 |
+
scheduler_action = "started"
|
| 79 |
+
elif scheduler.is_running():
|
| 80 |
+
scheduler.stop()
|
| 81 |
+
scheduler_action = "stopped"
|
| 82 |
+
|
| 83 |
+
if previous_strategy != target_strategy or scheduler_action != "unchanged":
|
| 84 |
+
logger.info(
|
| 85 |
+
"account refresh runtime reconciled: previous_strategy={} strategy={} leader={} scheduler_action={}",
|
| 86 |
+
previous_strategy,
|
| 87 |
+
target_strategy,
|
| 88 |
+
_refresh_scheduler_leader,
|
| 89 |
+
scheduler_action,
|
| 90 |
+
)
|
| 91 |
+
return target_strategy
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
__all__ = [
|
| 95 |
+
"get_refresh_service",
|
| 96 |
+
"set_refresh_service",
|
| 97 |
+
"get_refresh_scheduler",
|
| 98 |
+
"set_refresh_scheduler",
|
| 99 |
+
"is_refresh_scheduler_leader",
|
| 100 |
+
"set_refresh_scheduler_leader",
|
| 101 |
+
"reconcile_refresh_runtime",
|
| 102 |
+
]
|
app/control/account/scheduler.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Background scheduler for periodic account quota refresh.
|
| 2 |
+
|
| 3 |
+
Runs one independent loop per pool type (basic / super / heavy), each with
|
| 4 |
+
its own configurable interval read from:
|
| 5 |
+
|
| 6 |
+
account.refresh.basic_interval_sec (default 86400 — 24 h)
|
| 7 |
+
account.refresh.super_interval_sec (default 7200 — 2 h)
|
| 8 |
+
account.refresh.heavy_interval_sec (default 7200 — 2 h)
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import asyncio
|
| 12 |
+
|
| 13 |
+
from app.platform.config.snapshot import get_config
|
| 14 |
+
from app.platform.logging.logger import logger
|
| 15 |
+
from .refresh import AccountRefreshService
|
| 16 |
+
|
| 17 |
+
# Pool → (config key, built-in default seconds)
|
| 18 |
+
_POOL_CONFIG: dict[str, tuple[str, int]] = {
|
| 19 |
+
"basic": ("account.refresh.basic_interval_sec", 86_400),
|
| 20 |
+
"super": ("account.refresh.super_interval_sec", 7_200),
|
| 21 |
+
"heavy": ("account.refresh.heavy_interval_sec", 7_200),
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _interval(pool: str) -> int:
|
| 26 |
+
key, default = _POOL_CONFIG[pool]
|
| 27 |
+
v = get_config(key, None)
|
| 28 |
+
return int(v) if v is not None else default
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class AccountRefreshScheduler:
|
| 32 |
+
"""Runs one refresh loop per pool type at pool-specific intervals.
|
| 33 |
+
|
| 34 |
+
Lifecycle: ``start()`` → loops run in background → ``stop()`` to cancel.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, refresh_service: AccountRefreshService) -> None:
|
| 38 |
+
self._service = refresh_service
|
| 39 |
+
self._tasks: list[asyncio.Task] = []
|
| 40 |
+
self._stop = asyncio.Event()
|
| 41 |
+
|
| 42 |
+
def bind_service(self, refresh_service: AccountRefreshService) -> None:
|
| 43 |
+
"""Update the refresh service used by the singleton scheduler."""
|
| 44 |
+
self._service = refresh_service
|
| 45 |
+
|
| 46 |
+
def is_running(self) -> bool:
|
| 47 |
+
"""Return True while any pool refresh loop is still active."""
|
| 48 |
+
return any(not task.done() for task in self._tasks)
|
| 49 |
+
|
| 50 |
+
def start(self) -> None:
|
| 51 |
+
if self.is_running():
|
| 52 |
+
return
|
| 53 |
+
self._stop.clear()
|
| 54 |
+
self._tasks = [
|
| 55 |
+
asyncio.create_task(self._loop(pool), name=f"account-refresh-{pool}")
|
| 56 |
+
for pool in _POOL_CONFIG
|
| 57 |
+
]
|
| 58 |
+
intervals = {p: _interval(p) for p in _POOL_CONFIG}
|
| 59 |
+
logger.info(
|
| 60 |
+
"account refresh scheduler started: basic_interval_s={} super_interval_s={} heavy_interval_s={}",
|
| 61 |
+
intervals["basic"], intervals["super"], intervals["heavy"],
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
def stop(self) -> None:
|
| 65 |
+
was_running = self.is_running()
|
| 66 |
+
self._stop.set()
|
| 67 |
+
for t in self._tasks:
|
| 68 |
+
if not t.done():
|
| 69 |
+
t.cancel()
|
| 70 |
+
self._tasks = []
|
| 71 |
+
if was_running:
|
| 72 |
+
logger.info("account refresh scheduler stopped")
|
| 73 |
+
|
| 74 |
+
async def _loop(self, pool: str) -> None:
|
| 75 |
+
while not self._stop.is_set():
|
| 76 |
+
interval = _interval(pool)
|
| 77 |
+
try:
|
| 78 |
+
await asyncio.wait_for(self._stop.wait(), timeout=float(interval))
|
| 79 |
+
break # stop event fired
|
| 80 |
+
except asyncio.TimeoutError:
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
if self._stop.is_set():
|
| 84 |
+
break
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
result = await self._service.refresh_scheduled(pool=pool)
|
| 88 |
+
logger.info(
|
| 89 |
+
"account refresh cycle completed: pool={} checked={} refreshed={} recovered={} failed={}",
|
| 90 |
+
pool, result.checked, result.refreshed, result.recovered, result.failed,
|
| 91 |
+
)
|
| 92 |
+
except asyncio.CancelledError:
|
| 93 |
+
raise
|
| 94 |
+
except Exception as exc:
|
| 95 |
+
logger.error(
|
| 96 |
+
"account refresh cycle failed: pool={} error_type={} error={}",
|
| 97 |
+
pool,
|
| 98 |
+
type(exc).__name__,
|
| 99 |
+
exc,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# ---------------------------------------------------------------------------
|
| 104 |
+
# Module-level singleton
|
| 105 |
+
# ---------------------------------------------------------------------------
|
| 106 |
+
|
| 107 |
+
_scheduler: AccountRefreshScheduler | None = None
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_account_refresh_scheduler(
|
| 111 |
+
refresh_service: AccountRefreshService,
|
| 112 |
+
) -> AccountRefreshScheduler:
|
| 113 |
+
global _scheduler
|
| 114 |
+
if _scheduler is None:
|
| 115 |
+
_scheduler = AccountRefreshScheduler(refresh_service)
|
| 116 |
+
else:
|
| 117 |
+
_scheduler.bind_service(refresh_service)
|
| 118 |
+
return _scheduler
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
__all__ = ["AccountRefreshScheduler", "get_account_refresh_scheduler"]
|
app/control/account/state_machine.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
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events to an AccountRecord, advancing its status
|
| 4 |
+
and updating quota / usage fields accordingly.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass, field
|
| 8 |
+
|
| 9 |
+
from app.platform.runtime.clock import now_ms
|
| 10 |
+
from .enums import AccountStatus, FeedbackKind
|
| 11 |
+
from .models import AccountRecord, QuotaWindow
|
| 12 |
+
from .quota_defaults import default_quota_set
|
| 13 |
+
|
| 14 |
+
# ---------------------------------------------------------------------------
|
| 15 |
+
# Policy
|
| 16 |
+
# ---------------------------------------------------------------------------
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass(slots=True)
|
| 20 |
+
class StatePolicy:
|
| 21 |
+
"""Configurable thresholds for automatic state transitions."""
|
| 22 |
+
|
| 23 |
+
fail_threshold: int = 5 # consecutive failures → COOLING
|
| 24 |
+
forbidden_strikes: int = 1 # 403 count → DISABLED
|
| 25 |
+
default_cooling_ms: int = 15 * 60 * 1000 # 15 min
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
_DEFAULT_POLICY = StatePolicy()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# ---------------------------------------------------------------------------
|
| 32 |
+
# Feedback
|
| 33 |
+
# ---------------------------------------------------------------------------
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass(slots=True)
|
| 37 |
+
class AccountFeedback:
|
| 38 |
+
"""Outcome of a single upstream request.
|
| 39 |
+
|
| 40 |
+
``mode_id`` — which quota window to update (0=auto, 1=fast, 2=expert).
|
| 41 |
+
``quota_window`` — real quota window from the usage API (optional).
|
| 42 |
+
``apply_usage`` — whether to increment usage_use_count on SUCCESS.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
kind: FeedbackKind
|
| 46 |
+
mode_id: int = 0
|
| 47 |
+
at: int = field(default_factory=now_ms)
|
| 48 |
+
status_code: int | None = None
|
| 49 |
+
reason: str = ""
|
| 50 |
+
quota_window: QuotaWindow | None = None # real value from usage API
|
| 51 |
+
retry_after_ms: int | None = None
|
| 52 |
+
confirm_expired: bool = False
|
| 53 |
+
apply_usage: bool = True
|
| 54 |
+
|
| 55 |
+
@classmethod
|
| 56 |
+
def from_status_code(
|
| 57 |
+
cls,
|
| 58 |
+
status_code: int,
|
| 59 |
+
mode_id: int = 0,
|
| 60 |
+
*,
|
| 61 |
+
reason: str = "",
|
| 62 |
+
retry_after_ms: int | None = None,
|
| 63 |
+
confirm_expired: bool = False,
|
| 64 |
+
) -> "AccountFeedback":
|
| 65 |
+
if status_code == 401:
|
| 66 |
+
kind = FeedbackKind.UNAUTHORIZED
|
| 67 |
+
elif status_code == 403:
|
| 68 |
+
kind = FeedbackKind.FORBIDDEN
|
| 69 |
+
elif status_code == 429:
|
| 70 |
+
kind = FeedbackKind.RATE_LIMITED
|
| 71 |
+
elif status_code >= 500:
|
| 72 |
+
kind = FeedbackKind.SERVER_ERROR
|
| 73 |
+
elif 200 <= status_code < 300:
|
| 74 |
+
kind = FeedbackKind.SUCCESS
|
| 75 |
+
else:
|
| 76 |
+
kind = FeedbackKind.SERVER_ERROR
|
| 77 |
+
return cls(
|
| 78 |
+
kind=kind,
|
| 79 |
+
mode_id=mode_id,
|
| 80 |
+
status_code=status_code,
|
| 81 |
+
reason=reason,
|
| 82 |
+
retry_after_ms=retry_after_ms,
|
| 83 |
+
confirm_expired=confirm_expired,
|
| 84 |
+
apply_usage=False,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ---------------------------------------------------------------------------
|
| 89 |
+
# State helpers
|
| 90 |
+
# ---------------------------------------------------------------------------
|
| 91 |
+
|
| 92 |
+
_COOLDOWN_UNTIL_KEY = "cooldown_until"
|
| 93 |
+
_COOLDOWN_REASON_KEY = "cooldown_reason"
|
| 94 |
+
_DISABLED_AT_KEY = "disabled_at"
|
| 95 |
+
_DISABLED_REASON_KEY = "disabled_reason"
|
| 96 |
+
_EXPIRED_AT_KEY = "expired_at"
|
| 97 |
+
_EXPIRED_REASON_KEY = "expired_reason"
|
| 98 |
+
_FORBIDDEN_STRIKE_KEY = "forbidden_strikes"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def derive_status(record: AccountRecord, *, now: int | None = None) -> AccountStatus:
|
| 102 |
+
"""Compute the effective status, considering cooldown expiry."""
|
| 103 |
+
if record.status != AccountStatus.COOLING:
|
| 104 |
+
return record.status
|
| 105 |
+
cooldown_until = record.ext.get(_COOLDOWN_UNTIL_KEY)
|
| 106 |
+
if cooldown_until is None:
|
| 107 |
+
return AccountStatus.COOLING
|
| 108 |
+
ts = now if now is not None else now_ms()
|
| 109 |
+
if ts >= int(cooldown_until):
|
| 110 |
+
return AccountStatus.ACTIVE
|
| 111 |
+
return AccountStatus.COOLING
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def is_selectable(
|
| 115 |
+
record: AccountRecord, mode_id: int, *, now: int | None = None
|
| 116 |
+
) -> bool:
|
| 117 |
+
"""Return True if the account can be selected for *mode_id*."""
|
| 118 |
+
if record.is_deleted():
|
| 119 |
+
return False
|
| 120 |
+
status = derive_status(record, now=now)
|
| 121 |
+
if status != AccountStatus.ACTIVE:
|
| 122 |
+
return False
|
| 123 |
+
qs = record.quota_set()
|
| 124 |
+
win = qs.get(mode_id)
|
| 125 |
+
return win is not None and not win.is_exhausted()
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def is_manageable(record: AccountRecord, *, now: int | None = None) -> bool:
|
| 129 |
+
"""Return True if the account should participate in maintenance flows."""
|
| 130 |
+
if record.is_deleted():
|
| 131 |
+
return False
|
| 132 |
+
status = derive_status(record, now=now)
|
| 133 |
+
return status in (AccountStatus.ACTIVE, AccountStatus.COOLING)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# ---------------------------------------------------------------------------
|
| 137 |
+
# State transition
|
| 138 |
+
# ---------------------------------------------------------------------------
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def apply_feedback(
|
| 142 |
+
record: AccountRecord,
|
| 143 |
+
feedback: AccountFeedback,
|
| 144 |
+
*,
|
| 145 |
+
policy: StatePolicy = _DEFAULT_POLICY,
|
| 146 |
+
) -> AccountRecord:
|
| 147 |
+
"""Apply *feedback* to *record* and return an updated copy.
|
| 148 |
+
|
| 149 |
+
The returned object is a **new** record; the original is not mutated.
|
| 150 |
+
"""
|
| 151 |
+
ts = feedback.at
|
| 152 |
+
ext = dict(record.ext)
|
| 153 |
+
qs = record.quota_set()
|
| 154 |
+
|
| 155 |
+
status = record.status
|
| 156 |
+
last_fail_at = record.last_fail_at
|
| 157 |
+
last_fail_reason = record.last_fail_reason
|
| 158 |
+
last_use_at = record.last_use_at
|
| 159 |
+
last_sync_at = record.last_sync_at
|
| 160 |
+
use_count = record.usage_use_count
|
| 161 |
+
fail_count = record.usage_fail_count
|
| 162 |
+
sync_count = record.usage_sync_count
|
| 163 |
+
state_reason = record.state_reason
|
| 164 |
+
|
| 165 |
+
# Update quota window from real API data if provided.
|
| 166 |
+
if feedback.quota_window is not None:
|
| 167 |
+
qs.set(feedback.mode_id, feedback.quota_window)
|
| 168 |
+
last_sync_at = ts
|
| 169 |
+
sync_count += 1
|
| 170 |
+
elif feedback.kind == FeedbackKind.SUCCESS:
|
| 171 |
+
# Decrement locally when no real data is available.
|
| 172 |
+
win = qs.get(feedback.mode_id)
|
| 173 |
+
if win is not None:
|
| 174 |
+
updated_win = QuotaWindow(
|
| 175 |
+
remaining=max(0, win.remaining - 1),
|
| 176 |
+
total=win.total,
|
| 177 |
+
window_seconds=win.window_seconds,
|
| 178 |
+
reset_at=win.reset_at,
|
| 179 |
+
synced_at=win.synced_at,
|
| 180 |
+
source=win.source,
|
| 181 |
+
)
|
| 182 |
+
qs.set(feedback.mode_id, updated_win)
|
| 183 |
+
elif feedback.kind == FeedbackKind.RATE_LIMITED:
|
| 184 |
+
# Mark quota as zero; set reset_at from retry_after if available.
|
| 185 |
+
win = qs.get(feedback.mode_id)
|
| 186 |
+
if win is not None:
|
| 187 |
+
reset_at = (
|
| 188 |
+
ts + feedback.retry_after_ms
|
| 189 |
+
if feedback.retry_after_ms
|
| 190 |
+
else (ts + win.window_seconds * 1000)
|
| 191 |
+
)
|
| 192 |
+
qs.set(
|
| 193 |
+
feedback.mode_id,
|
| 194 |
+
QuotaWindow(
|
| 195 |
+
remaining=0,
|
| 196 |
+
total=win.total,
|
| 197 |
+
window_seconds=win.window_seconds,
|
| 198 |
+
reset_at=reset_at,
|
| 199 |
+
synced_at=win.synced_at,
|
| 200 |
+
source=win.source,
|
| 201 |
+
),
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# Update usage counters.
|
| 205 |
+
if feedback.kind == FeedbackKind.SUCCESS and feedback.apply_usage:
|
| 206 |
+
use_count += 1
|
| 207 |
+
last_use_at = ts
|
| 208 |
+
elif feedback.kind not in (
|
| 209 |
+
FeedbackKind.SUCCESS,
|
| 210 |
+
FeedbackKind.RESTORE,
|
| 211 |
+
FeedbackKind.DISABLE,
|
| 212 |
+
FeedbackKind.DELETE,
|
| 213 |
+
):
|
| 214 |
+
fail_count += 1
|
| 215 |
+
last_fail_at = ts
|
| 216 |
+
last_fail_reason = feedback.reason or str(feedback.status_code or "")
|
| 217 |
+
|
| 218 |
+
# Status transitions.
|
| 219 |
+
if feedback.kind == FeedbackKind.UNAUTHORIZED:
|
| 220 |
+
if feedback.confirm_expired:
|
| 221 |
+
status = AccountStatus.EXPIRED
|
| 222 |
+
state_reason = feedback.reason or "token_expired"
|
| 223 |
+
ext[_EXPIRED_AT_KEY] = ts
|
| 224 |
+
ext[_EXPIRED_REASON_KEY] = state_reason
|
| 225 |
+
else:
|
| 226 |
+
# Unconfirmed 401 — only note failure; do not expire.
|
| 227 |
+
pass
|
| 228 |
+
|
| 229 |
+
elif feedback.kind == FeedbackKind.FORBIDDEN:
|
| 230 |
+
strikes = int(ext.get(_FORBIDDEN_STRIKE_KEY, 0)) + 1
|
| 231 |
+
ext[_FORBIDDEN_STRIKE_KEY] = strikes
|
| 232 |
+
if strikes >= policy.forbidden_strikes:
|
| 233 |
+
status = AccountStatus.DISABLED
|
| 234 |
+
state_reason = feedback.reason or "forbidden"
|
| 235 |
+
ext[_DISABLED_AT_KEY] = ts
|
| 236 |
+
ext[_DISABLED_REASON_KEY] = state_reason
|
| 237 |
+
|
| 238 |
+
elif feedback.kind == FeedbackKind.RATE_LIMITED:
|
| 239 |
+
cooldown_ms = (
|
| 240 |
+
feedback.retry_after_ms
|
| 241 |
+
if feedback.retry_after_ms
|
| 242 |
+
else policy.default_cooling_ms
|
| 243 |
+
)
|
| 244 |
+
status = AccountStatus.COOLING
|
| 245 |
+
state_reason = feedback.reason or "rate_limited"
|
| 246 |
+
ext[_COOLDOWN_UNTIL_KEY] = ts + cooldown_ms
|
| 247 |
+
ext[_COOLDOWN_REASON_KEY] = state_reason
|
| 248 |
+
|
| 249 |
+
elif feedback.kind == FeedbackKind.SUCCESS:
|
| 250 |
+
if status == AccountStatus.COOLING:
|
| 251 |
+
cooldown_until = ext.get(_COOLDOWN_UNTIL_KEY)
|
| 252 |
+
if cooldown_until is not None and ts >= int(cooldown_until):
|
| 253 |
+
status = AccountStatus.ACTIVE
|
| 254 |
+
state_reason = None
|
| 255 |
+
ext.pop(_COOLDOWN_UNTIL_KEY, None)
|
| 256 |
+
ext.pop(_COOLDOWN_REASON_KEY, None)
|
| 257 |
+
ext.pop(_FORBIDDEN_STRIKE_KEY, None)
|
| 258 |
+
|
| 259 |
+
elif feedback.kind == FeedbackKind.DISABLE:
|
| 260 |
+
status = AccountStatus.DISABLED
|
| 261 |
+
state_reason = feedback.reason or "operator_disabled"
|
| 262 |
+
ext[_DISABLED_AT_KEY] = ts
|
| 263 |
+
ext[_DISABLED_REASON_KEY] = state_reason
|
| 264 |
+
|
| 265 |
+
elif feedback.kind == FeedbackKind.DELETE:
|
| 266 |
+
pass # Caller sets deleted_at.
|
| 267 |
+
|
| 268 |
+
elif feedback.kind == FeedbackKind.RESTORE:
|
| 269 |
+
status = AccountStatus.ACTIVE
|
| 270 |
+
state_reason = None
|
| 271 |
+
ext.pop(_COOLDOWN_UNTIL_KEY, None)
|
| 272 |
+
ext.pop(_COOLDOWN_REASON_KEY, None)
|
| 273 |
+
ext.pop(_DISABLED_AT_KEY, None)
|
| 274 |
+
ext.pop(_DISABLED_REASON_KEY, None)
|
| 275 |
+
ext.pop(_EXPIRED_AT_KEY, None)
|
| 276 |
+
ext.pop(_EXPIRED_REASON_KEY, None)
|
| 277 |
+
ext.pop(_FORBIDDEN_STRIKE_KEY, None)
|
| 278 |
+
# Reset quota to defaults.
|
| 279 |
+
qs = default_quota_set(record.pool)
|
| 280 |
+
|
| 281 |
+
return record.model_copy(
|
| 282 |
+
update={
|
| 283 |
+
"status": status,
|
| 284 |
+
"quota": qs.to_dict(),
|
| 285 |
+
"usage_use_count": use_count,
|
| 286 |
+
"usage_fail_count": fail_count,
|
| 287 |
+
"usage_sync_count": sync_count,
|
| 288 |
+
"last_use_at": last_use_at,
|
| 289 |
+
"last_fail_at": last_fail_at,
|
| 290 |
+
"last_fail_reason": last_fail_reason,
|
| 291 |
+
"last_sync_at": last_sync_at,
|
| 292 |
+
"state_reason": state_reason,
|
| 293 |
+
"ext": ext,
|
| 294 |
+
"updated_at": ts,
|
| 295 |
+
}
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def clear_failures(record: AccountRecord) -> AccountRecord:
|
| 300 |
+
"""Reset failure counters and restore ACTIVE status."""
|
| 301 |
+
ext = dict(record.ext)
|
| 302 |
+
for k in (
|
| 303 |
+
_COOLDOWN_UNTIL_KEY,
|
| 304 |
+
_COOLDOWN_REASON_KEY,
|
| 305 |
+
_DISABLED_AT_KEY,
|
| 306 |
+
_DISABLED_REASON_KEY,
|
| 307 |
+
_EXPIRED_AT_KEY,
|
| 308 |
+
_EXPIRED_REASON_KEY,
|
| 309 |
+
_FORBIDDEN_STRIKE_KEY,
|
| 310 |
+
):
|
| 311 |
+
ext.pop(k, None)
|
| 312 |
+
return record.model_copy(
|
| 313 |
+
update={
|
| 314 |
+
"status": AccountStatus.ACTIVE,
|
| 315 |
+
"usage_fail_count": 0,
|
| 316 |
+
"last_fail_at": None,
|
| 317 |
+
"last_fail_reason": None,
|
| 318 |
+
"state_reason": None,
|
| 319 |
+
"ext": ext,
|
| 320 |
+
"updated_at": now_ms(),
|
| 321 |
+
}
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
__all__ = [
|
| 326 |
+
"StatePolicy",
|
| 327 |
+
"AccountFeedback",
|
| 328 |
+
"derive_status",
|
| 329 |
+
"is_selectable",
|
| 330 |
+
"is_manageable",
|
| 331 |
+
"apply_feedback",
|
| 332 |
+
"clear_failures",
|
| 333 |
+
]
|
app/control/admin/__init__.py
ADDED
|
File without changes
|
app/control/model/__init__.py
ADDED
|
File without changes
|
app/control/model/enums.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Control-plane model enumerations."""
|
| 2 |
+
|
| 3 |
+
from enum import IntEnum, IntFlag
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class ModeId(IntEnum):
|
| 7 |
+
"""Upstream ``modeId`` parameter values.
|
| 8 |
+
|
| 9 |
+
Integer values are stable — used as array indices in the hot path.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
AUTO = 0 # modeId="auto"
|
| 13 |
+
FAST = 1 # modeId="fast"
|
| 14 |
+
EXPERT = 2 # modeId="expert"
|
| 15 |
+
HEAVY = 3 # modeId="heavy" — only available on heavy-pool accounts
|
| 16 |
+
GROK_4_3 = 4 # modeId="grok-420-computer-use-sa" — super/heavy only
|
| 17 |
+
CONSOLE = 5 # console.x.ai 独立配额 — basic pool console 模型专用
|
| 18 |
+
|
| 19 |
+
def to_api_str(self) -> str:
|
| 20 |
+
_OVERRIDES: dict[int, str] = {
|
| 21 |
+
ModeId.GROK_4_3: "grok-420-computer-use-sa",
|
| 22 |
+
}
|
| 23 |
+
return _OVERRIDES.get(self, self.name.lower()) # type: ignore[arg-type]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Tier(IntEnum):
|
| 27 |
+
"""Account tier — determines which pool is selected."""
|
| 28 |
+
|
| 29 |
+
BASIC = 0 # pool="basic"
|
| 30 |
+
SUPER = 1 # pool="super"
|
| 31 |
+
HEAVY = 2 # pool="heavy"
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Capability(IntFlag):
|
| 35 |
+
"""Bitmask of features a model supports."""
|
| 36 |
+
|
| 37 |
+
CHAT = 1
|
| 38 |
+
IMAGE = 2
|
| 39 |
+
IMAGE_EDIT = 4
|
| 40 |
+
VIDEO = 8
|
| 41 |
+
VOICE = 16
|
| 42 |
+
ASSET = 32
|
| 43 |
+
CONSOLE_CHAT = 64 # 通过 console.x.ai/v1/responses 路由
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Human-readable mode strings in API order.
|
| 47 |
+
MODE_STRINGS: dict[ModeId, str] = {
|
| 48 |
+
ModeId.AUTO: "auto",
|
| 49 |
+
ModeId.FAST: "fast",
|
| 50 |
+
ModeId.EXPERT: "expert",
|
| 51 |
+
ModeId.HEAVY: "heavy",
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
ALL_MODES: tuple[ModeId, ...] = (ModeId.AUTO, ModeId.FAST, ModeId.EXPERT)
|
| 55 |
+
ALL_MODES_WITH_HEAVY: tuple[ModeId, ...] = (
|
| 56 |
+
ModeId.AUTO,
|
| 57 |
+
ModeId.FAST,
|
| 58 |
+
ModeId.EXPERT,
|
| 59 |
+
ModeId.HEAVY,
|
| 60 |
+
)
|
| 61 |
+
ALL_MODES_FULL: tuple[ModeId, ...] = (
|
| 62 |
+
ModeId.AUTO,
|
| 63 |
+
ModeId.FAST,
|
| 64 |
+
ModeId.EXPERT,
|
| 65 |
+
ModeId.HEAVY,
|
| 66 |
+
ModeId.GROK_4_3,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
__all__ = [
|
| 70 |
+
"ModeId",
|
| 71 |
+
"Tier",
|
| 72 |
+
"Capability",
|
| 73 |
+
"MODE_STRINGS",
|
| 74 |
+
"ALL_MODES",
|
| 75 |
+
"ALL_MODES_WITH_HEAVY",
|
| 76 |
+
"ALL_MODES_FULL",
|
| 77 |
+
]
|
app/control/model/registry.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model registry — all supported model variants defined in one place."""
|
| 2 |
+
|
| 3 |
+
from .enums import Capability, ModeId, Tier
|
| 4 |
+
from .spec import ModelSpec
|
| 5 |
+
|
| 6 |
+
# ---------------------------------------------------------------------------
|
| 7 |
+
# Master model list.
|
| 8 |
+
# Add new models here; no other files need to change.
|
| 9 |
+
# ---------------------------------------------------------------------------
|
| 10 |
+
|
| 11 |
+
# fmt: off
|
| 12 |
+
MODELS: tuple[ModelSpec, ...] = (
|
| 13 |
+
# === Chat ==============================================================
|
| 14 |
+
|
| 15 |
+
# Basic fast; auto/expert require Super+
|
| 16 |
+
ModelSpec("grok-4.20-0309-non-reasoning", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4.20 0309 Non-Reasoning"),
|
| 17 |
+
ModelSpec("grok-4.20-0309", ModeId.AUTO, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309"),
|
| 18 |
+
ModelSpec("grok-4.20-0309-reasoning", ModeId.EXPERT, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309 Reasoning"),
|
| 19 |
+
# Super+
|
| 20 |
+
ModelSpec("grok-4.20-0309-non-reasoning-super", ModeId.FAST, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309 Non-Reasoning Super"),
|
| 21 |
+
ModelSpec("grok-4.20-0309-super", ModeId.AUTO, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309 Super"),
|
| 22 |
+
ModelSpec("grok-4.20-0309-reasoning-super", ModeId.EXPERT, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 0309 Reasoning Super"),
|
| 23 |
+
# Heavy+
|
| 24 |
+
ModelSpec("grok-4.20-0309-non-reasoning-heavy", ModeId.FAST, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 0309 Non-Reasoning Heavy"),
|
| 25 |
+
ModelSpec("grok-4.20-0309-heavy", ModeId.AUTO, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 0309 Heavy"),
|
| 26 |
+
ModelSpec("grok-4.20-0309-reasoning-heavy", ModeId.EXPERT, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 0309 Reasoning Heavy"),
|
| 27 |
+
ModelSpec("grok-4.20-multi-agent-0309", ModeId.HEAVY, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 Multi-Agent 0309"),
|
| 28 |
+
|
| 29 |
+
# --- 硬优先级反向选池 (heavy → super → basic) ---
|
| 30 |
+
ModelSpec("grok-4.20-fast", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4.20 Fast", prefer_best=True),
|
| 31 |
+
ModelSpec("grok-4.3-fast", ModeId.FAST, Tier.BASIC, Capability.CHAT, True, "Grok 4.3 Fast", prefer_best=True),
|
| 32 |
+
ModelSpec("grok-4.20-auto", ModeId.AUTO, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 Auto", prefer_best=True),
|
| 33 |
+
ModelSpec("grok-4.20-expert", ModeId.EXPERT, Tier.SUPER, Capability.CHAT, True, "Grok 4.20 Expert", prefer_best=True),
|
| 34 |
+
ModelSpec("grok-4.20-heavy", ModeId.HEAVY, Tier.HEAVY, Capability.CHAT, True, "Grok 4.20 Heavy", prefer_best=True),
|
| 35 |
+
|
| 36 |
+
# === grok-4.3 (grok-420-computer-use-sa) ==================================
|
| 37 |
+
# Super+(basic 池不支持此模式)
|
| 38 |
+
ModelSpec("grok-4.3-beta", ModeId.GROK_4_3, Tier.SUPER, Capability.CHAT, True, "Grok 4.3 Beta"),
|
| 39 |
+
|
| 40 |
+
# === Image ==============================================================
|
| 41 |
+
|
| 42 |
+
# Basic fast
|
| 43 |
+
ModelSpec("grok-imagine-image-lite", ModeId.FAST, Tier.BASIC, Capability.IMAGE, True, "Grok Imagine Image Lite"),
|
| 44 |
+
# Super+
|
| 45 |
+
ModelSpec("grok-imagine-image", ModeId.AUTO, Tier.SUPER, Capability.IMAGE, True, "Grok Imagine Image"),
|
| 46 |
+
ModelSpec("grok-imagine-image-pro", ModeId.AUTO, Tier.SUPER, Capability.IMAGE, True, "Grok Imagine Image Pro"),
|
| 47 |
+
|
| 48 |
+
# === Image Edit =========================================================
|
| 49 |
+
|
| 50 |
+
# Super+
|
| 51 |
+
ModelSpec("grok-imagine-image-edit", ModeId.AUTO, Tier.SUPER, Capability.IMAGE_EDIT, True, "Grok Imagine Image Edit"),
|
| 52 |
+
|
| 53 |
+
# === Video ==============================================================
|
| 54 |
+
|
| 55 |
+
# Super+
|
| 56 |
+
ModelSpec("grok-imagine-video", ModeId.AUTO, Tier.SUPER, Capability.VIDEO, True, "Grok Imagine Video"),
|
| 57 |
+
|
| 58 |
+
# === Console Chat (console.x.ai/v1/responses) ===========================
|
| 59 |
+
# 通过 console.x.ai 路由,使用 grok.com SSO token,免费账号可用
|
| 60 |
+
# basic pool 即可(不消耗 grok.com 配额,走 console API 独立配额)
|
| 61 |
+
ModelSpec("grok-4.3-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.3 (Console)"),
|
| 62 |
+
ModelSpec("grok-4.3-low", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.3 Low Thinking"),
|
| 63 |
+
ModelSpec("grok-4.3-medium", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.3 Medium Thinking"),
|
| 64 |
+
ModelSpec("grok-4.3-high", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.3 High Thinking"),
|
| 65 |
+
ModelSpec("grok-4.20-0309-reasoning-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 0309 Reasoning (Console)"),
|
| 66 |
+
ModelSpec("grok-4.20-0309-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 0309 (Console)"),
|
| 67 |
+
ModelSpec("grok-4.20-multi-agent-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent (Console)"),
|
| 68 |
+
ModelSpec("grok-4.20-multi-agent-low", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent Low"),
|
| 69 |
+
ModelSpec("grok-4.20-multi-agent-medium", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent Medium"),
|
| 70 |
+
ModelSpec("grok-4.20-multi-agent-high", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent High"),
|
| 71 |
+
ModelSpec("grok-4.20-multi-agent-xhigh", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 Multi-Agent XHigh"),
|
| 72 |
+
ModelSpec("grok-4.20-0309-non-reasoning-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok 4.20 0309 Non-Reasoning (Console)"),
|
| 73 |
+
ModelSpec("grok-build-console", ModeId.CONSOLE, Tier.BASIC, Capability.CONSOLE_CHAT, True, "Grok Build 0.1 (Console)"),
|
| 74 |
+
)
|
| 75 |
+
# fmt: on
|
| 76 |
+
|
| 77 |
+
# ---------------------------------------------------------------------------
|
| 78 |
+
# Internal lookup structures — built once at import time.
|
| 79 |
+
# ---------------------------------------------------------------------------
|
| 80 |
+
|
| 81 |
+
_BY_NAME: dict[str, ModelSpec] = {m.model_name: m for m in MODELS}
|
| 82 |
+
|
| 83 |
+
_BY_CAP: dict[int, list[ModelSpec]] = {}
|
| 84 |
+
for _m in MODELS:
|
| 85 |
+
_BY_CAP.setdefault(int(_m.capability), []).append(_m)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ---------------------------------------------------------------------------
|
| 89 |
+
# Public API
|
| 90 |
+
# ---------------------------------------------------------------------------
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def get(model_name: str) -> ModelSpec | None:
|
| 94 |
+
"""Return the spec for *model_name*, or ``None`` if not registered."""
|
| 95 |
+
return _BY_NAME.get(model_name)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def resolve(model_name: str) -> ModelSpec:
|
| 99 |
+
"""Return the spec for *model_name*; raise ``ValueError`` if unknown."""
|
| 100 |
+
spec = _BY_NAME.get(model_name)
|
| 101 |
+
if spec is None:
|
| 102 |
+
raise ValueError(f"Unknown model: {model_name!r}")
|
| 103 |
+
return spec
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def list_enabled() -> list[ModelSpec]:
|
| 107 |
+
"""Return all enabled models in registration order."""
|
| 108 |
+
return [m for m in MODELS if m.enabled]
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def list_by_capability(cap: Capability) -> list[ModelSpec]:
|
| 112 |
+
"""Return enabled models that include *cap* in their capability mask."""
|
| 113 |
+
return [m for m in MODELS if m.enabled and bool(m.capability & cap)]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
__all__ = ["MODELS", "get", "resolve", "list_enabled", "list_by_capability"]
|
app/control/model/spec.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ModelSpec — the single source of truth for model metadata."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
|
| 5 |
+
from .enums import Capability, ModeId, Tier
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass(slots=True, frozen=True)
|
| 9 |
+
class ModelSpec:
|
| 10 |
+
"""Immutable descriptor for one model variant.
|
| 11 |
+
|
| 12 |
+
``model_name`` is the public-facing identifier used in API requests.
|
| 13 |
+
``mode_id`` is the upstream ``modeId`` value (auto / fast / expert).
|
| 14 |
+
``tier`` determines which account pool is used (basic / super).
|
| 15 |
+
When ``prefer_best`` is True, ``tier`` only affects
|
| 16 |
+
``pool_name()``/``pool_id()``; the actual selection order
|
| 17 |
+
is reversed (heavy → super → basic).
|
| 18 |
+
``capability`` is a bitmask of supported operations.
|
| 19 |
+
``enabled`` gates whether the model appears in ``/v1/models``.
|
| 20 |
+
``public_name`` is the human-readable display name.
|
| 21 |
+
``prefer_best`` when True, reverses pool priority to try higher-tier
|
| 22 |
+
pools first (hard priority, not soft preference).
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
model_name: str
|
| 26 |
+
mode_id: ModeId
|
| 27 |
+
tier: Tier
|
| 28 |
+
capability: Capability
|
| 29 |
+
enabled: bool
|
| 30 |
+
public_name: str
|
| 31 |
+
prefer_best: bool = False
|
| 32 |
+
|
| 33 |
+
# --- convenience predicates ---
|
| 34 |
+
|
| 35 |
+
def is_chat(self) -> bool:
|
| 36 |
+
return bool(self.capability & Capability.CHAT)
|
| 37 |
+
|
| 38 |
+
def is_image(self) -> bool:
|
| 39 |
+
return bool(self.capability & Capability.IMAGE)
|
| 40 |
+
|
| 41 |
+
def is_image_edit(self) -> bool:
|
| 42 |
+
return bool(self.capability & Capability.IMAGE_EDIT)
|
| 43 |
+
|
| 44 |
+
def is_video(self) -> bool:
|
| 45 |
+
return bool(self.capability & Capability.VIDEO)
|
| 46 |
+
|
| 47 |
+
def is_voice(self) -> bool:
|
| 48 |
+
return bool(self.capability & Capability.VOICE)
|
| 49 |
+
|
| 50 |
+
def is_console_chat(self) -> bool:
|
| 51 |
+
"""通过 console.x.ai/v1/responses 路由的模型。"""
|
| 52 |
+
return bool(self.capability & Capability.CONSOLE_CHAT)
|
| 53 |
+
|
| 54 |
+
def pool_name(self) -> str:
|
| 55 |
+
"""Return the canonical pool string for this tier."""
|
| 56 |
+
if self.tier == Tier.SUPER:
|
| 57 |
+
return "super"
|
| 58 |
+
if self.tier == Tier.HEAVY:
|
| 59 |
+
return "heavy"
|
| 60 |
+
return "basic"
|
| 61 |
+
|
| 62 |
+
def pool_id(self) -> int:
|
| 63 |
+
"""Return the integer PoolId for the dataplane account table."""
|
| 64 |
+
return int(self.tier)
|
| 65 |
+
|
| 66 |
+
# 返回按优先级排序的候选池 ID
|
| 67 |
+
def pool_candidates(self) -> tuple[int, ...]:
|
| 68 |
+
"""Return pool IDs to try in priority order.
|
| 69 |
+
|
| 70 |
+
When ``prefer_best`` is True the order is reversed so that the
|
| 71 |
+
highest-tier pool is attempted first (hard priority — the first
|
| 72 |
+
pool with any available account wins; lower pools are only reached
|
| 73 |
+
when all accounts in higher pools are exhausted).
|
| 74 |
+
|
| 75 |
+
Default (prefer_best=False):
|
| 76 |
+
BASIC tier → try basic first, then super, then heavy
|
| 77 |
+
SUPER tier → try super first, then heavy
|
| 78 |
+
HEAVY tier → heavy only
|
| 79 |
+
|
| 80 |
+
Reversed (prefer_best=True):
|
| 81 |
+
BASIC tier → try heavy first, then super, then basic
|
| 82 |
+
SUPER tier → try heavy first, then super
|
| 83 |
+
HEAVY tier → heavy only
|
| 84 |
+
"""
|
| 85 |
+
if self.prefer_best:
|
| 86 |
+
if self.tier == Tier.HEAVY:
|
| 87 |
+
return (2,) # heavy only
|
| 88 |
+
if self.tier == Tier.SUPER:
|
| 89 |
+
return (2, 1) # heavy, super
|
| 90 |
+
return (2, 1, 0) # heavy, super, basic
|
| 91 |
+
if self.tier == Tier.BASIC:
|
| 92 |
+
return (0, 1, 2) # basic, super, heavy
|
| 93 |
+
if self.tier == Tier.SUPER:
|
| 94 |
+
return (1, 2) # super, heavy
|
| 95 |
+
return (2,) # heavy only
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
__all__ = ["ModelSpec"]
|
app/control/proxy/__init__.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ProxyDirectory — control-plane proxy pool coordinator.
|
| 2 |
+
|
| 3 |
+
Maintains the list of EgressNodes and ClearanceBundles.
|
| 4 |
+
Selection delegates to the dataplane ProxyTable; this module owns
|
| 5 |
+
configuration loading and clearance refresh lifecycle.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import asyncio
|
| 9 |
+
from urllib.parse import urlparse
|
| 10 |
+
|
| 11 |
+
from app.platform.logging.logger import logger
|
| 12 |
+
from app.platform.config.snapshot import get_config
|
| 13 |
+
from app.platform.runtime.clock import now_ms
|
| 14 |
+
from app.platform.runtime.ids import next_hex
|
| 15 |
+
from .config import resolve_clearance_config
|
| 16 |
+
from .models import (
|
| 17 |
+
EgressMode,
|
| 18 |
+
ClearanceMode,
|
| 19 |
+
EgressNode,
|
| 20 |
+
ClearanceBundle,
|
| 21 |
+
ProxyLease,
|
| 22 |
+
ProxyFeedback,
|
| 23 |
+
ProxyFeedbackKind,
|
| 24 |
+
RequestKind,
|
| 25 |
+
ProxyScope,
|
| 26 |
+
)
|
| 27 |
+
from .providers.manual import ManualClearanceProvider
|
| 28 |
+
from .providers.flaresolverr import FlareSolverrClearanceProvider
|
| 29 |
+
|
| 30 |
+
_DEFAULT_CLEARANCE_ORIGIN = "https://grok.com"
|
| 31 |
+
BundleKey = tuple[str, str]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _clearance_host(clearance_origin: str | None) -> str:
|
| 35 |
+
host = urlparse(clearance_origin or _DEFAULT_CLEARANCE_ORIGIN).hostname
|
| 36 |
+
return (host or "grok.com").lower()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ProxyDirectory:
|
| 40 |
+
"""Owns egress nodes and clearance bundles.
|
| 41 |
+
|
| 42 |
+
Thread-safety: all mutations are protected by ``_lock``.
|
| 43 |
+
"""
|
| 44 |
+
|
| 45 |
+
def __init__(self) -> None:
|
| 46 |
+
self._nodes: list[EgressNode] = []
|
| 47 |
+
self._resource_nodes: list[EgressNode] = [] # for media downloads
|
| 48 |
+
self._bundles: dict[BundleKey, ClearanceBundle] = {}
|
| 49 |
+
self._lock = asyncio.Lock()
|
| 50 |
+
# Single-flight guard: at most one FlareSolverr call per proxy+host key.
|
| 51 |
+
# Other coroutines wait on the Event until the active refresh completes.
|
| 52 |
+
self._refresh_events: dict[BundleKey, asyncio.Event] = {}
|
| 53 |
+
self._manual = ManualClearanceProvider()
|
| 54 |
+
self._flare = FlareSolverrClearanceProvider()
|
| 55 |
+
self._egress_mode: EgressMode = EgressMode.DIRECT
|
| 56 |
+
self._clearance_mode: ClearanceMode = ClearanceMode.NONE
|
| 57 |
+
self._config_sig: tuple | None = None
|
| 58 |
+
# Pool cursor for PROXY_POOL mode: sticky routing with failure-driven rotate.
|
| 59 |
+
# Incremented on node failure; all callers see the same cursor under _lock.
|
| 60 |
+
self._pool_cursor: int = 0
|
| 61 |
+
|
| 62 |
+
# ------------------------------------------------------------------
|
| 63 |
+
# Lifecycle
|
| 64 |
+
# ------------------------------------------------------------------
|
| 65 |
+
|
| 66 |
+
async def load(self) -> None:
|
| 67 |
+
"""Load proxy configuration from the current config snapshot."""
|
| 68 |
+
cfg = get_config()
|
| 69 |
+
egress_mode = EgressMode(cfg.get_str("proxy.egress.mode", "direct"))
|
| 70 |
+
clearance_mode = ClearanceMode.parse(
|
| 71 |
+
cfg.get_str("proxy.clearance.mode", "none")
|
| 72 |
+
)
|
| 73 |
+
base_url = cfg.get_str("proxy.egress.proxy_url", "")
|
| 74 |
+
res_url = cfg.get_str("proxy.egress.resource_proxy_url", "")
|
| 75 |
+
base_pool = tuple(cfg.get_list("proxy.egress.proxy_pool", []))
|
| 76 |
+
res_pool = tuple(cfg.get_list("proxy.egress.resource_proxy_pool", []))
|
| 77 |
+
clearance = resolve_clearance_config(cfg)
|
| 78 |
+
config_sig = (
|
| 79 |
+
egress_mode.value,
|
| 80 |
+
clearance_mode.value,
|
| 81 |
+
base_url,
|
| 82 |
+
res_url,
|
| 83 |
+
base_pool,
|
| 84 |
+
res_pool,
|
| 85 |
+
cfg.get_str("proxy.clearance.flaresolverr_url", ""),
|
| 86 |
+
clearance.cf_cookies,
|
| 87 |
+
clearance.user_agent,
|
| 88 |
+
clearance.cf_clearance,
|
| 89 |
+
clearance.browser,
|
| 90 |
+
cfg.get_int("proxy.clearance.timeout_sec", 60),
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
nodes: list[EgressNode] = []
|
| 94 |
+
resource_nodes: list[EgressNode] = []
|
| 95 |
+
|
| 96 |
+
if egress_mode == EgressMode.SINGLE_PROXY:
|
| 97 |
+
if base_url:
|
| 98 |
+
nodes.append(EgressNode(node_id="single", proxy_url=base_url))
|
| 99 |
+
if res_url:
|
| 100 |
+
resource_nodes.append(
|
| 101 |
+
EgressNode(node_id="res-single", proxy_url=res_url)
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
elif egress_mode == EgressMode.PROXY_POOL:
|
| 105 |
+
for i, url in enumerate(base_pool):
|
| 106 |
+
nodes.append(EgressNode(node_id=f"pool-{i}", proxy_url=url))
|
| 107 |
+
for i, url in enumerate(res_pool):
|
| 108 |
+
resource_nodes.append(
|
| 109 |
+
EgressNode(node_id=f"res-pool-{i}", proxy_url=url)
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
valid_affinities = {n.proxy_url or "direct" for n in [*nodes, *resource_nodes]}
|
| 113 |
+
if not valid_affinities:
|
| 114 |
+
valid_affinities = {"direct"}
|
| 115 |
+
|
| 116 |
+
async with self._lock:
|
| 117 |
+
if self._config_sig == config_sig:
|
| 118 |
+
return
|
| 119 |
+
from .models import ClearanceBundleState
|
| 120 |
+
|
| 121 |
+
self._egress_mode = egress_mode
|
| 122 |
+
self._clearance_mode = clearance_mode
|
| 123 |
+
self._nodes = nodes
|
| 124 |
+
self._resource_nodes = resource_nodes
|
| 125 |
+
self._pool_cursor = 0
|
| 126 |
+
self._bundles = {
|
| 127 |
+
key: bundle.model_copy(update={"state": ClearanceBundleState.INVALID})
|
| 128 |
+
for key, bundle in self._bundles.items()
|
| 129 |
+
if key[0] in valid_affinities
|
| 130 |
+
}
|
| 131 |
+
self._refresh_events = {
|
| 132 |
+
key: event
|
| 133 |
+
for key, event in self._refresh_events.items()
|
| 134 |
+
if key[0] in valid_affinities
|
| 135 |
+
}
|
| 136 |
+
self._config_sig = config_sig
|
| 137 |
+
|
| 138 |
+
logger.info(
|
| 139 |
+
"proxy directory loaded: egress_mode={} clearance_mode={} node_count={} resource_node_count={}",
|
| 140 |
+
egress_mode,
|
| 141 |
+
clearance_mode,
|
| 142 |
+
len(nodes),
|
| 143 |
+
len(resource_nodes),
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
# ------------------------------------------------------------------
|
| 147 |
+
# Acquisition
|
| 148 |
+
# ------------------------------------------------------------------
|
| 149 |
+
|
| 150 |
+
async def acquire(
|
| 151 |
+
self,
|
| 152 |
+
*,
|
| 153 |
+
scope: ProxyScope = ProxyScope.APP,
|
| 154 |
+
kind: RequestKind = RequestKind.HTTP,
|
| 155 |
+
resource: bool = False,
|
| 156 |
+
clearance_origin: str | None = None,
|
| 157 |
+
) -> ProxyLease:
|
| 158 |
+
"""Return a ProxyLease for the next request.
|
| 159 |
+
|
| 160 |
+
For DIRECT mode, returns a lease with no proxy or clearance.
|
| 161 |
+
"""
|
| 162 |
+
proxy_url = await self._pick_proxy_url(resource=resource)
|
| 163 |
+
affinity = proxy_url or "direct"
|
| 164 |
+
clearance_host = _clearance_host(clearance_origin)
|
| 165 |
+
|
| 166 |
+
bundle = await self._get_or_build_bundle(
|
| 167 |
+
affinity_key=affinity,
|
| 168 |
+
proxy_url=proxy_url or "",
|
| 169 |
+
clearance_origin=clearance_origin or _DEFAULT_CLEARANCE_ORIGIN,
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
return ProxyLease(
|
| 173 |
+
lease_id=next_hex(),
|
| 174 |
+
proxy_url=proxy_url,
|
| 175 |
+
cf_cookies=bundle.cf_cookies if bundle else "",
|
| 176 |
+
user_agent=bundle.user_agent if bundle else "",
|
| 177 |
+
clearance_host=clearance_host,
|
| 178 |
+
scope=scope,
|
| 179 |
+
kind=kind,
|
| 180 |
+
acquired_at=now_ms(),
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
async def feedback(self, lease: ProxyLease, result: ProxyFeedback) -> None:
|
| 184 |
+
"""Apply upstream feedback to the appropriate egress node."""
|
| 185 |
+
if result.kind in (
|
| 186 |
+
ProxyFeedbackKind.CHALLENGE,
|
| 187 |
+
ProxyFeedbackKind.UNAUTHORIZED,
|
| 188 |
+
):
|
| 189 |
+
# Invalidate associated clearance bundle.
|
| 190 |
+
key = (lease.proxy_url or "direct", lease.clearance_host)
|
| 191 |
+
async with self._lock:
|
| 192 |
+
from .models import ClearanceBundleState
|
| 193 |
+
|
| 194 |
+
bundle = self._bundles.get(key)
|
| 195 |
+
if bundle:
|
| 196 |
+
self._bundles[key] = bundle.model_copy(
|
| 197 |
+
update={"state": ClearanceBundleState.INVALID}
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
# In PROXY_POOL mode, rotate to the next node on any failure so the
|
| 201 |
+
# next acquire() prefers a different egress rather than hammering the
|
| 202 |
+
# same broken node.
|
| 203 |
+
if (
|
| 204 |
+
self._egress_mode == EgressMode.PROXY_POOL
|
| 205 |
+
and lease.proxy_url
|
| 206 |
+
and result.kind
|
| 207 |
+
in (
|
| 208 |
+
ProxyFeedbackKind.CHALLENGE,
|
| 209 |
+
ProxyFeedbackKind.UNAUTHORIZED,
|
| 210 |
+
ProxyFeedbackKind.FORBIDDEN,
|
| 211 |
+
ProxyFeedbackKind.TRANSPORT_ERROR,
|
| 212 |
+
)
|
| 213 |
+
):
|
| 214 |
+
async with self._lock:
|
| 215 |
+
self._pool_cursor += 1
|
| 216 |
+
logger.debug(
|
| 217 |
+
"proxy pool cursor advanced: proxy={} kind={} cursor={}",
|
| 218 |
+
lease.proxy_url,
|
| 219 |
+
result.kind,
|
| 220 |
+
self._pool_cursor,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
# ------------------------------------------------------------------
|
| 224 |
+
# Internal
|
| 225 |
+
# ------------------------------------------------------------------
|
| 226 |
+
|
| 227 |
+
async def _pick_proxy_url(self, resource: bool = False) -> str | None:
|
| 228 |
+
if self._egress_mode == EgressMode.DIRECT:
|
| 229 |
+
return None
|
| 230 |
+
async with self._lock:
|
| 231 |
+
# Prefer resource-specific nodes when available; fall back to base nodes.
|
| 232 |
+
nodes = (
|
| 233 |
+
self._resource_nodes
|
| 234 |
+
if resource and self._resource_nodes
|
| 235 |
+
else self._nodes
|
| 236 |
+
)
|
| 237 |
+
if not nodes:
|
| 238 |
+
return None
|
| 239 |
+
if self._egress_mode == EgressMode.SINGLE_PROXY:
|
| 240 |
+
return nodes[0].proxy_url
|
| 241 |
+
# PROXY_POOL: sticky routing — use current cursor, rotate on failure.
|
| 242 |
+
idx = self._pool_cursor % len(nodes)
|
| 243 |
+
return nodes[idx].proxy_url
|
| 244 |
+
|
| 245 |
+
async def _get_or_build_bundle(
|
| 246 |
+
self,
|
| 247 |
+
*,
|
| 248 |
+
affinity_key: str,
|
| 249 |
+
proxy_url: str,
|
| 250 |
+
clearance_origin: str,
|
| 251 |
+
) -> ClearanceBundle | None:
|
| 252 |
+
if self._clearance_mode == ClearanceMode.NONE:
|
| 253 |
+
return None
|
| 254 |
+
clearance_host = _clearance_host(clearance_origin)
|
| 255 |
+
key: BundleKey = (affinity_key, clearance_host)
|
| 256 |
+
|
| 257 |
+
# Single-flight: only one coroutine fetches clearance per proxy+host key.
|
| 258 |
+
# Concurrent callers wait on the Event and retry once it fires.
|
| 259 |
+
while True:
|
| 260 |
+
async with self._lock:
|
| 261 |
+
bundle = self._bundles.get(key)
|
| 262 |
+
if bundle and bundle.state.value == 0: # VALID
|
| 263 |
+
return bundle
|
| 264 |
+
event = self._refresh_events.get(key)
|
| 265 |
+
if event is None:
|
| 266 |
+
# This coroutine wins the right to refresh.
|
| 267 |
+
event = asyncio.Event()
|
| 268 |
+
self._refresh_events[key] = event
|
| 269 |
+
break
|
| 270 |
+
# Another coroutine is already refreshing — wait for it, then retry.
|
| 271 |
+
await event.wait()
|
| 272 |
+
|
| 273 |
+
try:
|
| 274 |
+
if self._clearance_mode == ClearanceMode.MANUAL:
|
| 275 |
+
bundle = self._manual.build_bundle(
|
| 276 |
+
affinity_key=affinity_key,
|
| 277 |
+
clearance_host=clearance_host,
|
| 278 |
+
)
|
| 279 |
+
else:
|
| 280 |
+
bundle = await self._flare.refresh_bundle(
|
| 281 |
+
affinity_key=affinity_key,
|
| 282 |
+
proxy_url=proxy_url,
|
| 283 |
+
target_url=clearance_origin,
|
| 284 |
+
)
|
| 285 |
+
if bundle:
|
| 286 |
+
async with self._lock:
|
| 287 |
+
self._bundles[key] = bundle
|
| 288 |
+
return bundle
|
| 289 |
+
finally:
|
| 290 |
+
async with self._lock:
|
| 291 |
+
self._refresh_events.pop(key, None)
|
| 292 |
+
event.set() # Wake all waiters so they retry with the new bundle.
|
| 293 |
+
|
| 294 |
+
# ------------------------------------------------------------------
|
| 295 |
+
# Clearance lifecycle helpers (used by ProxyClearanceScheduler)
|
| 296 |
+
# ------------------------------------------------------------------
|
| 297 |
+
|
| 298 |
+
async def invalidate_clearance(self) -> None:
|
| 299 |
+
"""Mark all cached clearance bundles as invalid.
|
| 300 |
+
|
| 301 |
+
The next ``acquire()`` call for each affinity key will trigger a fresh
|
| 302 |
+
FlareSolverr fetch (serialised by the single-flight guard).
|
| 303 |
+
"""
|
| 304 |
+
from .models import ClearanceBundleState
|
| 305 |
+
|
| 306 |
+
async with self._lock:
|
| 307 |
+
self._bundles = {
|
| 308 |
+
k: b.model_copy(update={"state": ClearanceBundleState.INVALID})
|
| 309 |
+
for k, b in self._bundles.items()
|
| 310 |
+
}
|
| 311 |
+
logger.debug("clearance bundles invalidated: count={}", len(self._bundles))
|
| 312 |
+
|
| 313 |
+
async def warm_up(self) -> None:
|
| 314 |
+
"""Pre-fetch clearance bundles for all configured affinity keys.
|
| 315 |
+
|
| 316 |
+
Called once at startup so the first real request does not have to wait
|
| 317 |
+
for FlareSolverr. Does NOT invalidate existing bundles first.
|
| 318 |
+
"""
|
| 319 |
+
if self._clearance_mode == ClearanceMode.NONE:
|
| 320 |
+
return
|
| 321 |
+
async with self._lock:
|
| 322 |
+
nodes = list(self._nodes)
|
| 323 |
+
affinity_keys = (
|
| 324 |
+
[(n.proxy_url or "direct", n.proxy_url or "") for n in nodes]
|
| 325 |
+
if nodes
|
| 326 |
+
else [("direct", "")]
|
| 327 |
+
)
|
| 328 |
+
for affinity, proxy_url in affinity_keys:
|
| 329 |
+
await self._get_or_build_bundle(
|
| 330 |
+
affinity_key=affinity,
|
| 331 |
+
proxy_url=proxy_url,
|
| 332 |
+
clearance_origin=_DEFAULT_CLEARANCE_ORIGIN,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
async def refresh_clearance_safe(self) -> None:
|
| 336 |
+
"""Scheduled clearance refresh: build new bundles then swap atomically.
|
| 337 |
+
|
| 338 |
+
Unlike ``invalidate_clearance() + warm_up()``, this never discards a
|
| 339 |
+
working bundle before a replacement is ready. If FlareSolverr is
|
| 340 |
+
temporarily unavailable the old bundle remains valid and continues to
|
| 341 |
+
serve requests.
|
| 342 |
+
"""
|
| 343 |
+
if self._clearance_mode == ClearanceMode.NONE:
|
| 344 |
+
return
|
| 345 |
+
async with self._lock:
|
| 346 |
+
nodes = list(self._nodes)
|
| 347 |
+
existing = list(self._bundles.keys())
|
| 348 |
+
|
| 349 |
+
refresh_targets: dict[BundleKey, tuple[str, str]] = {}
|
| 350 |
+
default_items = (
|
| 351 |
+
[(n.proxy_url or "direct", n.proxy_url or "") for n in nodes]
|
| 352 |
+
if nodes
|
| 353 |
+
else [("direct", "")]
|
| 354 |
+
)
|
| 355 |
+
for affinity, proxy_url in default_items:
|
| 356 |
+
key: BundleKey = (affinity, _clearance_host(_DEFAULT_CLEARANCE_ORIGIN))
|
| 357 |
+
refresh_targets[key] = (proxy_url, _DEFAULT_CLEARANCE_ORIGIN)
|
| 358 |
+
for key in existing:
|
| 359 |
+
affinity, clearance_host = key
|
| 360 |
+
refresh_targets.setdefault(
|
| 361 |
+
key,
|
| 362 |
+
("" if affinity == "direct" else affinity, f"https://{clearance_host}"),
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
for key, (proxy_url, clearance_origin) in refresh_targets.items():
|
| 366 |
+
affinity, clearance_host = key
|
| 367 |
+
if self._clearance_mode == ClearanceMode.MANUAL:
|
| 368 |
+
new_bundle = self._manual.build_bundle(
|
| 369 |
+
affinity_key=affinity,
|
| 370 |
+
clearance_host=clearance_host,
|
| 371 |
+
)
|
| 372 |
+
else:
|
| 373 |
+
new_bundle = await self._flare.refresh_bundle(
|
| 374 |
+
affinity_key=affinity,
|
| 375 |
+
proxy_url=proxy_url,
|
| 376 |
+
target_url=clearance_origin,
|
| 377 |
+
)
|
| 378 |
+
if new_bundle:
|
| 379 |
+
async with self._lock:
|
| 380 |
+
self._bundles[key] = new_bundle
|
| 381 |
+
logger.debug("clearance bundle refreshed: bundle={}", key)
|
| 382 |
+
else:
|
| 383 |
+
logger.warning(
|
| 384 |
+
"clearance refresh failed, keeping old bundle: bundle={}",
|
| 385 |
+
key,
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
# ------------------------------------------------------------------
|
| 389 |
+
# Properties
|
| 390 |
+
# ------------------------------------------------------------------
|
| 391 |
+
|
| 392 |
+
@property
|
| 393 |
+
def egress_mode(self) -> EgressMode:
|
| 394 |
+
return self._egress_mode
|
| 395 |
+
|
| 396 |
+
@property
|
| 397 |
+
def clearance_mode(self) -> ClearanceMode:
|
| 398 |
+
return self._clearance_mode
|
| 399 |
+
|
| 400 |
+
@property
|
| 401 |
+
def node_count(self) -> int:
|
| 402 |
+
return len(self._nodes)
|
| 403 |
+
|
| 404 |
+
@property
|
| 405 |
+
def nodes(self) -> list[EgressNode]:
|
| 406 |
+
"""Read-only snapshot of the current egress node list."""
|
| 407 |
+
return list(self._nodes)
|
| 408 |
+
|
| 409 |
+
@property
|
| 410 |
+
def bundles(self) -> dict[BundleKey, ClearanceBundle]:
|
| 411 |
+
"""Read-only snapshot of the current clearance bundles."""
|
| 412 |
+
return dict(self._bundles)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
# ---------------------------------------------------------------------------
|
| 416 |
+
# Module-level singleton
|
| 417 |
+
# ---------------------------------------------------------------------------
|
| 418 |
+
|
| 419 |
+
_directory: ProxyDirectory | None = None
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
async def get_proxy_directory() -> ProxyDirectory:
|
| 423 |
+
"""Return the module-level ProxyDirectory, reloading config if it changed."""
|
| 424 |
+
global _directory
|
| 425 |
+
if _directory is None:
|
| 426 |
+
_directory = ProxyDirectory()
|
| 427 |
+
await _directory.load()
|
| 428 |
+
return _directory
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
__all__ = ["ProxyDirectory", "get_proxy_directory"]
|
app/control/proxy/config.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Proxy clearance config helpers shared by control and dataplane code."""
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from app.platform.config.snapshot import get_config
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass(frozen=True)
|
| 10 |
+
class ClearanceConfig:
|
| 11 |
+
cf_cookies: str = ""
|
| 12 |
+
user_agent: str = ""
|
| 13 |
+
cf_clearance: str = ""
|
| 14 |
+
browser: str = ""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _cfg_str(cfg: Any, key: str) -> str:
|
| 18 |
+
value = cfg.get_str(key, "")
|
| 19 |
+
return value if value.strip() else ""
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def first_config_str(cfg: Any, *keys: str) -> str:
|
| 23 |
+
for key in keys:
|
| 24 |
+
value = _cfg_str(cfg, key)
|
| 25 |
+
if value:
|
| 26 |
+
return value
|
| 27 |
+
return ""
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def resolve_clearance_config(cfg: Any | None = None) -> ClearanceConfig:
|
| 31 |
+
cfg = cfg or get_config()
|
| 32 |
+
return ClearanceConfig(
|
| 33 |
+
cf_cookies=first_config_str(
|
| 34 |
+
cfg,
|
| 35 |
+
"proxy.cf_cookies",
|
| 36 |
+
"proxy.clearance.cf_cookies",
|
| 37 |
+
),
|
| 38 |
+
user_agent=first_config_str(
|
| 39 |
+
cfg,
|
| 40 |
+
"proxy.user_agent",
|
| 41 |
+
"proxy.clearance.user_agent",
|
| 42 |
+
),
|
| 43 |
+
cf_clearance=first_config_str(
|
| 44 |
+
cfg,
|
| 45 |
+
"proxy.cf_clearance",
|
| 46 |
+
"proxy.clearance.cf_clearance",
|
| 47 |
+
),
|
| 48 |
+
browser=first_config_str(
|
| 49 |
+
cfg,
|
| 50 |
+
"proxy.browser",
|
| 51 |
+
"proxy.clearance.browser",
|
| 52 |
+
),
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
__all__ = ["ClearanceConfig", "first_config_str", "resolve_clearance_config"]
|
app/control/proxy/feedback.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Classify upstream HTTP responses into proxy feedback categories."""
|
| 2 |
+
|
| 3 |
+
from .models import ProxyFeedback, ProxyFeedbackKind
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def classify_status_code(status_code: int) -> ProxyFeedbackKind:
|
| 7 |
+
if status_code == 200:
|
| 8 |
+
return ProxyFeedbackKind.SUCCESS
|
| 9 |
+
if status_code == 401:
|
| 10 |
+
return ProxyFeedbackKind.UNAUTHORIZED
|
| 11 |
+
if status_code == 403:
|
| 12 |
+
return ProxyFeedbackKind.CHALLENGE
|
| 13 |
+
if status_code == 429:
|
| 14 |
+
return ProxyFeedbackKind.RATE_LIMITED
|
| 15 |
+
if status_code >= 500:
|
| 16 |
+
return ProxyFeedbackKind.UPSTREAM_5XX
|
| 17 |
+
return ProxyFeedbackKind.FORBIDDEN
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def build_feedback(
|
| 21 |
+
status_code: int,
|
| 22 |
+
*,
|
| 23 |
+
is_cloudflare: bool = False,
|
| 24 |
+
reason: str = "",
|
| 25 |
+
retry_after_ms: int | None = None,
|
| 26 |
+
) -> ProxyFeedback:
|
| 27 |
+
"""Build a ``ProxyFeedback`` from an HTTP response status code."""
|
| 28 |
+
kind = classify_status_code(status_code)
|
| 29 |
+
if is_cloudflare and status_code == 403:
|
| 30 |
+
kind = ProxyFeedbackKind.CHALLENGE
|
| 31 |
+
return ProxyFeedback(
|
| 32 |
+
kind = kind,
|
| 33 |
+
status_code = status_code,
|
| 34 |
+
reason = reason,
|
| 35 |
+
retry_after_ms = retry_after_ms,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
__all__ = ["classify_status_code", "build_feedback"]
|
app/control/proxy/models.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Control-plane proxy domain models."""
|
| 2 |
+
|
| 3 |
+
from enum import IntEnum, StrEnum
|
| 4 |
+
from typing import Self
|
| 5 |
+
|
| 6 |
+
from pydantic import BaseModel
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ProxyScope(StrEnum):
|
| 10 |
+
APP = "app" # grok.com API calls
|
| 11 |
+
ASSET = "asset" # static asset / CDN fetches
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class RequestKind(StrEnum):
|
| 15 |
+
HTTP = "http"
|
| 16 |
+
WEBSOCKET = "websocket"
|
| 17 |
+
GRPC = "grpc"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class EgressMode(StrEnum):
|
| 21 |
+
DIRECT = "direct" # no proxy
|
| 22 |
+
SINGLE_PROXY = "single_proxy" # one fixed proxy URL
|
| 23 |
+
PROXY_POOL = "proxy_pool" # rotate from a pool
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ClearanceMode(StrEnum):
|
| 27 |
+
NONE = "none" # no CF clearance required
|
| 28 |
+
MANUAL = "manual" # operator-supplied cf_cookies
|
| 29 |
+
FLARESOLVERR = "flaresolverr" # maintained by FlareSolverr
|
| 30 |
+
|
| 31 |
+
@classmethod
|
| 32 |
+
def parse(cls, value: str | Self) -> Self:
|
| 33 |
+
if isinstance(value, cls):
|
| 34 |
+
return value
|
| 35 |
+
normalized = str(value or "").strip().lower()
|
| 36 |
+
if not normalized:
|
| 37 |
+
return cls.NONE
|
| 38 |
+
return cls(normalized)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class EgressNodeState(IntEnum):
|
| 42 |
+
HEALTHY = 0
|
| 43 |
+
DEGRADED = 1
|
| 44 |
+
UNHEALTHY = 2
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ClearanceBundleState(IntEnum):
|
| 48 |
+
VALID = 0
|
| 49 |
+
STALE = 1
|
| 50 |
+
INVALID = 2
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class ProxyFeedbackKind(StrEnum):
|
| 54 |
+
SUCCESS = "success"
|
| 55 |
+
CHALLENGE = "challenge" # CF JS challenge / captcha
|
| 56 |
+
UNAUTHORIZED = "unauthorized" # 401 on proxy auth
|
| 57 |
+
FORBIDDEN = "forbidden" # 403 not CF-related
|
| 58 |
+
RATE_LIMITED = "rate_limited" # 429
|
| 59 |
+
UPSTREAM_5XX = "upstream_5xx"
|
| 60 |
+
TRANSPORT_ERROR = "transport_error"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class EgressNode(BaseModel):
|
| 64 |
+
node_id: str
|
| 65 |
+
proxy_url: str | None = None # None → direct
|
| 66 |
+
scope: ProxyScope = ProxyScope.APP
|
| 67 |
+
state: EgressNodeState = EgressNodeState.HEALTHY
|
| 68 |
+
health: float = 1.0
|
| 69 |
+
inflight: int = 0
|
| 70 |
+
last_used: int | None = None # ms
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class ClearanceBundle(BaseModel):
|
| 74 |
+
bundle_id: str
|
| 75 |
+
cf_cookies: str = ""
|
| 76 |
+
user_agent: str = ""
|
| 77 |
+
state: ClearanceBundleState = ClearanceBundleState.VALID
|
| 78 |
+
affinity_key: str = "" # associates bundle with an egress node
|
| 79 |
+
clearance_host: str = "grok.com"
|
| 80 |
+
last_refresh_at: int | None = None # ms
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class ProxyLease(BaseModel):
|
| 84 |
+
lease_id: str
|
| 85 |
+
proxy_url: str | None = None
|
| 86 |
+
cf_cookies: str = ""
|
| 87 |
+
user_agent: str = ""
|
| 88 |
+
clearance_host: str = "grok.com"
|
| 89 |
+
scope: ProxyScope = ProxyScope.APP
|
| 90 |
+
kind: RequestKind = RequestKind.HTTP
|
| 91 |
+
acquired_at: int = 0 # ms
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def has_proxy(self) -> bool:
|
| 95 |
+
return bool(self.proxy_url)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class ProxyFeedback(BaseModel):
|
| 99 |
+
kind: ProxyFeedbackKind
|
| 100 |
+
status_code: int | None = None
|
| 101 |
+
reason: str = ""
|
| 102 |
+
retry_after_ms: int | None = None
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
__all__ = [
|
| 106 |
+
"ProxyScope", "RequestKind", "EgressMode", "ClearanceMode",
|
| 107 |
+
"EgressNodeState", "ClearanceBundleState", "ProxyFeedbackKind",
|
| 108 |
+
"EgressNode", "ClearanceBundle", "ProxyLease", "ProxyFeedback",
|
| 109 |
+
]
|
app/control/proxy/providers/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .manual import ManualClearanceProvider
|
| 2 |
+
from .flaresolverr import FlareSolverrClearanceProvider
|
| 3 |
+
|
| 4 |
+
__all__ = ["ManualClearanceProvider", "FlareSolverrClearanceProvider"]
|
app/control/proxy/providers/flaresolverr.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FlareSolverr-backed managed clearance provider."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import json
|
| 5 |
+
from urllib import request as urllib_request
|
| 6 |
+
from urllib.error import HTTPError, URLError
|
| 7 |
+
from urllib.parse import urlparse
|
| 8 |
+
|
| 9 |
+
from app.platform.logging.logger import logger
|
| 10 |
+
from app.platform.config.snapshot import get_config
|
| 11 |
+
from ..models import ClearanceBundle, ClearanceMode
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _extract_all_cookies(cookies: list[dict]) -> str:
|
| 15 |
+
return "; ".join(f"{c.get('name')}={c.get('value')}" for c in cookies)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class FlareSolverrClearanceProvider:
|
| 19 |
+
"""Refresh CF clearance bundles via a FlareSolverr instance."""
|
| 20 |
+
|
| 21 |
+
async def refresh_bundle(
|
| 22 |
+
self,
|
| 23 |
+
*,
|
| 24 |
+
affinity_key: str,
|
| 25 |
+
proxy_url: str,
|
| 26 |
+
target_url: str = "https://grok.com",
|
| 27 |
+
) -> ClearanceBundle | None:
|
| 28 |
+
cfg = get_config()
|
| 29 |
+
mode = ClearanceMode.parse(cfg.get_str("proxy.clearance.mode", "none"))
|
| 30 |
+
if mode != ClearanceMode.FLARESOLVERR:
|
| 31 |
+
return None
|
| 32 |
+
fs_url = cfg.get_str("proxy.clearance.flaresolverr_url", "")
|
| 33 |
+
timeout_sec = cfg.get_int("proxy.clearance.timeout_sec", 60)
|
| 34 |
+
if not fs_url:
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
result = await self._solve(
|
| 38 |
+
fs_url = fs_url,
|
| 39 |
+
proxy_url = proxy_url,
|
| 40 |
+
timeout_sec = timeout_sec,
|
| 41 |
+
target_url = target_url,
|
| 42 |
+
)
|
| 43 |
+
if not result:
|
| 44 |
+
logger.warning(
|
| 45 |
+
"flaresolverr clearance refresh failed: affinity={} proxy={} target={}",
|
| 46 |
+
affinity_key, proxy_url or "<direct>", target_url,
|
| 47 |
+
)
|
| 48 |
+
return None
|
| 49 |
+
host = result.get("clearance_host", "grok.com")
|
| 50 |
+
|
| 51 |
+
return ClearanceBundle(
|
| 52 |
+
bundle_id = f"flaresolverr:{affinity_key}@{host}",
|
| 53 |
+
cf_cookies = result.get("cookies", ""),
|
| 54 |
+
user_agent = result.get("user_agent", ""),
|
| 55 |
+
affinity_key = affinity_key,
|
| 56 |
+
clearance_host = host,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
async def _solve(
|
| 60 |
+
self,
|
| 61 |
+
*,
|
| 62 |
+
fs_url: str,
|
| 63 |
+
proxy_url: str,
|
| 64 |
+
timeout_sec: int,
|
| 65 |
+
target_url: str,
|
| 66 |
+
) -> dict[str, str] | None:
|
| 67 |
+
target = target_url.strip() or "https://grok.com"
|
| 68 |
+
payload: dict = {
|
| 69 |
+
"cmd": "request.get",
|
| 70 |
+
"url": target,
|
| 71 |
+
"maxTimeout": timeout_sec * 1000,
|
| 72 |
+
}
|
| 73 |
+
if proxy_url:
|
| 74 |
+
payload["proxy"] = {"url": proxy_url}
|
| 75 |
+
|
| 76 |
+
body = json.dumps(payload).encode()
|
| 77 |
+
request = urllib_request.Request(
|
| 78 |
+
f"{fs_url.rstrip('/')}/v1",
|
| 79 |
+
data = body,
|
| 80 |
+
method = "POST",
|
| 81 |
+
headers = {"Content-Type": "application/json"},
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
def _post() -> dict:
|
| 86 |
+
with urllib_request.urlopen(request, timeout=timeout_sec + 30) as resp:
|
| 87 |
+
return json.loads(resp.read().decode())
|
| 88 |
+
|
| 89 |
+
result = await asyncio.to_thread(_post)
|
| 90 |
+
if result.get("status") != "ok":
|
| 91 |
+
logger.warning(
|
| 92 |
+
"flaresolverr returned non-ok status: status={} message={}",
|
| 93 |
+
result.get("status"), result.get("message", ""),
|
| 94 |
+
)
|
| 95 |
+
return None
|
| 96 |
+
|
| 97 |
+
solution = result.get("solution", {})
|
| 98 |
+
cookies = solution.get("cookies", [])
|
| 99 |
+
if not cookies:
|
| 100 |
+
logger.warning("flaresolverr returned no cookies")
|
| 101 |
+
return None
|
| 102 |
+
|
| 103 |
+
ua = solution.get("userAgent", "") or ""
|
| 104 |
+
host = (urlparse(target).hostname or "").lower()
|
| 105 |
+
filtered = [
|
| 106 |
+
cookie for cookie in cookies
|
| 107 |
+
if not host or not cookie.get("domain") or host.endswith(str(cookie.get("domain", "")).lstrip(".").lower())
|
| 108 |
+
]
|
| 109 |
+
chosen = filtered or cookies
|
| 110 |
+
return {
|
| 111 |
+
"cookies": _extract_all_cookies(chosen),
|
| 112 |
+
"user_agent": ua,
|
| 113 |
+
"clearance_host": host or "grok.com",
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
except HTTPError as exc:
|
| 117 |
+
body_text = exc.read().decode("utf-8", "replace")[:300]
|
| 118 |
+
logger.warning("flaresolverr http request failed: status={} body={}", exc.code, body_text)
|
| 119 |
+
except URLError as exc:
|
| 120 |
+
logger.warning("flaresolverr connection failed: reason={}", exc.reason)
|
| 121 |
+
except Exception as exc:
|
| 122 |
+
logger.warning("flaresolverr request failed: error={}", exc)
|
| 123 |
+
|
| 124 |
+
return None
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
__all__ = ["FlareSolverrClearanceProvider"]
|
app/control/proxy/providers/manual.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Manual clearance provider — uses operator-supplied cookies directly."""
|
| 2 |
+
|
| 3 |
+
from app.platform.config.snapshot import get_config
|
| 4 |
+
from ..config import resolve_clearance_config
|
| 5 |
+
from ..models import ClearanceBundle, ClearanceMode
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class ManualClearanceProvider:
|
| 9 |
+
"""Build a ClearanceBundle from static config values."""
|
| 10 |
+
|
| 11 |
+
def build_bundle(
|
| 12 |
+
self,
|
| 13 |
+
*,
|
| 14 |
+
affinity_key: str,
|
| 15 |
+
clearance_host: str = "grok.com",
|
| 16 |
+
) -> ClearanceBundle | None:
|
| 17 |
+
cfg = get_config()
|
| 18 |
+
mode = ClearanceMode.parse(cfg.get_str("proxy.clearance.mode", "none"))
|
| 19 |
+
if mode != ClearanceMode.MANUAL:
|
| 20 |
+
return None
|
| 21 |
+
clearance = resolve_clearance_config(cfg)
|
| 22 |
+
return ClearanceBundle(
|
| 23 |
+
bundle_id=f"manual:{affinity_key}@{clearance_host}",
|
| 24 |
+
cf_cookies=clearance.cf_cookies,
|
| 25 |
+
user_agent=clearance.user_agent,
|
| 26 |
+
affinity_key=affinity_key,
|
| 27 |
+
clearance_host=clearance_host,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
__all__ = ["ManualClearanceProvider"]
|
app/control/proxy/scheduler.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Proxy clearance refresh scheduler.
|
| 2 |
+
|
| 3 |
+
Periodically refreshes ClearanceBundles for managed (FlareSolverr) mode.
|
| 4 |
+
Previously inline in ProxyDirectory; extracted for separation of concerns.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import asyncio
|
| 8 |
+
|
| 9 |
+
from app.platform.logging.logger import logger
|
| 10 |
+
from app.platform.config.snapshot import get_config
|
| 11 |
+
from app.control.proxy import ProxyDirectory
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class ProxyClearanceScheduler:
|
| 15 |
+
"""Periodically refreshes proxy clearance bundles."""
|
| 16 |
+
|
| 17 |
+
def __init__(self, directory: ProxyDirectory) -> None:
|
| 18 |
+
self._directory = directory
|
| 19 |
+
self._task: asyncio.Task | None = None
|
| 20 |
+
self._running = False
|
| 21 |
+
|
| 22 |
+
def start(self) -> None:
|
| 23 |
+
if self._running:
|
| 24 |
+
return
|
| 25 |
+
self._running = True
|
| 26 |
+
self._task = asyncio.create_task(self._loop())
|
| 27 |
+
logger.info("proxy clearance scheduler started")
|
| 28 |
+
|
| 29 |
+
def stop(self) -> None:
|
| 30 |
+
self._running = False
|
| 31 |
+
if self._task and not self._task.done():
|
| 32 |
+
self._task.cancel()
|
| 33 |
+
logger.info("proxy clearance scheduler stopped")
|
| 34 |
+
|
| 35 |
+
async def _loop(self) -> None:
|
| 36 |
+
# Warm up immediately on start so the first request doesn't block.
|
| 37 |
+
await self._warm_up()
|
| 38 |
+
while self._running:
|
| 39 |
+
try:
|
| 40 |
+
interval = self._get_interval()
|
| 41 |
+
await asyncio.sleep(interval)
|
| 42 |
+
if not self._running:
|
| 43 |
+
break
|
| 44 |
+
await self._refresh()
|
| 45 |
+
except asyncio.CancelledError:
|
| 46 |
+
break
|
| 47 |
+
except Exception as exc:
|
| 48 |
+
logger.error(
|
| 49 |
+
"proxy clearance scheduler loop failed: error_type={} error={}",
|
| 50 |
+
type(exc).__name__,
|
| 51 |
+
exc,
|
| 52 |
+
)
|
| 53 |
+
await asyncio.sleep(60)
|
| 54 |
+
|
| 55 |
+
async def _warm_up(self) -> None:
|
| 56 |
+
"""Pre-fetch clearance bundles without invalidating existing ones."""
|
| 57 |
+
try:
|
| 58 |
+
await self._directory.load()
|
| 59 |
+
await self._directory.warm_up()
|
| 60 |
+
logger.debug("proxy clearance warm-up completed")
|
| 61 |
+
except Exception as exc:
|
| 62 |
+
logger.warning("proxy clearance warm-up failed: error={}", exc)
|
| 63 |
+
|
| 64 |
+
async def _refresh(self) -> None:
|
| 65 |
+
"""Build fresh clearance bundles and swap atomically (build-then-swap).
|
| 66 |
+
|
| 67 |
+
Old bundles are kept if FlareSolverr is unavailable, so a transient
|
| 68 |
+
refresh failure never leaves requests without clearance.
|
| 69 |
+
"""
|
| 70 |
+
try:
|
| 71 |
+
await self._directory.load()
|
| 72 |
+
await self._directory.refresh_clearance_safe()
|
| 73 |
+
logger.debug("proxy clearance refresh completed")
|
| 74 |
+
except Exception as exc:
|
| 75 |
+
logger.warning("proxy clearance refresh failed: error={}", exc)
|
| 76 |
+
|
| 77 |
+
def _get_interval(self) -> int:
|
| 78 |
+
"""Return refresh interval in seconds from config."""
|
| 79 |
+
cfg = get_config()
|
| 80 |
+
return cfg.get_int("proxy.clearance.refresh_interval", 600)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
__all__ = ["ProxyClearanceScheduler"]
|
app/dataplane/__init__.py
ADDED
|
File without changes
|
app/dataplane/account/__init__.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""AccountDirectory — high-concurrency hot-path account store.
|
| 2 |
+
|
| 3 |
+
Wraps the columnar AccountRuntimeTable with lock-minimal coordination.
|
| 4 |
+
Bootstrap loads a full snapshot; incremental sync applies revision-based
|
| 5 |
+
changesets without holding the selection lock.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import asyncio
|
| 9 |
+
from typing import TYPE_CHECKING
|
| 10 |
+
|
| 11 |
+
from app.platform.config.snapshot import get_config
|
| 12 |
+
from app.platform.logging.logger import logger
|
| 13 |
+
from app.platform.runtime.clock import now_s
|
| 14 |
+
from app.control.account.repository import AccountRepository
|
| 15 |
+
from app.control.account.enums import FeedbackKind
|
| 16 |
+
from .table import AccountRuntimeTable
|
| 17 |
+
from .lease import AccountLease, new_lease
|
| 18 |
+
from .selector import current_strategy, select, select_any
|
| 19 |
+
from .sync import bootstrap as _bootstrap, apply_changes
|
| 20 |
+
from . import feedback as fb
|
| 21 |
+
from ..shared.enums import POOL_ID_TO_STR, StatusId
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class AccountDirectory:
|
| 28 |
+
"""High-concurrency, lock-minimal account store for the hot path.
|
| 29 |
+
|
| 30 |
+
Design:
|
| 31 |
+
- ``_table`` is replaced atomically; readers never see partial state.
|
| 32 |
+
- ``_lock`` guards all table mutations (feedback, sync, status updates).
|
| 33 |
+
- Selection (``reserve``) copies the candidate set under lock, then
|
| 34 |
+
scores outside the lock — lock is re-acquired only to increment
|
| 35 |
+
inflight.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(self, repository: AccountRepository) -> None:
|
| 39 |
+
self._repo = repository
|
| 40 |
+
self._table: AccountRuntimeTable | None = None
|
| 41 |
+
self._lock = asyncio.Lock()
|
| 42 |
+
self._sync_lock = asyncio.Lock()
|
| 43 |
+
|
| 44 |
+
# ------------------------------------------------------------------
|
| 45 |
+
# Lifecycle
|
| 46 |
+
# ------------------------------------------------------------------
|
| 47 |
+
|
| 48 |
+
async def bootstrap(self) -> None:
|
| 49 |
+
"""Load initial snapshot from the repository."""
|
| 50 |
+
table = await _bootstrap(self._repo)
|
| 51 |
+
async with self._lock:
|
| 52 |
+
self._table = table
|
| 53 |
+
logger.info("account directory ready: size={}", table.size)
|
| 54 |
+
|
| 55 |
+
async def sync_if_changed(self) -> bool:
|
| 56 |
+
"""Apply incremental changes since last revision.
|
| 57 |
+
|
| 58 |
+
Returns True if any changes were applied.
|
| 59 |
+
Uses a dedicated sync lock so only one sync runs at a time,
|
| 60 |
+
without blocking the selection lock.
|
| 61 |
+
"""
|
| 62 |
+
if self._table is None:
|
| 63 |
+
return False
|
| 64 |
+
|
| 65 |
+
async with self._sync_lock:
|
| 66 |
+
async with self._lock:
|
| 67 |
+
table = self._table
|
| 68 |
+
changed = await apply_changes(table, self._repo)
|
| 69 |
+
if changed:
|
| 70 |
+
logger.debug(
|
| 71 |
+
"account directory synced: revision={} size={}",
|
| 72 |
+
table.revision,
|
| 73 |
+
table.size,
|
| 74 |
+
)
|
| 75 |
+
return changed
|
| 76 |
+
|
| 77 |
+
# ------------------------------------------------------------------
|
| 78 |
+
# Selection (hot path)
|
| 79 |
+
# ------------------------------------------------------------------
|
| 80 |
+
|
| 81 |
+
async def reserve(
|
| 82 |
+
self,
|
| 83 |
+
pool_candidates: tuple[int, ...] | int,
|
| 84 |
+
mode_id: int,
|
| 85 |
+
*,
|
| 86 |
+
exclude_tokens: list[str] | None = None,
|
| 87 |
+
prefer_tags: list[str] | None = None,
|
| 88 |
+
now_s_override: int | None = None,
|
| 89 |
+
) -> AccountLease | None:
|
| 90 |
+
"""Select and reserve the best available account slot.
|
| 91 |
+
|
| 92 |
+
``pool_candidates`` is tried in order; the first pool with an available
|
| 93 |
+
account wins. A plain ``int`` is accepted and wrapped into a tuple.
|
| 94 |
+
|
| 95 |
+
Returns an AccountLease, or None if no account is available.
|
| 96 |
+
"""
|
| 97 |
+
table = self._table
|
| 98 |
+
if table is None:
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
pools: tuple[int, ...] = (
|
| 102 |
+
(pool_candidates,) if isinstance(pool_candidates, int) else pool_candidates
|
| 103 |
+
)
|
| 104 |
+
ts = now_s_override if now_s_override is not None else now_s()
|
| 105 |
+
|
| 106 |
+
# Resolve exclude set (O(n) once, before lock).
|
| 107 |
+
exclude_idxs: frozenset[int] | None = None
|
| 108 |
+
if exclude_tokens:
|
| 109 |
+
idxs = [
|
| 110 |
+
table.idx_by_token[t] for t in exclude_tokens if t in table.idx_by_token
|
| 111 |
+
]
|
| 112 |
+
if idxs:
|
| 113 |
+
exclude_idxs = frozenset(idxs)
|
| 114 |
+
|
| 115 |
+
# Resolve tag preference set.
|
| 116 |
+
prefer_tag_idxs: set[int] | None = None
|
| 117 |
+
if prefer_tags:
|
| 118 |
+
sets = [
|
| 119 |
+
table.tag_idx.get(tag) for tag in prefer_tags if tag in table.tag_idx
|
| 120 |
+
]
|
| 121 |
+
if sets:
|
| 122 |
+
prefer_tag_idxs = set().union(*sets)
|
| 123 |
+
|
| 124 |
+
async with self._lock:
|
| 125 |
+
idx: int | None = None
|
| 126 |
+
for pool_id in pools:
|
| 127 |
+
idx = select(
|
| 128 |
+
table,
|
| 129 |
+
pool_id,
|
| 130 |
+
mode_id,
|
| 131 |
+
exclude_idxs=exclude_idxs,
|
| 132 |
+
prefer_tag_idxs=prefer_tag_idxs,
|
| 133 |
+
now_s=ts,
|
| 134 |
+
)
|
| 135 |
+
if idx is not None:
|
| 136 |
+
break
|
| 137 |
+
|
| 138 |
+
if idx is None:
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
fb.increment_inflight(table, idx)
|
| 142 |
+
fb.update_last_use(table, idx, ts)
|
| 143 |
+
token = table.get_token(idx)
|
| 144 |
+
actual_pool = table.get_pool_id(idx)
|
| 145 |
+
|
| 146 |
+
return new_lease(
|
| 147 |
+
idx=idx,
|
| 148 |
+
token=token,
|
| 149 |
+
pool_id=actual_pool,
|
| 150 |
+
mode_id=mode_id,
|
| 151 |
+
selected_at=ts,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
async def reserve_any(
|
| 155 |
+
self,
|
| 156 |
+
pool_candidates: tuple[int, ...] | int,
|
| 157 |
+
*,
|
| 158 |
+
exclude_tokens: list[str] | None = None,
|
| 159 |
+
prefer_tags: list[str] | None = None,
|
| 160 |
+
now_s_override: int | None = None,
|
| 161 |
+
) -> AccountLease | None:
|
| 162 |
+
"""Select any active account from pool_candidates without mode quota checking.
|
| 163 |
+
|
| 164 |
+
Used for WebSocket-based operations that manage their own upstream rate limiting.
|
| 165 |
+
Returns an AccountLease with mode_id=-1 (no specific mode is tracked).
|
| 166 |
+
"""
|
| 167 |
+
table = self._table
|
| 168 |
+
if table is None:
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
pools: tuple[int, ...] = (
|
| 172 |
+
(pool_candidates,) if isinstance(pool_candidates, int) else pool_candidates
|
| 173 |
+
)
|
| 174 |
+
ts = now_s_override if now_s_override is not None else now_s()
|
| 175 |
+
|
| 176 |
+
exclude_idxs: frozenset[int] | None = None
|
| 177 |
+
if exclude_tokens:
|
| 178 |
+
idxs = [
|
| 179 |
+
table.idx_by_token[t] for t in exclude_tokens if t in table.idx_by_token
|
| 180 |
+
]
|
| 181 |
+
if idxs:
|
| 182 |
+
exclude_idxs = frozenset(idxs)
|
| 183 |
+
|
| 184 |
+
prefer_tag_idxs: set[int] | None = None
|
| 185 |
+
if prefer_tags:
|
| 186 |
+
sets = [
|
| 187 |
+
table.tag_idx.get(tag) for tag in prefer_tags if tag in table.tag_idx
|
| 188 |
+
]
|
| 189 |
+
if sets:
|
| 190 |
+
prefer_tag_idxs = set().union(*sets)
|
| 191 |
+
|
| 192 |
+
async with self._lock:
|
| 193 |
+
idx: int | None = None
|
| 194 |
+
for pool_id in pools:
|
| 195 |
+
idx = select_any(
|
| 196 |
+
table,
|
| 197 |
+
pool_id,
|
| 198 |
+
exclude_idxs=exclude_idxs,
|
| 199 |
+
prefer_tag_idxs=prefer_tag_idxs,
|
| 200 |
+
now_s=ts,
|
| 201 |
+
)
|
| 202 |
+
if idx is not None:
|
| 203 |
+
break
|
| 204 |
+
|
| 205 |
+
if idx is None:
|
| 206 |
+
return None
|
| 207 |
+
|
| 208 |
+
fb.increment_inflight(table, idx)
|
| 209 |
+
fb.update_last_use(table, idx, ts)
|
| 210 |
+
token = table.get_token(idx)
|
| 211 |
+
actual_pool = table.get_pool_id(idx)
|
| 212 |
+
|
| 213 |
+
return new_lease(
|
| 214 |
+
idx=idx,
|
| 215 |
+
token=token,
|
| 216 |
+
pool_id=actual_pool,
|
| 217 |
+
mode_id=-1, # no specific mode tracked for WS operations
|
| 218 |
+
selected_at=ts,
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
async def release(self, lease: AccountLease) -> None:
|
| 222 |
+
"""Decrement inflight counter for a finished request."""
|
| 223 |
+
table = self._table
|
| 224 |
+
if table is None:
|
| 225 |
+
return
|
| 226 |
+
async with self._lock:
|
| 227 |
+
fb.decrement_inflight(table, lease.idx)
|
| 228 |
+
|
| 229 |
+
# ------------------------------------------------------------------
|
| 230 |
+
# Feedback (hot path)
|
| 231 |
+
# ------------------------------------------------------------------
|
| 232 |
+
|
| 233 |
+
async def feedback(
|
| 234 |
+
self,
|
| 235 |
+
token: str,
|
| 236 |
+
kind: FeedbackKind,
|
| 237 |
+
mode_id: int,
|
| 238 |
+
*,
|
| 239 |
+
remaining: int | None = None,
|
| 240 |
+
reset_at_ms: int | None = None,
|
| 241 |
+
now_s_val: int | None = None,
|
| 242 |
+
) -> None:
|
| 243 |
+
"""Apply upstream response feedback to the account slot."""
|
| 244 |
+
table = self._table
|
| 245 |
+
if table is None:
|
| 246 |
+
return
|
| 247 |
+
|
| 248 |
+
idx = table.idx_by_token.get(token)
|
| 249 |
+
if idx is None:
|
| 250 |
+
return
|
| 251 |
+
|
| 252 |
+
ts = now_s_val if now_s_val is not None else now_s()
|
| 253 |
+
|
| 254 |
+
strategy = current_strategy()
|
| 255 |
+
|
| 256 |
+
async with self._lock:
|
| 257 |
+
if kind == FeedbackKind.SUCCESS:
|
| 258 |
+
if strategy == "random":
|
| 259 |
+
fb.apply_success_random(table, idx)
|
| 260 |
+
else:
|
| 261 |
+
fb.apply_success_quota(table, idx, mode_id)
|
| 262 |
+
|
| 263 |
+
elif kind == FeedbackKind.RATE_LIMITED:
|
| 264 |
+
if strategy == "random":
|
| 265 |
+
pool_id = int(table.pool_by_idx[idx])
|
| 266 |
+
cooling_sec = _pool_cooling_sec(pool_id, mode_id)
|
| 267 |
+
fb.apply_rate_limited_random(table, idx, cooling_sec=cooling_sec)
|
| 268 |
+
else:
|
| 269 |
+
fb.apply_rate_limited_quota(table, idx, mode_id)
|
| 270 |
+
fb.update_last_fail(table, idx, ts)
|
| 271 |
+
|
| 272 |
+
elif kind == FeedbackKind.UNAUTHORIZED:
|
| 273 |
+
fb.apply_auth_failure(table, idx)
|
| 274 |
+
fb.update_last_fail(table, idx, ts)
|
| 275 |
+
fb.apply_status_change(table, idx, int(StatusId.EXPIRED))
|
| 276 |
+
|
| 277 |
+
elif kind == FeedbackKind.FORBIDDEN:
|
| 278 |
+
fb.apply_forbidden(table, idx)
|
| 279 |
+
fb.update_last_fail(table, idx, ts)
|
| 280 |
+
|
| 281 |
+
elif kind == FeedbackKind.SERVER_ERROR:
|
| 282 |
+
fb.apply_server_error(table, idx)
|
| 283 |
+
fb.update_last_fail(table, idx, ts)
|
| 284 |
+
|
| 285 |
+
# Quota strategy may receive authoritative quota data from upstream
|
| 286 |
+
# response headers; the random strategy ignores this entirely.
|
| 287 |
+
if strategy == "quota" and remaining is not None and reset_at_ms is not None:
|
| 288 |
+
reset_s = int(reset_at_ms // 1000)
|
| 289 |
+
fb.apply_quota_update(table, idx, mode_id, remaining, reset_s)
|
| 290 |
+
|
| 291 |
+
# ------------------------------------------------------------------
|
| 292 |
+
# Diagnostics
|
| 293 |
+
# ------------------------------------------------------------------
|
| 294 |
+
|
| 295 |
+
@property
|
| 296 |
+
def size(self) -> int:
|
| 297 |
+
return self._table.size if self._table else 0
|
| 298 |
+
|
| 299 |
+
@property
|
| 300 |
+
def revision(self) -> int:
|
| 301 |
+
return self._table.revision if self._table else 0
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
# ---------------------------------------------------------------------------
|
| 305 |
+
# Helpers
|
| 306 |
+
# ---------------------------------------------------------------------------
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
_POOL_INTERVAL_CONFIG: dict[str, tuple[str, int]] = {
|
| 310 |
+
"basic": ("account.refresh.basic_interval_sec", 86_400),
|
| 311 |
+
"super": ("account.refresh.super_interval_sec", 7_200),
|
| 312 |
+
"heavy": ("account.refresh.heavy_interval_sec", 7_200),
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
# Console (mode_id=5) 窗口仅 3600s,使用 4 小时冷却(远大于窗口,
|
| 316 |
+
# 给上游 team 限速充分恢复时间,但不会沉寂一整天)
|
| 317 |
+
_CONSOLE_COOLING_SEC = 14_400
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _pool_cooling_sec(pool_id: int, mode_id: int = -1) -> int:
|
| 321 |
+
"""Cooling seconds for a 429 on a given pool (random strategy only).
|
| 322 |
+
|
| 323 |
+
Console 模式 (mode_id=5) 使用独立冷却时长 4 小时;
|
| 324 |
+
其它模式按 pool 决定(basic=24h, super/heavy=2h)。
|
| 325 |
+
"""
|
| 326 |
+
if mode_id == 5:
|
| 327 |
+
return _CONSOLE_COOLING_SEC
|
| 328 |
+
pool_str = POOL_ID_TO_STR.get(pool_id, "basic")
|
| 329 |
+
interval_key, default_interval = _POOL_INTERVAL_CONFIG.get(
|
| 330 |
+
pool_str, _POOL_INTERVAL_CONFIG["basic"]
|
| 331 |
+
)
|
| 332 |
+
return max(0, int(get_config(interval_key, default_interval)))
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
# ---------------------------------------------------------------------------
|
| 336 |
+
# Module-level singleton
|
| 337 |
+
# ---------------------------------------------------------------------------
|
| 338 |
+
|
| 339 |
+
_directory: AccountDirectory | None = None
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
async def get_account_directory(
|
| 343 |
+
repository: AccountRepository | None = None,
|
| 344 |
+
) -> AccountDirectory:
|
| 345 |
+
"""Return the module-level AccountDirectory, bootstrapping on first call.
|
| 346 |
+
|
| 347 |
+
After first initialization, ``repository`` may be omitted.
|
| 348 |
+
"""
|
| 349 |
+
global _directory
|
| 350 |
+
if _directory is None:
|
| 351 |
+
if repository is None:
|
| 352 |
+
raise RuntimeError(
|
| 353 |
+
"AccountDirectory not bootstrapped — repository required on first call"
|
| 354 |
+
)
|
| 355 |
+
_directory = AccountDirectory(repository)
|
| 356 |
+
await _directory.bootstrap()
|
| 357 |
+
return _directory
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
__all__ = ["AccountDirectory", "get_account_directory"]
|