Skip to content

server

server

Async Unix domain socket server for Marianne daemon IPC.

Binds a Unix socket, accepts concurrent client connections, reads newline-delimited JSON-RPC 2.0 requests, dispatches them through RequestHandler, and writes responses back. Handles connection lifecycle and socket cleanup on shutdown.

Classes

DaemonServer

DaemonServer(socket_path, handler, *, permissions=432, backlog=100, max_connections=DEFAULT_MAX_CONNECTIONS, max_concurrent_requests=DEFAULT_MAX_CONCURRENT_REQUESTS, max_streams=DEFAULT_MAX_STREAMS, request_timeout=300.0, write_timeout=10.0, read_idle_timeout=DEFAULT_READ_IDLE_TIMEOUT, enforce_peer_uid=True)

Async Unix domain socket server with JSON-RPC 2.0 routing.

Parameters

socket_path: Filesystem path for the Unix domain socket. handler: RequestHandler that dispatches JSON-RPC methods. permissions: Octal file permissions applied to the socket after creation. Defaults to 0o660 (owner + group read/write). max_connections: Maximum simultaneous connected clients. FD protection — idle connections are cheap, so the default is high (~500). max_concurrent_requests: Maximum requests being processed at once across all connections. This is the real concurrency control (~50). read_idle_timeout: Seconds a connection may sit between complete messages before the server closes it (dead/stuck client FD hygiene). enforce_peer_uid: Refuse connections whose peer UID differs from the daemon's effective UID. Defense-in-depth over socket file permissions — the 0o660 mode admits the owning group, and root bypasses file modes entirely. On platforms where the peer UID cannot be read (no SO_PEERCRED) the gate fails open, because absence of the credential is not evidence of a foreign peer. Unix credentials are user-granular: this stops other users, not other processes running as the same user.

Source code in src/marianne/daemon/ipc/server.py
def __init__(
    self,
    socket_path: Path,
    handler: RequestHandler,
    *,
    permissions: int = 0o660,
    backlog: int = 100,
    max_connections: int = DEFAULT_MAX_CONNECTIONS,
    max_concurrent_requests: int = DEFAULT_MAX_CONCURRENT_REQUESTS,
    max_streams: int = DEFAULT_MAX_STREAMS,
    request_timeout: float = 300.0,
    write_timeout: float = 10.0,
    read_idle_timeout: float = DEFAULT_READ_IDLE_TIMEOUT,
    enforce_peer_uid: bool = True,
) -> None:
    if backlog < 1 or max_streams < 1:
        raise ValueError("backlog and max_streams must be >= 1")
    if request_timeout <= 0 or write_timeout <= 0:
        raise ValueError("request_timeout and write_timeout must be > 0")
    if max_connections < 1:
        raise ValueError(f"max_connections must be >= 1, got {max_connections}")
    if max_concurrent_requests < 1:
        raise ValueError(
            f"max_concurrent_requests must be >= 1, got {max_concurrent_requests}"
        )
    if read_idle_timeout <= 0:
        raise ValueError(
            f"read_idle_timeout must be > 0, got {read_idle_timeout}"
        )

    self._socket_path = socket_path
    self._handler = handler
    self._permissions = permissions
    self._backlog = backlog
    self._max_connections = max_connections
    self._max_concurrent_requests = max_concurrent_requests
    self._read_idle_timeout = read_idle_timeout
    self._request_timeout = request_timeout
    self._write_timeout = write_timeout
    self._enforce_peer_uid = enforce_peer_uid
    self._server: asyncio.AbstractServer | None = None
    self._socket_owner = OwnedUnixSocket(socket_path)
    self._stop_task: asyncio.Task[None] | None = None
    self._connections: set[asyncio.Task[None]] = set()
    self._connection_semaphore = asyncio.Semaphore(max_connections)
    self._request_semaphore = asyncio.Semaphore(max_concurrent_requests)
    self._stream_semaphore = asyncio.Semaphore(max_streams)
Attributes
is_running property
is_running

Return whether the server is currently accepting connections.

Methods:
start async
start()

Bind the Unix socket and start accepting connections.

Source code in src/marianne/daemon/ipc/server.py
async def start(self) -> None:
    """Bind the Unix socket and start accepting connections."""
    if self._stop_task is not None and not self._stop_task.done():
        raise RuntimeError("IPC server shutdown is still in progress")
    self._stop_task = None
    self._server = await self._socket_owner.start(
        self._accept_connection,
        permissions=self._permissions,
        backlog=self._backlog,
        limit=MAX_MESSAGE_BYTES,
    )

    _logger.info(
        "ipc_server_started",
        socket_path=str(self._socket_path),
        max_connections=self._max_connections,
        max_concurrent_requests=self._max_concurrent_requests,
    )
stop async
stop()

Finish owned cleanup before propagating caller cancellation.

Source code in src/marianne/daemon/ipc/server.py
async def stop(self) -> None:
    """Finish owned cleanup before propagating caller cancellation."""
    if self._stop_task is None:
        if self._server is None:
            return
        self._stop_task = asyncio.create_task(
            self._stop_resources(), name="ipc-server-stop",
        )
    cleanup = self._stop_task
    cancelled = False
    # A canceled caller must not cancel handler finalizers or abandon the
    # lifetime lock. Concurrent stop callers share the same owned cleanup.
    while not cleanup.done():
        try:
            await asyncio.shield(cleanup)
        except asyncio.CancelledError:
            cancelled = True
    cleanup.result()
    if cancelled:
        raise asyncio.CancelledError

Functions: