Release Web 2.0.2 task logs

This commit is contained in:
AttilaNet
2026-11-11 15:35:36 +08:00
parent 1fa49f8ddf
commit a25076490f
21 changed files with 1367 additions and 83 deletions
+111 -17
View File
@@ -36,6 +36,7 @@ from collections import OrderedDict, deque
from copy import copy, deepcopy
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta, timezone
from functools import wraps
import json
import math
import re
@@ -52,6 +53,7 @@ from ranch_assistant.login import PasswordLogin
from ranch_assistant.model import Catalog
from .activity import ActivityLog, ActivityLogError
from .log_categories import endpoint_category, legacy_category, normalize_category, note_hints, operation_category, route_message
from .policies import apply_config, default_config, validate_config
from .scheduler import AccountSchedule, FAST_KINDS, Scheduler
from .store import WebStore, session_identity
@@ -97,6 +99,8 @@ class _Job:
error: str = ""
internal: bool = False
workspace: str = ""
category: str = "general"
due_kind: str | None = None
def public(self):
operation = {"__config": "set_config", "__view": "view"}.get(self.operation, self.operation)
@@ -158,7 +162,7 @@ class AccountWorker:
except ActivityLogError:
self._activity_warning = True
self._log_sequence = 1
self._logs = deque([{"id": 1, "seq": 1, "debug": False, "level": "warning",
self._logs = deque([{"id": 1, "seq": 1, "debug": False, "level": "warning", "category": "general",
"time": datetime.now(timezone.utc).isoformat(timespec="milliseconds"),
"message": "首次读取运行日志失败,当前日志暂存内存;后续日志将重试保存"}], maxlen=2000)
self._debug_entries = OrderedDict()
@@ -227,8 +231,66 @@ class AccountWorker:
apply_config(engine, config)
engine.auto = False
engine.heartbeat_enabled = bool(client)
self._route_engine_tasks(engine)
return engine
def _attribute_task(self, category):
# Only the serial account thread owns execution context. HTTP readers,
# stop requests and other accounts cannot inherit an in-flight task.
job = self._execution
if job is not None and threading.current_thread() is getattr(self, "thread", None):
job.category = normalize_category(category)
def _task_category(self):
if self._execution is not None and threading.current_thread() is getattr(self, "thread", None):
return self._execution.category
return "general"
def _dispatch_category(self, operation):
active = self._task_category()
category = endpoint_category(operation, active=active)
path = "/".join(str(operation).split("?", 1)[0].split("/")[-2:])
job = self._execution
if (job is not None and threading.current_thread() is getattr(self, "thread", None)
and job.operation == "__tick" and job.due_kind == "poll"
and active in {"general", "hatching"}
and path in {"monsterService/monsterSell", "monsterService/monsterIntensify", "stackService/stackTransferMonster"}):
return "hatching"
return category
def _route_engine_tasks(self, engine):
# Observe existing action boundaries on this worker's engine instance.
# Retain context through return/exception until _run publishes the job;
# generic local story results and pre-dispatch errors have no endpoint.
sources = {"_run_progression_intent": "mainline", "_execute_legacy_task": "commissions",
"_run_map_challenge": "maps", "_execute_explore": "exploration",
"_execute_breakthrough": "ranch", "claim_daily_entry": "daily"}
for name, category in sources.items():
method = getattr(engine, name, None)
if not callable(method):
continue
@wraps(method)
def routed(*args, _method=method, _name=name, _category=category, **kwargs):
category = _category
if _name == "_run_progression_intent":
try:
intent = args[0] if args else kwargs.get("intent")
if intent is None:
intent = next((item for item in engine._progression_intents
if not (item.get("block_reason") if isinstance(item, dict) else getattr(item, "block_reason", ""))), None)
if engine._is_commission(intent):
category = "commissions"
except CancelledBeforeDispatch:
raise
except Exception:
# Attribution must not prevent an otherwise valid action.
category = "general"
self._attribute_task(category)
return _method(*args, **kwargs)
setattr(engine, name, routed)
def remember(self, value):
with self._secret_lock:
if isinstance(value, dict):
@@ -276,15 +338,23 @@ class AccountWorker:
return result
raise ValueError("操作返回了不支持的公开数据类型")
def log(self, message, *, debug=False):
def log(self, message, *, debug=False, category=None, level="info"):
message = self.safe_text(message)
level = level if isinstance(level, str) and level in {"info", "warning", "error", "critical", "debug"} else "info"
debug = bool(debug or level == "debug")
if category is None:
category = self._task_category()
if category == "general":
category = legacy_category(message)
entry = {"time": datetime.now(timezone.utc).isoformat(timespec="milliseconds"),
"message": self.safe_text(message), "debug": bool(debug), "level": "debug" if debug else "info"}
"message": message, "category": normalize_category(category),
"debug": debug, "level": "debug" if debug else level}
with self.lock:
try:
if self._activity_warning:
# Confirm an actual durable write before declaring recovery;
# debug appends within a reserved block alone need no IO.
recovered = self._activity.append({"time": entry["time"], "debug": False, "level": "info",
recovered = self._activity.append({"time": entry["time"], "debug": False, "level": "info", "category": "general",
"message": "运行日志持久化已恢复;降级期间的日志仅保留在内存"}, after_sequence=self._log_sequence)
self._logs.append(recovered)
self._log_sequence = recovered["seq"]
@@ -297,13 +367,22 @@ class AccountWorker:
self._activity_warning = True
self._log_sequence += 1
self._logs.append({"id": self._log_sequence, "seq": self._log_sequence,
"time": entry["time"], "debug": False, "level": "warning",
"time": entry["time"], "debug": False, "level": "warning", "category": "general",
"message": "运行日志无法持久保存,当前日志仅保留在内存;请检查 Web 数据目录"})
entry["id"] = entry["seq"] = self._log_sequence + 1
self._log_sequence = entry["seq"]
self._logs.append(entry)
return entry["id"]
def _log_message(self, message):
sources = []
for name, category in (("planner", "hatching"), ("hatch_planner", "hatching"),
("gift_planner", "gifts"), ("breakthrough_planner", "ranch")):
notes = getattr(getattr(self.engine, name, None), "notes", ())
sources.append((category, [self.safe_text(note) for note in notes[:512]]))
for category, text in route_message(self.safe_text(message), context=self._task_category(), hints=note_hints(sources)):
self.log(text, category=category)
def _trace_event(self, event):
fields = [event.get("operation", "网络"), event.get("kind", "")]
if "http_status" in event:
@@ -312,7 +391,15 @@ class AccountWorker:
fields.append(str(event["elapsed_ms"]) + "ms")
if event.get("message"):
fields.append(str(event["message"]))
identifier = self.log(";".join(fields), debug=True)
source = self._dispatch_category(event.get("operation", ""))
if source == "general":
source = self._dispatch_category(event.get("url", ""))
if event.get("kind") == "request" and source != "general":
self._attribute_task(source)
category = self._task_category()
if category == "general":
category = source
identifier = self.log(";".join(fields), debug=True, category=category)
serialized = json.dumps(event, ensure_ascii=False, allow_nan=False).encode("utf-8")
if len(serialized) > 1024 * 1024:
event = {"kind": event.get("kind"), "operation": event.get("operation"),
@@ -417,7 +504,7 @@ class AccountWorker:
# A decoded business rejection proves neither disconnection nor
# expiry. Keep monitoring, but never retry its rejected write.
self.error = self._last_game_error_message = self.safe_text(str(error))
self.log(self.error)
self.log(self.error, level="error")
return
self.engine.heartbeat_enabled = False
if client is not None:
@@ -441,7 +528,7 @@ class AccountWorker:
message = "游戏请求失败,已停止策略和游戏请求,请手动恢复会话:" + str(error)
self.error = self.connection_message = self.safe_text(message)
self._last_game_error_message = self.error
self.log(self.connection_message)
self.log(self.connection_message, category="login", level="error")
def _game_succeeded(self, *, activated=False):
previous = self.connection_state
@@ -460,7 +547,7 @@ class AccountWorker:
self.schedule.game_resumed()
self.engine.heartbeat_enabled = True
if previous != "online" and not activated:
self.log("游戏连接已确认;" + ("已勾选的策略继续运行" if self.running else "策略保持停止"))
self.log("游戏连接已确认;" + ("已勾选的策略继续运行" if self.running else "策略保持停止"), category="login")
def status(self):
with self.lock:
@@ -568,6 +655,7 @@ class AccountWorker:
job.status, job.error, job.payload = "cancelled", "操作尚未开始,已取消", {}
continue
self._active = self._execution = job
job.category = operation_category(job.operation, job.payload)
job.status = "running"
final_status, final_error, public_result = "succeeded", "", None
failure_sequence = self._game_failure_sequence
@@ -589,7 +677,7 @@ class AccountWorker:
self.error = message
if job.consuming:
self.stop()
self.log(message)
self.log(message, category=job.category, level="error")
finally:
job.payload = {}
try:
@@ -601,7 +689,7 @@ class AccountWorker:
summary = dict(self._summary, error=self.error, running=False)
if final_status == "succeeded":
final_status, final_error = "failed", self.error
self.log(self.error)
self.log(self.error, category=job.category, level="error")
with self.condition:
if self._auto_relogin_pending_config and self._auto_relogin_pending_config[0] == job.id:
self._auto_relogin_pending_config = None
@@ -640,7 +728,7 @@ class AccountWorker:
self._mark_disconnected(session, saved)
if self.config["auto_relogin"]["enabled"]:
self.connection_message = "服务已启动或重启;将等待配置分钟后使用保存的密码重新登录原区服、原角色,策略保持停止"
self.log(self.connection_message)
self.log(self.connection_message, category="login")
if self.demo:
self.result(*self.engine.poll())
self.schedule.monitor(True)
@@ -687,7 +775,7 @@ class AccountWorker:
"""Actions may consume an Engine triple without exposing its internals."""
self.engine.snapshot = snapshot
if message:
self.log(message)
self._log_message(message)
self._invalidate_views()
self.schedule.arm(self.engine, self.config, self._running, plans)
return {"message": self.safe_text(message)}
@@ -776,6 +864,7 @@ class AccountWorker:
def _tick(self, job):
kind = self.schedule.due(self.engine, self.config, self._running)
job.due_kind, job.category = kind, operation_category(kind)
if kind is None:
return None
if kind == "auto_relogin":
@@ -795,6 +884,7 @@ class AccountWorker:
return self._auto_relogin()
if kind is None:
return None
job.due_kind, job.category = kind, operation_category(kind)
if not self.demo and self.engine.client is None:
return None
auto = False
@@ -841,7 +931,7 @@ class AccountWorker:
self.stop()
self.schedule.arm(self.engine, self.config, self._running, value[1], completed=kind)
elif isinstance(value, str):
self.log(value)
self._log_message(value)
return {"kind": kind}
except Exception:
self.schedule.maintenance_failed(kind)
@@ -935,7 +1025,7 @@ class AccountWorker:
self.schedule.auto_relogin_failed()
self._auto_relogin_blocked = isinstance(error, AutoReloginBlocked)
self._auto_relogin_error = "自动重登未完成:" + self.safe_text(str(error))
self.log(self._auto_relogin_error)
self.log(self._auto_relogin_error, category="login", level="error")
return {"connected": False, "running": False, "message": self._auto_relogin_error}
finally:
self._auto_relogin_inflight = False
@@ -966,6 +1056,10 @@ class AccountWorker:
def guarded_call(*args, **kwargs):
self.check_intent()
path = args[0] if args else kwargs.get("path", "")
category = self._dispatch_category(path)
if category != "general":
self._attribute_task(category)
# This precedes Client.call's wire payload construction. A
# saved candidate can lag the still-online client's counters.
self._share_session_counters(client.session)
@@ -1095,7 +1189,7 @@ class AccountWorker:
message = login_message + ";策略已自动开启,仅执行已勾选的规则"
result = {"connected": True, "running": self._running,
"has_saved_password": self._has_saved_password, "message": message}
self.log(message)
self.log(message, category="login")
except Exception:
with self.lock:
self.engine, self.active_identity, self.demo = old_engine, previous_identity, old_demo
@@ -1107,7 +1201,7 @@ class AccountWorker:
if mode_saved:
self.manager._set_demo(self, old_demo)
except (OSError, ValueError):
self.log("登录未完成,原连接保留;保存的会话仍可手动恢复")
self.log("登录未完成,原连接保留;保存的会话仍可手动恢复", category="login")
if identity != previous_identity:
self.manager._release_identity(self, identity)
raise