Skip to content

The agent that grows with you

refactor(tui_gateway): control-ack builder, callback/pid/route helpers, envelope collapse (group E)

Teknium46afe9ff44c7
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index 379d12b1c92..8778acf48ed 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -47,6 +47,11 @@ class _HostTransport:
_FLUSH_RESERVE_SECS = 1.0
+# Fallback control.error text when a routed server method returns an error without a message.
+_CONTROL_FAILURES = {
+ "session.save": "session save failed", "session.compress": "session compression failed"}
+
+
class ComputeHost:
# frame ``type`` -> handler method name (resolved per call so instance
# monkeypatches of a handler still take effect).
@@ -113,11 +118,7 @@ class ComputeHost:
deadline = time.monotonic() + budget - min(_FLUSH_RESERVE_SECS, budget / 2.0)
while True:
remaining = deadline - time.monotonic()
- if remaining <= 0:
- break
- with self._turn_futures_lock:
- pending = [f for f in self._turn_futures if not f.done()]
- if not pending:
+ if remaining <= 0 or not self._live_turns():
break
# Bounded by ``remaining``: a flat sleep would overshoot the deadline and
# eat the reserve it protects (all of it for small ``wait``).
@@ -217,6 +218,7 @@ class ComputeHost:
from tui_gateway import server
session = self._ensure_server_session(server, frame)
text = frame.get("text") if "text" in frame else frame.get("prompt", "")
+ inflight = frame.get("text") if "text" in frame else frame.get("prompt")
with session["history_lock"]:
queued_gen = frame.get("queued_prompt_generation")
current_gen = int(session.get("_queued_prompt_generation", 0))
@@ -226,11 +228,8 @@ class ComputeHost:
if session.get("running"):
self._reply("turn.error", sid, request_id, message="session busy")
return
- session["running"] = True
- session["_turn_cancel_requested"] = False
- session["last_active"] = time.time()
- server._start_inflight_turn(
- session, frame.get("text") if "text" in frame else frame.get("prompt"))
+ session.update(running=True, _turn_cancel_requested=False, last_active=time.time())
+ server._start_inflight_turn(session, inflight)
self._reply("turn.started", sid, request_id, started_ns=now_ns())
with contextlib.suppress(Exception):
server._ensure_session_db_row(session)
@@ -371,17 +370,6 @@ class ComputeHost:
def _error(message: str) -> None:
self._reply("control.error", sid, request_id, message=message)
-
- def _ack(**extra: Any) -> None:
- self._reply("control.ack", sid, request_id, route_name=route_name, **extra)
-
- def _call_method(name: str, params: dict[str, Any], failure: str) -> dict | None:
- """Run a server method; emit control.error and return None on error."""
- response = server._methods[name](request_id, params)
- if "error" in response:
- _error(str(response["error"].get("message") or failure))
- return None
- return response
try:
from tui_gateway import server
route = MUTATOR_ROUTE_TABLE.get(route_name)
@@ -398,33 +386,11 @@ class ComputeHost:
if route_name == "reload.mcp":
self._handle_reload_mcp({**frame, "type": "reload_mcp"})
return
- if route_name == "session.save":
- response = _call_method("session.save", {"session_id": sid}, "session save failed")
- if response is not None:
- _ack(result=response.get("result") or {})
- return
- if route_name == "session.compress":
- focus_topic = str(frame.get("command") or "").removeprefix("/compress").strip()
- params = {"session_id": sid}
- if focus_topic:
- params["focus_topic"] = focus_topic
- response = _call_method("session.compress", params, "session compression failed")
- if response is None:
- return
- with session["history_lock"]:
- meta = _history_meta(session)
- _ack(
- result=response.get("result") or {}, **meta,
- session_info=server._session_info(session.get("agent"), session))
- return
- command = str(frame.get("command") or "")
- output = server._mirror_slash_side_effects(sid, session, command) if command else ""
- with session["history_lock"]:
- messages = server._history_to_messages(list(session.get("history") or []))
- meta = _history_meta(session)
- _ack(
- output=output, **meta, messages=messages,
- session_info=server._session_info(session.get("agent"), session))
+ ack = self._control_ack(server, frame, session)
+ if "error" in ack:
+ _error(ack["error"])
+ else:
+ self._reply("control.ack", sid, request_id, route_name=route_name, **ack)
except Exception as exc:
if route_name in {"session.compress", "slash.compress"}:
# The compress mirror defers the context-engine boundary notification until
@@ -435,20 +401,51 @@ class ComputeHost:
with contextlib.suppress(Exception):
from tui_gateway import server as _server
from agent.conversation_compression import (
- finalize_context_engine_compression_notification)
+ finalize_context_engine_compression_notification as _finalize)
_agent = (_server._sessions.get(sid) or {}).get("agent")
if _agent is not None:
- finalize_context_engine_compression_notification(_agent, committed=False)
+ _finalize(_agent, committed=False)
_error(str(exc))
+ def _control_ack(self, server: Any, frame: dict[str, Any], session: dict) -> dict:
+ """control.ack payload for one classified route, or ``{"error": message}``."""
+ sid = str(frame.get("sid") or "")
+ route_name = str(frame.get("route_name") or "")
+ command = str(frame.get("command") or "")
+ if route_name in {"session.save", "session.compress"}:
+ params = {"session_id": sid}
+ if route_name == "session.compress":
+ focus_topic = command.removeprefix("/compress").strip()
+ if focus_topic:
+ params["focus_topic"] = focus_topic
+ response = server._methods[route_name](frame.get("request_id"), params)
+ if "error" in response:
+ failure = _CONTROL_FAILURES[route_name]
+ return {"error": str(response["error"].get("message") or failure)}
+ ack = {"result": response.get("result") or {}}
+ if route_name == "session.save":
+ return ack
+ with session["history_lock"]:
+ ack.update(_history_meta(session))
+ else:
+ output = server._mirror_slash_side_effects(sid, session, command) if command else ""
+ with session["history_lock"]:
+ messages = server._history_to_messages(list(session.get("history") or []))
+ ack = {"output": output, **_history_meta(session), "messages": messages}
+ ack["session_info"] = server._session_info(session.get("agent"), session)
+ return ack
+
def _bump_progress(self) -> None:
with self._progress_lock:
self._progress_counter += 1
+ def _live_turns(self) -> list[concurrent.futures.Future]:
+ with self._turn_futures_lock:
+ return [f for f in self._turn_futures if not f.done()]
+
def _heartbeat_loop(self) -> None:
while not self._closed.wait(self._heartbeat_secs):
- with self._turn_futures_lock:
- active_turns = sum(1 for f in self._turn_futures if not f.done())
+ active_turns = len(self._live_turns())
with self._progress_lock:
counter = self._progress_counter
self.emit({
diff --git a/tui_gateway/compute_host_bridge.py b/tui_gateway/compute_host_bridge.py
index 8ae3628b92b..f5155f57a5a 100644
--- a/tui_gateway/compute_host_bridge.py
+++ b/tui_gateway/compute_host_bridge.py
@@ -11,7 +11,6 @@ from .method_ctx import HandlerRegistry, bind_module
_registry = HandlerRegistry()
-
_compute_host_supervisor = None
_compute_host_supervisor_lock = threading.Lock()
# Cap on how long session.compress blocks its RPC on the compute host. Must stay
diff --git a/tui_gateway/host_supervisor.py b/tui_gateway/host_supervisor.py
index 925bac33b64..5cec67c807d 100644
--- a/tui_gateway/host_supervisor.py
+++ b/tui_gateway/host_supervisor.py
@@ -78,6 +78,14 @@ def _build_sha() -> str:
return _check_output(["git", "rev-parse", "HEAD"], cwd=str(_repo_root())) or "unknown"
+def _call_logged(cb: Callable[[dict], None], frame: dict, failure: str) -> None:
+ """Invoke a host-frame callback; a raising callback is logged, never propagated."""
+ try:
+ cb(frame)
+ except Exception:
+ logger.exception(failure)
+
+
def _pid_alive(pid: int) -> bool:
if pid <= 0:
return False
@@ -307,23 +315,17 @@ class HostSupervisor:
with contextlib.suppress(queue.Full):
q.put_nowait(frame)
return
- if late is None:
- return
- try:
- late[1](frame)
- except Exception:
- logger.exception(
- "compute host late control ack handler failed (request_id=%s)", request_id)
+ if late is not None:
+ _call_logged(
+ late[1], frame,
+ f"compute host late control ack handler failed (request_id={request_id})")
def _spawn_locked(self, *, reason: str) -> None:
if self._stopped_respawning:
raise RuntimeError("compute host respawn disabled after crash loop")
self._hello_event.clear()
self._hello = {}
- env = hermes_subprocess_env(inherit_credentials=True)
- env.update(os.environ)
- if self.env:
- env.update(self.env)
+ env = {**hermes_subprocess_env(inherit_credentials=True), **os.environ, **(self.env or {})}
env["HERMES_COMPUTE_HOST_HEARTBEAT_SECS"] = str(self.heartbeat_secs)
root = str(_repo_root())
env.setdefault("PYTHONPATH", root)
@@ -437,10 +439,7 @@ class HostSupervisor:
with self._lock:
pending = self._pending_turns.pop(request_id, None)
if pending is not None and pending[1] is not None:
- try:
- pending[1](frame)
- except Exception:
- logger.exception("compute host turn completion callback failed")
+ _call_logged(pending[1], frame, "compute host turn completion callback failed")
def _wait_for_exit(self, proc: subprocess.Popen[str]) -> None:
code = proc.wait()
@@ -464,20 +463,16 @@ class HostSupervisor:
"jsonrpc": "2.0", "method": "event",
"params": {"type": "error", "session_id": sid, "payload": dict(failure)}})
if cb is not None:
- try:
- cb({"type": "turn.error", "sid": sid, "request_id": request_id, **failure})
- except Exception:
- logger.exception("compute host error callback failed")
+ frame = {"type": "turn.error", "sid": sid, "request_id": request_id, **failure}
+ _call_logged(cb, frame, "compute host error callback failed")
# A crashed host never emits the late acks timed-out control waiters still
# expect; fail them too so the client's "still running" notice can't hang.
with self._lock:
late = self._late_control_handlers
self._late_control_handlers = {}
for request_id, (_registered_at, handler) in late.items():
- try:
- handler({"type": "control.error", "request_id": request_id, **failure})
- except Exception:
- logger.exception("compute host late control error handler failed")
+ frame = {"type": "control.error", "request_id": request_id, **failure}
+ _call_logged(handler, frame, "compute host late control error handler failed")
def _maybe_respawn_after_crash(self) -> None:
now = time.monotonic()
diff --git a/tui_gateway/hosted_room_service.py b/tui_gateway/hosted_room_service.py
index 1c5086310b8..8923dde6bda 100644
--- a/tui_gateway/hosted_room_service.py
+++ b/tui_gateway/hosted_room_service.py
@@ -26,7 +26,6 @@ from tui_gateway.hosted_room_peer_http import PeerRunsHTTPClient, PeerRunsHTTPEr
from tui_gateway.hosted_room_peer_transport import (
HostedRoomPeerClient, PeerHostedRoomTransport, PeerMemberRoute, build_member_dispatch)
-
_HOSTED_ROOM_IDLE_FALLBACK_SECONDS = 5.0
_HOSTED_ROOM_ACTIVE_POLL_SECONDS = 0.25
_HOSTED_ROOM_TERMINAL_GRACE_SECONDS = 30.0
@@ -45,10 +44,8 @@ def _hosted_room_turn_timeout_seconds() -> float:
try:
agent_timeout = float(os.getenv("HERMES_AGENT_TIMEOUT", "1800"))
except (TypeError, ValueError):
- agent_timeout = 1800.0
- if agent_timeout <= 0:
- agent_timeout = 1800.0
- return agent_timeout + _HOSTED_ROOM_TERMINAL_GRACE_SECONDS
+ agent_timeout = 0.0
+ return (agent_timeout if agent_timeout > 0 else 1800.0) + _HOSTED_ROOM_TERMINAL_GRACE_SECONDS
def _grant_revoke_is_terminal(exc: PeerRunsHTTPError) -> bool:
@@ -143,9 +140,7 @@ class HostedRoomService:
def bindings(self) -> tuple[HostedRoomBinding, ...]:
local_gateway_id = hosted_rooms.local_authority_gateway_id()
return tuple(
- HostedRoomBinding(
- room_id=str(room["room_id"]), gateway_id=str(room["authority_gateway_id"]),
- authority_epoch=int(room["authority_epoch"]))
+ HostedRoomBinding(str(room["room_id"]), *_authority(room))
for room in hosted_rooms.list_rooms(self.db_path)
if str(room["authority_gateway_id"]) == local_gateway_id)
@@ -179,15 +174,9 @@ class HostedRoomService:
for status in statuses:
yield from driver.list_tasks(self.db_path, room_id=room_id, status=status)
- def _save_link(
- self, *, room_id: str, member_id: str, target_url: str, target_profile: str, grant: str,
- catalog: GatewayRoomCatalog, cancellation_scope_id: str, trace_id: str) -> None:
- hosted_room_links.save_room_link(
- self.db_path,
- hosted_room_links.make_stored_link(
- room_id=room_id, member_id=member_id, target_url=target_url,
- target_profile=target_profile, grant=grant, catalog=catalog,
- cancellation_scope_id=cancellation_scope_id, trace_id=trace_id))
+ def _save_link(self, **link: Any) -> None:
+ """Persist one stored link (``make_stored_link`` keyword fields)."""
+ hosted_room_links.save_room_link(self.db_path, hosted_room_links.make_stored_link(**link))
def register_peer_route(
self, *, room_id: str, member_id: str, route: PeerMemberRoute,
@@ -212,12 +201,17 @@ class HostedRoomService:
cancellation_scope_id=route.cancellation_scope_id, trace_id=route.trace_id)
# Persistence is the publication boundary: a failed disk write must never
# leave a process-local route that disappears after restart.
- with self._policy_lock:
- self.peer_routes[(room_id, member_id)] = route
- self.peer_clients[(room_id, member_id)] = client
- self._peer_route_status[(room_id, member_id)] = "ready"
+ self._publish_route((room_id, member_id), route, client)
self.runtime.wakeup()
+ def _publish_route(self, key: tuple[str, str], route: PeerMemberRoute, client=None) -> None:
+ """Make a persisted route live as ``ready`` (and bind its client when given)."""
+ with self._policy_lock:
+ self.peer_routes[key] = route
+ if client is not None:
+ self.peer_clients[key] = client
+ self._peer_route_status[key] = "ready"
+
def revoke_room_routes(self, room_id: str) -> int:
"""Revoke and forget every scoped peer route for one room. Remote revocation is the
boundary: an unreachable target leaves the room intact for retry rather than
@@ -236,9 +230,8 @@ class HostedRoomService:
hosted_rooms.delete_room_link_records(self.db_path, room_id=room_id)
with self._policy_lock:
for key, _route in routes:
- self.peer_routes.pop(key, None)
- self._peer_route_status.pop(key, None)
- self.peer_clients.pop(key, None)
+ for table in (self.peer_routes, self._peer_route_status, self.peer_clients):
+ table.pop(key, None)
return len(routes)
def _resolve_member_transport(self, binding: HostedRoomBinding, task: Mapping[str, Any]):
@@ -264,8 +257,7 @@ class HostedRoomService:
def set_status(status: str):
return lambda: self._set_route_status(binding.room_id, member_id, status)
tracked_client = _RouteStatusPeerClient(
- client,
- on_ready=set_status("ready"),
+ client, on_ready=set_status("ready"),
on_reauthorization=set_status("needs_reauthorization"),
on_unavailable=set_status("unavailable"),
on_refreshed=lambda grant, catalog=None: self._rotate_route_grant(
@@ -303,12 +295,11 @@ class HostedRoomService:
def _member_is_peer(self, room_id: str, member_id: str) -> bool:
for member in self._room(room_id).get("members") or []:
- if not isinstance(member, Mapping):
- continue
- if str(member.get("member_id") or member.get("profile") or "") != member_id:
- continue
- target = member.get("target")
- return isinstance(target, Mapping) and target.get("kind") == "peer"
+ if (
+ isinstance(member, Mapping)
+ and str(member.get("member_id") or member.get("profile") or "") == member_id):
+ target = member.get("target")
+ return isinstance(target, Mapping) and target.get("kind") == "peer"
return False
def _set_route_status(self, room_id: str, member_id: str, status: str) -> None:
@@ -361,17 +352,14 @@ class HostedRoomService:
room_id=room_id, member_id=member_id, target_url=stored.target_url,
target_profile=stored.target_profile, grant=grant, catalog=catalog or stored.catalog,
cancellation_scope_id=stored.cancellation_scope_id, trace_id=stored.trace_id)
- with self._policy_lock:
- self.peer_routes[key] = rotated_route
- self._peer_route_status[key] = "ready"
+ self._publish_route(key, rotated_route)
def _route_statuses(self, room_id: str | None = None) -> list[dict[str, str]]:
with self._policy_lock:
- rows = [
- {"room_id": key[0], "member_id": key[1], "status": status}
- for key, status in self._peer_route_status.items()
- if room_id is None or key[0] == room_id]
- return sorted(rows, key=lambda row: (row["room_id"], row["member_id"]))
+ rows = sorted(self._peer_route_status.items())
+ return [
+ {"room_id": key[0], "member_id": key[1], "status": status}
+ for key, status in rows if room_id is None or key[0] == room_id]
def _events(self, room_id: str) -> list[dict[str, Any]]:
events: list[dict[str, Any]] = []
@@ -423,17 +411,14 @@ class HostedRoomService:
return
gateway_id, epoch = _authority(room)
hosted_rooms.append_event(
- self.db_path,
- room_id=str(room["room_id"]),
+ self.db_path, room_id=str(room["room_id"]),
event_id=f"dactivity:{decision.discussion_event_id}:{decision.reason}",
- kind="room.activity",
- actor={"kind": "gateway", "id": gateway_id},
+ kind="room.activity", actor={"kind": "gateway", "id": gateway_id},
payload={
"status": decision.status, "reason_code": decision.reason,
"thread_id": decision.thread_id,
"discussion_event_id": decision.discussion_event_id},
- authority_gateway_id=gateway_id,
- authority_epoch=epoch)
+ authority_gateway_id=gateway_id, authority_epoch=epoch)
def prepare_room(self, binding: HostedRoomBinding) -> None:
with self._policy_lock:
@@ -445,7 +430,7 @@ class HostedRoomService:
self.policy_checkpoint.compact_completed(room_id=binding.room_id)
driver.prune_published_terminal_tasks(
self.db_path, room_id=binding.room_id, clock=self.runtime.clock)
- if any(True for _ in self._list_tasks(binding.room_id, _LIVE_STATUSES)):
+ if next(iter(self._list_tasks(binding.room_id, _LIVE_STATUSES)), None) is not None:
return
decision = discussion.plan_next_task(
room, list(snapshot.events), local_profiles=self.local_profiles(),
@@ -457,14 +442,9 @@ class HostedRoomService:
# A stop can race the policy read from another process. Re-read after
# admission and cancel before the runtime can execute a task whose
# source event is now behind the room stop fence.
- stopped_through_seq = self._policy_snapshot(
- self._room(binding.room_id)
- ).stopped_through_seq
- if (
- decision.source_event_seq is not None
- and decision.source_event_seq < stopped_through_seq):
- self.runtime.cancel(
- decision.task.identity, cancel_id=f"stop-fence:{stopped_through_seq}")
+ fence = self._policy_snapshot(self._room(binding.room_id)).stopped_through_seq
+ if decision.source_event_seq is not None and decision.source_event_seq < fence:
+ self.runtime.cancel(decision.task.identity, cancel_id=f"stop-fence:{fence}")
elif decision.status in {"settled", "bounded"}:
self._append_room_status(room, decision)
diff --git a/tui_gateway/methods_groups.py b/tui_gateway/methods_groups.py
index 7eac62cb1c2..a0480aedfef 100644
--- a/tui_gateway/methods_groups.py
+++ b/tui_gateway/methods_groups.py
@@ -8,6 +8,7 @@ helpers reach them through keyword defaults. ``_room_method`` is the shared enve
from .method_ctx import HandlerRegistry
+import contextlib
import importlib
import os
import threading
@@ -112,14 +113,11 @@ def _api_server_key(profile: str | None = None) -> str:
# An explicit routed profile is authoritative. Never borrow the
# process/default profile's API key on a multiplexed gateway.
return str(build_profile_secret_scope(home).get("API_SERVER_KEY") or "").strip()
- try:
+ scoped = ""
+ with contextlib.suppress(Exception):
from agent.secret_scope import get_secret
scoped = (get_secret("API_SERVER_KEY", "") or "").strip()
- if scoped:
- return scoped
- except Exception:
- pass
- return (os.getenv("API_SERVER_KEY") or "").strip()
+ return scoped or (os.getenv("API_SERVER_KEY") or "").strip()
def _profile_execution_policy(profile: str) -> dict:
@@ -154,8 +152,7 @@ def _room_link_run_storage_durable() -> bool:
with _run_store_lock:
store = getattr(_bound_server, "_run_idempotency_store", None)
if store is None:
- store = RunIdempotencyStore()
- _bound_server._run_idempotency_store = store
+ store = _bound_server._run_idempotency_store = RunIdempotencyStore()
return bool(getattr(store, "durable", False))
@@ -172,6 +169,14 @@ def _grant_expiry(claims: dict) -> float:
return float(claims.get("status_expires_at", claims["expires_at"]))
+def _room_error_class(replica_only: bool) -> type:
+ if replica_only:
+ from gateway.hosted_room_replicas import ReplicaError
+ return ReplicaError
+ from gateway.hosted_rooms import HostedRoomError
+ return HostedRoomError
+
+
def _room_method(
name: str, *, code: int, room_code: int | None = None, replica_only: bool = False,
with_reason: bool = True, service_code: int | None = None,
@@ -183,6 +188,7 @@ def _room_method(
``HostedRoomError`` (only ``ReplicaError`` when ``replica_only``) to a 4xxx client
error with ``{"reason"}`` data when ``with_reason``; anything else maps to ``code``.
"""
+ error_class = _room_error_class # closure cell: handlers run under server.py globals
def dec(fn):
def handler(rid, params: dict) -> dict:
@@ -198,16 +204,9 @@ def _room_method(
try:
return fn(*args)
except Exception as exc:
- if room_code is not None:
- from gateway.hosted_rooms import HostedRoomError
- klass = HostedRoomError
- if replica_only:
- from gateway.hosted_room_replicas import ReplicaError
- klass = ReplicaError
- if isinstance(exc, klass):
- reason = getattr(exc, "reason", None) if with_reason else None
- data = {"reason": reason} if reason else None
- return _err(rid, room_code, str(exc), data)
+ if room_code is not None and isinstance(exc, error_class(replica_only)):
+ reason = getattr(exc, "reason", None) if with_reason else None
+ return _err(rid, room_code, str(exc), {"reason": reason} if reason else None)
return _err(rid, code, str(exc))
handler.__doc__ = fn.__doc__
return method(name)(handler)
@@ -328,25 +327,22 @@ def _(rid, params: dict, service) -> dict:
member_id = str(params.get("member_id") or "")
home_install_id = local_authority_gateway_id()
home_room = room_state(service.db_path, room_id=room_id)
+ expected_scope = {
+ "room_id": room_id, "home_install_id": home_install_id,
+ "authority_gateway_id": home_room.get("authority_gateway_id"),
+ "member_id": member_id, "target_profile": target_profile}
if (
- probe.get("room_id") != room_id
- or probe.get("home_install_id") != home_install_id
- or probe.get("authority_gateway_id") != home_room.get("authority_gateway_id")
- or int(probe.get("authority_epoch") or 0) != int(home_room.get("authority_epoch") or 0)
- or probe.get("member_id") != member_id
- or probe.get("target_profile") != target_profile):
+ any(probe.get(key) != value for key, value in expected_scope.items())
+ or int(probe.get("authority_epoch") or 0) != int(home_room.get("authority_epoch") or 0)):
raise ValueError("room grant scope does not match this route")
route = PeerMemberRoute(
- home_install_id=home_install_id,
- member_id=member_id,
- target_install_id=catalog.installation_id,
- target_profile=target_profile,
+ home_install_id=home_install_id, member_id=member_id,
+ target_install_id=catalog.installation_id, target_profile=target_profile,
capability_digest=catalog.catalog_digest,
execution_policy_digest=catalog.execution_policy.policy_digest,
cancellation_scope_id=str(
params.get("cancellation_scope_id") or f"cancel-{params.get('room_id') or ''}"),
- trace_id=str(params.get("trace_id") or f"trace-{os.urandom(16).hex()}"),
- grant=grant)
+ trace_id=str(params.get("trace_id") or f"trace-{os.urandom(16).hex()}"), grant=grant)
service.register_peer_route(
room_id=room_id, member_id=member_id, route=route, client=client, target_url=target_url,
catalog=catalog)
@@ -481,8 +477,7 @@ def _(rid, params: dict, service) -> dict:
def _passthrough(
name: str, module: str, fn_name: str, doc: str, *, code: int, room_code: int,
- params: tuple, replica_only: bool = False, wrap: str | None = None,
-) -> None:
+ params: tuple, replica_only: bool = False, wrap: str | None = None) -> None:
"""Register a method whose result is ``module.fn(db_path, **params)`` verbatim (or under
key ``wrap``). ``params`` items are ``key`` (-> ``params.get(key)``) or
``(key, extractor(params))``."""
@@ -490,8 +485,8 @@ def _passthrough(
@_room_method(
name, code=code, room_code=room_code, replica_only=replica_only,
with_reason=not replica_only, db=True)
- def handler(rid, params_in: dict, db_path) -> dict:
- fn = getattr(importlib.import_module(module), fn_name)
+ def handler(rid, params_in: dict, db_path, _import=importlib.import_module) -> dict:
+ fn = getattr(_import(module), fn_name)
kwargs = {}
for spec in params:
if isinstance(spec, str):