diff --git a/core/openmate_core/agents.py b/core/openmate_core/agents.py index 30be58d..3f222d8 100644 --- a/core/openmate_core/agents.py +++ b/core/openmate_core/agents.py @@ -17,14 +17,14 @@ from .agent import model_label from .hub import HubError from .textutil import clip, one_line -from .ui import Fresh, Page, day_start, empty, row, stat, state_of, state_text, tile, when +from .ui import Fresh, NotYet, Page, day_start, empty, row, snapshot_notice, snapshot_source, stat, state_of, state_text, tile, when log = logging.getLogger("openmate.agents") PAGE = "openmate-agents" CARD = "agents-card" AHEAD = 20.0 # older than this, read again in the background -STALE = 600.0 # older than this, a draw waits for a new read +STALE = 600.0 KEEP = 120.0 # while running, read this often anyway WAIT = 8.0 REFRESH = 60 @@ -113,7 +113,9 @@ class AgentsRead: def __init__(self, app, clock: Callable[[], float] = time.time, spawn: Optional[Callable] = None): self.app = app self.clock = clock - self._fresh = Fresh(self._read, AHEAD, STALE, clock=clock, spawn=spawn, name="Agents") + source = snapshot_source(getattr(getattr(app, "hub", None), "base", "")) + self._fresh = Fresh(self._read, AHEAD, STALE, clock=clock, key=lambda: source, spawn=spawn, name="Agents", + persist=(getattr(app, "store", None), "agents")) def warm(self) -> None: self._fresh.warm(every=KEEP, stop=getattr(self.app, "closing", None)) @@ -200,7 +202,9 @@ def warm(self) -> None: def _board(self) -> Tuple[Optional[Board], str]: try: - sessions = self.agents.read() + sessions = self.agents.read(0) + except NotYet: + return None, "" except HubError as e: return None, e.message except Exception as e: # never the page @@ -212,15 +216,17 @@ def render(self, params: dict) -> dict: version = int(params.get("ui_version") or 1) board, missing = self._board() if board is None: - note = empty("暂时读不到 Agent", missing + ",稍后自动重试", version) - return {"sections": [{"items": [note]}], "refresh_after": REFRESH} if self.card else \ - {"title": "Agent 进度", "sections": [{"items": [note]}], "refresh_after": REFRESH} - if self.card: - return self._card(board, version) - st = state_of(params) - if st.get("session"): - return self._detail(board, str(st["session"]), version) - return self._page(board, version) + note = (empty("暂时读不到 Agent", missing + ",稍后自动重试", version) if missing + else empty("正在读取 Agent", "稍后自动刷新", version)) + view = {"sections": [{"items": [note]}], "refresh_after": REFRESH} + if not self.card: + view["title"] = "Agent 进度" + elif self.card: + view = self._card(board, version) + else: + st = state_of(params) + view = self._detail(board, str(st["session"]), version) if st.get("session") else self._page(board, version) + return snapshot_notice(view, ("", self.agents._fresh)) # ---- pieces diff --git a/core/openmate_core/app.py b/core/openmate_core/app.py index 7d9f852..2bf6376 100644 --- a/core/openmate_core/app.py +++ b/core/openmate_core/app.py @@ -389,6 +389,9 @@ def shutdown(self) -> None: self._done_wake.set() with self.lock: # no hand-over begins after this (_take_in checks closing under this lock) self._handed.set() # nothing waits on a sign-in's hand-over any more (closing says no to all of it) + ui = self.ui + if ui is not None: + ui.close() held = self._done_mu.acquire(timeout=5.0) # a round touching the store finishes first if self.today_api is not None: try: @@ -763,9 +766,13 @@ def _done_round(self, only: Optional[set]) -> int: return today.service_done(needs, marked, states) def _ui(self) -> "UI": + if self.ui is not None: + return self.ui with self.lock: if self.ui is None: self.ui = UI(self, self.platform.ui_pages) + if self.closing.is_set(): + self.ui.close() return self.ui def mark_changed(self, *scopes: str) -> None: @@ -887,8 +894,7 @@ def account_epoch(self) -> int: service is asked (a read) or listened to (the live link), it says whose the answer is: the adapter takes the next account's session before the store is wiped for it, so what was asked under one generation is never the next account's own.""" - with self.lock: - return self._account_epoch + return self._account_epoch def settle(self) -> bool: """While a sign-in's account is being taken in (the adapter may answer as it already), wait until the store is @@ -1311,7 +1317,8 @@ def learn(m: Message, looked_up: bool = False) -> bool: return new def me_name(self) -> str: - return self.account.name if self.account and self.account.name else "我" + account = self.account + return account.name if account is not None and account.name else "我" # ------------------------------------------------------------------ status diff --git a/core/openmate_core/people.py b/core/openmate_core/people.py index dab6ecd..755ec4b 100644 --- a/core/openmate_core/people.py +++ b/core/openmate_core/people.py @@ -44,15 +44,19 @@ def _can(self) -> bool: def bots(self, ids: Iterable[str], epoch: Optional[int] = None) -> Set[str]: """Those of ids known to be programs. The unknown ones are asked about behind, for the account generation the caller read them for (epoch; None: now).""" + bots, unknown = self.classify(ids) + if unknown: + self.ask_unknown(unknown, epoch) + return bots + + def classify(self, ids: Iterable[str]): + """Known bots and unchecked ids, which a cached view can requeue without reading the store again.""" ids = {str(i) for i in ids if i} store = getattr(self.app, "store", None) if not ids or store is None: - return set() + return set(), set() known = store.people_kinds(ids) - unknown = ids - set(known) - if unknown: - self._ask(unknown, epoch) - return {i for i, k in known.items() if k == "bot"} + return {i for i, k in known.items() if k == "bot"}, ids - set(known) def _epoch(self) -> Optional[int]: get = getattr(self.app, "account_epoch", None) # the connector's account generation (a stand-in may have none) @@ -93,7 +97,7 @@ def kind_now(self, user_id: str, epoch: Optional[int] = None) -> str: return kind return "" - def _ask(self, ids: Set[str], epoch: Optional[int] = None) -> None: + def ask_unknown(self, ids: Set[str], epoch: Optional[int] = None) -> None: if not self._can(): return if epoch is None: diff --git a/core/openmate_core/store.py b/core/openmate_core/store.py index beb2df1..b2a73ff 100644 --- a/core/openmate_core/store.py +++ b/core/openmate_core/store.py @@ -12,13 +12,17 @@ import sqlite3 import threading import time +from pathlib import Path from typing import Dict, Iterable, List, Optional, Tuple from .backend import Chat, Message SCHEMA_VERSION = 2 # 2: messages.blocked +SNAPSHOT_MAX_BYTES = 1024 * 1024 + _SCHEMA = [ + "CREATE TABLE IF NOT EXISTS snapshots (key TEXT PRIMARY KEY, at REAL NOT NULL, value TEXT NOT NULL)", "CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)", """CREATE TABLE IF NOT EXISTS chats ( id TEXT PRIMARY KEY, @@ -202,8 +206,9 @@ def _message_row(r: sqlite3.Row) -> dict: d = dict(r) for k in ("mine", "at_me", "at_all", "from_history", "blocked"): d[k] = bool(d[k]) + media = d["media"] try: - d["media"] = json.loads(d["media"] or "[]") + d["media"] = json.loads(media) if media and media != "[]" else [] except ValueError: d["media"] = [] return d @@ -241,7 +246,7 @@ def _chat_row(r: sqlite3.Row) -> dict: class Store: - """Thread-safe: one connection behind one lock.""" + """A serialized writer and a separate read-only WAL connection.""" def __init__(self, path: str, legacy_blocked_texts: Iterable[str] = ()): @@ -255,6 +260,9 @@ def __init__(self, path: str, legacy_blocked_texts: Iterable[str] = ()): os.close(fd) os.chmod(path, 0o600) self._lock = threading.RLock() + self._read_lock = threading.Lock() + self.changes = 0 + self.snapshot_scope = (0, "") # the /agent runs an account switch wiped (ids are never reused): a thread of the account before that still # holds one never writes it back into the next account's store (run_put) self._wiped_runs: set = set() @@ -262,7 +270,8 @@ def __init__(self, path: str, legacy_blocked_texts: Iterable[str] = ()): self._db = sqlite3.connect(path, check_same_thread=False, isolation_level=None, timeout=30) self._db.row_factory = sqlite3.Row with self._lock: - self._db.execute("PRAGMA synchronous=FULL") + self._db.execute("PRAGMA journal_mode=WAL") + self._db.execute("PRAGMA synchronous=NORMAL") self._db.execute("PRAGMA foreign_keys=ON") self._migrate([str(t) for t in legacy_blocked_texts if t]) for stmt in _SCHEMA: @@ -273,6 +282,11 @@ def __init__(self, path: str, legacy_blocked_texts: Iterable[str] = ()): # a new store; an older one's version is _migrate's to set (with what it marks), never set over here self._db.execute("PRAGMA user_version=%d" % SCHEMA_VERSION) + self._reader = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True, + check_same_thread=False, isolation_level=None, timeout=30) + self._reader.row_factory = sqlite3.Row + self.snapshot_scope = (0, self.meta_get("account_id")) + def _migrate(self, legacy_blocked_texts: List[str]) -> None: """An older store's messages table gains the columns of this version, in one transaction. A version before this one sets user_version 1 again when it opens the store (a rollback): what it stored meanwhile carries no @@ -301,22 +315,27 @@ def run(db): self._tx(run) def close(self) -> None: - with self._lock: + with self._lock, self._read_lock: try: + self._reader.close() self._db.close() except sqlite3.Error: pass # ---- small helpers ---- - def _tx(self, fn): + def _tx(self, fn, *, count: bool = True): """fn(db) in one write transaction. Whatever fails (fn, or the COMMIT itself: SQLITE_BUSY), the transaction is - rolled back before the error goes up, so the next write starts clean.""" + rolled back before the error goes up. A commit that changes rows invalidates cached chat reads unless the + caller opts out for bookkeeping that cannot affect those reads.""" with self._lock: self._db.execute("BEGIN IMMEDIATE") try: + before = self._db.total_changes out = fn(self._db) self._db.execute("COMMIT") + if count and self._db.total_changes != before: + self.changes += 1 return out except BaseException: if self._db.in_transaction: @@ -327,12 +346,39 @@ def _tx(self, fn): raise def _all(self, sql: str, args: Iterable = ()) -> List[sqlite3.Row]: - with self._lock: - return self._db.execute(sql, tuple(args)).fetchall() + with self._read_lock: + return self._reader.execute(sql, tuple(args)).fetchall() def _one(self, sql: str, args: Iterable = ()) -> Optional[sqlite3.Row]: - with self._lock: - return self._db.execute(sql, tuple(args)).fetchone() + with self._read_lock: + return self._reader.execute(sql, tuple(args)).fetchone() + + # ---- persisted read models ---- + + def snapshot(self, key: str): + r = self._one("SELECT at, value FROM snapshots WHERE key = ? AND length(CAST(value AS BLOB)) <= ?", + (key, SNAPSHOT_MAX_BYTES)) + if r is None: + return None + data = json.loads(r["value"]) + return (r["at"], data["snapshot"]) if data.get("owner") == self.snapshot_scope[1] else None + + def save_snapshot(self, key: str, at: float, value, scope: tuple, valid) -> None: + encoded = json.dumps({"owner": scope[1], "snapshot": value}, ensure_ascii=False, + separators=(",", ":"), allow_nan=False) + if len(encoded.encode("utf-8")) > SNAPSHOT_MAX_BYTES: + return + + def run(db): + if scope == self.snapshot_scope and valid(): + db.execute("INSERT INTO snapshots (key, at, value) VALUES (?, ?, ?) " + "ON CONFLICT(key) DO UPDATE SET at = excluded.at, value = excluded.value", + (key, at, encoded)) + + self._tx(run, count=False) + + def drop_snapshot(self, key: str) -> None: + self._tx(lambda db: db.execute("DELETE FROM snapshots WHERE key = ?", (key,)), count=False) # ---- meta ---- @@ -753,27 +799,53 @@ def thread_messages(self, chat_id: str, root_id: str, limit: int) -> List[dict]: return [_message_row(r) for r in reversed(rows)] def inbox_rows(self, chat_id: str, limit: int = 60) -> List[dict]: - """The chat's last limit messages (oldest first), and before them its newest @me the account has not answered - when later chatter pushed it out of them: a mention stays a mention however busy the group is.""" - rows = self.messages_before(chat_id, None, limit) - if not rows or len(rows) < limit or any(r.get("mine") and r.get("type") != "SYSTEM" for r in rows): - return rows # the whole chat, or the account spoke in it: the window says it all + """The recent inbox rows and, if still unanswered, the older @me displaced by chatter.""" + return self.inbox_rows_many([chat_id], limit)[chat_id] + + def inbox_rows_many(self, chat_ids: Iterable[str], limit: int = 60) -> Dict[str, List[dict]]: + """Batch bounded index seeks even for chats with very long histories.""" + ids = list(dict.fromkeys(chat_ids)) + out: Dict[str, List[dict]] = {cid: [] for cid in ids} - def order(r) -> tuple: # a place in the chat: its position, then when (a thread reply shares a position) + def order(r) -> tuple: + # A thread reply can share a position with its root. return (int(r["position"]), float(r["at"] or 0), int(r["seq"])) - first = min(rows, key=order) - mine = self._one("SELECT position, at, seq FROM messages INDEXED BY messages_chat_mine WHERE chat_id = ? " - "AND mine = 1 AND type != 'SYSTEM' ORDER BY position DESC, seq DESC LIMIT 1", (chat_id,)) - lo = order(mine) if mine is not None else (-1, -1.0, -1) - found = self._all( - "SELECT " + _MESSAGE_COLUMNS + " FROM messages INDEXED BY messages_chat_at_me WHERE chat_id = ? " - "AND at_me = 1 AND mine = 0 AND position <= ? AND position >= ? ORDER BY position DESC, seq DESC LIMIT 20", - (chat_id, int(first["position"]), max(lo[0], 0))) - cands = [r for r in found if lo < order(r) < order(first)] - if not cands: - return rows - return [_message_row(max(cands, key=order))] + rows + for offset in range(0, len(ids), 200): # below SQLite's compound SELECT and bind limits + batch = ids[offset:offset + 200] + recent = ("SELECT * FROM (SELECT " + _MESSAGE_COLUMNS + " FROM messages WHERE chat_id = ? " + "ORDER BY position DESC, seq DESC LIMIT ?)") + for r in self._all(" UNION ALL ".join([recent] * len(batch)), [v for cid in batch for v in (cid, limit)]): + out[r["chat_id"]].append(_message_row(r)) + recover = {} + for cid in batch: + rows = out[cid] + rows.sort(key=lambda r: (r["position"], r["seq"])) + if rows and len(rows) == limit and not any(r["mine"] and r["type"] != "SYSTEM" for r in rows): + recover[cid] = min(map(order, rows)) + if not recover: + continue + + bounds = self._all( + "WITH wanted(id) AS (VALUES " + ",".join(["(?)"] * len(recover)) + ") " + "SELECT m.chat_id, m.position, m.at, m.seq FROM wanted JOIN messages m ON m.seq = (" + "SELECT seq FROM messages INDEXED BY messages_chat_mine WHERE chat_id = wanted.id " + "AND mine = 1 AND type != 'SYSTEM' ORDER BY position DESC, seq DESC LIMIT 1)", recover) + lows = {r["chat_id"]: order(r) for r in bounds} + mentions = ("SELECT * FROM (SELECT " + _MESSAGE_COLUMNS + " FROM messages INDEXED BY messages_chat_at_me " + "WHERE chat_id = ? AND at_me = 1 AND mine = 0 AND position <= ? AND position >= ? " + "ORDER BY position DESC, seq DESC LIMIT 20)") + args = [] + for cid, first in recover.items(): + args.extend((cid, first[0], max(lows.get(cid, (-1,))[0], 0))) + best = {} + for r in self._all(" UNION ALL ".join([mentions] * len(recover)), args): + cid, pos = r["chat_id"], order(r) + if lows.get(cid, (-1, -1.0, -1)) < pos < recover[cid] and (cid not in best or pos > order(best[cid])): + best[cid] = r + for cid, r in best.items(): + out[cid].insert(0, _message_row(r)) + return out def messages_after(self, chat_id: str, position: int, limit: int) -> List[dict]: rows = self._all( @@ -866,7 +938,8 @@ def send_claim(self, key: str, kind: str, now: Optional[float] = None) -> bool: "INSERT OR IGNORE INTO sends (key, kind, state, result, created, updated) VALUES (?, ?, 'sending', '{}', ?, ?)", (key, kind, now, now), ).rowcount - == 1 + == 1, + count=False, ) def send_finish(self, key: str, state: str, result: Dict, now: Optional[float] = None) -> None: @@ -875,17 +948,19 @@ def send_finish(self, key: str, state: str, result: Dict, now: Optional[float] = lambda db: db.execute( "UPDATE sends SET state = ?, result = ?, updated = ? WHERE key = ?", (state, json.dumps(result, ensure_ascii=False), now, key), - ) + ), + count=False, ) def send_release(self, key: str) -> None: """Drop a claim whose send surely did not go out: the same key may try again.""" - self._tx(lambda db: db.execute("DELETE FROM sends WHERE key = ? AND state = 'sending'", (key,))) + self._tx(lambda db: db.execute("DELETE FROM sends WHERE key = ? AND state = 'sending'", (key,)), count=False) def sends_interrupted(self, now: Optional[float] = None) -> int: """At start: a send still 'sending' was cut off by a crash; it may have gone out.""" now = now or time.time() - return self._tx(lambda db: db.execute("UPDATE sends SET state = 'uncertain', updated = ? WHERE state = 'sending'", (now,)).rowcount) + return self._tx(lambda db: db.execute("UPDATE sends SET state = 'uncertain', updated = ? WHERE state = 'sending'", + (now,)).rowcount, count=False) def sends_done(self, prefix: str, since: float) -> List[Tuple[str, dict]]: """(key, result) of the sends done since then whose key starts with prefix.""" @@ -904,7 +979,7 @@ def sends_prune(self, before: float) -> None: # stays, so a late repeat is answered from here and never sent a second time (a platform without outbound # sends has none) self._tx(lambda db: db.execute("DELETE FROM sends WHERE updated < ? AND state != 'sending' " - "AND key NOT LIKE 'outbound:%'", (before,))) + "AND key NOT LIKE 'outbound:%'", (before,)), count=False) def sent_message(self, msg_id: str, kind: str) -> bool: """Whether a completed send of this kind returned the service's message ID.""" @@ -1058,7 +1133,7 @@ def channel_msg_put(self, chat_id: str, msg_id: str, direction: str, owner: str "INSERT INTO channel_msgs (chat_id, id, dir, owner, placement, root_id, ref, text, quote, parent, unsupported, " "state, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + (tail or " ON CONFLICT (chat_id, id) DO NOTHING"), (chat_id, msg_id, direction, owner or "", placement or "", root_id or "", ref or "", text or "", - quote or "", parent or "", unsupported or "", state or "", now or time.time())).rowcount == 1) + quote or "", parent or "", unsupported or "", state or "", now or time.time())).rowcount == 1, count=False) def channel_msg(self, chat_id: str, msg_id: str) -> Optional[dict]: r = self._one("SELECT * FROM channel_msgs WHERE chat_id = ? AND id = ?", (chat_id, msg_id)) @@ -1072,7 +1147,7 @@ def channel_in_set(self, chat_id: str, msg_id: str, state: str) -> bool: """A pending line's end (False when it is no longer pending: wiped, or settled already).""" return self._tx(lambda db: db.execute( "UPDATE channel_msgs SET state = ? WHERE chat_id = ? AND id = ? AND dir = 'in' AND state = 'pending'", - (state, chat_id, msg_id)).rowcount == 1) + (state, chat_id, msg_id)).rowcount == 1, count=False) def channel_asked_since(self, chat_id: str, since: float, other_than: str = "") -> bool: """Whether a question (other than other_than) was first put in the chat after then (by its first piece).""" @@ -1090,12 +1165,12 @@ def channel_mark_here(self, chat_id: str, line_id: str, until: float) -> None: self._tx(lambda db: db.execute( "UPDATE channel_asks SET here = ? WHERE chat_id = ? AND state = 'open' AND at <= ? AND (here = '' OR here NOT IN " "(SELECT id FROM channel_msgs WHERE chat_id = channel_asks.chat_id AND dir = 'in' " - "AND state IN ('pending', 'handed')))", (line_id, chat_id, until))) + "AND state IN ('pending', 'handed')))", (line_id, chat_id, until)), count=False) def channel_forget_pending(self) -> int: """Signed out: the lines not handed over yet go nowhere.""" return self._tx(lambda db: db.execute( - "UPDATE channel_msgs SET state = 'expired' WHERE dir = 'in' AND state = 'pending'").rowcount) + "UPDATE channel_msgs SET state = 'expired' WHERE dir = 'in' AND state = 'pending'").rowcount, count=False) def channel_ref_bind(self, key: str, owner: str, now: Optional[float] = None) -> str: """The account key was first tried under (this one, when it is new).""" @@ -1103,13 +1178,13 @@ def run(db): db.execute("INSERT OR IGNORE INTO channel_refs (key, owner, at) VALUES (?, ?, ?)", (key, owner, now or time.time())) return db.execute("SELECT owner FROM channel_refs WHERE key = ?", (key,)).fetchone()["owner"] - return self._tx(run) + return self._tx(run, count=False) def channel_ask_put(self, ix: str, ref: str, chat_id: str, message_id: str, now: Optional[float] = None) -> bool: """Follow a question's piece (once: False when it was followed already).""" return self._tx(lambda db: db.execute( "INSERT OR IGNORE INTO channel_asks (ix, ref, chat_id, message_id, at) VALUES (?, ?, ?, ?, ?)", - (ix, ref, chat_id, message_id or "", now or time.time())).rowcount == 1) + (ix, ref, chat_id, message_id or "", now or time.time())).rowcount == 1, count=False) def channel_ask(self, ix: str, ref: str) -> Optional[dict]: r = self._one("SELECT * FROM channel_asks WHERE ix = ? AND ref = ?", (ix, ref)) @@ -1136,11 +1211,12 @@ def channel_ask_set(self, ix: str, ref: str, **fields) -> bool: return False sql = "UPDATE channel_asks SET %s WHERE ix = ? AND ref = ? AND state = 'open'" % ", ".join( "%s = ?" % k for k in cols) - return self._tx(lambda db: db.execute(sql, [fields[k] for k in cols] + [ix, ref]).rowcount == 1) + return self._tx(lambda db: db.execute(sql, [fields[k] for k in cols] + [ix, ref]).rowcount == 1, count=False) def channel_ask_end(self, ix: str, ref: str, state: str) -> None: """How a question being taken back ended.""" - self._tx(lambda db: db.execute("UPDATE channel_asks SET state = ? WHERE ix = ? AND ref = ?", (state, ix, ref))) + self._tx(lambda db: db.execute("UPDATE channel_asks SET state = ? WHERE ix = ? AND ref = ?", (state, ix, ref)), + count=False) def channel_restart(self, fresh_since: float, now: Optional[float] = None) -> None: """At the start: a question cut off while being taken back is looked at again; a line not handed over is @@ -1150,7 +1226,7 @@ def run(db): db.execute("UPDATE channel_msgs SET state = 'expired' WHERE dir = 'in' AND state = 'pending' AND at < ?", (fresh_since,)) - self._tx(run) + self._tx(run, count=False) def channel_prune(self, before: float, refs_before: float) -> None: def run(db): @@ -1158,7 +1234,7 @@ def run(db): db.execute("DELETE FROM channel_asks WHERE at < ?", (before,)) db.execute("DELETE FROM channel_refs WHERE at < ?", (refs_before,)) # as long as the send journal keeps one - self._tx(run) + self._tx(run, count=False) def autoreply_chats(self) -> List[str]: return [r["chat_id"] for r in self._all("SELECT chat_id FROM autoreply ORDER BY at")] @@ -1203,12 +1279,13 @@ def seen_has(self, key: str) -> bool: def seen_add(self, key: str, now: Optional[float] = None) -> bool: """Record key; False when it was recorded already (the thing was handled).""" now = now or time.time() - return self._tx(lambda db: db.execute("INSERT OR IGNORE INTO seen (key, at) VALUES (?, ?)", (key, now)).rowcount == 1) + return self._tx(lambda db: db.execute("INSERT OR IGNORE INTO seen (key, at) VALUES (?, ?)", (key, now)).rowcount == 1, + count=False) def seen_prune(self, before: float) -> None: - self._tx(lambda db: db.execute("DELETE FROM seen WHERE at < ?", (before,))) + self._tx(lambda db: db.execute("DELETE FROM seen WHERE at < ?", (before,)), count=False) - # ---- another account ---- + # ---- guest quota ---- def quota_backfill(self) -> None: """Once: the guest runs still kept count in the new ledger (so an upgrade never resets a group's quota).""" @@ -1226,14 +1303,14 @@ def run(db): (r["chat_id"], kind, r["created"])) db.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('guest_quota_backfilled', '1')") - self._tx(run) + self._tx(run, count=False) def quota_add(self, chat_id: str, kind: str, at: float) -> None: def run(db): db.execute("INSERT INTO guest_quota (chat_id, kind, at) VALUES (?, ?, ?)", (chat_id, kind, at)) db.execute("DELETE FROM guest_quota WHERE at < ?", (at - 3 * 86400,)) - self._tx(run) + self._tx(run, count=False) def quota_count(self, chat_id: str, kind: str, since: float) -> int: r = self._one("SELECT COUNT(*) AS n FROM guest_quota WHERE chat_id = ? AND kind = ? AND at >= ?", @@ -1249,7 +1326,7 @@ def run(db): runs = [r["id"] for r in db.execute("SELECT id FROM runs").fetchall()] # the groups marked for 自动代答 and who is a person were the old account's choices and knowledge for table in ("chats", "messages", "names", "runs", "seen", "autoreply", "people", "guest_quota", "gone", - "channel_msgs", "channel_asks", "avatars", "mutes", "markdown", "open_ids"): + "channel_msgs", "channel_asks", "avatars", "mutes", "markdown", "open_ids", "snapshots"): db.execute("DELETE FROM " + table) db.execute("DELETE FROM dismissed WHERE key LIKE 'chat:%'") # its chats' 处理完 (and 恢复) marks # its history marks, and its name (the next one's is written next, when it has one) @@ -1261,5 +1338,6 @@ def run(db): with self._lock: # no run_put between the wipe and the ids it took out self._wiped_runs.update(self._tx(run)) + self.snapshot_scope = (self.snapshot_scope[0] + 1, owner or self.snapshot_scope[1]) self._wiped_runs.update(self._pruned_runs) # pruned lately: a thread may still hold one of those too self._pruned_runs.clear() diff --git a/core/openmate_core/ui.py b/core/openmate_core/ui.py index 6f8bf87..cf29018 100644 --- a/core/openmate_core/ui.py +++ b/core/openmate_core/ui.py @@ -9,7 +9,11 @@ from __future__ import annotations import contextlib +import math +import sys +from collections import deque import datetime as _dt +import hashlib import json import logging import threading @@ -20,6 +24,7 @@ from . import views from .agent import BOT_THREAD_MOST from .textutil import one_line +from .wire import RPCError def account_epoch(app) -> Optional[int]: @@ -32,7 +37,6 @@ def owned(app, epoch: Optional[int]): """The connector's owned(epoch) (a write for the account the action began for), or always yes for a stand-in.""" fn = getattr(app, "owned", None) return fn(epoch) if fn is not None else contextlib.nullcontext(True) -from .wire import RPCError log = logging.getLogger("openmate.ui") @@ -190,164 +194,213 @@ def day_start(tz, now: Optional[float] = None) -> float: return d.replace(hour=0, minute=0, second=0, microsecond=0).timestamp() +FAST_REFRESH = 5 +FIRST_WAIT = 12.0 + + +def snapshot_source(*parts: str) -> str: + """Distinguish configured sources on disk without storing the settings in the cache.""" + return hashlib.sha256(json.dumps(parts, ensure_ascii=False).encode("utf-8")).hexdigest() + + +def snapshot_minutes(age: float) -> str: + return "%d 分钟前" % int(max(0.0, age) // 60) + + +def snapshot_notice(view: dict, *sources) -> dict: + """Add a caption to an existing section, and poll sooner while it is loading or stale.""" + notes = [] + for label, fresh in sources: + age = fresh.stale_age() + if age is not None: + notes.append((label + " " if label else "") + snapshot_minutes(age) + "的数据,正在更新") + elif fresh.age() is not None: + continue + view["refresh_after"] = min(view.get("refresh_after", FAST_REFRESH), FAST_REFRESH) + if notes: + view["sections"][0]["items"].append({"type": "text", "style": "caption", "text": " · ".join(notes)}) + return view + + class Fresh: - """A value kept fresh behind the pages: get() answers the last read at once and reads again in the background once - it is older than ahead; only a first read, one for another key (a new day) or one older than stale waits for it. - A failed read keeps the last value (until stale) and raises only when there is nothing to show. spawn runs a - background read (a thread; tests run it in place).""" + """One read model per key. Draws can ask without waiting; a cold consumer can wait up to a fixed budget. + + The store epoch scopes both the memory and disk copies. An in-flight read can only publish for the key and + epoch it began with. Holding the snapshot lock never involves I/O or waiting on a worker. + """ def __init__(self, read: Callable[[], Any], ahead: float, stale: float, clock: Callable[[], float] = time.time, key: Optional[Callable[[], Any]] = None, spawn: Optional[Callable[[Callable[[], None]], None]] = None, - name: str = "", remember_failures: bool = True): + name: str = "", persist=None, encode=None, decode=None): self.read, self.ahead, self.stale, self.clock = read, ahead, stale, clock self.key = key or (lambda: None) self.spawn = spawn or (lambda fn: threading.Thread(target=fn, name="openmate-fresh", daemon=True).start()) self.name = name - self.remember_failures = remember_failures # off: a read that fails with what it could read is tried each draw - self._mu = threading.Lock() # the kept value - self._reading = threading.Lock() # one read at a time - self._kept: Optional[Tuple[float, Any, Any]] = None # (read at, key, value) - self._busy = False - self._cold: Optional[Tuple[Any, threading.Event, dict]] = None # (key, done, its result) of a bounded read - self._failed: Optional[Tuple[Any, float, BaseException]] = None # (key, when, error) of the last failed one - self._warming = False # one warm loop per value, however many pages share it - self._looked = 0.0 # when a draw (or a tool) last asked: the warm loop rests while nobody does - self.on_ready: Optional[Callable[[], None]] = None # told when a read a page did not wait for is in + self._store, self._disk_key = persist or (None, "") + self._encode = encode or (lambda v: v) + self._mu = threading.Lock() + self._reading = threading.Lock() # one read at a time, also used by observers that need a fresh outcome + self._kept: Optional[Tuple[float, Any, Any]] = None + self._restored = False + self._pending: Dict[Any, threading.Event] = {} + self._failed: Optional[Tuple[Any, float, Exception]] = None + self._generation = 0 + self._warming = False + self._looked: Optional[float] = None + self.on_ready: Optional[Callable[[], None]] = None + if self._store is not None: + k = self._key() + try: + saved = self._store.snapshot(self._disk_key) + if saved is not None and saved[1]["key"] == self._disk_scope(k): + v = saved[1]["value"] + self._kept = (saved[0], k, decode(v) if decode is not None else v) + self._restored = True + except (AttributeError, KeyError, TypeError, ValueError): + log.debug("%s: saved snapshot could not be decoded", self.name) + + def _key(self): + scope = self._store.snapshot_scope if self._store is not None else None + return scope, self._generation, self.key() + + @staticmethod + def _disk_scope(k) -> str: + return json.dumps(k[2], separators=(",", ":"), sort_keys=True) def _usable(self, k, within: float) -> bool: + kept = self._snapshot(k) + return kept is not None and not self._restored and self.clock() - kept[0] < within + + def _snapshot(self, k): kept = self._kept - return kept is not None and kept[1] == k and self.clock() - kept[0] < within + return kept if kept is not None and kept[1] == k else None - def get(self, wait: Optional[float] = None) -> Any: - """The value. With wait, a read that has to be waited for is waited for that long at most (the page has 20 - seconds in all): NotYet when it is still on its way (it goes on in the background), its error when it failed.""" - self._looked = self.clock() # someone looks (a draw, a tool): the warm loop keeps reading - return self._get(wait) - - def _get(self, wait: Optional[float] = None) -> Any: - k = self.key() - again = False + def peek(self) -> Any: + kept = self._snapshot(self._key()) + return kept[2] if kept is not None else None + + def age(self) -> Optional[float]: + kept = self._snapshot(self._key()) + return max(0.0, self.clock() - kept[0]) if kept is not None else None + + def stale_age(self) -> Optional[float]: + age = self.age() + return age if age is not None and (self._restored or age >= self.stale) else None + + def invalidate(self) -> None: + """Forget the copy and refuse a read already on its way (an action changed its remote data).""" with self._mu: - if self._usable(k, self.ahead): - return self._kept[2] - if self._usable(k, self.stale): - value = self._kept[2] - if not self._busy: - self._busy = again = True - else: - value = None - if again: - self.spawn(self._again) - return value - if value is not None: - return value - if wait is not None: - return self._bounded(k, wait) - with self._reading: - with self._mu: # read by someone else meanwhile - if self._usable(k, self.ahead): - return self._kept[2] - value = self.read() - self._keep(k, value) - return value - - def _bounded(self, k, wait: float) -> Any: + self._generation += 1 + self._kept = self._failed = None + if self._store is not None: + self._store.drop_snapshot(self._disk_key) + + def get(self, wait: Optional[float] = None) -> Any: + self._looked = self.clock() + return self._get(FIRST_WAIT if wait is None else wait) + + def _get(self, wait: float, inline: bool = False) -> Any: + k = self._key() with self._mu: + kept = self._snapshot(k) + if self._usable(k, self.ahead) and k == self._key(): + return kept[2] failed = self._failed if failed is not None and failed[0] == k and self.clock() - failed[1] < FAILED_KEEP: - raise failed[2].with_traceback(None) # failed a moment ago: said, not tried again at once - cold = self._cold - start = cold is None or cold[0] != k # a read for another key (yesterday's) is not this one + if kept is not None: + return kept[2] + raise failed[2].with_traceback(None) + done = self._pending.get(k) + start = done is None if start: - cold = self._cold = (k, threading.Event(), {}) - _, ev, box = cold - - def run(): - waited = [False] - try: - with self._reading: - with self._mu: - done = self._usable(k, self.ahead) - if not done: - self._keep(k, self.read()) - with self._mu: - if self._failed is not None and self._failed[0] == k: - self._failed = None - except BaseException as e: - box["error"] = e - if self.remember_failures: - with self._mu: - self._failed = (k, self.clock(), e) - finally: - with self._mu: - if self._cold is not None and self._cold[1] is ev: - self._cold = None - waited[0] = not box.get("taken") - ev.set() - if waited[0] and "error" not in box and self.on_ready is not None: - try: - self.on_ready() # a page showed 正在读取: it draws again now - except Exception: - pass - + done = self._pending[k] = threading.Event() if start: - self.spawn(run) - done = ev.wait(max(0.0, wait)) + if inline: + self._run(k, done) + else: + self.spawn(lambda: self._run(k, done)) + if kept is not None and k == self._key(): + return kept[2] + done.wait(max(0.0, wait)) with self._mu: - if done: - box["taken"] = True - if self._usable(k, self.stale): - return self._kept[2] - if done and box.get("error") is not None: - raise box["error"].with_traceback(None) + if k == self._key(): + kept = self._snapshot(k) + if kept is not None: + return kept[2] + failed = self._failed + if failed is not None and failed[0] == k: + raise failed[2].with_traceback(None) raise NotYet(self.name) - def _again(self) -> None: - k = self.key() + def _run(self, k, done) -> None: try: with self._reading: - with self._mu: - if self._usable(k, self.ahead): - return + if k != self._key() or self._usable(k, self.ahead): + return value = self.read() - self._keep(k, value) - except Exception as e: # the last value stays - log.debug("%s: reading again failed (%s); the last read stays", self.name, e.__class__.__name__) + self._keep(k, value, done) + except Exception as e: + with self._mu: + if k == self._key(): + self._failed = (k, self.clock(), e.with_traceback(None)) + log.debug("%s: read failed (%s)", self.name, type(e).__name__) finally: with self._mu: - self._busy = False + self._pending.pop(k, None) + done.set() - def _keep(self, k, value) -> None: + def _keep(self, k, value, done: Optional[threading.Event] = None) -> None: + at = self.clock() with self._mu: - self._kept = (self.clock(), k, value) + if k != self._key(): + return + self._kept = (at, k, value) + self._restored = False + self._failed = None + if done is not None: + done.set() + # Invalidation and persistence may have to wait on other threads. The memory copy is visible already. + if self.on_ready is not None and self._looked is not None: + try: + self.on_ready() + except Exception: + pass + if self._store is not None: + try: + self._store.save_snapshot(self._disk_key, at, {"key": self._disk_scope(k), "value": self._encode(value)}, + k[0], lambda: k == self._key()) + except Exception as e: + log.debug("%s: snapshot could not be saved (%s)", self.name, type(e).__name__) def warm(self, every: float = 0.0, stop: Optional[threading.Event] = None) -> None: - """Read now in the background, so that the first draw does not wait; with every, keep reading that often (a - page opened after a long while then shows a read at most that old, and does not wait either). One loop per - value however many pages ask; while nobody has looked for WARM_IDLE it rests (a draw then reads, bounded).""" - owner = False + """Warm once on startup, and periodically while a view or tool is looking.""" with self._mu: if every and self._warming: return if every: - self._warming = owner = True # this loop owns the flag; a one-off warm never clears it + self._warming = True def run(): first = True - while True: - if stop is not None and stop.is_set(): - break - if first or self.clock() - self._looked < WARM_IDLE: - try: - self._get() # its own read is not someone looking - except Exception as e: - log.debug("%s: a read failed (%s)", self.name, e.__class__.__name__) - first = False - if not every or (stop.wait(every) if stop is not None else time.sleep(every)): - break - if owner: - with self._mu: - self._warming = False + try: + while stop is None or not stop.is_set(): + if first or self._looked is not None and self.clock() - self._looked < WARM_IDLE: + try: + self._get(0, inline=True) + except Exception: + pass # _run records the failure and throttles retries + first = False + if not every: + break + if stop is not None: + if stop.wait(every): + break + else: + time.sleep(every) + finally: + if every: + with self._mu: + self._warming = False self.spawn(run) @@ -371,7 +424,10 @@ def talk_closed(rows: List[dict]) -> bool: """A direct chat where the user spoke last and the other side only answered (a few lines, soon after, asking nothing): "27层" after "几楼呀" needs no answer.""" msgs = [r for r in rows if not views.is_system(r) and views.has_content(r)] - run = views.unanswered_run(msgs) + return _talk_closed(msgs, views.unanswered_run(msgs)) + + +def _talk_closed(msgs: List[dict], run: List[dict]) -> bool: if not run or len(run) == len(msgs) or len(run) > CLOSER_MOST: return False mine = msgs[len(msgs) - len(run) - 1] @@ -391,8 +447,24 @@ class ChatsToday: def __init__(self, app): self.app = app - self.expired = 0 # left out by needs(): older than needs_hours - self.closed = 0 # left out by needs(): direct chats where the other side only answered + self._cache = vars(app).setdefault("_chats_today_cache", {}) + self._last = threading.local() # counts and marks for this draw, including a filtered action's read + + @property + def bots(self) -> int: + return getattr(self._last, "bots", 0) + + @property + def done(self) -> List[dict]: + return getattr(self._last, "done", []) + + @property + def expired(self) -> int: + return getattr(self._last, "expired", 0) + + @property + def closed(self) -> int: + return getattr(self._last, "closed", 0) def needs_hours(self) -> int: try: @@ -405,28 +477,54 @@ def needs(self, only: Optional[set] = None) -> List[dict]: """Direct chats and @me the user has not answered (the inbox's rule), newest first. A bot's (People) are notices: left out, and counted in self.bots. The ones marked 处理完 and still the same are left out too, in self.done. With only, just those chats are looked at (the counts then cover only them).""" + app = self.app + store = app.store + self._last.bots, self._last.done, self._last.expired, self._last.closed = 0, [], 0, 0 + if store is None: + return [] + epoch, scope, changes = account_epoch(app), store.snapshot_scope, store.changes + now, hours, me = time.time(), self.needs_hours(), app.me_name() + key = (store, changes, scope, epoch, me, hours, app.timing.inbox_window, app.timing.inbox_most) + cached = self._cache.get("needs") if only is None else None + people = getattr(app, "people", None) + if cached is not None and cached[0] == key and cached[1] <= now <= cached[2]: + needs, done, bot_count, expired, closed, unknown = cached[3] + else: + until, result = self._read_needs(now, hours, me, only) + needs, done, bot_count, expired, closed, unknown = result + if only is None and changes == store.changes: + self._cache["needs"] = (key, now, until, result) + if scope != store.snapshot_scope or epoch != account_epoch(app): + return [] + if people is not None and unknown: + people.ask_unknown(unknown, epoch) + self._last.bots, self._last.done = bot_count, list(done) + self._last.expired, self._last.closed = expired, closed + return list(needs) + + def _read_needs(self, now, hours, me, only): app = self.app out = [] - self.bots = 0 - self.done = [] - self.expired = self.closed = 0 - if app.store is None: - return out - epoch = account_epoch(app) # the account the chats are read for: who is a bot is asked for it only - oldest = time.time() - self.needs_hours() * 3600.0 - since = min(time.time() - app.timing.inbox_window, oldest) # needs_hours may go back further (7 days) - chats = app.store.chats_since(since, app.timing.inbox_most if only is None else len(only), only=only) + closed = bot_count = 0 + horizon = hours * 3600.0 + window = max(app.timing.inbox_window, horizon) + oldest = now - horizon + chats = app.store.chats_since(now - window, app.timing.inbox_most if only is None else len(only), only=only) + expires = min((c["last_at"] + window for c in chats), default=float("inf")) + batched = app.store.inbox_rows_many(c["id"] for c in chats) for chat in chats: - if only is not None and chat["id"] not in only: + rows = batched[chat["id"]] + messages = [r for r in rows if not views.is_system(r) and views.has_content(r)] + run = views.unanswered_run(messages) + dm = views.chat_kind(chat) == "dm" + if not run or not dm and not any(r["at_me"] for r in run): continue - rows = app.store.inbox_rows(chat["id"], 60) - thing = views.inbox_thing(chat, rows, platform=app.platform.name, tz=app.tz, me=app.me_name(), rules="", - can_reply=False) - if thing is None or thing.get("done") or thing["kind"] not in ("dm", "mention"): - continue - if thing["kind"] == "dm" and talk_closed(rows): - self.closed += 1 + if dm and _talk_closed(messages, run): + closed += 1 continue + last = run[-1] + thing = {"kind": "dm" if dm else "mention", "title": views.chat_name(chat, chat["id"]), + "sender": views.sender_of(last, me), "preview": one_line(views.text_of(last), 200), "last": last["id"]} thing["_at"] = max((r.get("at") or 0) for r in rows) if rows else 0 thing["_version_at"] = next((r.get("at") or 0 for r in rows if r.get("id") == thing.get("last")), thing["_at"]) thing["_chat"] = chat @@ -438,13 +536,12 @@ def needs(self, only: Optional[set] = None) -> List[dict]: thing["_who"] = {w for w in who if w} out.append(thing) people = getattr(app, "people", None) - bots: set = set() + bots, unknown = set(), set() if people is not None and out: - bots = people.bots(set().union(*(t["_who"] for t in out)), epoch) + bots, unknown = people.classify(set().union(*(t["_who"] for t in out))) kept = [t for t in out if not (t["_who"] and t["_who"] <= bots)] - self.bots = len(out) - len(kept) + bot_count = len(out) - len(kept) out = kept - me = app.me_name() for t in out: # an @me says what asked for me, from whom and when, not the chat's last line (often a bot's) ats = [r for r in t.get("_ats") or [] if r.get("sender_id") not in bots] @@ -457,14 +554,16 @@ def needs(self, only: Optional[set] = None) -> List[dict]: t["_version_at"] = r.get("at") or t["_at"] t["_done_key"] = "chat:" + t["_chat"]["id"] fresh = [t for t in out if t["_at"] >= oldest] # the @me itself (a group) or the last line (a direct chat) - self.expired = len(out) - len(fresh) + expired = len(out) - len(fresh) out = fresh + expires = min(expires, min((t["_at"] + horizon for t in out), default=float("inf"))) out.sort(key=lambda t: -t["_at"]) marked = app.store.dismissed(t["_done_key"] for t in out) if out else {} for t in out: t["_mark"] = marked.get(t["_done_key"]) - self.done = [t for t in out if marked.get(t["_done_key"]) == t["_version"]] - return [t for t in out if marked.get(t["_done_key"]) != t["_version"]] + done = [t for t in out if t["_mark"] == t["_version"]] + needs = [t for t in out if t["_mark"] != t["_version"]] + return expires, (needs, done, bot_count, expired, closed, unknown) def dismiss(self, chat_id: str, version: Optional[str] = None) -> str: """Mark a chat's need 处理完 (until a newer message, or a newer @me in a group). With version, only the need @@ -545,7 +644,16 @@ def service_done(self, needs: List[dict], marked: Dict[str, str], states: Dict[s def counts(self, needs: List[dict]) -> Dict[str, int]: app = self.app start = day_start(app.tz) - today = app.store.count_since(start) if app.store is not None else {"messages": 0, "chats": 0} + store = app.store + today = {"messages": 0, "chats": 0} + if store is not None: + key = (store, store.changes, start) + cached = self._cache.get("counts") + if cached is not None and cached[0] == key: + today = cached[1] + else: + today = store.count_since(start) + self._cache["counts"] = (key, today) return {"needs": len(needs), "mentions": sum(1 for t in needs if t["kind"] == "mention"), "dms": sum(1 for t in needs if t["kind"] == "dm"), "messages": today["messages"], "chats": today["chats"], "bots": getattr(self, "bots", 0), "done": len(getattr(self, "done", []))} @@ -555,6 +663,10 @@ def active_groups(self) -> List[dict]: if app.store is None: return [] start = day_start(app.tz) + key = (app.store, app.store.changes, start) + cached = self._cache.get("groups") + if cached is not None and cached[0] == key: + return cached[1] out = [] for chat in app.store.chats_since(start, 50): if views.chat_kind(chat) == "dm": @@ -564,6 +676,7 @@ def active_groups(self) -> List[dict]: out.append((chat, rows[-1])) if len(out) >= GROUPS_MOST: break + self._cache["groups"] = (key, out) return out @@ -708,12 +821,13 @@ def put(c) -> None: if not c.get("name"): # an unnamed group shows a stand-in here only; nothing is stored under it c["name"] = "未命名的群(%s)" % c["id"].split("@", 1)[0][-4:] total = len(pool) - on = sorted((c for c in pool.values() if c["id"] in set(marked)), key=lambda c: -float(c.get("mine_at") or 0)) - groups = on + [c for c in pool.values() if c["id"] not in set(marked)] + marked = set(marked) + on = sorted((c for c in pool.values() if c["id"] in marked), key=lambda c: -float(c.get("mine_at") or 0)) + groups = on + [c for c in pool.values() if c["id"] not in marked] if q: needle = q.casefold() groups = [c for c in groups if needle in views.chat_name(c, c["id"]).casefold() or c["id"] == q] - return groups, set(marked), total + return groups, marked, total def _switch_rows(self, chats: List[dict], marked: set, version: int) -> List[dict]: agent = getattr(self.app, "agent", None) @@ -864,6 +978,103 @@ def _chat(self, chat_id: str, version: int) -> dict: "sections": [{"items": top}, {"title": views.where(app.platform.name, chat, chat_id), "items": items}]} +class RenderStats: + def __init__(self, interval: float = 3600): + self.interval = interval + self._lock = threading.Lock() + self._samples: Dict[str, List[float]] = {} + + def record(self, contribution: str, elapsed: float) -> None: + with self._lock: + if not self._samples: + timer = threading.Timer(self.interval, self.flush) + timer.daemon = True + timer.start() + self._samples.setdefault(contribution, []).append(elapsed * 1000) + + def flush(self) -> None: + with self._lock: + samples, self._samples = self._samples, {} + parts = [] + for name, times in sorted(samples.items()): + times.sort() + n = len(times) + parts.append("%s n=%d p50=%.2fms p95=%.2fms max=%.2fms" % + (name, n, times[math.ceil(n * 0.50) - 1], times[math.ceil(n * 0.95) - 1], times[-1])) + if parts: + log.info("render stats: %s", " | ".join(parts)) + + +class RenderWatchdog: + def __init__(self, delay: float = 2.0, clock=time.monotonic): + self.delay, self.clock = delay, clock + self._condition = threading.Condition() + self._active: Dict[object, Tuple[str, float]] = {} + self._thread: Optional[threading.Thread] = None + self._closed = False + self._dumps = deque() + + def start(self, contribution: str) -> object: + token = object() + with self._condition: + if not self._closed: + idle = not self._active + # Take the timestamp here so insertion order is also deadline order. + self._active[token] = (contribution, self.clock()) + if self._thread is None: + self._thread = threading.Thread(target=self._run, name="openmate-render-watchdog", daemon=True) + self._thread.start() + elif idle: + self._condition.notify() + return token + + def finish(self, token: object) -> None: + with self._condition: + first = next(iter(self._active), None) + self._active.pop(token, None) + if first is token: + self._condition.notify() + + def close(self) -> None: + with self._condition: + self._closed = True + self._active.clear() + self._condition.notify() + + def _run(self) -> None: + while True: + with self._condition: + if self._closed: + return + first = next(iter(self._active), None) + if first is None: + self._condition.wait() + continue + contribution, started = self._active[first] + remaining = started + self.delay - self.clock() + if remaining > 0: + self._condition.wait(remaining) + continue + del self._active[first] # check each render once, even when the dump is rate-limited + self._dump(contribution) + + def _dump(self, contribution: str) -> None: + now = self.clock() + while self._dumps and now - self._dumps[0] >= 3600: + self._dumps.popleft() + if len(self._dumps) >= 3: + return + self._dumps.append(now) + lines = [] + for ident, frame in sys._current_frames().items(): + lines.append("Thread %s (most recent call first):" % ident) + while frame is not None: + code = frame.f_code + lines.append(' File "%s", line %d in %s' % (code.co_filename, frame.f_lineno, code.co_name)) + frame = frame.f_back + log.warning("ui.render %s watchdog\n%s", contribution, "\n".join(lines)) + + class UI: """The contributions this program draws, and the navigation badge.""" @@ -878,6 +1089,8 @@ def __init__(self, app, extra: Optional[Callable[[Any], Dict[str, Page]]] = None self.pages.update(extra(app) or {}) except Exception: log.exception("the platform's pages could not be made") + self._render_stats = RenderStats() + self._watchdog = RenderWatchdog() self._badge: Optional[str] = None self._mu = threading.Lock() @@ -889,13 +1102,20 @@ def _page(self, params: dict) -> Page: def render(self, params: dict) -> dict: page = self._page(params) + contribution = str(params.get("contribution") or "") t0 = time.monotonic() + watched = self._watchdog.start(contribution) try: return page.render(params) finally: took = time.monotonic() - t0 - if took > SLOW_RENDER: # the hub and the apps wait on it: say which page was slow - log.info("ui.render %s took %dms", params.get("contribution"), took * 1000) + self._watchdog.finish(watched) + self._render_stats.record(contribution, took) + if took > SLOW_RENDER: + log.info("ui.render %s took %dms", contribution, took * 1000) + + def close(self) -> None: + self._watchdog.close() def action(self, params: dict) -> dict: return self._page(params).action(params) diff --git a/extensions/openmate-feishu/openmate_feishu/__init__.py b/extensions/openmate-feishu/openmate_feishu/__init__.py index 4f61df4..6ac8089 100644 --- a/extensions/openmate-feishu/openmate_feishu/__init__.py +++ b/extensions/openmate-feishu/openmate_feishu/__init__.py @@ -194,6 +194,7 @@ def tell(): shared._fresh.on_ready = drawn_again(agenda.PAGE, agenda.CARD, today.PAGE, today.CARD) persona._fresh.on_ready = drawn_again(today.PAGE, today.CARD) + wechat._fresh.on_ready = drawn_again(today.PAGE, today.CARD) mesh.mesh._fresh.on_ready = drawn_again(starkmesh.PAGE, starkmesh.CARD, today.PAGE) board._fresh.on_ready = drawn_again(agents.PAGE, agents.CARD, today.PAGE) return { diff --git a/extensions/openmate-feishu/openmate_feishu/agenda.py b/extensions/openmate-feishu/openmate_feishu/agenda.py index 2a0ae39..65307f8 100644 --- a/extensions/openmate-feishu/openmate_feishu/agenda.py +++ b/extensions/openmate-feishu/openmate_feishu/agenda.py @@ -12,7 +12,7 @@ import time from typing import Any, Callable, Dict, List, Optional, Tuple -from openmate_core.ui import Fresh, NotYet, Page, day_start, empty, row, stat +from openmate_core.ui import Fresh, NotYet, Page, day_start, empty, row, snapshot_notice, snapshot_source, stat from .larkcli import CalendarError, LarkCLI from .meetings import ACTION as MEETING_OPEN @@ -21,7 +21,7 @@ CARD = "calendar-today" DAYS = 7 AHEAD = 30.0 # older than this, read again in the background (the page shows the last read meanwhile) -STALE = 900.0 # older than this, a draw shows a loading state until the new read arrives +STALE = 900.0 KEEP = 300.0 # while running, read this often anyway, so that a draw after a long while does not wait REFRESH = 120 LATER_MOST = 30 @@ -103,8 +103,10 @@ def __init__(self, app, clock: Callable[[], float] = time.time, cli: Optional[La self.app = app self.clock = clock self.cli = cli or LarkCLI(app.config) - self._fresh = Fresh(self._read, AHEAD, STALE, clock=clock, key=lambda: day_start(self.app.tz, self.clock()), - spawn=spawn, name="calendar") + source = snapshot_source(str(app.tz), self.cli.setting, self.cli.profile) + self._fresh = Fresh(self._read, AHEAD, STALE, clock=clock, + key=lambda: (source, day_start(self.app.tz, self.clock())), spawn=spawn, name="calendar", + persist=(getattr(app, "store", None), "calendar")) def _read(self) -> List[dict]: begin = _dt.datetime.fromtimestamp(day_start(self.app.tz, self.clock()), self.app.tz) @@ -187,7 +189,7 @@ def render(self, params: dict) -> dict: if self.card: nxt = [e for e in today if e.all_day or (e.end or e.start) > now][:3] sections.append({"items": [self._row(e, False, False, "next") for e in nxt] or [empty("今天没有日程了", "", version)]}) - return {"sections": sections, "refresh_after": REFRESH} + return snapshot_notice({"sections": sections, "refresh_after": REFRESH}, ("", self.agenda._fresh)) pending = [e for e in events if e.rsvp == "needs_action"] if pending: sections.append({"title": "待回复的邀请", "items": [self._row(e, True, True, "pending") for e in pending[:PENDING_MOST]], @@ -201,7 +203,8 @@ def render(self, params: dict) -> dict: **({"footer": "还有 %d 个" % (len(later) - LATER_MOST)} if len(later) > LATER_MOST else {})}) if recent: sections.append(recent) - return {"title": "日程", "sections": sections, "refresh_after": REFRESH} + return snapshot_notice({"title": "日程", "sections": sections, "refresh_after": REFRESH}, + ("", self.agenda._fresh)) def action(self, params: dict) -> dict: a = params.get("action") diff --git a/extensions/openmate-feishu/openmate_feishu/larkagentx.py b/extensions/openmate-feishu/openmate_feishu/larkagentx.py index 40d3cd0..3cd2a85 100644 --- a/extensions/openmate-feishu/openmate_feishu/larkagentx.py +++ b/extensions/openmate-feishu/openmate_feishu/larkagentx.py @@ -1111,6 +1111,7 @@ def __init__(self, lx: types.SimpleNamespace, region: str): self._done_heard = False # every group the account is in (group_candidates): newest joined first, for the account that read them self._groups: List[Chat] = [] + self._groups_view: Tuple[str, Tuple[Chat, ...]] = ("", ()) self._groups_join: Dict[str, int] = {} self._groups_owner = "" self._groups_at = 0.0 # time.monotonic() of the last whole read (0: none yet) @@ -1358,6 +1359,7 @@ def logout(self) -> None: self._forget_cards() with self._groups_mu: self._groups, self._groups_join, self._groups_owner, self._groups_at = [], {}, "", 0.0 + self._groups_view = ("", ()) self._groups_whole_ids = set() self._groups_tried, self._groups_soon, self._groups_delta = 0.0, False, [] if old is not None: @@ -1701,11 +1703,10 @@ def later() -> None: # ------------------------------------------------------------ every group (自动代答's list) def group_candidates(self, limit: int) -> List[Chat]: - _, me = self._session() - with self._groups_mu: - if me is None or self._groups_owner != me.id: - return [] - return list(self._groups[: max(0, limit)]) + # The background reader publishes the list and owner together. Rendering never takes either adapter lock. + me = self._me + owner, groups = self._groups_view + return list(groups[:max(0, limit)]) if me is not None and me.id == owner and me is self._me else [] def _refresh_groups(self, client, me: Account) -> None: """Read every group again when due (GROUPS_EVERY, never read for this account, or a push named one the list @@ -1758,6 +1759,7 @@ def _groups_work(self, client, me: Account) -> None: # only onto this read's list: the core heard of these when they were pushed (this account's only) if owner == me.id: self._apply_chats_locked(infos, gone, me) + self._groups_view = (me.id, tuple(self._groups)) self._groups_delta = [] self._groups_busy = False self._report_gone(left, me) @@ -1871,6 +1873,7 @@ def _apply_chats(self, chats: dict, gone: List[str], me: Account) -> None: if self._groups_busy: self._groups_delta.append((me.id, infos, list(gone))) # put on the read's result too, when it comes left = self._apply_chats_locked(infos, gone, me) + self._groups_view = (self._groups_owner, tuple(self._groups)) self._report_gone(left, me) def _report_gone(self, chat_ids, me: Account) -> None: diff --git a/extensions/openmate-feishu/openmate_feishu/starkmesh.py b/extensions/openmate-feishu/openmate_feishu/starkmesh.py index f84231d..ae45ca6 100644 --- a/extensions/openmate-feishu/openmate_feishu/starkmesh.py +++ b/extensions/openmate-feishu/openmate_feishu/starkmesh.py @@ -22,7 +22,7 @@ import urllib.request from typing import Any, Callable, Dict, List, Optional, Tuple -from openmate_core.ui import Fresh, NotYet, Page, empty, row, stat, tile, when +from openmate_core.ui import Fresh, NotYet, Page, empty, row, snapshot_notice, snapshot_source, stat, tile, when log = logging.getLogger("openmate.starkmesh") @@ -42,8 +42,6 @@ ACCOUNT_PAGES = 10 # pages of PAGE_SIZE accounts read at most (1000 accounts) PAGE_SIZE = 100 # the most the read-only key gets a page (StarkMesh answers a larger page_size with 20) USAGE_BATCH = 100 # the most accounts the read-only key may ask the usage of at once (more: HTTP 400) -PAGE_WAIT = 12.0 # the page waits this long at most for a first read; the 今天 page's block CARD_WAIT -CARD_WAIT = 2.0 SUBSCRIPTION_TYPES = ("oauth", "setup-token") # the account types with 5 小时 and weekly windows (API Key, Bedrock, Vertex: none) USAGE_ID = "starkmesh" # the usage contribution (manifest contributes.usage): the sidebar's usage bars USAGE_WAIT = 20.0 # usage.query waits this long at most for a first read (the manager gives a source 45 s) @@ -328,6 +326,42 @@ def live_fable(a): self.windows[key] = w +def _snapshot_json(s: Snapshot) -> dict: + """Persist quota and display fields only. Raw gateway accounts can contain credentials.""" + def fields(d, keys): + return {k: d[k] for k in keys if k in d and isinstance(d[k], (str, int, float, bool))} + + accounts = [] + for account in s.accounts: + saved = fields(account, ("id", "name", "platform", "type", "status", "schedulable", "rate_limit_reset_at", + "overload_until", "temp_unschedulable_until", "session_window_end", "expires_at", + "auto_pause_on_expired")) + extra = account.get("extra") + if isinstance(extra, dict) and isinstance(extra.get("model_rate_limits"), dict): + hold = extra["model_rate_limits"].get(FABLE_MODEL) + if isinstance(hold, dict): + saved["extra"] = {"model_rate_limits": {FABLE_MODEL: fields(hold, ("rate_limit_reset_at",))}} + accounts.append(saved) + usage = {} + for aid, report in s.usage.items(): + saved = fields(report, ("updated_at",)) + for key in WINDOW_SECONDS: + win = report.get(key) + if isinstance(win, dict): + saved[key] = fields(win, ("resets_at", "utilization", "remaining_seconds")) + usage[aid] = saved + stats = fields(s.stats, ("today_requests", "today_tokens", "today_actual_cost", "today_cost", "rpm")) + return {"accounts": accounts, "usage": usage, "stats": stats, "now": s.now, "stats_failed": s.stats_failed, + "total": s.total, "usage_missed": s.usage_missed, "usage_failed": sorted(s.usage_failed), "cut": s.cut} + + +def _snapshot_from_json(data: dict) -> Snapshot: + s = Snapshot(data["accounts"], data["usage"], data["stats"], data["now"], data["stats_failed"]) + s.total, s.usage_missed, s.cut = data["total"], data["usage_missed"], data["cut"] + s.usage_failed = set(data["usage_failed"]) + return s + + class MeshFresh(Fresh): def current(self, stop, failure) -> Snapshot: """An observer needs the outcome of the read, even when a page can show the older value.""" @@ -340,13 +374,14 @@ def current(self, stop, failure) -> Snapshot: failed = failure() if failed is not None and self.clock() - failed[1] < self.ahead: raise failed[2].with_traceback(None) - k = self.key() + k = self._key() with self._mu: if self._usable(k, self.ahead): return self._kept[2] value = self.read() self._keep(k, value) - return value + if k == self._key(): + return value finally: self._reading.release() raise NotYet(self.name) @@ -360,11 +395,12 @@ def __init__(self, app, api: Optional[StarkMeshAPI] = None, clock: Callable[[], self.app = app self.api = api or StarkMeshAPI(app) self.clock = clock - self._fresh = MeshFresh(self._read, AHEAD, STALE, clock=clock, spawn=spawn, name="StarkMesh") - # (the newest read that came in, when a read last failed or None once one is in again), for usage.query: one - # tuple, set at once and read at once, so a read coming in between never pairs the old read with no failure - self.state: Tuple[Optional[Snapshot], Optional[float]] = (None, None) - self.failure: Optional[Tuple[float, float, Exception]] = None # first, latest, error of consecutive failed reads + source = snapshot_source(self.api.url, self.api.key) + self._fresh = MeshFresh(self._read, AHEAD, STALE, clock=clock, key=lambda: source, spawn=spawn, name="StarkMesh", + persist=(getattr(app, "store", None), "starkmesh"), encode=_snapshot_json, + decode=_snapshot_from_json) + # Publish the observation and its key together for usage.query and the alerts. + self._observed = (self._fresh._key(), (self._fresh.peek(), None), None) # first, latest, error of consecutive failed reads @property def configured(self) -> bool: @@ -382,6 +418,16 @@ def read(self, wait: Optional[float] = None, *, current: bool = False) -> Snapsh except NotYet: raise StarkMeshError("正在读取 StarkMesh,稍后自动刷新", "loading") + @property + def state(self): + key, state, _ = self._observed + return state if key == self._fresh._key() else (None, None) + + @property + def failure(self): + key, _, failure = self._observed + return failure if key == self._fresh._key() else None + @property def failed_at(self) -> Optional[float]: return self.state[1] @@ -392,15 +438,16 @@ def last_read(self) -> Optional[Snapshot]: def _read(self) -> Snapshot: # reads take turns (Fresh's lock), so the failure below changes a state no other read is changing + k = self._fresh._key() + prior, failure = self.state, self.failure try: snap = self._read_once() except Exception as e: at = self.clock() - self.failure = (self.failure[0] if self.failure is not None else at, at, e.with_traceback(None)) - self.state = (self.state[0], at) + failed = (failure[0] if failure is not None else at, at, e.with_traceback(None)) + self._observed = (k, (prior[0], at), failed) raise - self.failure = None - self.state = (snap, None) + self._observed = (k, (snap, None), None) return snap def _call(self, *args, **kwargs): @@ -506,7 +553,7 @@ def _snapshot(self, version: int) -> Tuple[Optional[Snapshot], Optional[dict]]: "在这个扩展的设置里填“StarkMesh 地址”(例如 %s)和“StarkMesh 只读管理密钥”(在 StarkMesh 后台 设置 › 管理密钥 新建,权限只勾 %s)" % (EXAMPLE_URL, PERMISSIONS), version) try: - return self.mesh.read(PAGE_WAIT), None + return self.mesh.read(0), None except StarkMeshError as e: if e.kind == "loading": return None, empty("正在读取 StarkMesh", "稍后自动刷新", version) @@ -627,14 +674,14 @@ def render(self, params: dict) -> dict: quota.update(icon="gauge", icon_color="teal") accounts.update(icon="list", icon_color="blue") view["sections"][3]["span"] = "full" - return view + return snapshot_notice(view, ("", self.mesh._fresh)) def card(self, version: int, links: bool, icons: bool) -> Optional[dict]: """The 今天 page's StarkMesh block: None until a key is set.""" if not self.mesh.configured: return None try: - s = self.mesh.read(CARD_WAIT) + s = self.mesh.read(0) except StarkMeshError as e: if e.kind == "loading": return {"title": CARD_TITLE, "items": [empty("正在读取 StarkMesh", "稍后自动刷新", version)]} @@ -664,7 +711,7 @@ def status_tile(self) -> Optional[tuple]: if not self.mesh.configured: return None try: - s = self.mesh.read(CARD_WAIT) + s = self.mesh.read(0) except StarkMeshError as e: if e.kind == "loading": return ("中转站", "—", "正在读取", "gauge", "gray", {"text": "读取中", "tone": "neutral"}, "b:mesh") @@ -875,7 +922,7 @@ def render(self, params: dict) -> dict: version = int(params.get("ui_version") or 1) s, note = self.page._snapshot(version) if s is None: - return {"sections": [{"items": [note]}], "refresh_after": REFRESH} + return {"sections": [{"items": [note]}], "refresh_after": 5 if "正在读取" in str(note) else REFRESH} word, tone = standing(s) head: Dict[str, Any] = {"type": "row", "key": "sm:head", "title": "可用号 %d/%d" % (len(s.ok_claude), len(s.claude)), "subtitle": "Claude 账号 · 数据读于 %s" % when(s.now, self.page.app.tz), @@ -892,4 +939,4 @@ def render(self, params: dict) -> dict: note = stats_notice(s, params.get("lang")) if note: items.append({"type": "text", "style": "caption", "text": note}) - return {"sections": [{"items": items}], "refresh_after": REFRESH} + return snapshot_notice({"sections": [{"items": items}], "refresh_after": REFRESH}, ("", self.page.mesh._fresh)) diff --git a/extensions/openmate-feishu/openmate_feishu/today.py b/extensions/openmate-feishu/openmate_feishu/today.py index 5e08a3e..321c291 100644 --- a/extensions/openmate-feishu/openmate_feishu/today.py +++ b/extensions/openmate-feishu/openmate_feishu/today.py @@ -11,15 +11,17 @@ from __future__ import annotations import datetime as _dt +from itertools import islice import logging import threading import time import urllib.parse -from typing import Any, Callable, Dict, List, Optional, Tuple +from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple from openmate_core.hub import HubError from openmate_core import views -from openmate_core.ui import (CHATS_PAGE, ChatsToday, Fresh, NotYet, Page, day_start, done_action, empty, parse_done, row, stat, state_of, +from openmate_core.ui import (CHATS_PAGE, FAST_REFRESH, ChatsToday, Fresh, NotYet, Page, day_start, done_action, empty, + parse_done, row, snapshot_minutes, snapshot_notice, snapshot_source, stat, state_of, state_text, tile, when) from openmate_core import agents as agents_mod @@ -37,7 +39,7 @@ PAGE = "openmate-today" CARD = "today-card" AHEAD = 30.0 # older than this, read again in the background -STALE = 600.0 # older than this, a draw waits for a new read +STALE = 600.0 # older than this, a draw marks the data as stale KEEP = 300.0 # while running, read this often anyway WAIT = 8.0 REFRESH = 120 @@ -51,32 +53,22 @@ NEEDS_ALL = 200 # 展开全部: at most this many (as many as WeChat lists) PEER = "openmate-wechat" # the extension whose chats 今天 shows too PEER_NAME = "微信" -PEER_WAIT = 3.0 # a draw waits this long at most for WeChat's read (the rest of the page does not wait for it) PAGE_WAIT_OPEN = 12.0 # an 打开 waits this long at most for the calendar -RENDER_BUDGET = 14.0 # every read of one draw together: started at once, each waited for out of what is left -PERSONA_WAIT = 9.0 -AGENTS_WAIT = 6.0 LINES_MOST = 20 # a WeChat chat's lines on its page here -class Partial(Exception): - """A read of Persona with parts missing: shown when there is nothing better, never kept.""" - - def __init__(self, out: dict): - super().__init__("parts missing: " + ", ".join(out["missing"])) - self.out = out +PARTS = {"waiting": ("等你的 Agent", "sessions"), "working": ("在跑的 Agent", "sessions"), + "inbox": ("Persona 收件箱", "items"), "todos": ("待办", "todos")} class PersonaToday: - """Persona's side of today, through the hub API: {"waiting": [...], "working": [...], "inbox": [...], - "todos": [...], "missing": [sentences]}. A draw shows the last whole read and reads again behind it (Fresh); a read - with a part missing is shown only when there is no whole one younger than STALE.""" + """Each hub part keeps its most recent successful value and the time it was read.""" def __init__(self, app, clock: Callable[[], float] = time.time, spawn: Optional[Callable] = None): - self.app = app - self.clock = clock - # a read with a part missing (Partial) carries the rest: tried again at the next draw, never kept as a failure - self._fresh = Fresh(self._read, AHEAD, STALE, clock=clock, spawn=spawn, name="Persona", remember_failures=False) + self.app, self.clock = app, clock + source = snapshot_source(getattr(getattr(app, "hub", None), "base", "")) + self._fresh = Fresh(self._read, AHEAD, STALE, clock=clock, key=lambda: source, spawn=spawn, name="Persona", + persist=(getattr(app, "store", None), "persona-today")) def _get(self, path: str, query: Optional[dict] = None) -> Any: return self.app.hub.request("GET", path, query=query, timeout=WAIT) @@ -87,68 +79,65 @@ def warm(self) -> None: def read(self, wait: Optional[float] = None) -> dict: """Persona's side; with wait, a first read is waited for that long at most (then it says it is reading).""" try: - return self._fresh.get(wait) - except Partial as p: - return p.out + out = self._fresh.get(wait) except NotYet: - return {"waiting": [], "working": [], "inbox": [], "todos": [], "missing": ["Persona(正在读取)"], - "degraded": []} - - @property - def last_missing(self) -> List[str]: - """What the latest read (this draw's, or the one behind it) could not read: a kept whole read is not 清空.""" - return list(getattr(self, "_last_missing", [])) + return dict({k: [] for k in PARTS}, missing=["Persona(正在读取)"], degraded=[]) + reuse = ["%s(沿用 %s的数据)" % (PARTS[k][0], snapshot_minutes(self.clock() - out["times"][k])) + for k in out["reused"]] + return dict(out, degraded=out["degraded"] + reuse) def _read(self) -> dict: - parts: Dict[str, Any] = {} + previous = self._fresh.peek() or {} + times = dict(previous.get("times") or {}) + out = {"missing": [], "degraded": [], "reused": [], "times": times} jobs = { "waiting": lambda: self._get("/api/v1/sessions", {"state": "needs_you", "summary": 1, "roots": 1, "limit": 20}), "working": lambda: self._get("/api/v1/sessions", {"state": "working", "summary": 1, "roots": 1, "limit": 20}), "inbox": lambda: self._get("/api/v1/inbox"), "todos": lambda: self._get("/api/v1/todos"), } - names = {"waiting": "等你的 Agent", "working": "在跑的 Agent", "inbox": "Persona 收件箱", "todos": "待办"} + parts: Dict[str, Any] = {} def run(key, fn): try: - parts[key] = fn() - except HubError as e: - parts[key] = e - except Exception as e: # never the page - parts[key] = e - - if getattr(self.app, "hub", None) is None or not getattr(self.app.hub, "available", False): - self._last_missing = ["拿不到 Persona hub 的地址或令牌"] - raise Partial({"waiting": [], "working": [], "inbox": [], "todos": [], "missing": ["拿不到 Persona hub 的地址或令牌"], - "degraded": []}) - threads = [threading.Thread(target=run, args=(k, f), daemon=True) for k, f in jobs.items()] - for t in threads: - t.start() - deadline = time.monotonic() + WAIT + 1 - for t in threads: - t.join(max(0.0, deadline - time.monotonic())) - out: Dict[str, Any] = {"missing": []} - for key in jobs: - v = parts.get(key) - if v is None or isinstance(v, Exception): - out[key] = [] - out["missing"].append(names[key]) + data = fn() + if isinstance(data, dict): + field = PARTS[key][1] + rows = data.get(field) + if rows is None or isinstance(rows, list): + parts[key] = self.clock(), data + except Exception: + pass # isolated to this part + + available = getattr(getattr(self.app, "hub", None), "available", False) + if available: + threads = [threading.Thread(target=run, args=(k, f), daemon=True) for k, f in jobs.items()] + for thread in threads: + thread.start() + deadline = time.monotonic() + WAIT + 1 + for thread in threads: + thread.join(max(0.0, deadline - time.monotonic())) + else: + out["missing"].append("拿不到 Persona hub 的地址或令牌") + for key, (name, field) in PARTS.items(): + answer = parts.get(key) + if answer is None: + out[key] = previous.get(key, []) + if key in times: + out["reused"].append(key) + elif available: + out["missing"].append(name) continue - if key in ("waiting", "working"): - out[key] = [s for s in (v.get("sessions") or []) if isinstance(s, dict)] - elif key == "inbox": - out[key] = [i for i in (v.get("items") or []) if isinstance(i, dict)] - triage = v.get("triage") if isinstance(v.get("triage"), dict) else {} - unread = [str(s.get("name") or s.get("source") or "") for s in triage.get("sources") or [] - if isinstance(s, dict) and s.get("read_error")] - if unread: # the list came, but a mail account in it was not read this round - out.setdefault("degraded", []).append("收件箱的 %s" % "、".join(x for x in unread if x) or "部分来源") - else: - out[key] = [t for t in (v.get("todos") or []) if isinstance(t, dict) and not t.get("done_at")] - out.setdefault("degraded", []) - self._last_missing = list(out["missing"]) + list(out["degraded"]) - if out["missing"]: - raise Partial(out) + at, data = answer + out[key] = [row for row in data.get(field) or [] if isinstance(row, dict) + and (key != "todos" or not row.get("done_at"))] + times[key] = at + if key == "inbox": + triage = data.get("triage") if isinstance(data.get("triage"), dict) else {} + unread = [str(source.get("name") or source.get("source") or "部分来源") + for source in triage.get("sources") or [] if isinstance(source, dict) and source.get("read_error")] + if unread: + out["degraded"].append("收件箱的 %s" % "、".join(unread)) return out @@ -161,13 +150,36 @@ class PeerToday: def __init__(self, app, ext: str = PEER, clock: Callable[[], float] = time.time, spawn: Optional[Callable] = None): self.app, self.ext, self.clock = app, ext, clock - self._gen = 0 self._denied_said = False - self._spawn = spawn or (lambda fn: threading.Thread(target=fn, name="openmate-peer", daemon=True).start()) - self._fresh = Fresh(self._read, AHEAD, STALE, clock=clock, key=self._key, spawn=spawn, name=PEER_NAME) - - def _key(self): - return (self._gen, day_start(self.app.tz, self.clock())) + self._spawn = spawn + self._detail_mu = threading.Lock() + self._details: Dict[tuple, Fresh] = {} + source = snapshot_source(getattr(getattr(app, "hub", None), "base", ""), ext) + self._fresh = Fresh(self._read, AHEAD, STALE, clock=clock, + key=lambda: (source, day_start(app.tz, self.clock())), spawn=spawn, name=PEER_NAME, + persist=(getattr(app, "store", None), "peer-today")) + + def detail(self, chat: str, account: str) -> Fresh: + store = getattr(self.app, "store", None) + key = (store.snapshot_scope if store is not None else None, account, chat) + with self._detail_mu: + fresh = self._details.pop(key, None) + if fresh is None: + def read(): + try: + return self.call("GET", "chat", query={"id": chat, "account": account, "n": LINES_MOST}) + except HubError as e: + if e.status in (403, 404, 409): + return {"error": e.code or "not_found"} + raise + + fresh = Fresh(read, AHEAD, STALE, clock=self.clock, spawn=self._spawn, name="WeChat chat", + key=lambda: store.snapshot_scope if store is not None else None) + fresh.on_ready = self._fresh.on_ready + self._details[key] = fresh + if len(self._details) > 8: + self._details.pop(next(iter(self._details))) + return fresh def path(self, route: str) -> str: return "/api/v1/extensions/%s/%s" % (self.ext, route) @@ -199,25 +211,22 @@ def _read(self) -> dict: def warm(self) -> None: self._fresh.warm(every=KEEP, stop=getattr(self.app, "closing", None)) - def read(self, wait: float = PEER_WAIT) -> dict: + def read(self, wait: float = 0) -> dict: """The last read of today: at once when one is kept, else waiting at most wait (the read goes on behind).""" - box: Dict[str, Any] = {} - done = threading.Event() - - def run(): - try: - box["v"] = self._fresh.get() - except Exception as e: - log.debug("%s: a read failed (%s)", self.ext, e.__class__.__name__) - finally: - done.set() - - self._spawn(run) - done.wait(wait) - return box.get("v") or {"state": "unreachable"} + try: + return self._fresh.get(wait) + except NotYet: + return {"state": "loading"} + except Exception as e: + log.debug("%s: a read failed (%s)", self.ext, type(e).__name__) + return {"state": "unreachable"} def invalidate(self) -> None: - self._gen += 1 + self._fresh.invalidate() + with self._detail_mu: + for fresh in self._details.values(): + fresh.invalidate() + self._details.clear() def call(self, method: str, route: str, body: Optional[dict] = None, query: Optional[dict] = None) -> Any: return self.app.hub.request(method, self.path(route), body, query=query, timeout=WAIT) @@ -359,34 +368,8 @@ def render(self, params: dict) -> dict: if not self.card and state.get("mail") and self.mail is not None: return self._mail_message(str(state["mail"]), version, now, str(state.get("acct") or "")) t0 = time.monotonic() - deadline = t0 + RENDER_BUDGET - - def left() -> float: - return max(0.0, deadline - time.monotonic()) - - wx_box: Dict[str, Any] = {} - wx_thread = None - if self.wechat is not None: # read beside Persona's, not after it - wx_thread = threading.Thread(target=lambda: wx_box.update(v=self.wechat.read()), name="openmate-peer-read", - daemon=True) - wx_thread.start() - # every slow read starts now, side by side (each answers at once from what it keeps, or reads behind) - kicks = [lambda: self.agenda.events(0.0)] - if self.mesh is not None and not self.card and self.mesh.mesh.configured: - kicks.append(lambda: self.mesh.mesh.read(0.0)) - if self.agents is not None and not self.card: - kicks.append(lambda: self.agents.read(0.0)) - for kick in kicks: - try: - kick() - except Exception: - pass - p = self.persona.read(min(PERSONA_WAIT, left())) - if wx_thread is not None: - wx_thread.join(min(PEER_WAIT + 0.5, left())) - wx = wx_box.get("v") if self.wechat is not None else None - if self.wechat is not None and wx is None: - wx = {"state": "unreachable"} + wx = self.wechat.read(0) if self.wechat is not None else None + p = self.persona.read(0) t1 = time.monotonic() chat_needs = self._safe(self.chats.needs, None) chats_failed = chat_needs is None # this draw's own: never another draw's @@ -403,8 +386,14 @@ def left() -> float: log.info("%s took %dms: Persona %dms, chats %dms, calendar %dms", CARD if self.card else PAGE, (t3 - t0) * 1000, (t1 - t0) * 1000, (t2 - t1) * 1000, (t3 - t2) * 1000) d = Day(self, version, now, p, chat_needs, counts, groups, today, pending, later, cal_missing, wx=wx, - all_needs=bool(state.get("all")), chats_failed=chats_failed, deadline=deadline) - return d.card() if self.card else d.full(state) + all_needs=bool(state.get("all")), chats_failed=chats_failed) + sources = [("Persona", self.persona._fresh), ("日程", self.agenda._fresh)] + if self.wechat is not None: + sources.append((PEER_NAME, self.wechat._fresh)) + view = d.card() if self.card else d.full(state) + if p.get("reused"): + view["refresh_after"] = FAST_REFRESH + return snapshot_notice(view, *sources, *d.sources.items()) @staticmethod def _safe(fn, default): @@ -529,14 +518,14 @@ def absent(self) -> set: absent.add("approvals") if self.mail is None or not self.mail.enabled: absent.add("mail") - if self.wechat is None or self.wechat.read(1.0).get("state") in ("absent", "denied"): + if self.wechat is None or self.wechat.read(0).get("state") in ("absent", "denied"): absent.add("wechat") return absent # ---- WeChat's chats def _wx_title(self, chat_id: str) -> str: - kept = self.wechat.read(0.5) if self.wechat is not None else {} + kept = self.wechat.read(0) if self.wechat is not None else {} for n in kept.get("needs") or []: if n.get("chat") == chat_id: return str(n.get("title") or PEER_NAME) @@ -584,15 +573,26 @@ def _wx_done(self, params: dict, ident: str) -> dict: def _wx_chat(self, chat_id: str, version: int, now, account: str = "") -> dict: """A WeChat chat that needs the user, opened from 今天: its latest lines and 处理完 (WeChat's own page is another extension's: 今天 cannot open it).""" - kept = self.wechat.read() + kept = self.wechat.read(0) st = state_text({"wx": chat_id, "acct": account}) title = next((str(n.get("title") or "") for n in kept.get("needs") or [] if n.get("chat") == chat_id), "") or PEER_NAME + fresh = self.wechat.detail(chat_id, account) try: - d = self.wechat.call("GET", "chat", query={"id": chat_id, "account": account, "n": LINES_MOST}) + if kept.get("account") and kept["account"] != account: + raise HubError(409, "", "account_changed") + if kept.get("state") == "signed_out": + raise HubError(409, "", "signed_out") + d = fresh.get(0) + if isinstance(d, dict) and d.get("error"): + raise HubError(404, "", d["error"]) + except NotYet: + return {"title": title, "sections": [{"items": [empty("正在读取会话", "稍后自动刷新", version)]}], + "state": st, "refresh_after": 5} except HubError as e: why = {"account_changed": "微信换了账号,这一件不在了", "signed_out": "微信没有登录"}.get( e.code, "这个会话现在没有要处理的了" if e.status in (404, 409) else "微信扩展暂时连不上,稍后再试") - return {"title": PEER_NAME, "sections": [{"items": [empty(why, "", version)]}], "state": st} + return {"title": PEER_NAME, "sections": [{"items": [empty(why, "", version)]}], "state": st, + "refresh_after": 5} if not isinstance(d, dict): return {"title": title, "sections": [{"items": [empty("微信的回答看不懂", "", version)]}], "state": st} title = str(d.get("title") or title) @@ -609,7 +609,8 @@ def _wx_chat(self, chat_id: str, version: int, now, account: str = "") -> dict: key="wxdone", **({"icon": "check", "icon_color": "green"} if version >= 6 else {}))]}) else: sections.append({"items": [self._note("已标记处理完(在微信页可以恢复)")]}) - return {"title": title, "sections": sections, "state": st, "refresh_after": REFRESH} + return snapshot_notice({"title": title, "sections": sections, "state": st, "refresh_after": REFRESH}, + ("", fresh)) @staticmethod def _note(text: str) -> dict: @@ -635,8 +636,9 @@ class Day: 需要我 across, then 日程 | 飞书今天, 正在跑的 Agent | 待办 once the apps lay sections out in columns).""" def __init__(self, page: TodayPage, version, now, p, chat_needs, counts, groups, today, pending, later, cal_missing, - wx: Optional[dict] = None, all_needs: bool = False, chats_failed: bool = False, deadline: Optional[float] = None): + wx: Optional[dict] = None, all_needs: bool = False, chats_failed: bool = False): self.page, self.version, self.now, self.p = page, version, now, p + self.sources: Dict[str, Fresh] = {} self.approvals = page._safe(page.approvals.view, ({}, {})) if page.approvals else None self.all_needs = all_needs # WeChat: None when it is not installed here (or the hub refused the call); else its read (state …) @@ -656,10 +658,8 @@ def __init__(self, page: TodayPage, version, now, p, chat_needs, counts, groups, self.inbox_needs = [i for i in p["inbox"] if not (i.get("done_at") or i.get("dismissed") or i.get("superseded")) and (str(i.get("status") or "") == "action" if "status" in i else str(i.get("tier") or "") in NEEDS_TIERS)] - self.partial_names = list(p.get("missing") or []) + list(p.get("degraded") or []) + \ - [x for x in page.persona.last_missing if x not in (p.get("missing") or [])] + (["飞书会话"] if chats_failed else []) + self.partial_names = p["missing"] + p.get("degraded", []) + (["飞书会话"] if chats_failed else []) self.partial = bool(self.partial_names) - self.deadline = deadline self.asks = [t for t in p["todos"] if t.get("ask")] self.todos = [t for t in p["todos"] if not t.get("ask")] self.done = len(getattr(page.chats, "done", []) or []) @@ -736,19 +736,18 @@ def nothing_words(self) -> str: return "读到的来源暂时没有要你处理的事;%s暂时读不到" % "、".join(dict.fromkeys(unread)) return "没有要你处理的事" - def needs_rows(self) -> List[dict]: - out = [] + def needs_rows(self) -> Iterator[dict]: for s in self.p["waiting"]: - out.append(row(agent_title(s), agent_detail(s) or "在等你回答", "", key="wait:" + str(s.get("session_id")), - badge={"text": "Agent 等你", "tone": "danger"}, **self._icon("robot", "red"), - actions=self._done("wait:" + str(s.get("session_id")), version_of(s, *DONE_KINDS["wait"][2])))) + yield row(agent_title(s), agent_detail(s) or "在等你回答", "", key="wait:" + str(s.get("session_id")), + badge={"text": "Agent 等你", "tone": "danger"}, **self._icon("robot", "red"), + actions=self._done("wait:" + str(s.get("session_id")), version_of(s, *DONE_KINDS["wait"][2]))) for i in self.inbox_needs: - out.append(row(str(i.get("title") or "收件箱"), str(i.get("summary") or i.get("preview") or ""), "", - key="inbox:" + str(i.get("id")), badge={"text": "收件箱", "tone": "caution"}, - **self._icon("mail", "amber"), - actions=self._done("inbox:" + str(i.get("id")), version_of(i, *DONE_KINDS["inbox"][2])))) + yield row(str(i.get("title") or "收件箱"), str(i.get("summary") or i.get("preview") or ""), "", + key="inbox:" + str(i.get("id")), badge={"text": "收件箱", "tone": "caution"}, + **self._icon("mail", "amber"), + actions=self._done("inbox:" + str(i.get("id")), version_of(i, *DONE_KINDS["inbox"][2]))) for t in self.asks: - out.append(self._todo_row(t, "ask:")) + yield self._todo_row(t, "ask:") chats = [(float(t.get("_at") or 0), 0, str((t.get("_chat") or {}).get("id") or t.get("thread") or ""), t) for t in self.chat_needs] chats += [(float(n.get("at") or 0), 1, str(n["chat"]), n) for n in self.wx_needs] @@ -758,20 +757,19 @@ def needs_rows(self) -> List[dict]: mention = t["kind"] == "mention" stamp = when(at, tz, now) if at else "" if not wechat: - out.append(row(t["title"], "%s:%s" % (t["sender"], t["preview"]), stamp, - "chat:" + chat_id if self.links and chat_id else "", key="chat:" + str(t.get("thread") or chat_id), - badge={"text": "@我" if mention else "私聊", "tone": "caution" if mention else "neutral"}, - **self._icon("chat", "orange" if mention else "indigo"), - actions=self._done("chat:" + chat_id, t.get("_version")) if chat_id else None)) + yield row(t["title"], "%s:%s" % (t["sender"], t["preview"]), stamp, + "chat:" + chat_id if self.links and chat_id else "", key="chat:" + str(t.get("thread") or chat_id), + badge={"text": "@我" if mention else "私聊", "tone": "caution" if mention else "neutral"}, + **self._icon("chat", "orange" if mention else "indigo"), + actions=self._done("chat:" + chat_id, t.get("_version")) if chat_id else None) continue q = urllib.parse.quote(chat_id, safe="") acct = urllib.parse.quote(str(self.wx.get("account") or ""), safe="") - out.append(row(str(t.get("title") or PEER_NAME), "%s:%s" % (t.get("sender") or "", t.get("preview") or ""), stamp, - "wx:%s:%s" % (q, acct) if self.links else "", key="wx:" + chat_id, - badge={"text": "微信 @我" if mention else "微信私聊", "tone": "caution" if mention else "neutral"}, - **self._icon("chat", "green"), - actions=self._done("wx:%s:%s:%s" % (q, urllib.parse.quote(str(t["version"]), safe=""), acct)))) - return out + yield row(str(t.get("title") or PEER_NAME), "%s:%s" % (t.get("sender") or "", t.get("preview") or ""), stamp, + "wx:%s:%s" % (q, acct) if self.links else "", key="wx:" + chat_id, + badge={"text": "微信 @我" if mention else "微信私聊", "tone": "caution" if mention else "neutral"}, + **self._icon("chat", "green"), + actions=self._done("wx:%s:%s:%s" % (q, urllib.parse.quote(str(t["version"]), safe=""), acct))) # ---- the card @@ -782,8 +780,10 @@ def card(self) -> dict: head = [self._tiles(blocks[:3], "blocks"), self._tiles(blocks[3:], "blocks2")] else: head = [self._tiles(blocks, "blocks")] - rows = [{k: x for k, x in r.items() if k not in ("action", "actions")} for r in self.needs_rows()[:3]] # a card only shows + rows = [{k: x for k, x in r.items() if k not in ("action", "actions")} for r in islice(self.needs_rows(), 3)] # a card only shows nothing = empty(self.nothing_words(), "", v) + if self.p.get("degraded") and rows: + head.append(self._caption("暂时读不到:%s(稍后自动重试)" % "、".join(self.p["degraded"]))) return {"sections": [{"items": head}, {"items": rows or [nothing]}], "refresh_after": REFRESH} # ---- the page @@ -815,7 +815,7 @@ def full(self, state: Optional[dict] = None) -> dict: sec.pop("span", None) sec.pop("columns", None) sections.append(sec) - missing = list(self.p["missing"]) + ([PEER_NAME] if self.wx_unknown else []) + missing = self.p["missing"] + self.p.get("degraded", []) + ([PEER_NAME] if self.wx_unknown else []) if missing: note: Dict[str, Any] = {"items": [self._caption("暂时读不到:%s(稍后自动重试)" % "、".join(missing))]} if self.v8: @@ -870,6 +870,7 @@ def status_blocks(self, mesh: bool = False) -> List[tuple]: if mesh and page is not None: t = page.status_tile() if t is not None: + self.sources["中转站"] = page.mesh._fresh out.append(t) return out @@ -908,9 +909,11 @@ def agents_block(self) -> dict: read = getattr(self.page, "agents", None) if read is None: return self.agents_card() + self.sources["Agent"] = read._fresh try: - left = max(0.0, (self.deadline or time.monotonic() + AGENTS_WAIT) - time.monotonic()) - board = agents_mod.Board(read.read(min(AGENTS_WAIT, left)), self.now.timestamp(), self.page.app.tz) + board = agents_mod.Board(read.read(0), self.now.timestamp(), self.page.app.tz) + except NotYet: + return self.agents_card() except Exception as e: log.info("the Agent block could not be read: %s", e.__class__.__name__) return self.agents_card() @@ -968,16 +971,16 @@ def needs_card(self) -> dict: parts.append("已聊完 %d" % chats.closed) if getattr(chats, "expired", 0): parts.append("超过 %d 小时的 %d 条不算" % (chats.needs_hours(), chats.expired)) - rows = self.needs_rows() most = NEEDS_ALL if self.all_needs else NEEDS_MOST + rows = list(islice(self.needs_rows(), most)) sec: Dict[str, Any] = {"title": "需要我 · %d" % self.needs_total if self.needs_total else "需要我", "items": [self._caption(" · ".join(parts))] - + (rows[:most] or [empty("微信暂时读不到,其他的没有要你处理的事" if self.wx_unknown + + (rows or [empty("微信暂时读不到,其他的没有要你处理的事" if self.wx_unknown else "没有要你处理的事", "", self.version)])} - if len(rows) > most: - sec["footer"] = "还有 %d 件" % (len(rows) - most) - if len(rows) > NEEDS_MOST and not self.all_needs and self.links: # Feishu's and WeChat's together, here - sec["items"].append(row("展开全部 %d 件" % len(rows), "", "", "needs:all", key="link:needs-all")) + if self.needs_total > most: + sec["footer"] = "还有 %d 件" % (self.needs_total - most) + if self.needs_total > NEEDS_MOST and not self.all_needs and self.links: + sec["items"].append(row("展开全部 %d 件" % self.needs_total, "", "", "needs:all", key="link:needs-all")) if self.v8: sec["span"], sec["columns"] = "full", 2 link = ("全部", "needs:all") if self.wx_needs else ("全部", "go:chats") if self.chat_needs else None @@ -1064,7 +1067,10 @@ def mesh_card(self) -> Optional[dict]: if page is None: return None sec = page.card(self.version, self.links, self.icons) - return self._card(sec, "gauge", "teal", ("打开", "go:starkmesh")) if sec is not None else None + if sec is None: + return None + self.sources["中转站"] = page.mesh._fresh + return self._card(sec, "gauge", "teal", ("打开", "go:starkmesh")) def auto_card(self) -> Optional[dict]: """What the Agent answered as the user today without being asked each time (自动代答 in a marked group, a diff --git a/extensions/openmate-feishu/persona-extension.json b/extensions/openmate-feishu/persona-extension.json index deb50af..080046c 100644 --- a/extensions/openmate-feishu/persona-extension.json +++ b/extensions/openmate-feishu/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.75", + "version": "0.11.76", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/extensions/openmate-feishu/tests/test_agenda.py b/extensions/openmate-feishu/tests/test_agenda.py index 67960ba..3829c05 100644 --- a/extensions/openmate-feishu/tests/test_agenda.py +++ b/extensions/openmate-feishu/tests/test_agenda.py @@ -236,7 +236,10 @@ def test_a_failed_read_keeps_the_last_events(self): now[0] += 61 self.assertEqual(section(page.render({"ui_version": 6}), "今天")[0]["title"], "站会", "the last read stays") now[0] += 900 - self.assertIn("auth login", items(page.render({"ui_version": 6}))[0]["detail"], "too old: says why") + view = page.render({"ui_version": 6}) + self.assertEqual(section(view, "今天")[0]["title"], "站会") + self.assertEqual(view["refresh_after"], 5) + self.assertIn("16 分钟前的数据,正在更新", str(view)) def test_a_comment_reply(self): runner = Runner({"ok": True, "data": {"reply_id": "r7"}}) diff --git a/extensions/openmate-feishu/tests/test_larkagentx.py b/extensions/openmate-feishu/tests/test_larkagentx.py index 562b9ba..8d9fe34 100644 --- a/extensions/openmate-feishu/tests/test_larkagentx.py +++ b/extensions/openmate-feishu/tests/test_larkagentx.py @@ -1642,6 +1642,23 @@ def set_groups(self, me, groups): self.b._groups_owner = me.id self.b._groups = [larkagentx.Chat(id=i, kind="group", name=n, members=m, topic=t) for i, n, m, t in groups] self.b._groups_join = {g[0]: 100 - k for k, g in enumerate(groups)} + self.b._groups_view = (me.id, tuple(self.b._groups)) + + def test_group_candidates_uses_published_list_without_adapter_locks(self): + _, me = self.b._signed_in() + self.set_groups(me, [("fixture", "示例群", 2, False)]) + done, result = threading.Event(), [] + + def read(): + result.extend(g.id for g in self.b.group_candidates(5)) + done.set() + + with self.b._lock, self.b._groups_mu: + worker = threading.Thread(target=read, daemon=True) + worker.start() + self.assertTrue(done.wait(1)) + worker.join(1) + self.assertEqual(result, ["fixture"]) def test_groups_change_with_pushes_and_messages(self): client, me = self.b._signed_in() diff --git a/extensions/openmate-feishu/tests/test_meetings.py b/extensions/openmate-feishu/tests/test_meetings.py index 5d11251..0045b8b 100644 --- a/extensions/openmate-feishu/tests/test_meetings.py +++ b/extensions/openmate-feishu/tests/test_meetings.py @@ -516,7 +516,7 @@ def test_today_and_calendar_are_local_and_open_links(self): def test_meeting_block_reads_one_indexed_query(self): self.service.sync() - db = self.app.store._db + db = self.app.store._reader queries = [] db.set_trace_callback(queries.append) try: diff --git a/extensions/openmate-feishu/tests/test_starkmesh.py b/extensions/openmate-feishu/tests/test_starkmesh.py index 3434ad0..3229708 100644 --- a/extensions/openmate-feishu/tests/test_starkmesh.py +++ b/extensions/openmate-feishu/tests/test_starkmesh.py @@ -334,7 +334,7 @@ def test_the_pool_as_one_claude_account(self): together = [dict(ACCOUNTS[0], id=i) for i in (21, 22)] snap = starkmesh.Snapshot(together, {"21": {"five_hour": win(40, 3600)}, "22": {"five_hour": win(60, 3630)}}, {}, NOW) page.mesh.read = lambda wait=None: snap - page.mesh.state = (snap, None) # as a read that came in + page.mesh._observed = (page.mesh._fresh._key(), (snap, None), None) # as a read that came in self.assertEqual(page.usage({"lang": "zh-Hans"})["accounts"][0]["windows"][0]["resets_at"], starkmesh._iso(NOW + 3630), "resetting together: one window with the last one's end, so it never ends early") page.mesh.read = starkmesh.StarkMesh.read.__get__(page.mesh) @@ -419,16 +419,16 @@ def test_a_read_that_came_in_since_is_the_answer(self): # the read and its failure mark are one state: the newer read with no failure, or the old one with it old, new = (starkmesh.Snapshot(ACCOUNTS, USAGE, {}, x) for x in (NOW + 200, NOW + 210)) mesh.read = lambda wait=None: old - mesh.state = (new, None) + mesh._observed = (mesh._fresh._key(), (new, None), None) self.assertEqual(page.usage({})["accounts"][0]["sampled_at"], starkmesh._iso(NOW + 210)) - mesh.state = (old, NOW + 205) + mesh._observed = (mesh._fresh._key(), (old, NOW + 205), None) with self.assertRaises(RPCError): page.usage({}) - mesh.state = (old, NOW + 100) # failed by a clock that stepped back: the newest read failed all the same + mesh._observed = (mesh._fresh._key(), (old, NOW + 100), None) # failed by a clock that stepped back: the newest read failed all the same with self.assertRaises(RPCError): page.usage({}) stepped = starkmesh.Snapshot(ACCOUNTS, USAGE, {}, NOW + 150) # read in after the clock stepped back - mesh.state = (stepped, None) + mesh._observed = (mesh._fresh._key(), (stepped, None), None) self.assertEqual(page.usage({})["accounts"][0]["sampled_at"], starkmesh._iso(NOW + 150), "the newest, not the latest clock") def test_a_part_of_the_pool_is_not_the_whole(self): @@ -675,7 +675,7 @@ def test_the_gateways_times_against_the_querys_clock(self): snap = starkmesh.Snapshot([a], {"51": {"five_hour": win(80, 60)}}, {}, NOW + 120) page, _ = make() page.mesh.read = lambda wait=None: snap - page.mesh.state = (snap, None) + page.mesh._observed = (page.mesh._fresh._key(), (snap, None), None) w = page.usage({"lang": "zh-Hans"})["accounts"][0]["windows"][0] self.assertEqual((round(w["used_percent"], 6), w.get("resets_at")), (80.0, starkmesh._iso(NOW + 60))) diff --git a/extensions/openmate-feishu/tests/test_today.py b/extensions/openmate-feishu/tests/test_today.py index f56d5aa..48d4a42 100644 --- a/extensions/openmate-feishu/tests/test_today.py +++ b/extensions/openmate-feishu/tests/test_today.py @@ -268,8 +268,10 @@ def test_marked_done(self): answers["/api/v1/inbox"] = {"items": [dict(PERSONA["/api/v1/inbox"]["items"][0], updated_at="2026-11-16T03:00:00Z")]} answers["/api/v1/sessions?state=needs_you"] = {"sessions": [dict(PERSONA["/api/v1/sessions?state=needs_you"]["sessions"][0], state_since="2026-11-16T03:00:00Z")]} - now[0] += 700 # past STALE: a fresh read - view = page.render({"ui_version": 6}) + now[0] += 700 + stale = page.render({"ui_version": 6}) + self.assertNotIn("修复登录问题", str(stale)) + view = page.render({"ui_version": 6}) # the refreshed versions are visible on the next draw self.assertEqual([r["title"] for r in rows(body(view)[0])][:2], ["修复登录问题", "示例告警"]) self.assertIn("已处理 2", texts(body(view)[0])[0]) @@ -406,6 +408,25 @@ def test_old_apps(self): for s in v2["sections"] for it in s["items"]), "no pages on top before 3") self.assertEqual(card.render({"ui_version": 1})["sections"][0]["items"][0]["type"], "text") + def test_persona_reuses_only_the_failed_part_and_throttles_draws(self): + now = [NOW] + answers = dict(PERSONA) + page, card, hub = make(answers=answers, clock=lambda: now[0]) + page.render({"ui_version": 6}) + answers["/api/v1/inbox"] = HubError(503, "fixture offline") + answers["/api/v1/todos"] = {"todos": [{"id": "new", "title": "新待办"}]} + now[0] += 700 + page.render({"ui_version": 6}) # returns the older value and refreshes + view = page.render({"ui_version": 6}) + self.assertIn("Persona 收件箱(沿用 11 分钟前的数据)", str(view)) + self.assertIn("示例告警", str(view)) + self.assertIn("新待办", str(view)) + self.assertNotIn("下周的事", str(view)) + self.assertEqual(len(hub.calls), 8) + card.render({"ui_version": 6}) + page.render({"ui_version": 6}) + self.assertEqual(len(hub.calls), 8) + def test_a_slow_draw_says_where_the_time_went(self): page, _, _ = make() with self.assertLogs("openmate.today", "INFO") as logs: diff --git a/extensions/openmate-feishu/tests/test_today_wechat.py b/extensions/openmate-feishu/tests/test_today_wechat.py index 4f02962..a1f8735 100644 --- a/extensions/openmate-feishu/tests/test_today_wechat.py +++ b/extensions/openmate-feishu/tests/test_today_wechat.py @@ -204,12 +204,31 @@ def test_a_wechat_chat_opens_here(self): self.assertEqual(again["toast"], "有新消息,已刷新") self.assertEqual(again["view"]["title"], "示例家庭群", "the chat drawn again, not a toast alone") hub.answers[BASE + "chat"] = HubError(404, "gone", "not_found") + page.wechat.invalidate() gone = page.render({"ui_version": 6, "state": out["push"]["state"]}) self.assertEqual(gone["sections"][0]["items"][0]["title"], "这个会话现在没有要处理的了") other = page.render({"ui_version": 6, "state": json.dumps({"wx": "w1@chatroom", "acct": "wxid_old"})}) self.assertEqual((other["title"], other["sections"][0]["items"][0]["title"]), ("微信", "微信换了账号,这一件不在了"), "a page drawn for the account before shows nothing of this one's") + def test_chat_detail_render_schedules_hub_reads(self): + page, _, hub, _ = make() + jobs = [] + page.wechat = today.PeerToday(page.app, clock=lambda: NOW, spawn=jobs.append) + hub.answers[BASE + "chat"] = {"chat": "w1@chatroom", "title": "示例家庭群", "kind": "mention", + "lines": [{"who": "示例亲戚", "text": "周末吃饭吗"}]} + params = {"ui_version": 6, "state": json.dumps({"wx": "w1@chatroom", "acct": "wxid_me"})} + loading = page.render(params) + self.assertIn("正在读取会话", str(loading)) + self.assertEqual(loading["refresh_after"], 5) + self.assertEqual(hub.calls, []) + self.assertEqual(len(jobs), 2) + for job in jobs: + job() + self.assertIn("周末吃饭吗", str(page.render(params))) + self.assertEqual(len(hub.calls), 2) + self.assertEqual(len(jobs), 2) + def test_more_than_twelve_needs_open_here(self): many = json.loads(json.dumps(WX)) many["needs"] = [{"chat": "w%d" % i, "kind": "dm", "title": "朋友%d" % i, "sender": "朋友%d" % i, "preview": "在吗", diff --git a/extensions/openmate-wechat/persona-extension.json b/extensions/openmate-wechat/persona-extension.json index e960366..3d98a64 100644 --- a/extensions/openmate-wechat/persona-extension.json +++ b/extensions/openmate-wechat/persona-extension.json @@ -2,7 +2,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.69", + "version": "0.1.70", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", diff --git a/packages/openmate-feishu/0.11.76/openmate-feishu-0.11.76.tar.gz b/packages/openmate-feishu/0.11.76/openmate-feishu-0.11.76.tar.gz new file mode 100644 index 0000000..149eb8e Binary files /dev/null and b/packages/openmate-feishu/0.11.76/openmate-feishu-0.11.76.tar.gz differ diff --git a/packages/openmate-wechat/0.1.70/openmate-wechat-0.1.70.tar.gz b/packages/openmate-wechat/0.1.70/openmate-wechat-0.1.70.tar.gz new file mode 100644 index 0000000..9d0b8f6 Binary files /dev/null and b/packages/openmate-wechat/0.1.70/openmate-wechat-0.1.70.tar.gz differ diff --git a/persona-extensions.json b/persona-extensions.json index 768cf12..ab95e3c 100644 --- a/persona-extensions.json +++ b/persona-extensions.json @@ -9,7 +9,7 @@ "manifest_version": 1, "id": "openmate-feishu", "name": "飞书(OpenMate)", - "version": "0.11.75", + "version": "0.11.76", "description": "把飞书私聊和群消息接进 Persona 的收件箱和知识库,通过确认卡片以你的身份发消息,支持 /agent。通过你自己安装的 LarkAgentX(非官方网页协议)连接,与飞书官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -534,9 +534,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-feishu/0.11.75/openmate-feishu-0.11.75.tar.gz", - "sha256": "03ed3937cda8584e550266688acebb93b49b232338b2035bbfc5115055a0366d", - "size": 409623 + "url": "packages/openmate-feishu/0.11.76/openmate-feishu-0.11.76.tar.gz", + "sha256": "a628e572fd8ba8b5d6d9840a7b0384f4991848c068362053da381156e2959327", + "size": 413811 } ] }, @@ -545,7 +545,7 @@ "manifest_version": 1, "id": "openmate-wechat", "name": "微信(OpenMate)", - "version": "0.1.69", + "version": "0.1.70", "description": "把微信私聊和群里 @你 的消息接进 Persona 的收件箱和会话页,私聊进知识库;在微信里用 /agent 让 Agent 以你的身份处理和回复,勾选的群里有人 @ 你时自动代答,助手代发的消息都要你在确认卡片上确认。以一台新电脑的身份登录你的微信(非官方协议),与腾讯官方无关。", "publisher": "NginxL", "homepage": "https://github.com/NginxL/openmate", @@ -842,9 +842,9 @@ "icon": "assets/icon.png", "packages": [ { - "url": "packages/openmate-wechat/0.1.69/openmate-wechat-0.1.69.tar.gz", - "sha256": "a64ca8c20176c460000f96ebdc0e4fdbd9a3da9bc9a89a0aae4af8c21b9d2263", - "size": 307560 + "url": "packages/openmate-wechat/0.1.70/openmate-wechat-0.1.70.tar.gz", + "sha256": "ed0b87965955197b7c05e06fa72efe3837854ca75aad471c4f5ebdf10f26f31d", + "size": 310916 } ] } diff --git a/tests/test_account_switch.py b/tests/test_account_switch.py index e13bd5d..88ed30e 100644 --- a/tests/test_account_switch.py +++ b/tests/test_account_switch.py @@ -981,7 +981,7 @@ def mark_changed(self, *scopes): people = People(App(), spawn=later.append) people._can = lambda: True people._epoch = lambda: 1 # the draw began for the account before; forget ran before it queued them - people._ask({"user_example_shared"}) + people.ask_unknown({"user_example_shared"}) self.assertEqual((people._want, people._asking), ({}, set()), "queued for the next account, never let go") diff --git a/tests/test_events_store.py b/tests/test_events_store.py index 6d2b989..ccd690c 100644 --- a/tests/test_events_store.py +++ b/tests/test_events_store.py @@ -26,15 +26,13 @@ def test_a_failed_commit_leaves_no_transaction_behind(self): path = os.path.join(d, "t.db") st = Store(path) self.addCleanup(st.close) - st._db.execute("PRAGMA busy_timeout=50") - other = sqlite3.connect(path, isolation_level=None) - other.execute("BEGIN") - other.execute("SELECT * FROM meta").fetchall() # a reader's lock: the writer's COMMIT is refused (busy) - with self.assertRaises(sqlite3.OperationalError): - st.meta_set("k", "v") + st._db.execute("CREATE TABLE parent (id INTEGER PRIMARY KEY)") + st._db.execute("CREATE TABLE child (pid REFERENCES parent (id) DEFERRABLE INITIALLY DEFERRED)") + with self.assertRaises(sqlite3.IntegrityError): + st._tx(lambda db: db.execute("INSERT INTO child VALUES (42)")) self.assertFalse(st._db.in_transaction, "rolled back: not left open") - other.execute("COMMIT") - other.close() + self.assertEqual(st.changes, 0) + self.assertEqual(st._all("SELECT * FROM child"), []) st.meta_set("k", "v2") # the next write works self.assertEqual(st.meta_get("k"), "v2") diff --git a/tests/test_fresh.py b/tests/test_fresh.py index 24b3518..67ae571 100644 --- a/tests/test_fresh.py +++ b/tests/test_fresh.py @@ -45,7 +45,7 @@ def test_a_first_read_waits_then_the_last_one_comes_at_once(self): self.assertEqual(f.get(), "v1", "older than ahead: the last one, and a read behind it") self.assertEqual((self.src.n, f.get()), (2, "v2")) - def test_a_failed_read_keeps_the_last_one_until_stale(self): + def test_a_failed_read_keeps_the_last_one_after_stale(self): f = self.make() f.get() self.src.fail = True @@ -53,8 +53,9 @@ def test_a_failed_read_keeps_the_last_one_until_stale(self): self.assertEqual(f.get(), "v1") self.assertEqual(f.get(), "v1", "kept after the failed read behind it") self.now[0] += 900 - with self.assertRaises(RuntimeError, msg="stale: a draw waits, and says it failed"): - f.get() + self.assertEqual(f.get(0), "v1") + self.assertEqual(f.age(), 960) + self.assertEqual(f.stale_age(), 960) def test_a_new_day_waits(self): f = self.make() @@ -81,8 +82,9 @@ def read(): return slow() f.read = read - self.now[0] += 60 - self.assertEqual(f.get(), "v1") + self.now[0] += 960 + self.assertEqual(f.get(0), "v1") + self.assertEqual(f.age(), 960) self.assertTrue(started.wait(5)) self.assertEqual(f.get(), "v1", "while the read behind is still going") gate.set() @@ -111,6 +113,7 @@ def test_one_warm_loop_per_value_and_it_rests_while_nobody_looks(self): f.warm(every=0.02, stop=stop) f.warm(every=0.02, stop=stop) # another page asks too self.assertEqual(len([x for x in loops if x.__name__ == "run"]), 1, "one loop") + f.get() # the loop keeps reading while looked at wait_until(lambda: self.src.n >= 2, what="reads while looked at") self.now[0] += ui_mod.WARM_IDLE + 1 # nobody looked for a long while time.sleep(0.1) @@ -126,6 +129,7 @@ def test_kept_warm_until_stopped(self): f.ahead = 0 # each get reads again (behind, in place below) f.spawn = lambda fn: threading.Thread(target=fn, daemon=True).start() f.warm(every=0.02, stop=stop) + f.get() wait_until(lambda: self.src.n >= 3, what="read again and again") stop.set() time.sleep(0.1) diff --git a/tests/test_snapshot_perf.py b/tests/test_snapshot_perf.py new file mode 100644 index 0000000..2c82e24 --- /dev/null +++ b/tests/test_snapshot_perf.py @@ -0,0 +1,288 @@ +"""Regression tests for page read models, disk scope, and rendering diagnostics.""" + +import datetime as dt +import os +import stat +import tempfile +import threading +import time +import types +import unittest +from queue import Queue +from unittest.mock import patch + +import _runtmp # noqa: F401 (keeps temporary files in the test run directory) +import harness # noqa: F401 (puts core on the path) +from openmate_core.backend import Chat, Message +from openmate_core.people import People +from openmate_core.store import Store +from openmate_core import ui + + +class StoreCase(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.path = os.path.join(directory.name, "cache.db") + self.store = self.open_store() + + def open_store(self): + store = Store(self.path) + self.addCleanup(store.close) + return store + + def test_default_transaction_write_invalidates_cached_needs(self): + self.store.upsert_chat(Chat("dm", "dm", "旧会话名", peer_id="person")) + self.store.add_messages([Message("dm-1", "dm", 1, sender_id="person", text="在吗?", at=time.time())], False) + app = types.SimpleNamespace(store=self.store, tz=dt.timezone.utc, me_name=lambda: "我", + timing=types.SimpleNamespace(inbox_window=86400, inbox_most=200)) + page = ui.ChatsToday(app) + self.assertEqual([t["title"] for t in page.needs()], ["旧会话名"]) + before = self.store.changes + self.store._tx(lambda db: db.execute("UPDATE chats SET name = '新会话名' WHERE id = 'dm'")) + self.assertEqual(self.store.changes, before + 1) + self.assertEqual([t["title"] for t in page.needs()], ["新会话名"]) + + now = time.time() + before = self.store.changes + self.store._tx(lambda db: db.execute("UPDATE chats SET name = '无匹配行' WHERE id = 'missing'")) + self.store.save_snapshot("fixture", now, ["cached"], self.store.snapshot_scope, lambda: True) + self.assertEqual(self.store.snapshot("fixture"), (now, ["cached"])) + self.store.drop_snapshot("fixture") + self.assertIsNone(self.store.snapshot("fixture")) + self.store.quota_backfill() + self.store.quota_add("dm", "auto", now) + self.assertTrue(self.store.seen_add("fixture", now)) + self.store.seen_prune(now + 1) + self.assertTrue(self.store.channel_msg_put("dm", "m1", "in", now=now)) + self.assertTrue(self.store.send_claim("fixture", "reply", now)) + self.assertEqual(self.store.changes, before) + + def test_wal_reads_during_long_transaction_and_private_files(self): + self.store.meta_set("key", "committed") + started, release, read_done = threading.Event(), threading.Event(), threading.Event() + result = [] + + def write(db): + db.execute("UPDATE meta SET value='uncommitted' WHERE key='key'") + started.set() + release.wait(5) + + def read(): + result.append(self.store.meta_get("key")) + read_done.set() + + writer = threading.Thread(target=lambda: self.store._tx(write)) + reader = threading.Thread(target=read) + writer.start() + try: + self.assertTrue(started.wait(2)) + reader.start() + self.assertTrue(read_done.wait(1), "a reader may not wait for the writer to commit") + self.assertEqual(result, ["committed"]) + for suffix in ("", "-wal", "-shm"): + self.assertEqual(stat.S_IMODE(os.stat(self.path + suffix).st_mode), 0o600) + finally: + release.set() + writer.join(5) + if reader.ident is not None: + reader.join(5) + self.assertEqual(self.store.meta_get("key"), "uncommitted") + self.assertEqual(self.store._db.execute("PRAGMA synchronous").fetchone()[0], 1) + + def test_snapshot_reopens_with_age_and_rejects_oversize(self): + later = [] + self.store.wipe_account_data("first") + f = ui.Fresh(lambda: {"rows": [1, 2]}, 30, 600, clock=lambda: 1000, spawn=lambda run: run(), + persist=(self.store, "fixture")) + self.assertEqual(f.get(0), {"rows": [1, 2]}) + too_big = ui.Fresh(lambda: "例" * 360000, 30, 600, spawn=lambda run: run(), + persist=(self.store, "oversize")) + self.assertTrue(too_big.get(0)) + self.assertIsNone(self.store.snapshot("oversize")) + self.store.close() + store = self.open_store() + f = ui.Fresh(lambda: {"rows": [3]}, 30, 600, clock=lambda: 1120, spawn=later.append, + persist=(store, "fixture")) + self.assertEqual(f.get(0), {"rows": [1, 2]}) + self.assertEqual(f.age(), 120) + view = ui.snapshot_notice({"sections": [{"items": []}]}, ("", f)) + self.assertEqual(view["refresh_after"], 5) + self.assertIn("2 分钟前的数据,正在更新", str(view)) + self.assertEqual(len(later), 1) + later.pop()() + self.assertEqual(f.get(0), {"rows": [3]}) + self.assertIsNone(f.stale_age()) + + def test_account_wipe_rejects_memory_disk_and_inflight_snapshots(self): + self.store.wipe_account_data("first") + now = [1000.0] + f = ui.Fresh(lambda: "first", 30, 600, clock=lambda: now[0], spawn=lambda run: run(), + persist=(self.store, "fixture")) + self.assertEqual(f.get(0), "first") + now[0] += 60 + + def read(): + self.store.wipe_account_data("second") # switch after the read started + return "result from first" + + f.read = read + with self.assertRaises(ui.NotYet): + f.get(0) + self.assertIsNone(f.peek()) + self.assertIsNone(self.store.snapshot("fixture")) + f.read = lambda: "second" + self.assertEqual(f.get(0), "second") + + def test_snapshot_owner_rejects_rows_left_by_an_older_release(self): + self.store.wipe_account_data("first") + f = ui.Fresh(lambda: ["first"], 30, 600, spawn=lambda run: run(), persist=(self.store, "fixture")) + self.assertEqual(f.get(0), ["first"]) + self.store.meta_set("account_id", "second") # simulate a release which never clears snapshots + self.store.close() + store = self.open_store() + second = ui.Fresh(lambda: ["second"], 30, 600, spawn=lambda run: run(), persist=(store, "fixture")) + self.assertIsNone(second.peek()) + self.assertEqual(second.get(0), ["second"]) + + def test_needs_batches_and_reuses_reads_until_committed_changes(self): + now = time.time() + self.store.upsert_chat(Chat("dm", "dm", "fixture", peer_id="person")) + msgs = [Message("dm-1", "dm", 1, sender_id="person", text="在吗?", at=now)] + for i in range(20): + cid = "group-%d" % i + self.store.upsert_chat(Chat(cid, "group", cid)) + msgs.extend(Message(str(j), cid, j, sender_id="member", text="请确认", at=now, at_me=j == 1) + for j in range(1, 64)) + self.store.add_messages(msgs, False) + app = types.SimpleNamespace(store=self.store, tz=dt.timezone.utc, me_name=lambda: "我", backend=None, + timing=types.SimpleNamespace(inbox_window=86400, inbox_most=200), + platform=types.SimpleNamespace(name="fixture")) + app.people = People(app) + one, two = ui.ChatsToday(app), ui.ChatsToday(app) + with patch.object(self.store, "_all", wraps=self.store._all) as queries: + self.assertEqual(len(one.needs()), 21) + self.assertEqual({t["_version"] for t in one.needs() if t["kind"] == "mention"}, {"1"}) + self.assertLessEqual(queries.call_count, 6) + queries.reset_mock() + self.assertEqual(two.needs(), one.needs()) + self.assertEqual(queries.call_count, 0) + + writes = [ + (lambda: self.store.add_messages([Message("dm-2", "dm", 2, text="补充?", at=now)], False), 21), + (lambda: self.store.dismiss("chat:dm", "dm-2"), 20), + (lambda: self.store.set_people_kinds({"member": "bot"}), 0), + (lambda: self.store.set_mute("group-0", "muted"), 0), + (lambda: self.store.set_avatar("group-0", "synthetic"), 0), + ] + for write, expected in writes: + with self.subTest(write=write): + before = self.store.changes + write() + self.assertEqual(self.store.changes, before + 1) + queries.reset_mock() + self.assertEqual(len(two.needs()), expected) + self.assertGreater(queries.call_count, 0) + queries.reset_mock() + self.assertEqual(one.needs(), two.needs()) + self.assertEqual(queries.call_count, 0) + + +class RenderDiagnosticsTest(unittest.TestCase): + def test_watchdog_dumps_a_blocked_render_once_and_limits_an_hour(self): + started, release = threading.Event(), threading.Event() + checked = Queue() + offset = [0.0] + watchdog = ui.RenderWatchdog(delay=0.02, clock=lambda: time.monotonic() + offset[0]) + self.addCleanup(watchdog.close) + page = ui.UI(types.SimpleNamespace()) + page._watchdog = watchdog + page._render_stats = types.SimpleNamespace(record=lambda *_: None) + + def blocked_render(params): + fixture_value = "should not be in a stack dump" + started.set() + release.wait(3) + return {"title": fixture_value} + + page.pages["blocked"] = types.SimpleNamespace(render=blocked_render) + dump = watchdog._dump + + def capture(contribution): + dump(contribution) + checked.put(contribution) + + with self.assertLogs("openmate.ui", "WARNING") as logs, patch.object(watchdog, "_dump", side_effect=capture): + thread = threading.Thread(target=lambda: page.render({"contribution": "blocked"})) + thread.start() + try: + self.assertTrue(started.wait(1)) + self.assertEqual(checked.get(timeout=1), "blocked") + self.assertEqual(len(logs.output), 1) + self.assertIn("in blocked_render", logs.output[0]) + self.assertNotIn("should not be in a stack dump", logs.output[0]) + others = ["fixture-%d" % n for n in range(5)] + for name in others: + watchdog.start(name) + self.assertEqual([checked.get(timeout=1) for _ in others], others) + self.assertEqual(len(logs.output), 3) + self.assertEqual(sum("ui.render blocked watchdog" in line for line in logs.output), 1) + offset[0] += 3600 + watchdog.start("next-hour") + self.assertEqual(checked.get(timeout=1), "next-hour") + self.assertEqual(len(logs.output), 4) + finally: + release.set() + thread.join(3) + + def test_watchdog_reuses_worker_and_waits_indefinitely_when_idle(self): + waits = Queue() + workers = [] + watchdog = ui.RenderWatchdog() + self.addCleanup(watchdog.close) + wait = watchdog._condition.wait + + def observe_wait(timeout=None): + waits.put((threading.current_thread(), timeout)) + return wait(timeout) + + with patch.object(watchdog._condition, "wait", side_effect=observe_wait): + for _ in range(2): + token = watchdog.start("fixture") + worker, timeout = waits.get(timeout=1) + workers.append(worker) + self.assertTrue(worker.daemon) + self.assertGreater(timeout, 0) + self.assertLessEqual(timeout, 2) + watchdog.finish(token) + self.assertEqual(waits.get(timeout=1), (worker, None)) + self.assertIs(workers[0], workers[1]) + watchdog.close() + worker.join(1) + self.assertFalse(worker.is_alive()) + + def test_render_stats_emit_one_line_per_hour_with_percentiles(self): + timers = [] + + class Timer: + def __init__(self, interval, run): + timers.append((interval, run)) + + def start(self): + pass + + stats = ui.RenderStats() + with patch.object(ui.threading, "Timer", Timer), self.assertLogs("openmate.ui", "INFO") as logs: + for elapsed in range(1, 21): + stats.record("today", elapsed / 1000) + stats.record("chats", 0.003) + self.assertEqual([t[0] for t in timers], [3600]) + timers[0][1]() + self.assertEqual(len(logs.output), 1) + self.assertIn("today n=20 p50=10.00ms p95=19.00ms max=20.00ms", logs.output[0]) + self.assertIn("chats n=1", logs.output[0]) + stats.record("today", 0.001) + self.assertEqual([t[0] for t in timers], [3600, 3600]) + timers[1][1]() + self.assertEqual(len(logs.output), 2) + self.assertIn("today n=1", logs.output[1])