diff --git a/backend/core/accounts.py b/backend/core/accounts.py index 71dbad3..e618093 100644 --- a/backend/core/accounts.py +++ b/backend/core/accounts.py @@ -6,9 +6,7 @@ import io import json import os -import shutil import threading -import time from . import settings, tasks, updater from . import atomicio, paradox @@ -416,18 +414,9 @@ def go(): return tid -def remove_account(file: str, backup=True): +def remove_account(file: str): path = os.path.join(_accounts_dir(), os.path.basename(file)) if not os.path.isfile(path): raise FileNotFoundError(file) - if backup: - bak_dir = os.path.join(os.path.dirname(path), '_removed') - os.makedirs(bak_dir, exist_ok=True) - # 备份名带时间戳:同名新账号再次删除时 move 目标已存在会退化成 - # 覆盖,旧备份被顶掉(#61) - dst = os.path.join(bak_dir, '%s.%s' % ( - os.path.basename(path), time.strftime('%Y%m%d-%H%M%S'))) - shutil.move(path, dst) - else: - os.remove(path) + os.remove(path) return True diff --git a/backend/core/applog.py b/backend/core/applog.py new file mode 100644 index 0000000..e1370d5 --- /dev/null +++ b/backend/core/applog.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +"""debug/app.log 的 core 侧写入端。 + +main.log() 一直能写这个文件,但 core 模块不能 import main(main → core +单向,见 appupdate 的退出注册),于是同步 / 签到 / 抽卡这些后台链路出 +错时只有界面任务日志(内存态,重启即没),app.log 里什么都看不到—— +排障经常拿不到现场。本模块给 core 一个独立的文件写入端:与 main.log +写同一个目标,时间戳前缀、2MB 轮转一致。写失败静默:日志不能拖垮业务。 +""" +from __future__ import annotations + +import os +import threading +import time + +from . import settings + +_lock = threading.Lock() +_MAX_LINE = 4000 # 单行上限:响应体再长也截,防止一条日志撑爆轮转 + + +def write(line: str): + """已带时间戳的原始行落盘(main.log 复用同一实现,避免双写端轮转竞争)。""" + try: + with _lock: + path = settings.LOG_PATH + os.makedirs(os.path.dirname(path), exist_ok=True) + if os.path.isfile(path) and os.path.getsize(path) > 2 * 1024 * 1024: + os.replace(path, path + '.1') + with open(path, 'a', encoding='utf-8') as f: + f.write(str(line).rstrip('\n')[:_MAX_LINE] + '\n') + except Exception: + pass + + +def log(msg: str): + """带时间戳写一行(core 模块用这个)。""" + write('[%s] %s' % (time.strftime('%H:%M:%S'), msg)) diff --git a/backend/core/copilot.py b/backend/core/copilot.py index a4e875c..4a8b2fa 100644 --- a/backend/core/copilot.py +++ b/backend/core/copilot.py @@ -21,7 +21,8 @@ import urllib.request from concurrent.futures import ThreadPoolExecutor -from . import resources, settings +from . import applog, resources, settings +from .net import err_body API = 'https://prts.maa.plus/copilot' UA = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) MAA-PRTS/1.0'} @@ -135,6 +136,13 @@ def _http_json(url, timeout=40, retries=3): req = urllib.request.Request(url, headers=UA) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode('utf-8')) + except urllib.error.HTTPError as e: + # 4xx/5xx 不重试;响应体落 app.log 再抛——搜索/预下载报障时 + # 作业站返回的 code/message 是第一现场 + u = urllib.parse.urlsplit(url) + applog.log('[作业站] HTTP %s GET %s %s' % ( + e.code, u.netloc + u.path, err_body(e) or '(无响应体)')) + raise except (urllib.error.URLError, TimeoutError, OSError) as e: last = e if i == retries - 1: diff --git a/backend/core/gacha.py b/backend/core/gacha.py index b479208..10ac853 100644 --- a/backend/core/gacha.py +++ b/backend/core/gacha.py @@ -33,7 +33,8 @@ import urllib.parse import urllib.request -from . import atomicio, settings, tasks +from . import applog, atomicio, settings, tasks +from .net import err_body # 通行证 appCode:明日方舟与终末地共用同一个(写 'endfield' 会 400: # appCode 校验要求十六进制) @@ -87,8 +88,15 @@ def _http(method, url, data=None, headers=None, timeout=25, retries=3): method=method or ('POST' if body else 'GET')) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode('utf-8')), r.headers - except urllib.error.HTTPError: - raise # 4xx/5xx 是明确的业务/接口错误,重试无意义 + except urllib.error.HTTPError as e: + # 4xx/5xx 是明确的业务/接口错误,重试无意义;但响应体(code/msg) + # 是排障关键,先落 app.log 再抛。抽卡记录 URL 的 query 带 authkey, + # 只记 host+path + u = urllib.parse.urlsplit(url) + applog.log('[抽卡] HTTP %s %s %s %s' % ( + e.code, method or ('POST' if body is not None else 'GET'), + u.netloc + u.path, err_body(e) or '(无响应体)')) + raise except (urllib.error.URLError, OSError, ValueError) as e: last = e if attempt >= retries: diff --git a/backend/core/net.py b/backend/core/net.py index 7f79d11..5d48c49 100644 --- a/backend/core/net.py +++ b/backend/core/net.py @@ -17,6 +17,7 @@ """ from __future__ import annotations +import gzip import http.client import socket import time @@ -26,6 +27,19 @@ from . import settings +def err_body(e, limit=4000) -> str: + """HTTPError 响应体摘要(通用工具,不走代理,谁都能用):4xx/5xx 的 + JSON code/message 是排障关键。gzip 错误页解压后再截;响应体到这里就 + 被读掉了,调用方别再 e.read()。""" + try: + raw = e.read() or b'' + if raw[:2] == b'\x1f\x8b': # 网关偶发无视 Accept-Encoding 仍压 gzip + raw = gzip.decompress(raw) + return ' '.join(raw.decode('utf-8', 'replace').split())[:limit] + except Exception: + return '' + + class _NoRedirect(urllib.request.HTTPRedirectHandler): """appupdate 要读 302 的 Location(releases/latest → tag),不能跟""" diff --git a/backend/core/skland.py b/backend/core/skland.py index 2afa5ba..94bd0c3 100644 --- a/backend/core/skland.py +++ b/backend/core/skland.py @@ -22,6 +22,9 @@ import urllib.parse import urllib.request +from . import applog +from .net import err_body + APP_CODE = '4ca99fa6b56cc2ba' GRANT_URL = 'https://as.hypergryph.com/user/oauth2/v2/grant' CRED_URL = 'https://zonai.skland.com/api/v1/user/auth/generate_cred_by_code' @@ -117,11 +120,19 @@ def _http(method, url, headers, body=None, timeout=30, retries=3, note=None): return json.loads(raw.decode('utf-8')) except urllib.error.HTTPError as e: last = e + full = err_body(e, limit=4000) # app.log 记完整响应体 + body = full[:200] # 界面任务日志维持 200 字摘要不变 + u = urllib.parse.urlsplit(url) # 只记 host+path:query 可能带 uid 等账号参数 + applog.log('[森空岛] HTTP %s %s %s %s' % ( + e.code, method, u.netloc + u.path, full or '(无响应体)')) # 401/403 只有「headers 是函数」的可重签名请求才值得重试(时间戳 # 过期);登录链的死 token 重试三次只是浪费 if e.code not in (401, 403) or not callable(headers) or attempt >= retries: + if body: + (note or _note)(' [HTTP %s] %s' % (e.code, body)) raise - (note or _note)(' [签名重试 %d/%d] HTTP %s' % (attempt, retries - 1, e.code)) + (note or _note)(' [签名重试 %d/%d] HTTP %s%s' + % (attempt, retries - 1, e.code, ' ' + body if body else '')) time.sleep(1.0 * attempt) except (urllib.error.URLError, socket.timeout, TimeoutError, ConnectionError, OSError) as e: diff --git a/backend/core/tasks.py b/backend/core/tasks.py index 788f452..360ccf9 100644 --- a/backend/core/tasks.py +++ b/backend/core/tasks.py @@ -7,6 +7,8 @@ import traceback import uuid +from . import applog + _tasks = {} _lock = threading.Lock() _keep = 40 @@ -46,10 +48,19 @@ def finish(tid, result=None, error=None): t = _tasks.get(tid) if not t: return + was_running = t['status'] == 'running' t['status'] = 'error' if error else 'done' t['result'] = result t['error'] = error t['endedAt'] = time.time() + if error and was_running: + # 失败任务此前只存在于内存(前端还能看,重启即没)。摘要 + traceback + # 落一份到 debug/app.log,排障才有现场——文件 IO 放锁外,别卡任务队列 + tb = '' + if isinstance(result, dict): + tb = (result.get('traceback') or '').strip() + applog.log(('[任务失败] %s:%s' % (t['title'], error)) + + (('\n' + tb) if tb else '')) def log(tid, line: str): diff --git a/backend/main.py b/backend/main.py index 6645b65..2824e34 100644 --- a/backend/main.py +++ b/backend/main.py @@ -21,7 +21,7 @@ if HERE not in sys.path: sys.path.insert(0, HERE) -from core import accounts, api, appupdate, settings, tasks, version # noqa: E402 +from core import accounts, api, applog, appupdate, settings, tasks, version # noqa: E402 WEB = settings.static_dir() LOG_PATH = settings.LOG_PATH @@ -38,14 +38,7 @@ def log(msg): print(line, flush=True) except Exception: pass - try: - os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True) - if os.path.isfile(LOG_PATH) and os.path.getsize(LOG_PATH) > 2 * 1024 * 1024: - os.replace(LOG_PATH, LOG_PATH + '.1') - with open(LOG_PATH, 'a', encoding='utf-8') as f: - f.write(line + '\n') - except Exception: - pass + applog.write(line) # 落盘/轮转统一走 core.applog,两个独立写端会竞争轮转 # ---------------------------------------------------------------- 解除网络锁定 diff --git a/docs/backend.md b/docs/backend.md index 28aba4e..44981ef 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -72,7 +72,7 @@ main() | GET | `/api/accounts` | 账号列表(含每个账号的统计摘要) | | GET | `/api/account?file=` | 单个账号完整配置:account / stats / missing / chars | | POST | `/api/account/maa` | 把 `maa.profile` 等用户字段写回账号 JSON(同步不覆盖的那几个) | -| POST | `/api/account/remove` | 删除账号:不真删,移入 `config/_removed/` 备份。**预留,无界面入口** | +| POST | `/api/account/remove` | 删除账号:直接删除账号 JSON,不备份不可恢复。账号列表卡片悬停 ✕ 触发,前端有二次确认 | | POST | `/api/account/refresh` | 同步账号。带 `token` 同步单个(密文写进账号文件 `skd` 段);不带则按各账号文件 ∪ 旧 `tokens.json` 全部同步。返回 `taskId` | | POST | `/api/account/import-maa` | 从账号绑定的 MAA 目录读干员识别结果(`done=false` 残缺名单拒绝),覆盖练度/统计/缺卡(账号信息与 `skd` 保留),同步任务直接返回摘要 | | POST | `/api/account/create-from-maa` | 不用森空岛 token:用 `dir` 指定 MAA 目录的干员识别结果直接建本地账号(合成 uid、昵称取备注或目录名、无 `skd` 段、重名顺延 (2)(3)),返回建号摘要 | diff --git a/frontend/app.js b/frontend/app.js index 4a5e166..90f5122 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -282,6 +282,7 @@ function renderAccounts() { ${esc(a.nickName)}${ef ? '终末地' : ''} ${sub} + ✕ `; }).join(''); } @@ -311,6 +312,9 @@ function bindAccountOrder(box) { }; box.addEventListener('click', e => { + // 删除 ✕ 先于选号拦截:点的是卡片里的 ✕ 就不该再把账号切成选中 + const del = e.target.closest('.acct-del'); + if (del) { deleteAccount(del.dataset.file); return; } const b = e.target.closest('.acct'); if (b) selectAccount(b.dataset.file); }); @@ -341,6 +345,50 @@ function bindAccountOrder(box) { }); } +/* 删除账号:卡片 hover 出 ✕,点后二次确认。删就是删——账号文件直接 + 删除,不留备份(要找回只能重新同步)。 */ +async function deleteAccount(file) { + const a = S.accounts.find(x => x.file === file); + if (!a) return; + const game = gameOf(a); + const wasCurrent = S.current === file; + modal(` +

