Files
gabrielvidalandClaude Fable 5.2 efdd83de18 Merge main (batch plugin reads, #32) into hub-mcp-plugin
The endpoint-only guard moves into plugins/batch.resolve_call — the one rule
set the action route, its GET and the batch read share since #32 — so an
endpoint's action is refused on all three. OpenAPI, the orval types and the
permissions matrix regenerated on the merged tree.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 13:54:01 +01:00

350 lines
15 KiB
Python

"""Many plugin reads in one request — what the conversation's Details drawer
asks when it opens (since 2026-11-28, the details-panel load work).
Each ``conversation.details`` slot used to load its document, then post its
own ``readOnly`` action from inside its frame: a dozen frames, a dozen HTML
fetches and a dozen action requests queued behind the thread's read on a busy
hub. Two endpoints make that two requests:
* ``POST|GET /api/plugins/batch-read`` (:func:`batch_read`) — up to
:data:`MAX_ITEMS` ``readOnly`` actions of any active plugins, run at once
(at most :data:`BATCH_CONCURRENCY` per batch, so one batch never takes every
``REQUEST_SCRIPT_SLOTS``), each through :mod:`plugins.singleflight` (a
header chip and the drawer asking the same thing share one handler run),
each answered on its own — one failing item never fails the batch. A
success is kept a few seconds (:class:`ReadCache`): 30 s for a finished
conversation's read, 3 s for a running one's, 5 s for a read naming no
conversation — and keyed on a stamp of the conversation's summary + meta,
so a new turn misses at once. ``fresh`` skips it; any write to the plugin
(install, reload, config, secret, grant, ``hub/changed``) drops it
(:func:`invalidate`).
* ``GET /api/plugins/ui-bundle?where=`` (:func:`ui_bundle`) — every active
slot document for one place, in one body, ``ETag``'d on its files.
Authorization is :func:`resolve_call`, the one ``_invoke_action`` uses.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import pathlib
import threading
import time
from collections import OrderedDict
from dataclasses import dataclass
from typing import Any
from fastapi import HTTPException
from starlette.concurrency import run_in_threadpool
from plugins import singleflight
from plugins.runner import ActionError, requester_context, run_script
from plugins.store import OWNER_UID
MAX_ITEMS = 32
BODY_MAX = 32 * 1024
GET_ITEMS_MAX = 16 * 1024
PAYLOAD_MAX = 8 * 1024
KEY_MAX = 128
BATCH_CONCURRENCY = 5
UI_DOC_MAX = 512 * 1024
TTL_FINISHED = 30.0
TTL_RUNNING = 3.0
TTL_NO_CONVERSATION = 5.0
_CONV_KEYS = ("conversationId", "sessionId", "sid")
def _uid(caller) -> str:
return OWNER_UID if caller.is_owner else caller.id
# ── one action call, resolved as the caller ───────────────────────────────────
@dataclass
class Call:
uid: str
run_uid: str
pid: str
action: str
rec: dict[str, Any]
act: dict[str, Any]
grant: dict[str, Any] | None
using_own: bool
requester: dict[str, Any] | None
context: dict[str, Any] | None
def run(self, deps, payload: dict[str, Any]):
return run_in_threadpool(
run_script, deps, deps.plugin_store, self.run_uid, self.rec, self.act["script"],
payload=payload,
timeout_sec=int(self.act.get("timeoutSec") or 30),
grant=self.grant,
using_own_secret=self.using_own,
requester=self.requester,
context=self.context,
)
def flight_key(self, payload: dict[str, Any]) -> tuple:
# The same key ``_invoke_action`` shares a read under.
return singleflight.key_of(self.uid, self.run_uid, self.pid, self.action, payload=payload)
def resolve_call(deps, caller, pid: str, action: str, *, read: bool) -> Call:
"""Who runs ``pid``'s ``action`` for ``caller`` and with what — or the
HTTPException ``/api/plugins/{pid}/actions/{action}`` answers."""
uid = _uid(caller)
rec, grant, is_managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
if not rec:
raise HTTPException(404, f"plugin '{pid}' not active")
act = (rec["manifest"].get("actions") or {}).get(action)
if not act:
raise HTTPException(404, f"action '{action}' not declared")
from plugins.endpoints import endpoint_actions
if action in endpoint_actions(rec["manifest"]):
# An endpoint's action answers HTTP only (plugins/endpoints.py): its
# payload is the host's word on who is asking — never a caller's.
raise HTTPException(403, {"message": f"action '{action}' answers HTTP only",
"kind": "endpoint_only"})
if read and not act.get("readOnly"):
raise HTTPException(405, f"action '{action}' is not read-only: POST it")
if act.get("ownerOnly") and not caller.is_owner:
raise HTTPException(403, f"action '{action}' is owner-only")
using_own = deps.plugin_store.has_user_override_secret(uid, pid, rec["manifest"]) if is_managed else False
run_uid = uid
requester = None
if act.get("runAs") == "owner" and is_managed and not caller.is_owner:
requester = requester_context(deps, uid, grant)
run_uid = OWNER_UID
# The owner looking through a guest's eyes: the plugin can keep a preview
# from counting as the guest's own visit (What's new's seen marks).
context = {"impersonatedBy": caller.impersonator} if caller.impersonator else None
return Call(uid, run_uid, pid, action, rec, act, grant, using_own, requester, context)
# ── the short read cache ──────────────────────────────────────────────────────
class ReadCache:
"""A bounded LRU of read results, each with its expiry. A per-plugin
generation makes :meth:`invalidate` win over a read still in flight: a
result whose plugin changed while it ran is not kept."""
def __init__(self, max_entries: int = 512):
self.max = max_entries
self._lock = threading.Lock()
self._data: OrderedDict[tuple, tuple[float, str, Any]] = OrderedDict()
self._gen: dict[str, int] = {}
self._all = 0
def generation(self, pid: str) -> tuple[int, int]:
with self._lock:
return self._all, self._gen.get(pid, 0)
def get(self, key: tuple) -> tuple[bool, Any]:
now = time.monotonic()
with self._lock:
hit = self._data.get(key)
if not hit:
return False, None
if hit[0] <= now:
self._data.pop(key, None)
return False, None
self._data.move_to_end(key)
return True, hit[2]
def put(self, key: tuple, pid: str, value: Any, ttl: float, gen: tuple[int, int]) -> None:
with self._lock:
if (self._all, self._gen.get(pid, 0)) != gen:
return
self._data[key] = (time.monotonic() + ttl, pid, value)
self._data.move_to_end(key)
while len(self._data) > self.max:
self._data.popitem(last=False)
def invalidate(self, pid: str | None = None) -> None:
with self._lock:
if pid is None:
self._all += 1
self._data.clear()
return
self._gen[pid] = self._gen.get(pid, 0) + 1
for k in [k for k, v in self._data.items() if v[1] == pid]:
self._data.pop(k, None)
def __len__(self) -> int:
return len(self._data)
CACHE = ReadCache()
def invalidate(pid: str | None = None) -> None:
"""Drop the cached reads of ``pid`` (every plugin's when None)."""
CACHE.invalidate(pid)
def conversation_stamp(deps, payload: dict[str, Any]) -> tuple[tuple, float]:
"""``(stamp, ttl)`` of the conversation a read names: a stamp of its
summary + meta (a new turn, a new stamp), the TTL its state allows."""
raw = next((payload[k] for k in _CONV_KEYS if isinstance(payload.get(k), str) and payload[k]), None)
if raw is None:
return (), TTL_NO_CONVERSATION
try:
from plugins.hubchecks import locate
hit = locate(deps, raw)
except Exception: # noqa: BLE001 — a cache key never fails a read
hit = None
if not hit:
return ("?", raw), TTL_RUNNING
_cid, _path, s = hit
sid = s.get("sessionId") or raw
try:
meta = deps.meta_store.peek(sid) or {}
except Exception: # noqa: BLE001
meta = {}
try:
from core import liveruns
live = liveruns.alive(sid)
except Exception: # noqa: BLE001
live = False
running = bool(live or meta.get("state") == "running")
stamp = (s.get("endedAt"), s.get("turns", s.get("userTurns")), s.get("cost"), id(meta), running)
return stamp, (TTL_RUNNING if running else TTL_FINISHED)
def _canon(payload: Any) -> str:
return json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)
# ── the batch ─────────────────────────────────────────────────────────────────
def parse_items(raw: Any) -> list[dict[str, Any]]:
"""The validated items of a batch body (400 on a malformed one)."""
if not isinstance(raw, list):
raise HTTPException(400, "items must be a list")
if len(raw) > MAX_ITEMS:
raise HTTPException(400, f"at most {MAX_ITEMS} items")
out: list[dict[str, Any]] = []
keys: set[str] = set()
for i, it in enumerate(raw):
if not isinstance(it, dict):
raise HTTPException(400, f"items[{i}] must be an object")
key, pid, action = it.get("key"), it.get("pluginId"), it.get("action")
if not isinstance(key, str) or not 1 <= len(key) <= KEY_MAX:
raise HTTPException(400, f"items[{i}].key must be 1..{KEY_MAX} characters")
if key in keys:
raise HTTPException(400, f"items[{i}].key repeats {key!r}")
if not isinstance(pid, str) or not pid or not isinstance(action, str) or not action:
raise HTTPException(400, f"items[{i}] needs pluginId and action")
payload = it.get("payload")
if payload is None:
payload = {}
if not isinstance(payload, dict):
raise HTTPException(400, f"items[{i}].payload must be a JSON object")
if len(_canon(payload).encode("utf-8")) > PAYLOAD_MAX:
raise HTTPException(413, f"items[{i}].payload too large")
keys.add(key)
out.append({"key": key, "pluginId": pid, "action": action, "payload": payload,
"fresh": bool(it.get("fresh"))})
return out
def _error(status: int, err: Any) -> dict[str, Any]:
if isinstance(err, dict):
err = err.get("message") or json.dumps(err)
return {"ok": False, "status": status, "error": str(err)}
async def _one(deps, caller, item: dict[str, Any], fresh: bool, gate: asyncio.Semaphore) -> dict[str, Any]:
payload = item["payload"]
try:
call = resolve_call(deps, caller, item["pluginId"], item["action"], read=True)
except HTTPException as e:
if e.status_code == 405:
return _error(405, "action is not read-only")
return _error(e.status_code, e.detail)
fp = call.rec.get("fingerprint") or ""
try:
stamp, ttl = await run_in_threadpool(conversation_stamp, deps, payload)
except Exception: # noqa: BLE001
stamp, ttl = ("!",), 0.0
ckey = (call.uid, call.run_uid, call.pid, fp, call.action, _canon(payload), stamp,
(call.context or {}).get("impersonatedBy"))
if not (fresh or item["fresh"]):
hit, value = CACHE.get(ckey)
if hit:
return {"ok": True, "data": value, "cached": True}
gen = CACHE.generation(call.pid)
try:
async with gate:
data = await singleflight.shared(call.flight_key(payload), lambda: call.run(deps, payload))
except ActionError as e:
return _error(e.status, e.message)
except HTTPException as e:
return _error(e.status_code, e.detail)
except Exception as e: # noqa: BLE001 — one item never fails the batch
return _error(500, f"{type(e).__name__}: {e}")
if ttl > 0:
CACHE.put(ckey, call.pid, data, ttl, gen)
return {"ok": True, "data": data, "cached": False}
async def batch_read(deps, caller, items: list[dict[str, Any]], *, fresh: bool = False) -> dict[str, Any]:
"""``{"results": {key: {ok, data, cached} | {ok: false, status, error}}}``."""
gate = asyncio.Semaphore(BATCH_CONCURRENCY)
answers = await asyncio.gather(*(_one(deps, caller, it, fresh, gate) for it in items))
return {"results": {it["key"]: a for it, a in zip(items, answers)}}
# ── every slot document of one place ─────────────────────────────────────────
def _active_pids(deps, caller) -> list[str]:
"""The caller's active plugins in ``GET /api/plugins/ui``'s order: their
own, then (a guest) the managed ones granted to them."""
uid = _uid(caller)
store = deps.plugin_store
pids = [pid for pid, _mf, _cfg in store.active_manifests(uid)]
if not caller.is_owner:
seen = set(pids)
for rec in store.managed_plugins():
if rec["id"] not in seen and store.effective_grant(caller.id, rec["id"], rec["manifest"]).get("enabled"):
pids.append(rec["id"])
return pids
def ui_bundle(deps, caller, where: str, if_none_match: str | None = None) -> tuple[str, dict[str, Any] | None]:
"""``(version, {where, version, docs: {"<pid>:<slot>": html}})`` — the
``version`` a hash of each file's identity (the ETag); the body is None
when ``if_none_match`` already names it (nothing is read then)."""
uid = _uid(caller)
files: list[tuple[str, pathlib.Path]] = []
ident: list[tuple] = []
for pid in _active_pids(deps, caller):
rec, _grant, _managed = deps.plugin_store.resolve_active_for_caller(uid, pid)
if not rec:
continue
slots = [s for s in ((rec["manifest"].get("ui") or {}).get("slots") or []) if s.get("where") == where]
if not slots:
continue
root = pathlib.Path(rec["dir"]).resolve()
for sl in slots:
target = (root / str(sl.get("html") or "")).resolve()
try:
target.relative_to(root)
st = target.stat()
except (ValueError, OSError):
continue
if not target.is_file():
continue
files.append((f"{pid}:{sl['id']}", target))
ident.append((pid, rec.get("fingerprint") or "", sl["id"], st.st_mtime_ns, st.st_size))
version = hashlib.sha256(repr(sorted(ident)).encode()).hexdigest()[:16]
if if_none_match and version in {t.strip().strip('"').removeprefix('W/"') for t in if_none_match.split(",")}:
return version, None
docs: dict[str, str] = {}
for key, target in files:
try:
docs[key] = target.read_text(encoding="utf-8", errors="replace")[:UI_DOC_MAX]
except OSError:
continue
return version, {"where": where, "version": version, "docs": docs}