Files
gabrielvidalandClaude Opus 5.5 c7c0c92fe4 fix(askform): past the 1000-form cap the mirror re-added evicted forms forever
Every sync re-added the oldest closed forms a machine still listed (new +
changed), the GC dropped others, and each read published dozens of askform
SSE events (~2/s since 12:50 on 2026-11-27). Every tab then refetched
/api/inbox/waiting + /api/ask-form/forms, the 40-thread pool sat at 40/40
and every request waited 30 s (phones gave up: Traefik 499s).

- store remembers what its GC dropped; skip_report() keeps the mirror from
  taking those back, or any closed form older than 30 days it doesn't hold
- cap 1000 -> 5000

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:13:52 +01:00

210 lines
9.4 KiB
Python

"""
The ask-form mirror — pulls every machine's forms into the hub's store.
Per tick, per machine (the lab's host sidecar, each online worker):
``GET /ask-form/forms`` on its sidecar → ``store.upsert`` each form →
``on_new`` for a form never seen before (the push), ``publish`` for a
changed one (SSE ``askform``). A machine with an open form is read every
``fast`` seconds, an idle one every ``slow``; ``poke()`` reads one now (the
events webhook, a revoke from the viewer). A machine without ask-form
(``askform_missing``) or with an older sidecar (404) is retried every
``missing`` seconds and never logged twice.
This is the reconciliation path. The events webhook (``service.ingest_event``)
is the fast one: with it configured, the poll only catches what a lost event
would have missed.
Every ``embed_every`` seconds a machine's ``/ask-form/health`` also says which
sites its `ask-form serve` lets frame its pages (``embedOrigins``): the viewer
opens a form of that machine over its conversation when the page's own origin
is one of them, in a new tab otherwise. A machine that doesn't list the hub's
``origins`` yet is asked to (``POST /ask-form/embed`` → the sidecar's
``wire_embed``: its serve.env, then a restart once no form is open).
A machine dict may carry ``vet`` (``service.machines`` sets it for a guest's
own computer): a form it reports is mirrored only when ``vet(form)`` says it
is one of that computer's own sessions', the store then refuses it any
record another machine filed, and what it says about framing is ignored —
its pages never open inside the app (docs/security.md, 2026-11-15).
"""
from __future__ import annotations
import logging
import threading
import time
from typing import Callable
from fastapi import HTTPException
from workers.store import sidecar_request
log = logging.getLogger("askform")
class AskFormMirror(threading.Thread):
def __init__(self, store, *, machines: Callable[[], list[dict]],
on_new: Callable[[dict], None],
publish: Callable[[dict], None],
on_closed: Callable[[dict], None] | None = None,
recover: Callable[[], int] | None = None,
origins: Callable[[], list[str]] | None = None,
fast: float = 5.0, slow: float = 60.0, missing: float = 300.0,
embed_every: float = 600.0):
super().__init__(daemon=True, name="askform-mirror")
self.store = store
self.machines, self.on_new, self.publish = machines, on_new, publish
self.on_closed = on_closed
# Files the link of a form no machine's webhook gave one for, from the
# conversation's transcripts (links.recover) — after every read.
self.recover = recover
self.fast, self.slow, self.missing_s = fast, slow, missing
# The hub's own origins, which every machine should let frame its forms.
self.origins = origins
self.embed_every = embed_every
self.embed: dict[str, list[str]] = {} # machine id → who may frame its pages
self._embed_due: dict[str, float] = {}
self._due: dict[str, float] = {} # machine id → next read (monotonic)
self._missing: set[str] = set()
self._wake = threading.Event()
self._stop = threading.Event()
self._lock = threading.Lock()
def stop(self) -> None:
self._stop.set()
self._wake.set()
def poke(self, machine: str | None = None) -> None:
"""Read ``machine`` (every one when None) on the next loop turn."""
with self._lock:
for mid in ([machine] if machine else list(self._due)):
self._due[mid] = 0.0
self._wake.set()
# ── one machine ───────────────────────────────────────────────────────
def sync(self, m: dict) -> int:
"""Read one machine; returns how many forms it reported. Raises the
sidecar's HTTPException."""
out = sidecar_request(m["url"], m["token"], "/ask-form/forms", None,
method="GET", timeout=8,
label=m.get("label") or m["id"])
n = 0
for f in out.get("forms") or []:
if not isinstance(f, dict):
continue
vet = m.get("vet")
if self.store.skip_report(f):
continue # old history the hub let go of: no churn, no SSE
try:
if vet and not vet(f):
continue # a guest's computer: not one of its sessions
rec, new, changed = self.store.upsert(m["id"], f, trusted=not vet)
except ValueError:
continue
n += 1
if new and rec.get("status") == "pending":
try:
self.on_new(rec)
except Exception:
log.exception("askform: on_new %s", rec.get("id"))
if changed:
if self.on_closed and rec.get("status") not in (None, "", "pending"):
try:
self.on_closed(rec)
except Exception:
log.exception("askform: on_closed %s", rec.get("id"))
self.publish({"type": "askform", "id": rec["id"],
"sessionId": rec.get("sessionId") or "",
"status": rec.get("status")})
return n
def embed_origins(self, mid: str) -> list[str]:
"""The sites machine ``mid`` lets frame its pages, as last read."""
return list(self.embed.get(mid) or [])
def check_embed(self, m: dict) -> float:
"""Read who may frame machine ``m``'s pages; ask it to let the hub in
when it doesn't yet. Returns seconds until the next check."""
label = m.get("label") or m["id"]
if m.get("vet"):
# A guest's computer says nothing about who may frame what: its
# forms open on their own page, in a new tab.
self.embed.pop(m["id"], None)
return self.embed_every
h = sidecar_request(m["url"], m["token"], "/ask-form/health", None,
method="GET", timeout=6, label=label)
live = [o for o in (h.get("embedOrigins") or []) if isinstance(o, str)]
self.embed[m["id"]] = live
want = self.origins() if self.origins else []
if not want or not h.get("installed", True) or all(o in live for o in want):
return self.embed_every
try:
out = sidecar_request(m["url"], m["token"], "/ask-form/embed", {"origins": want},
timeout=15, label=label)
except HTTPException:
return self.embed_every # a sidecar from before /ask-form/embed
state = out.get("state")
if state != "already":
log.info("askform: %s embed origins: %s", m["id"], state)
# wired: serve restarted, read it again soon; busy: once its forms close.
return {"wired": 10.0, "busy": 60.0}.get(state, self.embed_every)
def tick(self) -> float:
"""Read every due machine; returns seconds until the next due one."""
now = time.monotonic()
pending = self.store.pending_machines()
soonest = self.slow
for m in self.machines():
mid = m["id"]
with self._lock:
due = self._due.get(mid, 0.0)
if due > now:
soonest = min(soonest, due - now)
continue
try:
self.sync(m)
if self._embed_due.get(mid, 0.0) <= now:
try:
again = self.check_embed(m)
except Exception:
again = self.embed_every
self._embed_due[mid] = time.monotonic() + again
if mid in self._missing:
self._missing.discard(mid)
log.info("askform: %s is back", mid)
wait = self.fast if mid in pending or mid in self.store.pending_machines() else self.slow
except HTTPException as e:
d = e.detail if isinstance(e.detail, dict) else {}
kind = d.get("kind") or ""
if kind in ("askform_missing", "askform_down") or e.status_code == 404:
if mid not in self._missing:
self._missing.add(mid)
log.info("askform: %s — %s", mid,
d.get("message") or "no /ask-form on that sidecar")
wait = self.missing_s
else:
log.warning("askform: %s: %s", mid, d.get("message") or e.detail)
wait = self.slow
except Exception:
log.exception("askform: %s", mid)
wait = self.slow
with self._lock:
self._due[mid] = time.monotonic() + wait
soonest = min(soonest, wait)
if self.recover:
try:
self.recover()
except Exception:
log.exception("askform: recovering links")
return max(0.5, soonest)
def run(self) -> None:
while not self._stop.is_set():
try:
delay = self.tick()
except Exception:
log.exception("askform mirror tick")
delay = self.slow
self._wake.wait(delay)
self._wake.clear()