完善脚本

This commit is contained in:
xiaobai committed 2026-03-23 21:42:02 +08:00
1 parent 9d9509a26b
commit 0c740f5a53
9 files changed
+1176 -212

No files matched your search

+185 -1
View File
@@ -8,6 +8,7 @@ import os
import sys
import threading
import time
import urllib.parse
from collections import defaultdict
from datetime import datetime, timezone
from functools import wraps
@@ -33,6 +34,7 @@ from maintain.cpa_runner_core import (
runner_config_from_db,
save_state,
)
import cliproxy_auth_sweeper as cliproxy_sweeper
_plog = logging.getLogger("cpa-runner")
if not _plog.handlers:
@@ -246,6 +248,15 @@ def api_overview():
"cliproxy_probe_timeout_sec": settings.get(
"cliproxy_probe_timeout_sec", "30"
),
"cliproxy_sweeper_threshold": settings.get(
"cliproxy_sweeper_threshold", "3"
),
"cliproxy_sweeper_run_mode": settings.get(
"cliproxy_sweeper_run_mode", "delete"
),
"cliproxy_sweeper_allow_name_fallback": settings.get(
"cliproxy_sweeper_allow_name_fallback", "1"
),
"codex_stats_oauth_dir": settings.get("codex_stats_oauth_dir", ""),
},
}
@@ -478,6 +489,27 @@ def _run_cliproxy_inspect_worker(task_id: int, source: str) -> None:
message=f"管理端不可用或密钥无效(未删任何文件): {mgmt_err}",
)
return
# 巡检前先跑一次 usage 阈值失效清理,保证“巡检=检查+清理”。
try:
sweep = _run_cliproxy_sweeper_worker(
task_id,
f"{source} usage清理",
finalize_task=False,
)
rtlog().info(
"[inspect#%s] %s usage清理完成 threshold=%s matched=%s deleted=%s failed=%s mode=%s",
task_id,
source,
sweep.get("threshold"),
sweep.get("matched"),
sweep.get("deleted"),
sweep.get("failed"),
sweep.get("mode"),
)
except Exception as e:
rtlog().warning("[inspect#%s] %s usage清理异常,继续探测流程: %s", task_id, source, e)
entries = db.list_oauth_codex_entries()
total = len(entries)
rtlog().info(
@@ -585,6 +617,137 @@ def _start_inspect_job(source: str) -> tuple[bool, Optional[int], str]:
return True, tid, "ok"
def _run_cliproxy_sweeper_worker(
task_id: int,
source: str,
*,
finalize_task: bool = True,
) -> dict[str, int | str]:
"""按 usage 连续失败阈值清理 auth-files 里的失效 JSON。"""
base = db.get_setting("cliproxy_management_base", "").strip()
key = db.get_setting("cliproxy_management_key", "").strip()
if not base or not key:
msg = "请先在「配置编辑」填写 Cliproxy 管理地址与密钥"
if finalize_task:
db.update_task(task_id, status="error", message=msg)
raise RuntimeError(msg)
timeout = max(1, int(float(db.get_setting("cliproxy_probe_timeout_sec", "30"))))
threshold = max(1, int(db.get_setting("cliproxy_sweeper_threshold", "3")))
run_mode = db.get_setting("cliproxy_sweeper_run_mode", "delete").strip().lower()
if run_mode not in {"delete", "observe"}:
run_mode = "delete"
allow_name_fallback = (
db.get_setting("cliproxy_sweeper_allow_name_fallback", "1").strip() == "1"
)
apply_mode = run_mode == "delete"
rtlog().info(
"[sweeper#%s] %s 开始 base=%s threshold=%s mode=%s",
task_id,
source,
base,
threshold,
run_mode,
)
db.update_task(task_id, status="running", message=f"{source}: 拉取 usage/auth-files …", done=0)
headers = {
"Accept": "application/json",
"Authorization": f"Bearer {key}",
"X-Management-Key": key,
}
run_started_epoch = int(time.time())
usage_obj = cliproxy_sweeper.request_json_or_die(
base_url=base.rstrip("/"),
path="/usage",
method="GET",
headers=headers,
timeout=timeout,
insecure=False,
)
analysis = cliproxy_sweeper.build_usage_analysis(
usage_obj=usage_obj,
threshold=threshold,
run_started_epoch=run_started_epoch,
)
auth_files_obj = cliproxy_sweeper.request_json_or_die(
base_url=base.rstrip("/"),
path="/auth-files",
method="GET",
headers=headers,
timeout=timeout,
insecure=False,
)
match = cliproxy_sweeper.build_candidates(
analysis=analysis,
auth_files_obj=auth_files_obj,
allow_name_fallback=allow_name_fallback,
)
candidates = match.get("candidates", [])
deleted = 0
failed = 0
if apply_mode:
total = len(candidates)
for i, c in enumerate(candidates, 1):
db.update_task(
task_id,
message=f"{source}: 删除 {i}/{total} …",
done=i,
)
file_name = str(c.get("file_name", ""))
encoded_name = urllib.parse.quote(file_name, safe="")
code, _ = cliproxy_sweeper.http_request_with_retry(
base_url=base.rstrip("/"),
path=f"/auth-files?name={encoded_name}",
method="DELETE",
headers=headers,
timeout=timeout,
insecure=False,
)
if 200 <= code < 300:
deleted += 1
else:
failed += 1
msg = (
f"{source}: 阈值={threshold} 命中={len(candidates)} "
f"已删={deleted} 删除失败={failed} 模式={run_mode}"
)
rtlog().info("[sweeper#%s] %s", task_id, msg)
if finalize_task:
db.update_task(task_id, status="done", message=msg, done=1)
return {
"threshold": threshold,
"matched": len(candidates),
"deleted": deleted,
"failed": failed,
"mode": run_mode,
"message": msg,
}
def _start_sweeper_job(source: str) -> tuple[bool, Optional[int], str]:
# 与巡检共用锁,避免并发删除同一批 auth-files。
if not INSPECT_LOCK.acquire(blocking=False):
return False, None, "busy"
tid = db.create_task("cliproxy_sweeper", "queued", f"{source}:排队…", None, 1)
def bg() -> None:
try:
_run_cliproxy_sweeper_worker(tid, source)
except Exception as e:
rtlog().exception("[sweeper#%s] 后台异常: %s", tid, e)
db.update_task(tid, status="error", message=str(e)[:500])
finally:
INSPECT_LOCK.release()
threading.Thread(target=bg, daemon=True).start()
return True, tid, "ok"
def _start_pipeline_job(source: str) -> tuple[bool, Optional[int], str]:
"""
异步启动一条子进程流水线。全局 PIPELINE_LOCK 保证同时最多一条。
@@ -773,7 +936,28 @@ def api_task_inspect_now():
{
"ok": True,
"task_id": tid,
"message": "已排队巡检;完成后若仍有缺口将自动批量补号(每批上限见 max_auto_register_per_tick)",
"message": "已排队巡检(先按 /usage 阈值清理,再探测删失效);完成后若仍有缺口将自动批量补号",
}
)
@app.post("/api/tasks/sweep-failed-now")
@require_login
def api_task_sweep_failed_now():
if not db.cliproxy_inspect_configured():
return jsonify(
{
"error": "未配置 Cliproxy 管理地址/密钥,请在「配置编辑」填写 cliproxy_management_base 与密钥",
}
), 400
started, tid, reason = _start_sweeper_job("手动失效清理")
if reason == "busy":
return jsonify({"error": "已有巡检/清理任务在执行,请稍后再试"}), 409
return jsonify(
{
"ok": True,
"task_id": tid,
"message": "已排队失效清理任务(基于 /usage 连续失败阈值)",
}
)
+3
View File
@@ -117,6 +117,9 @@ def init_db() -> None:
"cliproxy_management_base": "",
"cliproxy_management_key": "",
"cliproxy_probe_timeout_sec": "30",
"cliproxy_sweeper_threshold": "3",
"cliproxy_sweeper_run_mode": "delete",
"cliproxy_sweeper_allow_name_fallback": "1",
# 成功后 JSON 若在 Cliproxy auth 目录,填绝对路径;留空则用项目 accounts/oauth
"codex_stats_oauth_dir": "",
"inspect_probe_valid_json": "",
+25
View File
@@ -126,6 +126,7 @@
<div class="panel">
<h3>手动巡检</h3>
<button class="primary" type="button" id="btnInspectNow" style="width:100%;margin-bottom:14px">立即巡检(探测删失效 → 不足则批量注册)</button>
<button class="ghost" type="button" id="btnSweepFailedNow" style="width:100%;margin-bottom:14px">立即按失败阈值清理(/usage → /auth-files)</button>
<label>单次批量注册数量</label>
<input type="number" id="manualCount" min="1" max="500" value="20" />
<div id="manualCpaWrap">
@@ -196,6 +197,14 @@
<input type="password" id="cfgClipKey" autocomplete="new-password" placeholder="留空表示不修改已保存的密钥" />
<label>探测超时(秒)</label>
<input type="number" id="cfgClipTimeout" min="5" max="120" value="30" />
<label>失效清理阈值(连续失败次数)</label>
<input type="number" id="cfgSweepThreshold" min="1" max="20" value="3" />
<label>失效清理模式</label>
<select id="cfgSweepMode">
<option value="delete">delete(实际删除)</option>
<option value="observe">observe(仅观察)</option>
</select>
<div class="row"><input type="checkbox" id="cfgSweepNameFallback" checked /><label for="cfgSweepNameFallback" style="margin:0">启用 name 回退匹配</label></div>
<button class="primary" type="button" id="saveCliproxy">保存 Cliproxy 设置</button>
</div>
<div class="panel">
@@ -297,6 +306,9 @@
$('cfgStatsOauthDir').value = st.codex_stats_oauth_dir || '';
$('cfgClipBase').value = st.cliproxy_management_base || '';
$('cfgClipTimeout').value = st.cliproxy_probe_timeout_sec || '30';
$('cfgSweepThreshold').value = st.cliproxy_sweeper_threshold || '3';
$('cfgSweepMode').value = st.cliproxy_sweeper_run_mode || 'delete';
$('cfgSweepNameFallback').checked = (st.cliproxy_sweeper_allow_name_fallback || '1') === '1';
$('cfgClipKey').value = '';
$('cfgClipKey').placeholder = st.cliproxy_management_key_set ? '已保存密钥(留空不改)' : '必填';
}
@@ -472,6 +484,9 @@
codex_stats_oauth_dir: $('cfgStatsOauthDir').value.trim(),
cliproxy_management_base: $('cfgClipBase').value.trim(),
cliproxy_probe_timeout_sec: $('cfgClipTimeout').value,
cliproxy_sweeper_threshold: $('cfgSweepThreshold').value,
cliproxy_sweeper_run_mode: $('cfgSweepMode').value,
cliproxy_sweeper_allow_name_fallback: $('cfgSweepNameFallback').checked ? '1' : '0',
};
const k = $('cfgClipKey').value;
if (k) body.cliproxy_management_key = k;
@@ -489,6 +504,16 @@
toast(j.message || '已排队');
refreshData();
};
$('btnSweepFailedNow').onclick = async () => {
const r = await api('/api/tasks/sweep-failed-now', { method: 'POST', body: '{}' });
if (!r) return;
const j = await r.json().catch(() => ({}));
if (r.status === 400) { toast(j.error || '配置不全'); return; }
if (r.status === 409) { toast(j.error || '忙'); return; }
if (!r.ok) { toast(j.error || '失败'); return; }
toast(j.message || '清理任务已排队');
refreshData();
};
$('btnManual').onclick = async () => {
const r = await api('/api/tasks/manual', { method: 'POST', body: JSON.stringify({
cpa_id: parseInt($('manualCpa').value, 10),