Skip to content

endpoint

endpoint

The memory gateway's Unix-socket endpoint (spec 02 BE1, BE2 teardown, BE7).

One listening socket per session, bound when the session opens (:meth:MemoryEndpoint.open_session) and unlinked when it closes (:meth:MemoryEndpoint.close_session). The session IS the socket: a request never names a session, a principal or a scope.

Security property, stated exactly

Admission is same UID, read from SO_PEERCRED at accept. That stops other users on the host. It does NOT stop another process of the same user that learns the socket path: such a process is admitted to that session like any other. The only protections against siblings are an unguessable per-dispatch path (a SHA-256 prefix, see :mod:.paths), living inside a 0700 directory, and one session per socket. No sibling isolation is claimed beyond that. No token travels on the channel.

Wire format (memory-gateway-wire/1)

Newline-delimited JSON, UTF-8, one frame per line.

  • request: {"id": <str|int>, "tool": <name>, "args": {...}, "budget_seconds"?: <number>}
  • success: {"id": ..., "ok": true, "result": {...}}
  • failure: {"id": ..., "ok": false, "error": {"code": "E#", "name": ..., "subtype": ..., "message": ..., "remedy": ...}} (errors/1)

Requests on one connection are served strictly in order. A client-supplied session/session_id/principal/scope/permissions/... field (top level or inside args) is dropped, audited as a refused attempt (result_status: refused, ignored_fields), and echoed as ignored_fields in the response; the call proceeds on the socket's session.

Failure policy: a malformed line, non-object, unknown tool or bad arguments gets a typed E7 frame and the connection stays open (framing is intact). A line over the length limit, a peer refused at accept, a connection over the per-session limit and an idle connection are closed (after one frame where a frame can be sent). The gateway's calls are synchronous and run in a worker thread; if the client disconnects mid-call the wait is cancelled and the endpoint audits cancelled (a thread cannot be interrupted, so the backend call may still complete and the gateway will also record its own outcome). Expiry of a session is enforced by the gateway on every call (E10); the socket stays bound until close_session.

Classes

MemoryEndpoint

MemoryEndpoint(gateway, *, run_dir, limits=None, peer_uid_reader=read_peer_uid, uid=None, blocking=None)

Hosts one Unix socket per gateway session under run_dir.

Source code in src/marianne/memory/gateway/endpoint.py
def __init__(
    self, gateway: Gateway, *, run_dir: Path | str, limits: EndpointLimits | None = None,
    peer_uid_reader: PeerUidReader = read_peer_uid, uid: int | None = None,
    blocking: Callable[..., Awaitable[Any]] | None = None,
) -> None:
    # Where gateway open/close (which fsync the audit log) run. A host that wants every
    # such action ordered passes its own runner; the default is a free thread.
    self._blocking: Callable[..., Awaitable[Any]] = blocking or asyncio.to_thread
    self._gateway = gateway
    self._run_dir = Path(run_dir)
    self._limits = limits or EndpointLimits()
    self._peer_uid = peer_uid_reader
    self._uid = os.getuid() if uid is None else uid
    self._bound: dict[str, _Bound] = {}
    self._inflight: dict[str, int] = {}
    self._inflight_lock = threading.Lock()
    self.max_workers = MAX_GATEWAY_WORKERS
    self._executor = ThreadPoolExecutor(
        max_workers=self.max_workers, thread_name_prefix="memory-gateway",
    )
Methods:
open_session async
open_session(**kwargs)

Admit a session on the gateway and bind its socket. Returns both.

Source code in src/marianne/memory/gateway/endpoint.py
async def open_session(self, **kwargs: Any) -> tuple[Session, Path]:
    """Admit a session on the gateway and bind its socket. Returns both."""
    # The audit append fsyncs: keep it off the event loop (the table and log are locked).
    session = await self._blocking(lambda: self._gateway.open_session(**kwargs))
    try:
        path = await self.bind(session)
    except BaseException:
        await asyncio.shield(self._blocking(self._gateway.close_session, session.session_id))
        raise
    return session, path
close_session async
close_session(session_id)

Stop listening, drop connections, wait (bounded) for in-flight calls, unlink.

Returns how many calls were still running when the wait ran out (0 when clean); each such case is audited as in_flight_at_close. The gateway session is closed either way.

Source code in src/marianne/memory/gateway/endpoint.py
async def close_session(self, session_id: str) -> int:
    """Stop listening, drop connections, wait (bounded) for in-flight calls, unlink.

    Returns how many calls were still running when the wait ran out (0 when clean); each
    such case is audited as ``in_flight_at_close``. The gateway session is closed either way.
    """
    bound = self._bound.get(session_id)
    if bound is not None:
        bound.server.close()  # no new connections while draining
        for w in list(bound.writers):
            w.close()
    end = asyncio.get_running_loop().time() + self._limits.close_wait_seconds
    while self._in_flight(session_id) and asyncio.get_running_loop().time() < end:
        await asyncio.sleep(0.02)
    left = self._in_flight(session_id)
    if left:
        with contextlib.suppress(MemoryBackendError):
            await self._blocking(
                lambda: self._gateway.audit_endpoint_event(
                    session_id, tool=None, result_status="in_flight_at_close", in_flight=left,
                )
            )
    await self.unbind(session_id)
    await asyncio.shield(self._blocking(self._gateway.close_session, session_id))
    return left
close async
close()

Close every session; returns {session_id: calls still running} for any that remain.

Source code in src/marianne/memory/gateway/endpoint.py
async def close(self) -> dict[str, int]:
    """Close every session; returns {session_id: calls still running} for any that remain."""
    report: dict[str, int] = {}
    for sid in list(self._bound):
        left = await self.close_session(sid)
        if left:
            report[sid] = left
    self._executor.shutdown(wait=False, cancel_futures=True)
    return report

Functions:

read_peer_uid

read_peer_uid(sock)

The peer's UID from SO_PEERCRED (Linux), or None when unavailable.

Source code in src/marianne/memory/gateway/endpoint.py
def read_peer_uid(sock: socket.socket) -> int | None:
    """The peer's UID from ``SO_PEERCRED`` (Linux), or ``None`` when unavailable."""
    try:
        raw = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
    except (OSError, AttributeError):
        return None
    _pid, uid, _gid = struct.unpack("3i", raw)
    return int(uid)