# -*- coding: utf-8 -*- """webhost 宿主运行时共享状态:模块级可变全局的唯一真源(单一 owner,禁止他处另建副本)。 - ALLOWED 在启动(lifespan)时决定且会被整体重新赋值,故一律经 state 模块引用读写 (`from webhost.backend import state as st; st.ALLOWED / st.set_allowed(v)`), 避免 from-import 复制绑定读不到最新值。 - RUNS/RUN_LOCK/_NS_LOCKS/PLATFORMS 均为可变对象,跨模块传的是同一引用。 依赖方向:state ← 领域逻辑与路由模块。 """ from __future__ import annotations import threading from webhost.backend.core import auth as platform_auth # 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态) PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]} for p in platform_auth.platforms()} # 运行会话:run_id -> {status, account, result, error} RUNS: dict = {} RUN_LOCK = threading.Lock() MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长 # 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致) ALLOWED: set | None = None def set_allowed(v: set | None) -> None: global ALLOWED ALLOWED = v # 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢 _NS_LOCKS: dict[str, threading.Lock] = {} _NS_GUARD = threading.Lock() def _ns_gate(platform: str) -> threading.Lock: key = (platform or "").strip() or "local" with _NS_GUARD: if key not in _NS_LOCKS: _NS_LOCKS[key] = threading.Lock() return _NS_LOCKS[key] def _set_run(run_id: str, **kw) -> None: """更新运行记录字段(保留 account 等既有键)。""" with RUN_LOCK: run = RUNS.get(run_id) if run is not None: run.update(kw)