删除账号

+
确定删除「${esc(a.nickName || file)}」?删除后不可恢复,练度数据需要重新同步。
+ `, { + onMount(el, close) { + $('#acct-del-yes', el).addEventListener('click', async () => { + const yes = $('#acct-del-yes', el); + yes.disabled = true; + try { + await api('/api/account/remove', { file }); + close(); + const acc = await api('/api/accounts'); + S.accounts = acc.accounts; + if (wasCurrent) { + // 换到同栏剩下的第一个;同栏空了就另一栏;全空清掉选中 + const next = (S.accounts.find(x => gameOf(x) === game) || S.accounts[0] || {}).file || ''; + if (next) await selectAccount(next, true); + else { + S.current = ''; S.detail = null; S.sideGame = 'arknights'; + renderHero(); + applyModuleAvailability(); + } + } + renderAccounts(); + toast(`已删除「${a.nickName || file}」`); + } catch (e) { + yes.disabled = false; + toast('删除失败:' + e.message, 'err', 5000); + } + }); + } + }); +} + /* 切号请求的代数:快速连点 A→B 时两个请求并发,晚归的旧响应不能 覆盖新选择(详情串台:头像/统计是 A 的、高亮在 B 上) */ let _selectSeq = 0; @@ -408,7 +456,16 @@ function renderHero() { algoSel.disabled = !d || ef; if (d) algoSel.value = d.preferAlgo || 'rating'; } - if (!d) return; + if (!d) { + // 没有选中账号(删光了):回到 index.html 的初始占位,别残留上一个 + // 账号的头像/统计 + $('#hero-name').textContent = '未选择账号'; + $('#hero-sub').textContent = '用森空岛 token 添加一个账号开始'; + $('#hero-avatar').textContent = '?'; + $('#hero-avatar').classList.remove('ef'); + $('#hero-stats').innerHTML = ''; + return; + } const a = d.account || {}, st = d.stats || {}; const name = a.nickName || '未知账号'; $('#hero-name').textContent = name; diff --git a/frontend/style.css b/frontend/style.css index 432230e..037daa6 100644 --- a/frontend/style.css +++ b/frontend/style.css @@ -245,6 +245,20 @@ input:focus, select:focus, button:focus-visible { outline: none; } } .acct-sub { font-size: 11.5px; color: var(--text-3); white-space: nowrap; } .acct-sub b { color: var(--text-2); font-weight: 500; } +/* 删除 ✕:平时不占视觉,悬停卡片才出现(span 而非 button——卡片本身 + 是 button,HTML 不允许按钮嵌按钮) */ +.acct-del { + flex: 0 0 auto; + display: none; + width: 20px; height: 20px; + border-radius: 6px; + place-items: center; + font-size: 11px; + color: var(--text-3); + cursor: pointer; +} +.acct:hover .acct-del { display: grid; } +.acct-del:hover { color: var(--rose); background: rgba(255, 122, 138, 0.13); } .add-account { margin-top: 10px; diff --git a/tools/smoketest/smoke_test.py b/tools/smoketest/smoke_test.py index 1fc5fac..b2b3b6f 100644 --- a/tools/smoketest/smoke_test.py +++ b/tools/smoketest/smoke_test.py @@ -1751,6 +1751,140 @@ def api_post(self, path, body=None, headers=None, **kw): accounts.list_accounts, accounts.token_for = orig_rows, orig_tok signin.skland.Skland, signin.time = orig_sk, orig_time +def check_skland_http_body(_tmp): + """skland HTTP 错误响应体进任务日志(不联网,假 urlopen): + + - 可重签名请求的 401:每轮重试行带响应体,重试耗尽抛出前再单记一行 + - 登录链(dict headers)的 401:不重试,抛出前只记一行响应体 + - 空响应体:不加 [HTTP] 行,重试行不带尾巴 + """ + import io + import types + import urllib.error + from core import skland + + calls, logs = [], [] + body = b'{"code":10001,"message":"invalid sign"}' + + def fake_urlopen(req, timeout=None): + calls.append(req) + raise urllib.error.HTTPError(req.full_url, 401, 'Unauthorized', {}, + io.BytesIO(body)) + + orig_urlopen, orig_time = urllib.request.urlopen, skland.time + try: + urllib.request.urlopen = fake_urlopen + skland.time = types.SimpleNamespace(sleep=lambda s: None) + + # 可重签名请求:重签两轮后抛出,每轮日志都带响应体 + try: + skland._http('GET', 'https://x/api', lambda: {}, note=logs.append) + except urllib.error.HTTPError: + pass + else: + raise AssertionError('401 重试耗尽应抛 HTTPError') + assert len(calls) == 3, len(calls) + assert logs == [ + ' [签名重试 1/2] HTTP 401 ' + body.decode(), + ' [签名重试 2/2] HTTP 401 ' + body.decode(), + ' [HTTP 401] ' + body.decode(), + ], logs + + # 登录链:dict headers 的 401 直接抛出,只记一行响应体、不重试 + calls.clear(); logs.clear() + try: + skland._http('POST', 'https://x/auth', {}, body={'t': 1}, note=logs.append) + except urllib.error.HTTPError: + pass + else: + raise AssertionError('登录链 401 应直接抛出') + assert len(calls) == 1, len(calls) + assert logs == [' [HTTP 401] ' + body.decode()], logs + + # 空响应体:不加 [HTTP] 行,重试行也不带尾巴 + def no_body(req, timeout=None): + raise urllib.error.HTTPError(req.full_url, 401, 'Unauthorized', {}, + io.BytesIO(b'')) + urllib.request.urlopen = no_body + logs.clear() + try: + skland._http('GET', 'https://x/api', lambda: {}, retries=2, note=logs.append) + except urllib.error.HTTPError: + pass + assert logs == [' [签名重试 1/1] HTTP 401'], logs + finally: + urllib.request.urlopen = orig_urlopen + skland.time = orig_time + + +def check_applog_capture(_tmp): + """B27:失败现场落 debug/app.log(core 侧写入端 applog) + + - applog.log 写 settings.LOG_PATH(隔离根下,不碰真实用户数据) + - skland HTTP 401:界面任务日志维持 200 截断口径不变,app.log 记 + 完整响应体,且只记 host+path(query 带 uid,不落盘) + - 后台任务失败:finish 时摘要 + traceback 落 app.log + """ + import io + import types + import urllib.error + from core import applog, settings, skland, tasks + + def read_log(): + try: + with open(settings.LOG_PATH, encoding='utf-8') as f: + return f.read() + except FileNotFoundError: + return '' + + applog.log('B27 自检标记 xyz123') + assert 'B27 自检标记 xyz123' in read_log(), 'applog 没写进 settings.LOG_PATH' + + # skland 401:任务日志 200 截断、app.log 全量 + long_tail = 'T' * 300 + body = '{"code":10001,"message":"invalid sign","detail":"' + long_tail + '"}' + + def fake_urlopen(req, timeout=None): + raise urllib.error.HTTPError(req.full_url, 401, 'Unauthorized', {}, + io.BytesIO(body.encode('utf-8'))) + + logs = [] + orig_urlopen, orig_time = urllib.request.urlopen, skland.time + try: + urllib.request.urlopen = fake_urlopen + skland.time = types.SimpleNamespace(sleep=lambda s: None) + try: + skland._http('GET', 'https://x/api/v1/game/player/info?uid=1', + lambda: {}, note=logs.append) + except urllib.error.HTTPError: + pass + finally: + urllib.request.urlopen = orig_urlopen + skland.time = orig_time + + assert logs and logs[-1].endswith(body[:200]), logs[-1] + assert 'T' * 220 not in ''.join(logs), '任务日志不该带完整响应体' + filed = read_log() + assert '[森空岛] HTTP 401 GET x/api/v1/game/player/info' in filed, 'app.log 缺 401 行' + assert body in filed, 'app.log 应记完整响应体(不截 200)' + assert 'uid=1' not in filed, 'app.log 不该带 query(账号参数不落盘)' + + # 后台任务失败:摘要 + traceback 落 app.log + def boom(): + raise RuntimeError('炸给 B27 看') + + tid = tasks.create('B27 失败任务', boom) + for _ in range(50): + st = tasks.get(tid) + if st and st['status'] != 'running': + break + time.sleep(0.1) + assert st and st['status'] == 'error', st + filed = read_log() + assert '[任务失败] B27 失败任务:RuntimeError: 炸给 B27 看' in filed, '缺任务失败摘要' + assert 'boom' in filed, '缺 traceback 现场' + + # ---------------------------------------------------------------- 入口 def main(): try: @@ -1793,6 +1927,8 @@ def main(): r.check('B23 作业黑名单(maa:// 代码归一化 + 出口过滤)', lambda: check_op_blacklist(tmp)) r.check('B24 抽卡统计(星级归一/保底/池合并/终末地翻页/武器口径/跨游戏隔离)', lambda: check_gacha_stats(tmp)) r.check('B25 森空岛签到(两套口径/已签到判定/403/跳过/去重)', lambda: check_signin(tmp)) + r.check('B26 skland HTTP 错误响应体进任务日志(401 鉴别信息)', lambda: check_skland_http_body(tmp)) + r.check('B27 app.log 失败现场(森空岛响应体全量 + 任务失败摘要/traceback)', lambda: check_applog_capture(tmp)) finally: shutil.rmtree(tmp, ignore_errors=True)