refactor(adapters/api_server): 10589->8871; extract OpenAI-compatible routes into api_server_openai_routes.py, dedupe SSE/response builders, drop dead idempotency acknowledge path
This commit is contained in:
+836
-3456
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -11,6 +11,8 @@ try:
|
||||
except ImportError:
|
||||
web = None # type: ignore[assignment]
|
||||
|
||||
from gateway.platforms.api_server_room_grants import _json_error
|
||||
|
||||
|
||||
async def _ensure_hosted_member_session(self, dispatch: Any) -> str:
|
||||
"""Create or verify the target's canonical hidden group session.
|
||||
@@ -30,36 +32,45 @@ async def _ensure_hosted_member_session(self, dispatch: Any) -> str:
|
||||
)
|
||||
session_id = f"room_{hashlib.sha256(seed.encode()).hexdigest()[:32]}"
|
||||
|
||||
def ensure() -> str:
|
||||
def atomic(conn):
|
||||
row = conn.execute(
|
||||
"SELECT id, title, source FROM sessions WHERE id=?",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
if row["title"] != title or row["source"] != "bot_room":
|
||||
raise RuntimeError("room session identity conflicts with existing data")
|
||||
return session_id
|
||||
clean_title = db.sanitize_title(title)
|
||||
conflict = conn.execute(
|
||||
"SELECT id FROM sessions WHERE title=? AND id!=?",
|
||||
(clean_title, session_id),
|
||||
).fetchone()
|
||||
if conflict:
|
||||
raise RuntimeError(
|
||||
"Another group already uses this room title on the target gateway. "
|
||||
"Rename or migrate that group before retrying."
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO sessions(id, source, title, hidden, started_at) "
|
||||
"VALUES(?, 'bot_room', ?, 1, ?)",
|
||||
(session_id, clean_title, time.time()),
|
||||
)
|
||||
def atomic(conn):
|
||||
row = conn.execute(
|
||||
"SELECT id, title, source FROM sessions WHERE id=?", (session_id,)
|
||||
).fetchone()
|
||||
if row is not None:
|
||||
if row["title"] != title or row["source"] != "bot_room":
|
||||
raise RuntimeError("room session identity conflicts with existing data")
|
||||
return session_id
|
||||
clean_title = db.sanitize_title(title)
|
||||
conflict = conn.execute(
|
||||
"SELECT id FROM sessions WHERE title=? AND id!=?", (clean_title, session_id)
|
||||
).fetchone()
|
||||
if conflict:
|
||||
raise RuntimeError(
|
||||
"Another group already uses this room title on the target gateway. "
|
||||
"Rename or migrate that group before retrying."
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO sessions(id, source, title, hidden, started_at) "
|
||||
"VALUES(?, 'bot_room', ?, 1, ?)",
|
||||
(session_id, clean_title, time.time()),
|
||||
)
|
||||
return session_id
|
||||
|
||||
return db._execute_write(atomic)
|
||||
return await asyncio.to_thread(db._execute_write, atomic)
|
||||
|
||||
return await asyncio.to_thread(ensure)
|
||||
|
||||
def _room_dispatch_error(exc: Exception, *, _openai_error) -> "web.Response":
|
||||
message = str(exc)
|
||||
lowered = message.lower()
|
||||
if "execution policy" in lowered or "remote room execution requires" in lowered:
|
||||
message = "Room execution policy changed; reauthorization is required."
|
||||
code = "room_execution_policy_changed"
|
||||
elif "capability catalog changed" in lowered:
|
||||
message = "Room capability catalog changed; reauthorization is required."
|
||||
code = "room_capability_catalog_changed"
|
||||
else:
|
||||
code = "invalid_room_dispatch"
|
||||
return _json_error(_openai_error, message, code=code, status=403)
|
||||
|
||||
|
||||
async def _normalize_room_dispatch(
|
||||
@@ -77,38 +88,23 @@ async def _normalize_room_dispatch(
|
||||
if not room_token:
|
||||
return body, None
|
||||
|
||||
allowed_room_fields = {"input", "hosted_room_dispatch"}
|
||||
if not isinstance(body, dict) or set(body) - allowed_room_fields:
|
||||
return body, web.json_response(
|
||||
_openai_error(
|
||||
"Room dispatch accepts only input and hosted_room_dispatch.",
|
||||
code="invalid_room_dispatch",
|
||||
),
|
||||
status=400,
|
||||
if not isinstance(body, dict) or set(body) - {"input", "hosted_room_dispatch"}:
|
||||
return body, _json_error(
|
||||
_openai_error, "Room dispatch accepts only input and hosted_room_dispatch.",
|
||||
code="invalid_room_dispatch", status=400,
|
||||
)
|
||||
try:
|
||||
from gateway import hosted_rooms
|
||||
from gateway.hosted_room_peer import (
|
||||
GatewayRoomCatalog,
|
||||
HostedMemberDispatch,
|
||||
PROTOCOL_VERSION as ROOM_LINK_PROTOCOL_VERSION,
|
||||
catalog_mapping,
|
||||
verify_room_grant,
|
||||
)
|
||||
from gateway.hosted_room_execution_policy import (
|
||||
RoomExecutionPolicy,
|
||||
execution_policy_mapping,
|
||||
)
|
||||
from gateway.hosted_room_execution_policy import RoomExecutionPolicy
|
||||
from gateway.platforms.api_server_room_grants import _local_room_catalog
|
||||
|
||||
dispatch = HostedMemberDispatch.from_mapping(
|
||||
body.get("hosted_room_dispatch")
|
||||
)
|
||||
verify_room_grant(
|
||||
self._room_grant_secret(),
|
||||
room_token,
|
||||
dispatch,
|
||||
permission="dispatch",
|
||||
)
|
||||
dispatch = HostedMemberDispatch.from_mapping(body.get("hosted_room_dispatch"))
|
||||
verify_room_grant(self._room_grant_secret(), room_token, dispatch, permission="dispatch")
|
||||
active_profile = _api_request_profile.get() or "default"
|
||||
local_install = hosted_rooms.local_authority_gateway_id()
|
||||
if (
|
||||
@@ -116,37 +112,14 @@ async def _normalize_room_dispatch(
|
||||
or dispatch.target_install_id != local_install
|
||||
):
|
||||
raise ValueError("room dispatch target does not match this profile")
|
||||
with self._profile_scope(active_profile):
|
||||
execution_policy = execution_policy_mapping(
|
||||
target_profile=active_profile
|
||||
)
|
||||
catalog = GatewayRoomCatalog.from_mapping(
|
||||
catalog_mapping(
|
||||
installation_id=local_install,
|
||||
protocol_versions=(ROOM_LINK_PROTOCOL_VERSION,),
|
||||
link_modes=("direct",),
|
||||
persistent_process=True,
|
||||
text=True,
|
||||
attachments=False,
|
||||
target_profile=active_profile,
|
||||
execution_policy=execution_policy,
|
||||
)
|
||||
)
|
||||
policy = RoomExecutionPolicy.from_mapping(
|
||||
catalog.execution_policy.as_mapping()
|
||||
)
|
||||
if not hmac.compare_digest(
|
||||
policy.policy_digest,
|
||||
dispatch.execution_policy_digest,
|
||||
):
|
||||
_, catalog_map = _local_room_catalog(self, active_profile, local_install)
|
||||
catalog = GatewayRoomCatalog.from_mapping(catalog_map)
|
||||
policy = RoomExecutionPolicy.from_mapping(catalog.execution_policy.as_mapping())
|
||||
if not hmac.compare_digest(policy.policy_digest, dispatch.execution_policy_digest):
|
||||
raise ValueError("room execution policy changed")
|
||||
if not hmac.compare_digest(
|
||||
catalog.catalog_digest,
|
||||
dispatch.capability_digest,
|
||||
):
|
||||
if not hmac.compare_digest(catalog.catalog_digest, dispatch.capability_digest):
|
||||
raise ValueError("room capability catalog changed")
|
||||
supplied_input = body.get("input")
|
||||
if supplied_input not in {None, dispatch.prompt}:
|
||||
if body.get("input") not in {None, dispatch.prompt}:
|
||||
raise ValueError("room dispatch input does not match its prompt")
|
||||
expected_key = f"room:{dispatch.task_id}:{dispatch.execution_generation}"
|
||||
if request.headers.get("Idempotency-Key", "").strip() != expected_key:
|
||||
@@ -159,28 +132,4 @@ async def _normalize_room_dispatch(
|
||||
"_room_execution_policy": policy.as_mapping(),
|
||||
}, None
|
||||
except Exception as exc:
|
||||
message = str(exc)
|
||||
lowered = message.lower()
|
||||
policy_changed = (
|
||||
"execution policy" in lowered
|
||||
or "remote room execution requires" in lowered
|
||||
)
|
||||
return body, web.json_response(
|
||||
_openai_error(
|
||||
(
|
||||
"Room execution policy changed; reauthorization is required."
|
||||
if policy_changed
|
||||
else "Room capability catalog changed; reauthorization is required."
|
||||
if "capability catalog changed" in lowered
|
||||
else message
|
||||
),
|
||||
code=(
|
||||
"room_execution_policy_changed"
|
||||
if policy_changed
|
||||
else "room_capability_catalog_changed"
|
||||
if "capability catalog changed" in lowered
|
||||
else "invalid_room_dispatch"
|
||||
),
|
||||
),
|
||||
status=403,
|
||||
)
|
||||
return body, _room_dispatch_error(exc, _openai_error=_openai_error)
|
||||
|
||||
@@ -14,62 +14,68 @@ class RoomGrantReauthorizationRequired(ValueError):
|
||||
"""A validly signed room grant was revoked or superseded."""
|
||||
|
||||
|
||||
def _json_error(_openai_error, message: str, *, status: int, **error_kwargs) -> "web.Response":
|
||||
"""``web.json_response(_openai_error(message, **kw), status=...)`` with the injected envelope builder."""
|
||||
return web.json_response(_openai_error(message, **error_kwargs), status=status)
|
||||
|
||||
|
||||
def _require_unchanged_execution_policy(
|
||||
claims: dict[str, Any],
|
||||
execution_policy: dict[str, Any],
|
||||
) -> None:
|
||||
"""Keep renewal from silently granting a changed execution policy."""
|
||||
if (
|
||||
str(execution_policy.get("policy_digest") or "")
|
||||
!= str(claims.get("execution_policy_digest") or "")
|
||||
if str(execution_policy.get("policy_digest") or "") != str(
|
||||
claims.get("execution_policy_digest") or ""
|
||||
):
|
||||
raise RoomGrantReauthorizationRequired(
|
||||
"room execution policy changed"
|
||||
)
|
||||
raise RoomGrantReauthorizationRequired("room execution policy changed")
|
||||
|
||||
|
||||
def _room_grant_error_response(exc: Exception, *, _openai_error) -> "web.Response":
|
||||
reauthorization = isinstance(exc, RoomGrantReauthorizationRequired)
|
||||
return web.json_response(
|
||||
_openai_error(
|
||||
(
|
||||
"Room authorization needs to be renewed."
|
||||
if reauthorization
|
||||
else "Room authorization is invalid or expired."
|
||||
),
|
||||
err_type="gateway_auth_error",
|
||||
code=(
|
||||
"room_reauthorization_required"
|
||||
if reauthorization
|
||||
else "invalid_room_grant"
|
||||
),
|
||||
),
|
||||
status=403 if reauthorization else 401,
|
||||
reauth = isinstance(exc, RoomGrantReauthorizationRequired)
|
||||
return _json_error(
|
||||
_openai_error,
|
||||
"Room authorization needs to be renewed." if reauth else "Room authorization is invalid or expired.",
|
||||
err_type="gateway_auth_error",
|
||||
code="room_reauthorization_required" if reauth else "invalid_room_grant",
|
||||
status=403 if reauth else 401,
|
||||
)
|
||||
|
||||
|
||||
def _hard_expiry(claims: dict[str, Any]) -> float:
|
||||
return float(claims.get("status_expires_at", claims["expires_at"]))
|
||||
|
||||
|
||||
def _require_local_target(claims: dict[str, Any], profile: str, installation_id: str) -> None:
|
||||
if claims["target_profile"] != profile or claims["target_install_id"] != installation_id:
|
||||
raise ValueError("room grant target does not match this profile")
|
||||
|
||||
|
||||
def _local_room_catalog(self, profile: str, installation_id: str) -> tuple[dict, dict]:
|
||||
"""Return ``(execution_policy, catalog)`` for this gateway's *profile*."""
|
||||
from gateway.hosted_room_peer import PROTOCOL_VERSION, catalog_mapping
|
||||
from gateway.hosted_room_execution_policy import execution_policy_mapping
|
||||
|
||||
with self._profile_scope(profile):
|
||||
execution_policy = execution_policy_mapping(target_profile=profile)
|
||||
catalog = catalog_mapping(
|
||||
installation_id=installation_id,
|
||||
protocol_versions=(PROTOCOL_VERSION,),
|
||||
link_modes=("direct",),
|
||||
persistent_process=True,
|
||||
text=True,
|
||||
attachments=False,
|
||||
target_profile=profile,
|
||||
execution_policy=execution_policy,
|
||||
)
|
||||
return execution_policy, catalog
|
||||
|
||||
|
||||
def _http_routes(self) -> list[tuple[str, str, Any]]:
|
||||
return [
|
||||
(
|
||||
"POST",
|
||||
"/v1/room-members/invitations",
|
||||
self._handle_room_member_invitation,
|
||||
),
|
||||
(
|
||||
"GET",
|
||||
"/v1/room-members/capabilities",
|
||||
self._handle_room_member_capabilities,
|
||||
),
|
||||
(
|
||||
"POST",
|
||||
"/v1/room-members/grants/refresh",
|
||||
self._handle_room_member_grant_refresh,
|
||||
),
|
||||
(
|
||||
"POST",
|
||||
"/v1/room-members/grants/revoke",
|
||||
self._handle_room_member_grant_revoke,
|
||||
),
|
||||
("POST", "/v1/room-members/invitations", self._handle_room_member_invitation),
|
||||
("GET", "/v1/room-members/capabilities", self._handle_room_member_capabilities),
|
||||
("POST", "/v1/room-members/grants/refresh", self._handle_room_member_grant_refresh),
|
||||
("POST", "/v1/room-members/grants/revoke", self._handle_room_member_grant_revoke),
|
||||
]
|
||||
|
||||
|
||||
@@ -87,33 +93,19 @@ def _room_grant_secret(self) -> bytes:
|
||||
return gateway_room_grant_secret()
|
||||
|
||||
|
||||
def _room_grant_claims(
|
||||
self,
|
||||
request: "web.Request",
|
||||
*,
|
||||
permission: str,
|
||||
) -> dict[str, Any]:
|
||||
def _room_grant_claims(self, request: "web.Request", *, permission: str) -> dict[str, Any]:
|
||||
from gateway.hosted_room_peer import decode_room_grant
|
||||
|
||||
token = self._room_grant_token(request)
|
||||
if not token:
|
||||
raise ValueError("room grant is missing")
|
||||
claims = decode_room_grant(
|
||||
self._room_grant_secret(),
|
||||
token,
|
||||
permission=permission,
|
||||
)
|
||||
claims = decode_room_grant(self._room_grant_secret(), token, permission=permission)
|
||||
from gateway import hosted_rooms
|
||||
|
||||
if hosted_rooms.room_grant_is_revoked(
|
||||
hosted_rooms.default_db_path(),
|
||||
claims=claims,
|
||||
):
|
||||
db_path = hosted_rooms.default_db_path()
|
||||
if hosted_rooms.room_grant_is_revoked(db_path, claims=claims):
|
||||
raise RoomGrantReauthorizationRequired("room grant is revoked")
|
||||
if not hosted_rooms.peer_room_grant_is_current(
|
||||
hosted_rooms.default_db_path(),
|
||||
claims=claims,
|
||||
):
|
||||
if not hosted_rooms.peer_room_grant_is_current(db_path, claims=claims):
|
||||
raise RoomGrantReauthorizationRequired("room grant is no longer current")
|
||||
return claims
|
||||
|
||||
@@ -132,31 +124,16 @@ async def _handle_room_member_invitation(
|
||||
body, error = await self._read_json_body(request)
|
||||
if error:
|
||||
return error
|
||||
required = {
|
||||
"room_id",
|
||||
"home_install_id",
|
||||
"authority_gateway_id",
|
||||
"authority_epoch",
|
||||
"member_id",
|
||||
}
|
||||
required = {"room_id", "home_install_id", "authority_gateway_id", "authority_epoch", "member_id"}
|
||||
allowed = required | {"grant_id", "ttl_seconds", "status_ttl_seconds"}
|
||||
if set(body) - allowed or not required <= set(body):
|
||||
return web.json_response(
|
||||
_openai_error(
|
||||
"Invitation is missing required room authority fields.",
|
||||
code="invalid_room_invitation",
|
||||
),
|
||||
status=400,
|
||||
return _json_error(
|
||||
_openai_error, "Invitation is missing required room authority fields.",
|
||||
code="invalid_room_invitation", status=400,
|
||||
)
|
||||
try:
|
||||
from gateway import hosted_rooms
|
||||
from gateway.hosted_room_peer import (
|
||||
PROTOCOL_VERSION as ROOM_LINK_PROTOCOL_VERSION,
|
||||
catalog_mapping,
|
||||
decode_room_grant,
|
||||
issue_room_grant,
|
||||
)
|
||||
from gateway.hosted_room_execution_policy import execution_policy_mapping
|
||||
from gateway.hosted_room_peer import decode_room_grant, issue_room_grant
|
||||
|
||||
profile = _api_request_profile.get() or "default"
|
||||
target_install_id = hosted_rooms.local_authority_gateway_id()
|
||||
@@ -168,18 +145,7 @@ async def _handle_room_member_invitation(
|
||||
raise ValueError(
|
||||
"status_ttl_seconds must be at least ttl_seconds and no more than 2592000"
|
||||
)
|
||||
with self._profile_scope(profile):
|
||||
execution_policy = execution_policy_mapping(target_profile=profile)
|
||||
catalog = catalog_mapping(
|
||||
installation_id=target_install_id,
|
||||
protocol_versions=(ROOM_LINK_PROTOCOL_VERSION,),
|
||||
link_modes=("direct",),
|
||||
persistent_process=True,
|
||||
text=True,
|
||||
attachments=False,
|
||||
target_profile=profile,
|
||||
execution_policy=execution_policy,
|
||||
)
|
||||
execution_policy, catalog = _local_room_catalog(self, profile, target_install_id)
|
||||
token = issue_room_grant(
|
||||
self._room_grant_secret(),
|
||||
grant_id=str(body.get("grant_id") or f"grant-{uuid.uuid4().hex}"),
|
||||
@@ -195,19 +161,12 @@ async def _handle_room_member_invitation(
|
||||
ttl_seconds=ttl,
|
||||
status_ttl_seconds=status_ttl,
|
||||
)
|
||||
claims = decode_room_grant(
|
||||
self._room_grant_secret(), token, permission="status"
|
||||
)
|
||||
claims = decode_room_grant(self._room_grant_secret(), token, permission="status")
|
||||
hosted_rooms.reserve_peer_room(
|
||||
hosted_rooms.default_db_path(),
|
||||
claims=claims,
|
||||
expires_at=float(claims.get("status_expires_at", claims["expires_at"])),
|
||||
hosted_rooms.default_db_path(), claims=claims, expires_at=_hard_expiry(claims)
|
||||
)
|
||||
except Exception as exc:
|
||||
return web.json_response(
|
||||
_openai_error(str(exc), code="invalid_room_invitation"),
|
||||
status=400,
|
||||
)
|
||||
return _json_error(_openai_error, str(exc), code="invalid_room_invitation", status=400)
|
||||
return web.json_response(
|
||||
{
|
||||
"object": "hermes.room_member.invitation",
|
||||
@@ -231,32 +190,12 @@ async def _handle_room_member_capabilities(
|
||||
"""Verify a scoped grant and return this target's live room catalog."""
|
||||
try:
|
||||
from gateway import hosted_rooms
|
||||
from gateway.hosted_room_peer import (
|
||||
PROTOCOL_VERSION as ROOM_LINK_PROTOCOL_VERSION,
|
||||
catalog_mapping,
|
||||
)
|
||||
from gateway.hosted_room_execution_policy import execution_policy_mapping
|
||||
|
||||
claims = self._room_grant_claims(request, permission="status")
|
||||
profile = _api_request_profile.get() or "default"
|
||||
installation_id = hosted_rooms.local_authority_gateway_id()
|
||||
if (
|
||||
claims["target_profile"] != profile
|
||||
or claims["target_install_id"] != installation_id
|
||||
):
|
||||
raise ValueError("room grant target does not match this profile")
|
||||
with self._profile_scope(profile):
|
||||
execution_policy = execution_policy_mapping(target_profile=profile)
|
||||
catalog = catalog_mapping(
|
||||
installation_id=installation_id,
|
||||
protocol_versions=(ROOM_LINK_PROTOCOL_VERSION,),
|
||||
link_modes=("direct",),
|
||||
persistent_process=True,
|
||||
text=True,
|
||||
attachments=False,
|
||||
target_profile=profile,
|
||||
execution_policy=execution_policy,
|
||||
)
|
||||
_require_local_target(claims, profile, installation_id)
|
||||
_, catalog = _local_room_catalog(self, profile, installation_id)
|
||||
except Exception as exc:
|
||||
return _room_grant_error_response(exc, _openai_error=_openai_error)
|
||||
return web.json_response(
|
||||
@@ -285,47 +224,28 @@ async def _handle_room_member_grant_refresh(
|
||||
if error:
|
||||
return error
|
||||
if set(body) - {"ttl_seconds"}:
|
||||
return web.json_response(
|
||||
_openai_error(
|
||||
"Grant refresh accepts only ttl_seconds.",
|
||||
code="invalid_room_grant_refresh",
|
||||
),
|
||||
status=400,
|
||||
return _json_error(
|
||||
_openai_error, "Grant refresh accepts only ttl_seconds.",
|
||||
code="invalid_room_grant_refresh", status=400,
|
||||
)
|
||||
try:
|
||||
from gateway import hosted_rooms
|
||||
from gateway.hosted_room_peer import (
|
||||
MAX_DISPATCH_GRANT_TTL_SECONDS,
|
||||
issue_room_grant,
|
||||
)
|
||||
from gateway.hosted_room_peer import MAX_DISPATCH_GRANT_TTL_SECONDS, issue_room_grant
|
||||
from gateway.hosted_room_execution_policy import execution_policy_mapping
|
||||
|
||||
# A status-only bearer may observe a run but must never mint new
|
||||
# dispatch authority. Renewal is possible only while the existing
|
||||
# dispatch permission is still live.
|
||||
# dispatch authority: renewal requires a still-live dispatch permission.
|
||||
claims = self._room_grant_claims(request, permission="dispatch")
|
||||
profile = _api_request_profile.get() or "default"
|
||||
installation_id = hosted_rooms.local_authority_gateway_id()
|
||||
if (
|
||||
claims["target_profile"] != profile
|
||||
or claims["target_install_id"] != installation_id
|
||||
):
|
||||
raise ValueError("room grant target does not match this profile")
|
||||
_require_local_target(claims, profile, installation_id)
|
||||
now = time.time()
|
||||
hard_expiry = float(
|
||||
claims.get("status_expires_at", claims["expires_at"])
|
||||
)
|
||||
hard_expiry = _hard_expiry(claims)
|
||||
remaining = hard_expiry - now
|
||||
requested = float(
|
||||
body.get("ttl_seconds", MAX_DISPATCH_GRANT_TTL_SECONDS)
|
||||
)
|
||||
requested = float(body.get("ttl_seconds", MAX_DISPATCH_GRANT_TTL_SECONDS))
|
||||
if remaining <= 0 or requested <= 0:
|
||||
raise ValueError("room grant renewal horizon expired")
|
||||
dispatch_ttl = min(
|
||||
requested,
|
||||
MAX_DISPATCH_GRANT_TTL_SECONDS,
|
||||
remaining,
|
||||
)
|
||||
dispatch_ttl = min(requested, MAX_DISPATCH_GRANT_TTL_SECONDS, remaining)
|
||||
with self._profile_scope(profile):
|
||||
execution_policy = execution_policy_mapping(target_profile=profile)
|
||||
_require_unchanged_execution_policy(claims, execution_policy)
|
||||
@@ -370,12 +290,9 @@ async def _handle_room_member_grant_revoke(
|
||||
if error:
|
||||
return error
|
||||
if body:
|
||||
return web.json_response(
|
||||
_openai_error(
|
||||
"Grant revoke accepts no fields.",
|
||||
code="invalid_room_grant_revoke",
|
||||
),
|
||||
status=400,
|
||||
return _json_error(
|
||||
_openai_error, "Grant revoke accepts no fields.",
|
||||
code="invalid_room_grant_revoke", status=400,
|
||||
)
|
||||
try:
|
||||
from gateway import hosted_rooms
|
||||
@@ -384,40 +301,19 @@ async def _handle_room_member_grant_revoke(
|
||||
token = self._room_grant_token(request)
|
||||
if not token:
|
||||
raise ValueError("room grant is missing")
|
||||
# Revoke is idempotent: a response-lost retry may authenticate with
|
||||
# the grant that was just added to the denylist. Verify signature,
|
||||
# scope, and hard horizon directly, then upsert the same grant id.
|
||||
claims = decode_room_grant(
|
||||
self._room_grant_secret(),
|
||||
token,
|
||||
permission="status",
|
||||
)
|
||||
# Revoke is idempotent: a response-lost retry may authenticate with the
|
||||
# grant just denylisted, so verify signature/scope/horizon directly
|
||||
# (not via _room_grant_claims) and upsert the same grant id.
|
||||
claims = decode_room_grant(self._room_grant_secret(), token, permission="status")
|
||||
profile = _api_request_profile.get() or "default"
|
||||
installation_id = hosted_rooms.local_authority_gateway_id()
|
||||
if (
|
||||
claims["target_profile"] != profile
|
||||
or claims["target_install_id"] != installation_id
|
||||
):
|
||||
raise ValueError("room grant target does not match this profile")
|
||||
_require_local_target(claims, profile, installation_id)
|
||||
hosted_rooms.revoke_room_grant_scope(
|
||||
hosted_rooms.default_db_path(),
|
||||
claims=claims,
|
||||
expires_at=float(
|
||||
claims.get("status_expires_at", claims["expires_at"])
|
||||
),
|
||||
hosted_rooms.default_db_path(), claims=claims, expires_at=_hard_expiry(claims)
|
||||
)
|
||||
except Exception:
|
||||
return web.json_response(
|
||||
_openai_error(
|
||||
"Room authorization is invalid or expired.",
|
||||
err_type="gateway_auth_error",
|
||||
code="invalid_room_grant",
|
||||
),
|
||||
status=401,
|
||||
return _json_error(
|
||||
_openai_error, "Room authorization is invalid or expired.",
|
||||
err_type="gateway_auth_error", code="invalid_room_grant", status=401,
|
||||
)
|
||||
return web.json_response(
|
||||
{
|
||||
"object": "hermes.room_member.grant.revocation",
|
||||
"revoked": True,
|
||||
}
|
||||
)
|
||||
return web.json_response({"object": "hermes.room_member.grant.revocation", "revoked": True})
|
||||
|
||||
@@ -13,6 +13,42 @@ from typing import Any, Dict
|
||||
# Keep the extracted store's log records on the API server logger.
|
||||
logger = logging.getLogger("gateway.platforms.api_server")
|
||||
|
||||
TERMINAL_STATUSES = frozenset({"completed", "failed", "cancelled", "interrupted"})
|
||||
|
||||
_SELECT_BY_KEY = (
|
||||
"SELECT fingerprint, run_id, status_json, owner_pid, owner_started, updated_at "
|
||||
"FROM run_idempotency WHERE scope=? AND idempotency_key=?"
|
||||
)
|
||||
_EXTEND_RETENTION_BY_KEY = (
|
||||
"UPDATE run_idempotency SET retention_until=MAX(retention_until, ?) "
|
||||
"WHERE scope=? AND idempotency_key=? AND fingerprint=?"
|
||||
)
|
||||
_EXTEND_RETENTION_BY_RUN = (
|
||||
"UPDATE run_idempotency SET retention_until=MAX(retention_until, ?) "
|
||||
"WHERE scope=? AND run_id=?"
|
||||
)
|
||||
# Columns added after the first schema shipped; applied when missing.
|
||||
_MIGRATIONS = {
|
||||
"owner_pid": "INTEGER NOT NULL DEFAULT 0",
|
||||
"owner_started": "INTEGER NOT NULL DEFAULT 0",
|
||||
"retention_until": "REAL NOT NULL DEFAULT 0",
|
||||
"acknowledged_at": "REAL",
|
||||
}
|
||||
|
||||
|
||||
def _encode_status(status: Dict[str, Any]) -> str:
|
||||
return json.dumps(status, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def _record(run_id, status_json, owner_pid, owner_started, updated_at) -> dict[str, Any]:
|
||||
return {
|
||||
"run_id": run_id,
|
||||
"status": json.loads(status_json),
|
||||
"owner_pid": int(owner_pid or 0),
|
||||
"owner_started": int(owner_started or 0),
|
||||
"updated_at": float(updated_at or 0),
|
||||
}
|
||||
|
||||
|
||||
class RunIdempotencyStore:
|
||||
"""Durable, tenant-scoped reservations for ``POST /v1/runs``.
|
||||
@@ -69,27 +105,10 @@ class RunIdempotencyStore:
|
||||
PRIMARY KEY (scope, idempotency_key)
|
||||
)"""
|
||||
)
|
||||
columns = {
|
||||
str(row[1])
|
||||
for row in self._conn.execute("PRAGMA table_info(run_idempotency)")
|
||||
}
|
||||
if "owner_pid" not in columns:
|
||||
self._conn.execute(
|
||||
"ALTER TABLE run_idempotency ADD COLUMN owner_pid INTEGER NOT NULL DEFAULT 0"
|
||||
)
|
||||
if "owner_started" not in columns:
|
||||
self._conn.execute(
|
||||
"ALTER TABLE run_idempotency ADD COLUMN owner_started INTEGER NOT NULL DEFAULT 0"
|
||||
)
|
||||
if "retention_until" not in columns:
|
||||
self._conn.execute(
|
||||
"ALTER TABLE run_idempotency ADD COLUMN "
|
||||
"retention_until REAL NOT NULL DEFAULT 0"
|
||||
)
|
||||
if "acknowledged_at" not in columns:
|
||||
self._conn.execute(
|
||||
"ALTER TABLE run_idempotency ADD COLUMN acknowledged_at REAL"
|
||||
)
|
||||
columns = {str(row[1]) for row in self._conn.execute("PRAGMA table_info(run_idempotency)")}
|
||||
for column, ddl in _MIGRATIONS.items():
|
||||
if column not in columns:
|
||||
self._conn.execute(f"ALTER TABLE run_idempotency ADD COLUMN {column} {ddl}")
|
||||
self._conn.execute(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS run_idempotency_run_id ON run_idempotency(run_id)"
|
||||
)
|
||||
@@ -100,19 +119,13 @@ class RunIdempotencyStore:
|
||||
def _tighten_permissions(self) -> None:
|
||||
if not self._db_path:
|
||||
return
|
||||
for candidate in (
|
||||
Path(self._db_path),
|
||||
Path(self._db_path + "-wal"),
|
||||
Path(self._db_path + "-shm"),
|
||||
):
|
||||
for suffix in ("", "-wal", "-shm"):
|
||||
candidate = Path(self._db_path + suffix)
|
||||
try:
|
||||
if candidate.exists():
|
||||
candidate.chmod(0o600)
|
||||
except OSError:
|
||||
logger.debug(
|
||||
"Failed to restrict run idempotency store permissions",
|
||||
exc_info=True,
|
||||
)
|
||||
logger.debug("Failed to restrict run idempotency store permissions", exc_info=True)
|
||||
|
||||
def reserve(
|
||||
self,
|
||||
@@ -129,54 +142,28 @@ class RunIdempotencyStore:
|
||||
"""Atomically reserve a key; return ``(outcome, stored_record)``."""
|
||||
now = time.time()
|
||||
retention_until = max(0.0, float(retention_until or 0))
|
||||
encoded = json.dumps(status, sort_keys=True, separators=(",", ":"))
|
||||
encoded = _encode_status(status)
|
||||
with self._lock:
|
||||
self._conn.execute("BEGIN IMMEDIATE")
|
||||
try:
|
||||
self._prune_stale_terminal_locked(now)
|
||||
row = self._conn.execute(
|
||||
"SELECT fingerprint, run_id, status_json, owner_pid, owner_started, updated_at "
|
||||
"FROM run_idempotency WHERE scope=? AND idempotency_key=?",
|
||||
(scope, key),
|
||||
).fetchone()
|
||||
row = self._conn.execute(_SELECT_BY_KEY, (scope, key)).fetchone()
|
||||
if row is not None:
|
||||
if retention_until:
|
||||
self._conn.execute(
|
||||
"""UPDATE run_idempotency
|
||||
SET retention_until=MAX(retention_until, ?)
|
||||
WHERE scope=? AND idempotency_key=?
|
||||
AND fingerprint=?""",
|
||||
(retention_until, scope, key, fingerprint),
|
||||
_EXTEND_RETENTION_BY_KEY, (retention_until, scope, key, fingerprint)
|
||||
)
|
||||
self._conn.commit()
|
||||
outcome = (
|
||||
"reused"
|
||||
if hmac.compare_digest(row[0], fingerprint)
|
||||
else "conflict"
|
||||
)
|
||||
return outcome, {
|
||||
"run_id": row[1],
|
||||
"status": json.loads(row[2]),
|
||||
"owner_pid": int(row[3] or 0),
|
||||
"owner_started": int(row[4] or 0),
|
||||
"updated_at": float(row[5] or 0),
|
||||
}
|
||||
outcome = "reused" if hmac.compare_digest(row[0], fingerprint) else "conflict"
|
||||
return outcome, _record(*row[1:])
|
||||
self._conn.execute(
|
||||
"INSERT INTO run_idempotency("
|
||||
"scope,idempotency_key,fingerprint,run_id,status_json,"
|
||||
"owner_pid,owner_started,retention_until,created_at,updated_at"
|
||||
") VALUES(?,?,?,?,?,?,?,?,?,?)",
|
||||
(
|
||||
scope,
|
||||
key,
|
||||
fingerprint,
|
||||
run_id,
|
||||
encoded,
|
||||
int(owner_pid or 0),
|
||||
int(owner_started or 0),
|
||||
retention_until,
|
||||
now,
|
||||
now,
|
||||
scope, key, fingerprint, run_id, encoded,
|
||||
int(owner_pid or 0), int(owner_started or 0), retention_until, now, now,
|
||||
),
|
||||
)
|
||||
self._conn.commit()
|
||||
@@ -191,14 +178,7 @@ class RunIdempotencyStore:
|
||||
self._conn.rollback()
|
||||
raise
|
||||
|
||||
def lookup(
|
||||
self,
|
||||
scope: str,
|
||||
key: str,
|
||||
fingerprint: str,
|
||||
*,
|
||||
retention_until: float = 0,
|
||||
):
|
||||
def lookup(self, scope: str, key: str, fingerprint: str, *, retention_until: float = 0):
|
||||
"""Return ``missing``, ``reused`` or ``conflict`` without reserving."""
|
||||
now = time.time()
|
||||
retention_until = max(0.0, float(retention_until or 0))
|
||||
@@ -207,18 +187,10 @@ class RunIdempotencyStore:
|
||||
try:
|
||||
if retention_until:
|
||||
self._conn.execute(
|
||||
"""UPDATE run_idempotency
|
||||
SET retention_until=MAX(retention_until, ?)
|
||||
WHERE scope=? AND idempotency_key=?
|
||||
AND fingerprint=?""",
|
||||
(retention_until, scope, key, fingerprint),
|
||||
_EXTEND_RETENTION_BY_KEY, (retention_until, scope, key, fingerprint)
|
||||
)
|
||||
self._prune_stale_terminal_locked(now)
|
||||
row = self._conn.execute(
|
||||
"SELECT fingerprint, run_id, status_json, owner_pid, owner_started, updated_at "
|
||||
"FROM run_idempotency WHERE scope=? AND idempotency_key=?",
|
||||
(scope, key),
|
||||
).fetchone()
|
||||
row = self._conn.execute(_SELECT_BY_KEY, (scope, key)).fetchone()
|
||||
self._conn.commit()
|
||||
except Exception:
|
||||
self._conn.rollback()
|
||||
@@ -226,13 +198,7 @@ class RunIdempotencyStore:
|
||||
if row is None:
|
||||
return "missing", None
|
||||
outcome = "reused" if hmac.compare_digest(row[0], fingerprint) else "conflict"
|
||||
return outcome, {
|
||||
"run_id": row[1],
|
||||
"status": json.loads(row[2]),
|
||||
"owner_pid": int(row[3] or 0),
|
||||
"owner_started": int(row[4] or 0),
|
||||
"updated_at": float(row[5] or 0),
|
||||
}
|
||||
return outcome, _record(*row[1:])
|
||||
|
||||
def _prune_stale_terminal_locked(self, now: float) -> None:
|
||||
"""Prune replay records only after their stored run is terminal.
|
||||
@@ -242,74 +208,30 @@ class RunIdempotencyStore:
|
||||
disconnected room turn may legitimately outlive the retention window.
|
||||
"""
|
||||
stale = self._conn.execute(
|
||||
"""SELECT scope, idempotency_key, status_json, retention_until,
|
||||
acknowledged_at, updated_at
|
||||
"""SELECT scope, idempotency_key, status_json
|
||||
FROM run_idempotency
|
||||
WHERE acknowledged_at <= ?
|
||||
OR (retention_until > 0 AND retention_until <= ?)
|
||||
OR (retention_until <= 0 AND updated_at < ?)""",
|
||||
(
|
||||
now - self.ACKNOWLEDGED_RETENTION_SECONDS,
|
||||
now,
|
||||
now - self.RETENTION_SECONDS,
|
||||
),
|
||||
(now - self.ACKNOWLEDGED_RETENTION_SECONDS, now, now - self.RETENTION_SECONDS),
|
||||
).fetchall()
|
||||
for (
|
||||
stale_scope,
|
||||
stale_key,
|
||||
stale_status,
|
||||
retention_until,
|
||||
acknowledged_at,
|
||||
updated_at,
|
||||
) in stale:
|
||||
for stale_scope, stale_key, stale_status in stale:
|
||||
try:
|
||||
terminal = json.loads(stale_status).get("status") in {
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
}
|
||||
terminal = json.loads(stale_status).get("status") in TERMINAL_STATUSES
|
||||
except Exception:
|
||||
terminal = False
|
||||
expired = bool(
|
||||
(
|
||||
acknowledged_at is not None
|
||||
and float(acknowledged_at)
|
||||
<= now - self.ACKNOWLEDGED_RETENTION_SECONDS
|
||||
)
|
||||
or (
|
||||
float(retention_until or 0) > 0
|
||||
and now >= float(retention_until)
|
||||
)
|
||||
or (
|
||||
float(retention_until or 0) <= 0
|
||||
and float(updated_at or 0) < now - self.RETENTION_SECONDS
|
||||
)
|
||||
)
|
||||
if terminal and expired:
|
||||
if terminal:
|
||||
self._conn.execute(
|
||||
"""DELETE FROM run_idempotency
|
||||
WHERE scope=? AND idempotency_key=?""",
|
||||
"DELETE FROM run_idempotency WHERE scope=? AND idempotency_key=?",
|
||||
(stale_scope, stale_key),
|
||||
)
|
||||
|
||||
def status_for_run(
|
||||
self,
|
||||
scope: str,
|
||||
run_id: str,
|
||||
*,
|
||||
retention_until: float = 0,
|
||||
) -> dict[str, Any] | None:
|
||||
def status_for_run(self, scope: str, run_id: str, *, retention_until: float = 0) -> dict[str, Any] | None:
|
||||
"""Load one durable run status inside its authenticated scope."""
|
||||
retention_until = max(0.0, float(retention_until or 0))
|
||||
with self._lock:
|
||||
if retention_until:
|
||||
self._conn.execute(
|
||||
"""UPDATE run_idempotency
|
||||
SET retention_until=MAX(retention_until, ?)
|
||||
WHERE scope=? AND run_id=?""",
|
||||
(retention_until, scope, run_id),
|
||||
)
|
||||
self._conn.execute(_EXTEND_RETENTION_BY_RUN, (retention_until, scope, run_id))
|
||||
self._conn.commit()
|
||||
row = self._conn.execute(
|
||||
"SELECT status_json, owner_pid, owner_started, updated_at "
|
||||
@@ -325,18 +247,6 @@ class RunIdempotencyStore:
|
||||
"updated_at": float(row[3] or 0),
|
||||
}
|
||||
|
||||
def acknowledge_terminal(self, scope: str, run_id: str) -> bool:
|
||||
"""Allow cleanup once the room home durably imported terminal output."""
|
||||
now = time.time()
|
||||
with self._lock:
|
||||
changed = self._conn.execute(
|
||||
"""UPDATE run_idempotency SET acknowledged_at=?
|
||||
WHERE scope=? AND run_id=?""",
|
||||
(now, scope, run_id),
|
||||
).rowcount
|
||||
self._conn.commit()
|
||||
return changed == 1
|
||||
|
||||
def extend_retention(self, scope: str, run_id: str, until: float) -> bool:
|
||||
"""Persist the latest verified recovery horizon for an active grant."""
|
||||
checked_until = max(0.0, float(until or 0))
|
||||
@@ -344,10 +254,7 @@ class RunIdempotencyStore:
|
||||
return False
|
||||
with self._lock:
|
||||
changed = self._conn.execute(
|
||||
"""UPDATE run_idempotency
|
||||
SET retention_until=MAX(retention_until, ?)
|
||||
WHERE scope=? AND run_id=?""",
|
||||
(checked_until, scope, run_id),
|
||||
_EXTEND_RETENTION_BY_RUN, (checked_until, scope, run_id)
|
||||
).rowcount
|
||||
self._conn.commit()
|
||||
return changed == 1
|
||||
@@ -363,11 +270,10 @@ class RunIdempotencyStore:
|
||||
)
|
||||
|
||||
def update_status(self, run_id: str, status: Dict[str, Any]) -> None:
|
||||
encoded = json.dumps(status, sort_keys=True, separators=(",", ":"))
|
||||
with self._lock:
|
||||
self._conn.execute(
|
||||
"UPDATE run_idempotency SET status_json=?, updated_at=? WHERE run_id=?",
|
||||
(encoded, time.time(), run_id),
|
||||
(_encode_status(status), time.time(), run_id),
|
||||
)
|
||||
self._conn.commit()
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1242,51 +1242,6 @@ class TestRunIdempotency:
|
||||
) == ("missing", None)
|
||||
store.close()
|
||||
|
||||
def test_explicit_home_acknowledgement_releases_terminal_receipt(
|
||||
self, tmp_path, monkeypatch
|
||||
):
|
||||
from gateway.platforms import api_server_run_idempotency as idempotency
|
||||
|
||||
now = [100.0]
|
||||
monkeypatch.setattr(idempotency.time, "time", lambda: now[0])
|
||||
store = idempotency.RunIdempotencyStore(str(tmp_path / "idem.db"))
|
||||
assert store.reserve(
|
||||
"room-scope",
|
||||
"room:task-1:1",
|
||||
"room-fingerprint",
|
||||
"run-room",
|
||||
{"run_id": "run-room", "status": "completed"},
|
||||
retention_until=now[0] + 30 * 24 * 60 * 60,
|
||||
)[0] == "created"
|
||||
assert store.acknowledge_terminal("room-scope", "run-room") is True
|
||||
store.reserve(
|
||||
"other-scope",
|
||||
"other-key",
|
||||
"other-fingerprint",
|
||||
"run-other",
|
||||
{"run_id": "run-other", "status": "queued"},
|
||||
)
|
||||
assert store.lookup(
|
||||
"room-scope",
|
||||
"room:task-1:1",
|
||||
"room-fingerprint",
|
||||
)[0] == "reused"
|
||||
|
||||
now[0] += store.ACKNOWLEDGED_RETENTION_SECONDS + 1
|
||||
store.reserve(
|
||||
"third-scope",
|
||||
"third-key",
|
||||
"third-fingerprint",
|
||||
"run-third",
|
||||
{"run_id": "run-third", "status": "queued"},
|
||||
)
|
||||
assert store.lookup(
|
||||
"room-scope",
|
||||
"room:task-1:1",
|
||||
"room-fingerprint",
|
||||
) == ("missing", None)
|
||||
store.close()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_missing_key_preserves_legacy_new_run_behavior(
|
||||
self, adapter, tmp_path
|
||||
|
||||
Reference in New Issue
Block a user