Files
Gabriel VidalandClaude Opus 5.5 9ebc2de810 perf(plugins): plugin pages paint at once and look native
Speed
- seed_registry.effective() cached the "any provider plugin active?" check on
  the plugin store's version: it deep-copied all 46 manifests on every price
  lookup (9.4 ms → 8 µs per rates_for) — half the hub's CPU, and what made
  Graph / Goals / Plan usage bridges take 17–180 s.
- GET /api/plugins/ui: the slim list every page reads (UI descriptors,
  provides, each active plugin's glyph + config), a few KB instead of the
  253 KB full list, which is now for Settings → Plugins only.
- Identical readOnly actions in flight share one handler run
  (plugins/singleflight.py).
- composer.shortcuts / composer.mode are stale-while-revalidate
  (plugins/swr.py); inbox.waiting stays fresh but concurrent calls share one
  run, auto-archive reuses a ≤ 30 s answer; provider lookups copy only the
  matching records (store.active_providing / active_ids).
- aiAgentPlugin.query(): host-kept reads — the last answer at once (own
  IndexedDB store, not busted per deploy), then the fresh one; learned
  preload starts a page's reads as its route mounts; UI documents kept the
  same way.

UI
- The page's subtitle, buttons and a refresh that spins while its reads run
  live in the app's header (setHeader / onHeaderAction / onRefresh); the
  frame is borderless across the content area; a skeleton (after 150 ms)
  holds its place until the frame painted, then it fades in.
- A UI kit (aia-* classes, the app's font and tokens) injected into every
  plugin frame.
- Dashboards / Files nav: plugin pages in the same rearrangeable list, with
  the plugin's description as subtitle.
- Mock: a demo plugin page (/plugins/demo/board?mock=1).

Docs: docs/plugins.md → "Pages that feel native: reads, header, kit".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 21:22:43 +01:00

93 lines
3.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Stale-while-revalidate for what the host asks plugins on every page load
(composer shortcuts and modes, ``plugins/shortcuts.py`` / ``waiting.py``).
Each of those is a handler subprocess (0.3–2 s on a busy hub). A fresh entry
is served as is; an entry past ``ttl`` but within ``max_stale`` is served at
once while one background thread runs the plugin again; only a missing (or
too old) entry makes the caller wait — and concurrent callers of that key
wait for one run, not one each.
"""
from __future__ import annotations
import logging
import threading
import time
from collections.abc import Callable
from typing import Any
log = logging.getLogger(__name__)
class SWRCache:
def __init__(self, ttl: float, max_stale: float, name: str = "swr"):
self.ttl = ttl
self.max_stale = max_stale
self.name = name
self._lock = threading.Lock()
self._data: dict[str, tuple[float, Any]] = {}
# key → Event set when its run ends (a cold miss or a refresh)
self._running: dict[str, threading.Event] = {}
def get(self, key: str, compute: Callable[[], Any]) -> Any:
now = time.monotonic()
with self._lock:
hit = self._data.get(key)
age = None if hit is None else now - hit[0]
if hit is not None and age is not None and age < self.ttl:
return hit[1]
running = self._running.get(key)
if hit is not None and age is not None and age < self.max_stale:
if running is None:
self._running[key] = threading.Event()
threading.Thread(target=self._refresh, args=(key, compute),
name=f"{self.name}-refresh", daemon=True).start()
return hit[1]
if running is None:
self._running[key] = ev = threading.Event()
leader = True
else:
ev, leader = running, False
if not leader:
ev.wait(timeout=60)
with self._lock:
hit = self._data.get(key)
if hit is not None:
return hit[1]
return compute()
return self._run(key, compute, ev)
def _refresh(self, key: str, compute: Callable[[], Any]) -> None:
with self._lock:
ev = self._running.get(key) or threading.Event()
try:
self._run(key, compute, ev)
except Exception as e: # noqa: BLE001 — the stale value stays served
log.warning("%s refresh of %s failed: %s", self.name, key, e)
def _run(self, key: str, compute: Callable[[], Any], ev: threading.Event) -> Any:
try:
value = compute()
with self._lock:
# A drop() while this ran wins: its key is gone from _running.
if self._running.get(key) is ev:
self._data[key] = (time.monotonic(), value)
return value
finally:
with self._lock:
if self._running.get(key) is ev:
self._running.pop(key, None)
ev.set()
def drop(self, match: Callable[[str], bool] | None = None) -> None:
"""Forget every entry (or those whose key ``match``es) — a plugin
changed; a run in flight for one of them is not stored."""
with self._lock:
for k in [k for k in self._data if match is None or match(k)]:
self._data.pop(k, None)
for k in [k for k in self._running if match is None or match(k)]:
self._running.pop(k, None)
def clear(self) -> None:
self.drop(None)