refactor(gateway): drop blank lines inside hosted-room function bodies; group tiny exception classes (AST-neutral)
This commit is contained in:
@@ -66,11 +66,9 @@ _EPOCH_STAMPED_KINDS = _TERMINAL_EVENT_KINDS | {"message.member", *_GATEWAY_EVEN
|
||||
|
||||
class DiscussionPolicyError(ValueError): """Base class for invalid policy input or unreconstructable state."""
|
||||
|
||||
|
||||
class DiscussionValidationError(DiscussionPolicyError):
|
||||
"""Raised when a room, roster, payload, or typed event is malformed."""
|
||||
|
||||
|
||||
class DiscussionReconstructionError(DiscussionPolicyError):
|
||||
"""Raised when a persisted task cannot be reproduced from durable state."""
|
||||
|
||||
@@ -225,13 +223,11 @@ def validate_roster(value: Any, *, local_profiles: Iterable[str]) -> tuple[Discu
|
||||
raise DiscussionValidationError(
|
||||
f"members must contain between {MIN_DISCUSSION_MEMBERS} and "
|
||||
f"{MAX_DISCUSSION_MEMBERS} entries")
|
||||
|
||||
known_profiles = {_identifier(profile, label="local profile") for profile in local_profiles}
|
||||
members: list[DiscussionMember] = []
|
||||
targets: set[str] = set()
|
||||
handles: set[str] = {"all", "everyone"} # reserved mention handles
|
||||
member_ids: set[str] = set()
|
||||
|
||||
for index, raw in enumerate(value):
|
||||
if not isinstance(raw, Mapping):
|
||||
raise DiscussionValidationError(f"member {index} must be an object")
|
||||
@@ -253,7 +249,6 @@ def validate_roster(value: Any, *, local_profiles: Iterable[str]) -> tuple[Discu
|
||||
display_name = display_name.strip()
|
||||
if len(display_name) > hosted_rooms.MAX_ACTOR_LABEL_CHARS:
|
||||
raise DiscussionValidationError(f"member {index} display_name is too long")
|
||||
|
||||
target_key = compact_json(target, ensure_ascii=False).casefold()
|
||||
target_message = (
|
||||
"member profiles must be unique" if target.get("kind") == "local"
|
||||
@@ -411,7 +406,6 @@ def _validate_terminal_event(
|
||||
_positive_int(payload.get("execution_generation"), label="execution_generation")
|
||||
if kind == "turn.failed" and "reason_code" in payload:
|
||||
from tools.bot_failure_reasons import ALL_REASONS
|
||||
|
||||
if payload["reason_code"] not in ALL_REASONS:
|
||||
raise DiscussionValidationError("turn.failed reason_code must use the shared failure vocabulary")
|
||||
return payload
|
||||
@@ -678,11 +672,9 @@ def plan_next_task(
|
||||
decide = partial(
|
||||
DiscussionDecision, discussion_event_id=discussion.event_id, source_event_seq=discussion.seq,
|
||||
thread_id=thread_id)
|
||||
|
||||
thread_messages, discussion_messages, member_messages = _thread_messages(validated, discussion)
|
||||
if len(member_messages) >= MAX_DISCUSSION_MESSAGES:
|
||||
return decide("bounded", "max_messages")
|
||||
|
||||
terminals = {
|
||||
(int(event.payload["round_index"]), str(event.payload["member_id"])): event
|
||||
for event in validated
|
||||
@@ -690,7 +682,6 @@ def plan_next_task(
|
||||
and event.payload.get("discussion_event_id") == discussion.event_id}
|
||||
watermarks = _effective_watermarks(validated, initial_watermarks)
|
||||
seen_through_seq = max(event.seq for event in thread_messages)
|
||||
|
||||
for round_index in range(MAX_DISCUSSION_ROUNDS):
|
||||
# The user's message selects the first round, with no mention meaning
|
||||
# everyone. Later rounds are opt-in: only a peer explicitly cited by a
|
||||
@@ -714,12 +705,10 @@ def plan_next_task(
|
||||
room=room, discussion_event=discussion, member=member, member_index=member_index,
|
||||
round_index=round_index, seen_through_seq=seen_through_seq, prompt=prompt)
|
||||
return decide("task", "member_turn", task=task)
|
||||
|
||||
if not any(int(event.payload["round_index"]) == round_index for event in member_messages):
|
||||
return decide("settled", "silent_round")
|
||||
if round_index == MAX_DISCUSSION_ROUNDS - 1:
|
||||
return decide("bounded", "max_rounds")
|
||||
|
||||
raise AssertionError("bounded Discussion loop exhausted unexpectedly")
|
||||
|
||||
|
||||
@@ -817,7 +806,6 @@ def _settled_effects(
|
||||
def _failed_effects(result: Any, **_: Any) -> tuple[dict[str, Any], list[EventPlan]]:
|
||||
error_text = _terminal_text(result, field="error", fallback="member turn failed")
|
||||
from tools.bot_failure_reasons import ALL_REASONS, classify_agent_error
|
||||
|
||||
supplied_reason = (
|
||||
str(result.get("reason_code") or result.get("reason") or "").strip()
|
||||
if isinstance(result, Mapping) else "")
|
||||
@@ -864,7 +852,6 @@ def plan_publication(
|
||||
if status == "deferred":
|
||||
message = "deferred publication requires an execution generation"
|
||||
_bounded_int(execution_generation, message=message, low=1)
|
||||
|
||||
newer_same_thread = any(
|
||||
event.kind == "message.user"
|
||||
and event.seq > task.seen_through_seq
|
||||
|
||||
@@ -103,25 +103,18 @@ _GENERATION_TRANSITIONS = {
|
||||
|
||||
class DriverStateError(ValueError): """Base class for invalid or conflicting driver-state operations."""
|
||||
|
||||
|
||||
class DriverValidationError(DriverStateError): """Raised when an identifier, clock, TTL, or payload is invalid."""
|
||||
|
||||
|
||||
class RoomUnavailableError(DriverStateError): """Raised when the hosted room does not exist or was disbanded."""
|
||||
|
||||
|
||||
class LeaseHeldError(DriverStateError): """Raised when another unexpired driver generation owns the room."""
|
||||
|
||||
|
||||
class StaleLeaseError(DriverStateError): """Raised when a lease generation can no longer mutate room state."""
|
||||
|
||||
|
||||
class TaskConflictError(DriverStateError): """Raised when an idempotency key is reused for different task state."""
|
||||
|
||||
|
||||
class StaleTaskError(DriverStateError): """Raised when an obsolete task attempt or cancellation tries to commit."""
|
||||
|
||||
|
||||
class InvalidTaskTransitionError(DriverStateError): """Raised when a requested task transition is not allowed."""
|
||||
|
||||
|
||||
@@ -296,14 +289,11 @@ def _connect(db_path: Path | str) -> sqlite3.Connection:
|
||||
The driver schema never shipped, so an incompatible draft fails closed in ``_validate_schema``.
|
||||
"""
|
||||
existing: list[bool] = []
|
||||
|
||||
def ready(conn: sqlite3.Connection) -> bool:
|
||||
existing.append(_schema_objects_exist(conn))
|
||||
return existing[0] and _task_schema_supports_current_statuses(conn)
|
||||
|
||||
def initialize(conn: sqlite3.Connection) -> None:
|
||||
(_migrate_task_status_constraint if existing[0] else _initialize_schema)(conn)
|
||||
|
||||
conn = connect(db_path, db_label="state.db (hosted_room_driver)", ready=ready, initialize=initialize)
|
||||
if existing[0]:
|
||||
try:
|
||||
@@ -450,7 +440,6 @@ def _settlement_replay(settlement_id: str, status: str, result_json: str) -> Cal
|
||||
if (row["settlement_id"], row["settlement_status"], row["result_json"]) == (settlement_id, status, result_json):
|
||||
return _task_from_row(row, idempotent=True)
|
||||
raise TaskConflictError("task already has a different terminal settlement")
|
||||
|
||||
return replay
|
||||
|
||||
|
||||
@@ -505,11 +494,9 @@ def _generation_transition(
|
||||
replay: Callable[[sqlite3.Row], Any] | None = None) -> dict[str, Any]:
|
||||
"""Lease-first transition from ``_GENERATION_TRANSITIONS`` fenced on status + both generations."""
|
||||
status, set_clause, generation_stale, stale = _GENERATION_TRANSITIONS[name]
|
||||
|
||||
def guard(row: sqlite3.Row) -> None:
|
||||
if not _generations_match(row, status, execution_generation, cancel_generation):
|
||||
raise StaleTaskError(generation_stale)
|
||||
|
||||
return _transition(
|
||||
db_path, identity, lease=lease, now=now, replay=replay, guard=guard, sql=_generation_update(set_clause, status),
|
||||
set_params=set_params, fence_params=(execution_generation, cancel_generation), stale=stale)
|
||||
@@ -523,7 +510,6 @@ def _run_fence_transition(
|
||||
``lease_generation`` casts the stored run_lease_generation: ``int`` raises on NULL, ``int(v or 0)`` reads 0.
|
||||
"""
|
||||
lease = attempt.lease
|
||||
|
||||
def guard(row: sqlite3.Row) -> None:
|
||||
if not (
|
||||
_generations_match(row, "running", attempt.execution_generation, attempt.cancel_generation)
|
||||
@@ -531,7 +517,6 @@ def _run_fence_transition(
|
||||
and row["run_process_generation"] == lease.process_generation
|
||||
and lease_generation(row["run_lease_generation"]) == lease.lease_generation):
|
||||
raise StaleTaskError(guard_stale)
|
||||
|
||||
return _transition(
|
||||
db_path, attempt.identity, lease=lease, guard=guard,
|
||||
fence_params=(
|
||||
@@ -550,7 +535,6 @@ def acquire_lease(
|
||||
ttl_seconds = _ttl(ttl_seconds)
|
||||
now = _timestamp(clock)
|
||||
expires_at = _expiry(now, ttl_seconds)
|
||||
|
||||
with _transaction(db_path) as conn:
|
||||
_require_room_authority(conn, room_id=room_id, gateway_id=gateway_id, authority_epoch=authority_epoch)
|
||||
row = conn.execute(_SELECT_LEASE, (room_id,)).fetchone()
|
||||
@@ -561,7 +545,6 @@ def acquire_lease(
|
||||
) VALUES (?, ?, ?, ?, 1, ?, ?, ?, NULL)""",
|
||||
(room_id, gateway_id, authority_epoch, process_generation, expires_at, now, now))
|
||||
return _lease_from_row(conn.execute(_SELECT_LEASE, (room_id,)).fetchone())
|
||||
|
||||
same_authority = row["gateway_id"] == gateway_id and int(row["authority_epoch"]) == authority_epoch
|
||||
live = row["released_at"] is None and float(row["expires_at"]) > now
|
||||
if same_authority and row["process_generation"] == process_generation and live:
|
||||
@@ -572,7 +555,6 @@ def acquire_lease(
|
||||
return _lease_from_row({**dict(row), "expires_at": renewed_expiry})
|
||||
if same_authority and live:
|
||||
raise LeaseHeldError("room driver lease is held by another generation")
|
||||
|
||||
updated = conn.execute("""UPDATE hosted_room_driver_leases
|
||||
SET gateway_id=?, authority_epoch=?, process_generation=?, lease_generation=lease_generation + 1,
|
||||
expires_at=?, acquired_at=?, updated_at=?, released_at=NULL
|
||||
@@ -771,11 +753,9 @@ def defer_indeterminate_task(
|
||||
reason = _identifier(reason, label="defer_reason")
|
||||
result_json = _canonical_json({"reason": reason, "retryable": True})
|
||||
now = _timestamp(clock)
|
||||
|
||||
def replay(row: sqlite3.Row) -> dict[str, Any] | None:
|
||||
deferred = _generations_match(row, "deferred", expected_execution_generation, expected_cancel_generation)
|
||||
return _task_from_row(row, idempotent=True) if deferred and row["result_json"] == result_json else None
|
||||
|
||||
return _generation_transition(
|
||||
db_path, identity, lease, "defer", expected_execution_generation, expected_cancel_generation, now=now,
|
||||
replay=replay, set_params=(result_json, now, now))
|
||||
@@ -796,7 +776,6 @@ def requeue_not_admitted_task(db_path: Path | str, attempt: TaskAttempt, *, cloc
|
||||
"""Return a running task to its durable queue after proven non-admission."""
|
||||
now = _timestamp(clock)
|
||||
_check_same_room(attempt.lease, attempt.identity)
|
||||
|
||||
def replay(row: sqlite3.Row) -> dict[str, Any] | None:
|
||||
requeued = (
|
||||
_generations_match(row, "queued", attempt.execution_generation, attempt.cancel_generation)
|
||||
@@ -804,7 +783,6 @@ def requeue_not_admitted_task(db_path: Path | str, attempt: TaskAttempt, *, cloc
|
||||
and row["run_process_generation"] is None
|
||||
and row["run_lease_generation"] is None)
|
||||
return _task_from_row(row, idempotent=True) if requeued else None
|
||||
|
||||
return _run_fence_transition(
|
||||
db_path, attempt, guard_stale="not-admitted task attempt lost its fence",
|
||||
lease_generation=lambda value: int(value or 0), now=now, replay=replay, sql=_REQUEUE_RUNNING_SQL,
|
||||
@@ -818,14 +796,12 @@ def cancel_task(
|
||||
cancel_id = _identifier(cancel_id, label="cancel_id")
|
||||
_cancel_generation(expected_cancel_generation)
|
||||
now = _timestamp(clock)
|
||||
|
||||
def guard(row: sqlite3.Row) -> None:
|
||||
if row["status"] in TERMINAL_STATUSES:
|
||||
raise InvalidTaskTransitionError(f"cannot cancel task in state '{row['status']}'")
|
||||
if row["status"] not in {"queued", "deferred"}:
|
||||
raise InvalidTaskTransitionError("running work requires acknowledged two-phase cancellation")
|
||||
_require_cancel_generation(row, expected_cancel_generation)
|
||||
|
||||
return _transition(
|
||||
db_path, identity, now=now, replay=_cancel_replay(cancel_id), guard=guard, sql=_CANCEL_QUEUED_SQL,
|
||||
set_params=(expected_cancel_generation + 1, cancel_id, now, now), fence_params=(expected_cancel_generation,),
|
||||
@@ -839,12 +815,10 @@ def begin_task_cancel(
|
||||
cancel_id = _identifier(cancel_id, label="cancel_id")
|
||||
_cancel_generation(expected_cancel_generation)
|
||||
now = _timestamp(clock)
|
||||
|
||||
def guard(row: sqlite3.Row) -> None:
|
||||
if row["status"] in TERMINAL_STATUSES or row["status"] == "queued":
|
||||
raise InvalidTaskTransitionError(f"cannot request remote stop in state '{row['status']}'")
|
||||
_require_cancel_generation(row, expected_cancel_generation)
|
||||
|
||||
return _transition(
|
||||
db_path, identity, now=now, replay=_cancel_replay(cancel_id, "stopping"), guard=guard, sql=_BEGIN_STOP_SQL,
|
||||
set_params=(expected_cancel_generation + 1, cancel_id, now), fence_params=(expected_cancel_generation,),
|
||||
@@ -857,12 +831,10 @@ def complete_task_cancel(
|
||||
"""Commit cancellation only after the transport acknowledges exact Stop."""
|
||||
cancel_id = _identifier(cancel_id, label="cancel_id")
|
||||
now = _timestamp(clock)
|
||||
|
||||
def guard(row: sqlite3.Row) -> None:
|
||||
if (row["status"], row["cancel_id"], int(row["cancel_generation"])) != (
|
||||
"stopping", cancel_id, expected_cancel_generation):
|
||||
raise StaleTaskError("task stop acknowledgement is stale")
|
||||
|
||||
return _transition(
|
||||
db_path, identity, now=now, replay=_cancel_replay(cancel_id), guard=guard, sql=_COMPLETE_STOP_SQL,
|
||||
set_params=(now, now), fence_params=(cancel_id, expected_cancel_generation),
|
||||
@@ -917,7 +889,6 @@ def prune_published_terminal_tasks(
|
||||
if retention_seconds <= 0:
|
||||
raise DriverValidationError("retention_seconds must be positive")
|
||||
_bounded_int(retain, message="retain must be a non-negative integer")
|
||||
|
||||
with _transaction(db_path) as conn:
|
||||
publications = conn.execute(
|
||||
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='hosted_room_policy_publications'").fetchone()
|
||||
|
||||
@@ -76,15 +76,12 @@ def execution_policy_mapping(*, target_profile: str, config: Mapping[str, Any] |
|
||||
"""Resolve the effective API-server policy from the target's own config."""
|
||||
if config is None:
|
||||
from gateway.run import _load_gateway_config
|
||||
|
||||
config = _load_gateway_config()
|
||||
if not isinstance(config, Mapping):
|
||||
raise RoomExecutionPolicyError("gateway config is invalid")
|
||||
|
||||
from hermes_cli.config import resolve_turn_limit
|
||||
from hermes_cli.tools_config import _get_platform_tools
|
||||
from tools.approval import _YOLO_MODE_FROZEN, _normalize_approval_mode
|
||||
|
||||
toolsets = sorted({*_get_platform_tools(dict(config), "api_server"), "bot_room"})
|
||||
agent = config.get("agent") if isinstance(config.get("agent"), Mapping) else {}
|
||||
approvals = config.get("approvals") if isinstance(config.get("approvals"), Mapping) else {}
|
||||
|
||||
@@ -41,7 +41,6 @@ TransportSecurity = Literal["tls", "loopback"]
|
||||
|
||||
class HostedRoomPeerError(ValueError): """Base error for malformed or unauthorized peer-room input."""
|
||||
|
||||
|
||||
class HostedRoomGrantError(HostedRoomPeerError): """Raised when a room-scoped grant is invalid or expired."""
|
||||
|
||||
|
||||
@@ -65,7 +64,6 @@ def _gateway_room_grant_secret_for_home(home_value: str) -> bytes:
|
||||
home = Path(home_value)
|
||||
home.mkdir(parents=True, exist_ok=True)
|
||||
path = home / _ROOM_GRANT_SECRET_FILE
|
||||
|
||||
def _read() -> bytes:
|
||||
data = path.read_bytes()
|
||||
if len(data) != 32:
|
||||
@@ -73,7 +71,6 @@ def _gateway_room_grant_secret_for_home(home_value: str) -> bytes:
|
||||
if stat.S_IMODE(path.stat().st_mode) & 0o077:
|
||||
path.chmod(0o600)
|
||||
return data
|
||||
|
||||
try:
|
||||
material = _read()
|
||||
except FileNotFoundError:
|
||||
@@ -107,7 +104,6 @@ def gateway_room_grant_secret(root: Path | str | None = None) -> bytes:
|
||||
"""
|
||||
if root is None:
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
# Profile routing uses a context-local HERMES_HOME override. The process
|
||||
# environment retains the installation root and is the authority here.
|
||||
root = os.environ.get("HERMES_HOME") or get_hermes_home()
|
||||
@@ -315,7 +311,6 @@ def _room_link_url_from_config(home: str) -> str | None:
|
||||
"""Read the restart-scoped user setting without polling config on probes."""
|
||||
from gateway.config import load_gateway_config
|
||||
from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override
|
||||
|
||||
if str(get_hermes_home()) == home:
|
||||
value = load_gateway_config().room_link_url
|
||||
else:
|
||||
@@ -333,7 +328,6 @@ def _configured_room_link_url() -> str | None:
|
||||
if override is not None:
|
||||
return override
|
||||
from hermes_constants import get_default_hermes_root, get_hermes_home
|
||||
|
||||
home = get_hermes_home()
|
||||
configured = _room_link_url_from_config(str(home))
|
||||
if configured:
|
||||
@@ -363,7 +357,6 @@ def validate_room_link_url(value: Any) -> tuple[str, TransportSecurity]:
|
||||
return raw, "tls"
|
||||
if parsed.scheme.lower() != "http":
|
||||
raise HostedRoomPeerError("target_url must use https")
|
||||
|
||||
loopback = hostname == "localhost" or hostname.endswith(".localhost")
|
||||
if not loopback:
|
||||
try:
|
||||
|
||||
@@ -105,7 +105,6 @@ class HostedRoomPolicyCheckpoint:
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
from hermes_state import apply_wal_with_fallback
|
||||
|
||||
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(self.db_path, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
@@ -287,7 +286,6 @@ class HostedRoomPolicyCheckpoint:
|
||||
cursor = self._ensure_cursor_and_transcript(conn, room_id)
|
||||
if cursor > latest_seq:
|
||||
raise RuntimeError("room policy cursor is ahead of the durable log")
|
||||
|
||||
while cursor < latest_seq:
|
||||
page = hosted_rooms.read_events(
|
||||
self.db_path, room_id=room_id, since_seq=cursor, limit=hosted_rooms.MAX_LOG_LIMIT)
|
||||
|
||||
@@ -32,10 +32,8 @@ _SELECT_REPLICA = "SELECT * FROM hosted_room_replicas WHERE room_id=?"
|
||||
|
||||
class ReplicaError(HostedRoomError): """Base class for invalid or conflicting replica operations."""
|
||||
|
||||
|
||||
class ReplicaGapError(ReplicaError): """A page does not start at the replica's next expected sequence."""
|
||||
|
||||
|
||||
class ReplicaEpochRegressionError(ReplicaError): """A page or demotion carries an older authority epoch than stored."""
|
||||
|
||||
|
||||
@@ -157,12 +155,10 @@ def ingest_page(
|
||||
_, members_json = _validate_members(members)
|
||||
events, authority = _validate_page(page)
|
||||
now = clock(now)
|
||||
|
||||
with _replica_transaction(db_path) as conn:
|
||||
row, stored_epoch, last_seq, stored_bytes = _replica_row_state(conn, room_id)
|
||||
if authority["epoch"] < stored_epoch:
|
||||
raise ReplicaEpochRegressionError("page authority epoch is older than the stored replica epoch")
|
||||
|
||||
new_events = [e for e in events if int(e["seq"]) > last_seq]
|
||||
if new_events and int(new_events[0]["seq"]) != last_seq + 1:
|
||||
raise ReplicaGapError("page skips sequences the replica has not stored")
|
||||
@@ -219,7 +215,6 @@ def promote_replica(
|
||||
raise ReplicaError("reason must be a non-empty string of at most 200 chars")
|
||||
now = clock(now)
|
||||
local_gateway = local_authority_gateway_id()
|
||||
|
||||
with _replica_transaction(db_path) as conn:
|
||||
replica = conn.execute(_SELECT_REPLICA, (room_id,)).fetchone()
|
||||
if replica is None:
|
||||
@@ -230,7 +225,6 @@ def promote_replica(
|
||||
raise RoomConflictError("room_id already exists in the local authoritative store")
|
||||
if conn.execute("SELECT 1 FROM hosted_room_retired_ids WHERE room_id=?", (room_id,)).fetchone():
|
||||
raise RoomConflictError("room_id belongs to a disbanded room")
|
||||
|
||||
previous_gateway = str(replica["authority_gateway_id"])
|
||||
previous_epoch = int(replica["authority_epoch"])
|
||||
target_epoch = previous_epoch + 1
|
||||
@@ -240,7 +234,6 @@ def promote_replica(
|
||||
"previous_gateway_id": previous_gateway, "authority_gateway_id": local_gateway,
|
||||
"authority_epoch": target_epoch, "promoted_from_replica": True, "reason": reason})
|
||||
claim_bytes = utf8_len(claim_event_id, "authority.claimed", claim_actor_json, claim_payload_json)
|
||||
|
||||
conn.execute("""INSERT INTO hosted_rooms
|
||||
(room_id, name, members_json, authority_gateway_id, authority_epoch, next_seq, event_bytes,
|
||||
revision, created_at, updated_at, disbanded_at)
|
||||
@@ -280,7 +273,6 @@ def demote_room(
|
||||
observed_epoch = _positive_int(observed_epoch, message="observed_epoch must be a positive integer")
|
||||
now = clock(now)
|
||||
local_gateway = local_authority_gateway_id()
|
||||
|
||||
with _transaction(db_path, immediate=True) as conn:
|
||||
row = conn.execute("""SELECT authority_gateway_id, authority_epoch, next_seq
|
||||
FROM hosted_rooms WHERE room_id=? AND disbanded_at IS NULL""", (room_id,)).fetchone()
|
||||
|
||||
@@ -185,32 +185,23 @@ _SELECT_LIVE_RESERVATION = (f"SELECT 1 FROM hosted_room_peer_reservations {_LIVE
|
||||
|
||||
class HostedRoomError(ValueError): """Base class for invalid or conflicting hosted-room operations."""
|
||||
|
||||
|
||||
class RoomNotFoundError(HostedRoomError): """Raised when a room does not exist or has been disbanded."""
|
||||
|
||||
|
||||
class RoomHistoryExpiredError(RoomNotFoundError):
|
||||
"""Raised when a retired room remains reserved after history compaction."""
|
||||
|
||||
reason = "room_history_expired"
|
||||
|
||||
|
||||
class RoomConflictError(HostedRoomError): """Raised when an idempotency key is reused for different room state."""
|
||||
|
||||
|
||||
class RoomProbeUnavailableError(HostedRoomError):
|
||||
"""Raised when a non-blocking ownership probe cannot read the room store."""
|
||||
|
||||
|
||||
class EventConflictError(HostedRoomError): """Raised when an event id is reused with different immutable content."""
|
||||
|
||||
|
||||
class AuthorityConflictError(HostedRoomError):
|
||||
"""Raised when a stale room authority attempts to mutate hosted state."""
|
||||
|
||||
reason = "authority_conflict"
|
||||
|
||||
|
||||
class AuthoritySupersededError(AuthorityConflictError):
|
||||
"""Raised when a successful authority claim was later superseded."""
|
||||
|
||||
@@ -440,7 +431,6 @@ def _schema_is_current(conn: sqlite3.Connection) -> bool:
|
||||
def default_db_path() -> Path:
|
||||
"""Return the gateway-wide state database for the active install."""
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
home = get_hermes_home()
|
||||
root = home.parent.parent if home.parent.name == "profiles" else home
|
||||
return root / "state.db"
|
||||
@@ -449,7 +439,6 @@ def default_db_path() -> Path:
|
||||
def local_authority_gateway_id() -> str:
|
||||
"""Return the stable server-owned identity for hosted-room authority."""
|
||||
from hermes_cli.install_identity import get_install_id
|
||||
|
||||
install_id = get_install_id()
|
||||
if not install_id:
|
||||
raise HostedRoomError("stable gateway install identity is unavailable")
|
||||
@@ -915,7 +904,6 @@ def create_room(
|
||||
normalized_members, members_json = _validate_members(members)
|
||||
authority_gateway_id = _actor_id(authority_gateway_id, "authority_gateway_id")
|
||||
now = _now(now)
|
||||
|
||||
with _transaction(db_path, immediate=True) as conn:
|
||||
if _is_retired(conn, room_id):
|
||||
raise RoomConflictError("room_id belongs to a disbanded room")
|
||||
@@ -936,7 +924,6 @@ def create_room(
|
||||
if existing["authority_gateway_id"] != authority_gateway_id:
|
||||
raise RoomConflictError("room_id already belongs to a different authority")
|
||||
return _room_from_row(existing, idempotent=True)
|
||||
|
||||
active_rooms = int(conn.execute("SELECT COUNT(*) FROM hosted_rooms WHERE disbanded_at IS NULL").fetchone()[0])
|
||||
if active_rooms >= MAX_ACTIVE_ROOMS:
|
||||
raise HostedRoomError("This host has too many active Group Chats. Delete one and try again.")
|
||||
@@ -1026,7 +1013,6 @@ def append_event(
|
||||
raise HostedRoomError("payload must be an object")
|
||||
payload_json = _payload_json(payload)
|
||||
now = _now(now)
|
||||
|
||||
with _transaction(db_path, immediate=True) as conn:
|
||||
existing = _load_event(conn, room_id, event_id)
|
||||
if existing is not None:
|
||||
@@ -1157,7 +1143,6 @@ def claim_authority(
|
||||
target_epoch = expected_epoch + 1
|
||||
claim_actor_json = _system_actor_json("authority-control")
|
||||
claim_payload_json = _claim_payload_json(expected_gateway_id, new_gateway_id, target_epoch)
|
||||
|
||||
with _transaction(db_path, immediate=True) as conn:
|
||||
row = _room_row(
|
||||
conn,
|
||||
@@ -1218,7 +1203,6 @@ def disband_room(
|
||||
expected_gateway_id = _actor_id(expected_gateway_id, "expected_gateway_id")
|
||||
_require_positive_int(expected_epoch, "expected_epoch")
|
||||
now = _now(now)
|
||||
|
||||
with _transaction(db_path, immediate=True) as conn:
|
||||
room = conn.execute("""SELECT authority_gateway_id, authority_epoch, next_seq, event_bytes, disbanded_at
|
||||
FROM hosted_rooms WHERE room_id=?""", (room_id,)).fetchone()
|
||||
@@ -1252,7 +1236,6 @@ def read_events(
|
||||
room_id = _room_id(room_id)
|
||||
since_seq = _non_negative(since_seq, "since_seq")
|
||||
limit = _bounded_limit(limit, MAX_LOG_LIMIT)
|
||||
|
||||
with _transaction(db_path) as conn:
|
||||
room = _room_row(
|
||||
conn,
|
||||
@@ -1280,16 +1263,13 @@ def read_events(
|
||||
WHERE cumulative_bytes<=?
|
||||
ORDER BY seq ASC""", (room_id, since_seq, limit, MAX_LOG_PAGE_BYTES)).fetchall()
|
||||
events = [_event_from_row(row) for row in rows]
|
||||
|
||||
def build_page(page_events: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
cursor = page_events[-1]["seq"] if page_events else since_seq
|
||||
return {
|
||||
"events": page_events, "cursor": cursor, "latest_seq": latest_seq, "has_more": cursor < latest_seq,
|
||||
"authority": authority}
|
||||
|
||||
def page_bytes(page: dict[str, Any]) -> int:
|
||||
return len(json.dumps(page, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
|
||||
|
||||
page = build_page(events)
|
||||
if events and page_bytes(page) > MAX_LOG_PAGE_BYTES:
|
||||
# Binary-search the largest prefix whose serialized page fits the budget.
|
||||
|
||||
@@ -118,7 +118,6 @@ def connect(
|
||||
first opener initializes the DB, especially on Windows).
|
||||
"""
|
||||
from hermes_state import apply_wal_with_fallback
|
||||
|
||||
path = Path(db_path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(path, timeout=10)
|
||||
|
||||
Reference in New Issue
Block a user