Skip to content

API reference

rulfo

Messaging where a request gets zero, one or many replies and always an end.

Peer

The requests to and from one remote party, over one connection after another.

Keep one Peer for each remote party, also across reconnects: it remembers the ids it ran. A second Peer for the same party runs a repeated request again. A server keeps them in a dict by the authenticated name of the caller, and can drop one when idle is true and no connection serves it.

Use it from one event loop.

PARAMETER DESCRIPTION
handlers

The handler for each key this side serves. It returns the one reply, or None after it sent its replies with Request.reply. It raises Busy to refuse.

TYPE: Mapping[str, Handler] | None DEFAULT: None

config

The settings.

TYPE: Config | None DEFAULT: None

clock

Milliseconds that never go back and count suspended time. Processes that send copies of one id need a shared clock (rule 14 in the operations page).

TYPE: Callable[[], int] | None DEFAULT: None

name

A name for the remote party. Handlers read it as Request.caller.

TYPE: str DEFAULT: ''

Source code in src/rulfo/_peer.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
class Peer:
    """The requests to and from one remote party, over one connection after another.

    Keep one ``Peer`` for each remote party, also across reconnects: it remembers the ids it ran.
    A second ``Peer`` for the same party runs a repeated request again. A server keeps them in a
    dict by the authenticated name of the caller, and can drop one when ``idle`` is true and no
    connection serves it.

    Use it from one event loop.

    Args:
        handlers: The handler for each key this side serves. It returns the one reply, or None
            after it sent its replies with ``Request.reply``. It raises ``Busy`` to refuse.
        config: The settings.
        clock: Milliseconds that never go back and count suspended time. Processes that send
            copies of one id need a shared clock (rule 14 in the operations page).
        name: A name for the remote party. Handlers read it as ``Request.caller``.
    """

    def __init__(
        self,
        *,
        handlers: Mapping[str, Handler] | None = None,
        config: Config | None = None,
        clock: Callable[[], int] | None = None,
        name: str = "",
    ) -> None:
        self.name = name
        self._calls = 0  # calls of request and request_copy that have not returned
        self._state = PeerState(config)
        self.config = self._state.config
        self._handlers = dict(handlers or {})
        self._clock = clock or _boot_clock
        self._link: _Link | None = None
        self._replace = asyncio.Lock()
        self._changed = asyncio.Event()  # set, and replaced, when a waiting call must look again
        self._pending: dict[bytes, _Pending] = {}
        self._running: set[asyncio.Task[None]] = set()
        self._timer: asyncio.TimerHandle | None = None
        self._closed = False

    @property
    def connected(self) -> bool:
        """Whether a request can be sent now."""
        return self._link is not None and self._state.ready

    @property
    def running(self) -> int:
        """Handlers that run now."""
        return len(self._running)

    @property
    def idle(self) -> bool:
        """No open request, running handler or kept id: dropping the ``Peer`` loses nothing."""
        return self._state.idle and not self._running and not self._calls

    async def wait_connected(self) -> None:
        """Returns when a request can be sent. Limit the wait with ``asyncio.timeout``.

        Raises:
            PeerClosed: ``aclose`` was called.
        """
        while not self.connected:
            if self._closed:
                raise PeerClosed
            await self._changed.wait()

    async def serve(self, transport: Transport) -> None:
        """Uses one connection until it ends, and closes it.

        A call replaces the connection of an earlier call, which then returns. The caller decides
        when to connect again.

        Raises:
            PeerClosed: ``serve`` was called after ``aclose``. A call that runs when ``aclose``
                is called returns.
            ProtocolError: The other side broke the wire format, or the handshake took too long.
            Overloaded: The other side takes too little of what this side sends.
            Exception: What ``transport`` raises.
        """
        try:
            link = await self._start_link(transport)
        except BaseException:
            await transport.close()
            raise
        tasks: list[asyncio.Task[object]] = [
            asyncio.create_task(self._read(link)),
            asyncio.create_task(self._write(link)),
            asyncio.create_task(link.stop.wait()),
        ]
        try:
            done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
            if link.error is not None:
                raise link.error
            if not link.stop.is_set():
                for task in done:
                    task.result()
        finally:
            for task in tasks:
                task.cancel()
            # Before the first await: a second cancel must not leave the connection in place.
            self._drop(link)
            link.done.set()
            try:
                await asyncio.gather(*tasks, return_exceptions=True)
            finally:
                await transport.close()

    async def _start_link(self, transport: Transport) -> _Link:
        """Ends the connection in place, and starts one on ``transport``."""
        async with self._replace:
            await self._end_link()
            if self._closed:
                raise PeerClosed
            link = _Link(transport)
            self._link = link
            self._state.connected(self._clock())
            self._after()
        return link

    async def request(
        self,
        key: str,
        body: bytes = b"",
        *,
        timeout: float,  # noqa: ASYNC109 -- the deadline that goes on the wire
    ) -> Result:
        """Sends a request and returns its outcome with the replies.

        Without a connection the outcome is ``unroutable`` at once. A request that was sent
        stays open across reconnects until ``timeout``. Cancelling the call stops the wait: the
        other side is not told, and may run the request to its end.

        Args:
            key: Which handler runs it.
            body: The bytes for the handler.
            timeout: Seconds until the request expires. All replies are kept in memory.

        Raises:
            ValueError: An empty key, or a key and body above the largest length.
            PeerClosed: ``aclose`` was called.
        """
        check_request(key, body, self.config.max_length)
        deadline = self._clock() + timeout_ms(timeout)
        return await self._call(os.urandom(_ID_SIZE), key, body, deadline, sent_before=False)

    async def request_copy(
        self,
        request_id: bytes,
        key: str,
        body: bytes = b"",
        *,
        deadline_ms: int,
        sent_before: bool,
    ) -> Result:
        """Sends a request whose id and deadline the caller chose, and returns its outcome.

        Use it when more than one process may send the same request, for example when a second
        process takes over from one that stopped. All of them pass the same id, key, body and
        deadline, and read the same clock (rule 14 in the operations page).

        With ``sent_before`` false it behaves as ``request``. With ``sent_before`` true another
        copy may have run, so the outcome is never ``unroutable`` or ``busy``: without a
        connection the call waits for one. The replier runs the request only if it does not know
        the id. A replier that cannot take it (no handler for the key, or a limit reached) does
        not answer, and the call ends ``expired`` at the deadline.

        Do not send an id again after you cancelled its call.

        Args:
            request_id: 16 random bytes, the same in every copy.
            key: Which handler runs it.
            body: The bytes for the handler.
            deadline_ms: When the request expires, in milliseconds on ``clock``.
            sent_before: Whether a copy may have been sent already. When in doubt, pass true.

        Raises:
            ValueError: An id that is not 16 bytes, a deadline too far away, an empty key, or a
                key and body above the largest length.
            CallError: This ``Peer`` already waits for this id, or ``sent_before`` is true and
                the other side does not drop repeated ids.
            PeerClosed: ``aclose`` was called.
        """
        if len(request_id) != _ID_SIZE:
            msg = f"a request id has {_ID_SIZE} bytes, not {len(request_id)}"
            raise ValueError(msg)
        check_request(key, body, self.config.max_length)
        if deadline_ms - self._clock() > _LONGEST_TIMEOUT * 1000:
            msg = f"the deadline is more than {_LONGEST_TIMEOUT} seconds away"
            raise ValueError(msg)
        return await self._call(request_id, key, body, deadline_ms, sent_before=sent_before)

    async def _call(
        self, request_id: bytes, key: str, body: bytes, deadline: int, *, sent_before: bool
    ) -> Result:
        """Waits until the request can be sent, sends it and waits for its outcome."""
        self._calls += 1
        try:
            while True:
                if self._closed:
                    raise PeerClosed
                now = self._clock()
                if now >= deadline:
                    return Result(Outcome.EXPIRED, ())
                if self._link is None and not sent_before:
                    return Result(Outcome.UNROUTABLE, ())
                if (
                    self._link is not None
                    and self._state.ready
                    and self._state.open_requests < self.config.max_requests
                    and self._buffered() <= self.config.send_buffer
                ):
                    break
                with contextlib.suppress(TimeoutError):
                    async with asyncio.timeout(min(deadline - now, _LONGEST_WAIT_MS) / 1000):
                        await self._changed.wait()
            self._state.request(request_id, key, body, deadline, now, sent_before=sent_before)
            pending = _Pending(asyncio.get_running_loop().create_future())
            self._pending[request_id] = pending
            self._after()
            try:
                return await pending.future
            finally:
                if self._pending.pop(request_id, None) is not None:  # cancelled
                    self._state.abandon(request_id)
                    self._after()
                    self._notify()
        finally:
            self._calls -= 1

    async def aclose(self) -> None:
        """Closes the connection, fails the open requests and cancels the handlers.

        Bytes that are not sent yet are dropped, also the end of a handler that just returned.
        """
        # Everything is done before the first await, so a cancelled call leaves nothing waiting.
        self._closed = True
        link = self._link
        if link is not None:
            # The connection goes first: a cancelled handler must not send an end.
            link.stop.set()
            self._drop(link)
        pending, self._pending = self._pending, {}
        for request_id, waiting in pending.items():
            self._state.abandon(request_id)
            if not waiting.future.done():
                waiting.future.set_exception(PeerClosed())
        handlers = [task for task in self._running if task is not asyncio.current_task()]
        for task in handlers:
            task.cancel()
        self._arm()
        self._notify()
        if link is not None:
            await link.done.wait()
        await asyncio.gather(*handlers, return_exceptions=True)

    def _buffered(self) -> int:
        return self._state.unsent + (self._link.sending if self._link else 0)

    async def _drain(self) -> None:
        """Waits while the connection has too many bytes to send."""
        while self._link is not None and self._buffered() > self.config.send_buffer:
            await self._changed.wait()

    def _notify(self) -> None:
        changed, self._changed = self._changed, asyncio.Event()
        changed.set()

    def _unsent_limit(self) -> int:
        """More unsent bytes than this end the connection.

        ``request`` and ``reply`` wait far below it. The refusals, the requests sent again and
        the replies sent again do not wait: a request sent again and the stored replies are
        counted here, and refusals reach the limit only when the other side stops reading.
        """
        config = self.config
        return (
            4 * config.send_buffer
            + config.max_length
            + config.replay_bytes
            + self._state.open_bytes
        )

    def _after(self) -> None:
        """Runs after every call of the state: bytes may wait and the next time may differ."""
        link = self._link
        if link is not None and not link.stop.is_set():
            if self._buffered() > self._unsent_limit():
                link.error = Overloaded("the other side does not take what is sent to it")
                link.stop.set()
            elif self._state.unsent:
                link.wake.set()
        self._arm()

    def _arm(self) -> None:
        if self._timer is not None:
            self._timer.cancel()
            self._timer = None
        due = self._state.next_time()
        if due is None or self._closed:
            return
        # At least 1 ms: a timer that fires a little early must not spin.
        wait = min(max(due - self._clock(), 1), _LONGEST_WAIT_MS)
        self._timer = asyncio.get_running_loop().call_later(wait / 1000, self._on_timer)

    def _on_timer(self) -> None:
        self._timer = None
        try:
            self._dispatch(self._state.poll(self._clock()))
        finally:
            self._after()  # or no deadline is looked at again

    async def _read(self, link: _Link) -> None:
        while not link.stop.is_set():
            data = await link.transport.recv()
            if not data or link is not self._link:
                return
            self._dispatch(self._state.receive(data, self._clock()))
            self._after()
            await asyncio.sleep(0)  # a transport with data ready must not stop the other tasks

    async def _write(self, link: _Link) -> None:
        while True:
            await link.wake.wait()
            link.wake.clear()
            if link is not self._link:
                return
            data = self._state.data_to_send()
            link.sending = len(data)
            for start in range(0, len(data), _PIECE):
                piece = data[start : start + _PIECE]
                await link.transport.send(piece)
                link.sending -= len(piece)
                self._notify()

    async def _end_link(self) -> None:
        if self._link is not None:
            self._link.stop.set()
            await self._link.done.wait()

    def _drop(self, link: _Link) -> None:
        if self._link is link:
            self._link = None
            self._state.disconnected()
            self._after()
            self._notify()

    def _dispatch(self, events: list[Event]) -> None:
        for event in events:
            match event:
                case Ready():
                    self._notify()
                case Closed(status):
                    if self._link is not None:
                        self._link.error = ProtocolError(status)
                        self._link.stop.set()
                case ReplyReceived(request_id, number, body, error):
                    if pending := self._pending.get(request_id):
                        pending.replies.append(Reply(number, body, error))
                case Ended(request_id, outcome):
                    pending = self._pending.pop(request_id, None)
                    if pending is not None and not pending.future.done():
                        pending.future.set_result(Result(outcome, tuple(pending.replies)))
                    self._notify()
                case RequestReceived():
                    self._start(event)

    def _start(self, event: RequestReceived) -> None:
        handler = self._handlers.get(event.key)
        if handler is None:
            self._state.refuse(event.id, no_handler=True)
        elif len(self._running) >= self.config.max_running:
            self._state.refuse(event.id)
        else:
            task = asyncio.create_task(self._handle(handler, event))
            self._running.add(task)
            task.add_done_callback(self._running.discard)

    def _answer_failure(self, request: Request, error: Exception, *, replied: bool) -> None:
        """Refuses a request whose handler raised ``Busy``, and reports any other error."""
        if isinstance(error, Busy) and not replied:
            self._state.refuse(request.id)
            return
        _log.error("the handler of %r failed", request.key, exc_info=error)
        message = f"{type(error).__name__}: {error}".encode(errors="replace")
        self._state.reply(request.id, message[: self.config.max_length], error=True)
        self._state.end(request.id)

    async def _handle(self, handler: Handler, event: RequestReceived) -> None:
        """Runs a handler, and ends its request in the way that matches how it finished."""
        run = _Run()

        def remaining() -> float:
            return max(0, event.deadline - self._clock()) / 1000

        async def send(body: bytes, error: bool) -> None:  # noqa: FBT001
            await self._drain()
            if run.done:
                msg = "the handler of this request has finished"
                raise RuntimeError(msg)
            self._state.reply(event.id, body, error=error)
            run.replies += 1
            self._after()

        request = Request(event, remaining, send, self.name)
        limit = asyncio.timeout(remaining())
        try:
            async with limit:
                result = await handler(request)
                if result is not None:
                    await request.reply(result)
        except Exception as error:  # noqa: BLE001 -- every failure of a handler is answered
            if limit.expired():
                self._state.give_up(request.id)
            else:
                self._answer_failure(request, error, replied=run.replies > 0)
        except BaseException:  # cancelled: it did not finish
            self._state.give_up(request.id)
            raise
        else:
            if limit.expired():  # the handler kept running through its cancellation
                self._state.give_up(request.id)
            else:
                self._state.end(request.id)
        finally:
            run.done = True
            self._after()
connected property
connected: bool

Whether a request can be sent now.

running property
running: int

Handlers that run now.

idle property
idle: bool

No open request, running handler or kept id: dropping the Peer loses nothing.

wait_connected async
wait_connected() -> None

Returns when a request can be sent. Limit the wait with asyncio.timeout.

RAISES DESCRIPTION
PeerClosed

aclose was called.

Source code in src/rulfo/_peer.py
async def wait_connected(self) -> None:
    """Returns when a request can be sent. Limit the wait with ``asyncio.timeout``.

    Raises:
        PeerClosed: ``aclose`` was called.
    """
    while not self.connected:
        if self._closed:
            raise PeerClosed
        await self._changed.wait()
serve async
serve(transport: Transport) -> None

Uses one connection until it ends, and closes it.

A call replaces the connection of an earlier call, which then returns. The caller decides when to connect again.

RAISES DESCRIPTION
PeerClosed

serve was called after aclose. A call that runs when aclose is called returns.

ProtocolError

The other side broke the wire format, or the handshake took too long.

Overloaded

The other side takes too little of what this side sends.

Exception

What transport raises.

Source code in src/rulfo/_peer.py
async def serve(self, transport: Transport) -> None:
    """Uses one connection until it ends, and closes it.

    A call replaces the connection of an earlier call, which then returns. The caller decides
    when to connect again.

    Raises:
        PeerClosed: ``serve`` was called after ``aclose``. A call that runs when ``aclose``
            is called returns.
        ProtocolError: The other side broke the wire format, or the handshake took too long.
        Overloaded: The other side takes too little of what this side sends.
        Exception: What ``transport`` raises.
    """
    try:
        link = await self._start_link(transport)
    except BaseException:
        await transport.close()
        raise
    tasks: list[asyncio.Task[object]] = [
        asyncio.create_task(self._read(link)),
        asyncio.create_task(self._write(link)),
        asyncio.create_task(link.stop.wait()),
    ]
    try:
        done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
        if link.error is not None:
            raise link.error
        if not link.stop.is_set():
            for task in done:
                task.result()
    finally:
        for task in tasks:
            task.cancel()
        # Before the first await: a second cancel must not leave the connection in place.
        self._drop(link)
        link.done.set()
        try:
            await asyncio.gather(*tasks, return_exceptions=True)
        finally:
            await transport.close()
request async
request(
    key: str, body: bytes = b"", *, timeout: float
) -> Result

Sends a request and returns its outcome with the replies.

Without a connection the outcome is unroutable at once. A request that was sent stays open across reconnects until timeout. Cancelling the call stops the wait: the other side is not told, and may run the request to its end.

PARAMETER DESCRIPTION
key

Which handler runs it.

TYPE: str

body

The bytes for the handler.

TYPE: bytes DEFAULT: b''

timeout

Seconds until the request expires. All replies are kept in memory.

TYPE: float

RAISES DESCRIPTION
ValueError

An empty key, or a key and body above the largest length.

PeerClosed

aclose was called.

Source code in src/rulfo/_peer.py
async def request(
    self,
    key: str,
    body: bytes = b"",
    *,
    timeout: float,  # noqa: ASYNC109 -- the deadline that goes on the wire
) -> Result:
    """Sends a request and returns its outcome with the replies.

    Without a connection the outcome is ``unroutable`` at once. A request that was sent
    stays open across reconnects until ``timeout``. Cancelling the call stops the wait: the
    other side is not told, and may run the request to its end.

    Args:
        key: Which handler runs it.
        body: The bytes for the handler.
        timeout: Seconds until the request expires. All replies are kept in memory.

    Raises:
        ValueError: An empty key, or a key and body above the largest length.
        PeerClosed: ``aclose`` was called.
    """
    check_request(key, body, self.config.max_length)
    deadline = self._clock() + timeout_ms(timeout)
    return await self._call(os.urandom(_ID_SIZE), key, body, deadline, sent_before=False)
request_copy async
request_copy(
    request_id: bytes,
    key: str,
    body: bytes = b"",
    *,
    deadline_ms: int,
    sent_before: bool,
) -> Result

Sends a request whose id and deadline the caller chose, and returns its outcome.

Use it when more than one process may send the same request, for example when a second process takes over from one that stopped. All of them pass the same id, key, body and deadline, and read the same clock (rule 14 in the operations page).

With sent_before false it behaves as request. With sent_before true another copy may have run, so the outcome is never unroutable or busy: without a connection the call waits for one. The replier runs the request only if it does not know the id. A replier that cannot take it (no handler for the key, or a limit reached) does not answer, and the call ends expired at the deadline.

Do not send an id again after you cancelled its call.

PARAMETER DESCRIPTION
request_id

16 random bytes, the same in every copy.

TYPE: bytes

key

Which handler runs it.

TYPE: str

body

The bytes for the handler.

TYPE: bytes DEFAULT: b''

deadline_ms

When the request expires, in milliseconds on clock.

TYPE: int

sent_before

Whether a copy may have been sent already. When in doubt, pass true.

TYPE: bool

RAISES DESCRIPTION
ValueError

An id that is not 16 bytes, a deadline too far away, an empty key, or a key and body above the largest length.

CallError

This Peer already waits for this id, or sent_before is true and the other side does not drop repeated ids.

PeerClosed

aclose was called.

Source code in src/rulfo/_peer.py
async def request_copy(
    self,
    request_id: bytes,
    key: str,
    body: bytes = b"",
    *,
    deadline_ms: int,
    sent_before: bool,
) -> Result:
    """Sends a request whose id and deadline the caller chose, and returns its outcome.

    Use it when more than one process may send the same request, for example when a second
    process takes over from one that stopped. All of them pass the same id, key, body and
    deadline, and read the same clock (rule 14 in the operations page).

    With ``sent_before`` false it behaves as ``request``. With ``sent_before`` true another
    copy may have run, so the outcome is never ``unroutable`` or ``busy``: without a
    connection the call waits for one. The replier runs the request only if it does not know
    the id. A replier that cannot take it (no handler for the key, or a limit reached) does
    not answer, and the call ends ``expired`` at the deadline.

    Do not send an id again after you cancelled its call.

    Args:
        request_id: 16 random bytes, the same in every copy.
        key: Which handler runs it.
        body: The bytes for the handler.
        deadline_ms: When the request expires, in milliseconds on ``clock``.
        sent_before: Whether a copy may have been sent already. When in doubt, pass true.

    Raises:
        ValueError: An id that is not 16 bytes, a deadline too far away, an empty key, or a
            key and body above the largest length.
        CallError: This ``Peer`` already waits for this id, or ``sent_before`` is true and
            the other side does not drop repeated ids.
        PeerClosed: ``aclose`` was called.
    """
    if len(request_id) != _ID_SIZE:
        msg = f"a request id has {_ID_SIZE} bytes, not {len(request_id)}"
        raise ValueError(msg)
    check_request(key, body, self.config.max_length)
    if deadline_ms - self._clock() > _LONGEST_TIMEOUT * 1000:
        msg = f"the deadline is more than {_LONGEST_TIMEOUT} seconds away"
        raise ValueError(msg)
    return await self._call(request_id, key, body, deadline_ms, sent_before=sent_before)
aclose async
aclose() -> None

Closes the connection, fails the open requests and cancels the handlers.

Bytes that are not sent yet are dropped, also the end of a handler that just returned.

Source code in src/rulfo/_peer.py
async def aclose(self) -> None:
    """Closes the connection, fails the open requests and cancels the handlers.

    Bytes that are not sent yet are dropped, also the end of a handler that just returned.
    """
    # Everything is done before the first await, so a cancelled call leaves nothing waiting.
    self._closed = True
    link = self._link
    if link is not None:
        # The connection goes first: a cancelled handler must not send an end.
        link.stop.set()
        self._drop(link)
    pending, self._pending = self._pending, {}
    for request_id, waiting in pending.items():
        self._state.abandon(request_id)
        if not waiting.future.done():
            waiting.future.set_exception(PeerClosed())
    handlers = [task for task in self._running if task is not asyncio.current_task()]
    for task in handlers:
        task.cancel()
    self._arm()
    self._notify()
    if link is not None:
        await link.done.wait()
    await asyncio.gather(*handlers, return_exceptions=True)

Request

A request that a handler runs.

caller is the name of the Peer it came to: with Server, the name given to Server.serve.

repeat means that the requester sent it before and this peer does not know the id: a process that ran earlier may have run it. A handler that must not run twice across a restart checks its own record when repeat is true.

Source code in src/rulfo/_peer.py
class Request:
    """A request that a handler runs.

    ``caller`` is the ``name`` of the ``Peer`` it came to: with ``Server``, the name given to
    ``Server.serve``.

    ``repeat`` means that the requester sent it before and this peer does not know the id: a
    process that ran earlier may have run it. A handler that must not run twice across a restart
    checks its own record when ``repeat`` is true.
    """

    def __init__(
        self,
        event: RequestReceived,
        remaining: Callable[[], float],
        send: Callable[[bytes, bool], Awaitable[None]],
        caller: str,
    ) -> None:
        self.caller = caller
        self.id = event.id
        self.key = event.key
        self.body = event.body
        self.repeat = event.repeat
        self._remaining = remaining
        self._send = send

    def remaining(self) -> float:
        """Seconds until the deadline, 0 after it. The handler is cancelled then."""
        return self._remaining()

    async def reply(self, body: bytes, *, error: bool = False) -> None:
        """Sends one reply. Waits while too many bytes are not yet sent.

        Without a connection the reply is stored and sent when the requester asks again.

        Raises:
            ValueError: A body longer than ``max_length``.
            RuntimeError: The handler of this request has finished.
        """
        await self._send(body, error)
remaining
remaining() -> float

Seconds until the deadline, 0 after it. The handler is cancelled then.

Source code in src/rulfo/_peer.py
def remaining(self) -> float:
    """Seconds until the deadline, 0 after it. The handler is cancelled then."""
    return self._remaining()
reply async
reply(body: bytes, *, error: bool = False) -> None

Sends one reply. Waits while too many bytes are not yet sent.

Without a connection the reply is stored and sent when the requester asks again.

RAISES DESCRIPTION
ValueError

A body longer than max_length.

RuntimeError

The handler of this request has finished.

Source code in src/rulfo/_peer.py
async def reply(self, body: bytes, *, error: bool = False) -> None:
    """Sends one reply. Waits while too many bytes are not yet sent.

    Without a connection the reply is stored and sent when the requester asks again.

    Raises:
        ValueError: A body longer than ``max_length``.
        RuntimeError: The handler of this request has finished.
    """
    await self._send(body, error)

Server

One Peer for each remote party, found by name.

The program accepts the connections, checks who is calling, and passes each one to serve with that name. The Peer of a name stays across reconnects, so a request that is sent again does not run twice. A Peer that is idle and has no connection is dropped when the next connection arrives.

Each Peer allocates memory (about 235 KB with the default max_ids), and the limits of config count for each party separately.

Use it from one event loop.

PARAMETER DESCRIPTION
handlers

The handlers of every party. Request.caller is the name of the caller.

TYPE: Mapping[str, Handler] | None DEFAULT: None

config

The settings of every Peer.

TYPE: Config | None DEFAULT: None

clock

The clock of every Peer.

TYPE: Callable[[], int] | None DEFAULT: None

Source code in src/rulfo/_server.py
class Server:
    """One ``Peer`` for each remote party, found by name.

    The program accepts the connections, checks who is calling, and passes each one to ``serve``
    with that name. The ``Peer`` of a name stays across reconnects, so a request that is sent
    again does not run twice. A ``Peer`` that is idle and has no connection is dropped when the
    next connection arrives.

    Each ``Peer`` allocates memory (about 235 KB with the default ``max_ids``), and the limits of
    ``config`` count for each party separately.

    Use it from one event loop.

    Args:
        handlers: The handlers of every party. ``Request.caller`` is the name of the caller.
        config: The settings of every ``Peer``.
        clock: The clock of every ``Peer``.
    """

    def __init__(
        self,
        *,
        handlers: Mapping[str, Handler] | None = None,
        config: Config | None = None,
        clock: Callable[[], int] | None = None,
    ) -> None:
        self.config = config or Config()
        self._handlers = dict(handlers or {})
        self._clock = clock
        self._parties: dict[str, _Party] = {}
        self._closed = False

    @property
    def connected(self) -> tuple[str, ...]:
        """The names a request can be sent to now, sorted."""
        return tuple(sorted(n for n, party in self._parties.items() if party.peer.connected))

    async def serve(self, name: str, transport: Transport) -> None:
        """Uses one connection from ``name`` until it ends, and closes it.

        A second connection with the same name replaces the first, whose call returns. Pass a
        name that you checked: whoever gives a name gets its requests.

        Raises:
            PeerClosed: ``serve`` was called after ``aclose``.
            ProtocolError: The other side broke the wire format, or the handshake took too long.
            Overloaded: The other side takes too little of what this side sends.
            Exception: What ``transport`` raises.
        """
        if self._closed:
            await transport.close()
            raise PeerClosed
        self._drop_idle()
        party = self._party(name)
        party.serving += 1
        try:
            await party.peer.serve(transport)
        finally:
            party.serving -= 1

    async def request(
        self,
        name: str,
        key: str,
        body: bytes = b"",
        *,
        timeout: float,  # noqa: ASYNC109 -- the deadline that goes on the wire
    ) -> Result:
        """Sends a request to ``name``. See ``Peer.request``.

        The outcome is ``unroutable`` when ``name`` has no connection. During the handshake of a
        connection the call waits.

        Raises:
            ValueError: An empty key, a timeout out of range, or a key and body above the
                largest length.
            PeerClosed: ``aclose`` was called.
        """
        if self._closed:
            raise PeerClosed
        party = self._parties.get(name)
        if party is None:
            check_request(key, body, self.config.max_length)
            timeout_ms(timeout)
            return Result(Outcome.UNROUTABLE, ())
        return await party.peer.request(key, body, timeout=timeout)

    async def request_copy(  # noqa: PLR0913
        self,
        name: str,
        request_id: bytes,
        key: str,
        body: bytes = b"",
        *,
        deadline_ms: int,
        sent_before: bool,
    ) -> Result:
        """Sends to ``name`` a request whose id and deadline the caller chose.

        See ``Peer.request_copy``. With ``sent_before`` true the call also waits for a name that
        has not connected yet.

        Raises:
            ValueError: As ``Peer.request_copy``.
            CallError: As ``Peer.request_copy``.
            PeerClosed: ``aclose`` was called.
        """
        if self._closed:
            raise PeerClosed
        party = self._party(name)
        try:
            return await party.peer.request_copy(
                request_id, key, body, deadline_ms=deadline_ms, sent_before=sent_before
            )
        finally:
            if party.serving == 0 and party.peer.idle and self._parties.get(name) is party:
                del self._parties[name]

    async def aclose(self) -> None:
        """Closes every ``Peer``. If this call is cancelled, call it again."""
        self._closed = True
        # One at a time, in this task: a handler that calls this must not be waited for.
        for name, party in list(self._parties.items()):
            await party.peer.aclose()
            self._parties.pop(name, None)

    def _party(self, name: str) -> _Party:
        party = self._parties.get(name)
        if party is None:
            peer = Peer(handlers=self._handlers, config=self.config, clock=self._clock, name=name)
            party = self._parties[name] = _Party(peer)
        return party

    def _drop_idle(self) -> None:
        for name, party in list(self._parties.items()):
            if party.serving == 0 and party.peer.idle:
                del self._parties[name]
connected property
connected: tuple[str, ...]

The names a request can be sent to now, sorted.

serve async
serve(name: str, transport: Transport) -> None

Uses one connection from name until it ends, and closes it.

A second connection with the same name replaces the first, whose call returns. Pass a name that you checked: whoever gives a name gets its requests.

RAISES DESCRIPTION
PeerClosed

serve was called after aclose.

ProtocolError

The other side broke the wire format, or the handshake took too long.

Overloaded

The other side takes too little of what this side sends.

Exception

What transport raises.

Source code in src/rulfo/_server.py
async def serve(self, name: str, transport: Transport) -> None:
    """Uses one connection from ``name`` until it ends, and closes it.

    A second connection with the same name replaces the first, whose call returns. Pass a
    name that you checked: whoever gives a name gets its requests.

    Raises:
        PeerClosed: ``serve`` was called after ``aclose``.
        ProtocolError: The other side broke the wire format, or the handshake took too long.
        Overloaded: The other side takes too little of what this side sends.
        Exception: What ``transport`` raises.
    """
    if self._closed:
        await transport.close()
        raise PeerClosed
    self._drop_idle()
    party = self._party(name)
    party.serving += 1
    try:
        await party.peer.serve(transport)
    finally:
        party.serving -= 1
request async
request(
    name: str,
    key: str,
    body: bytes = b"",
    *,
    timeout: float,
) -> Result

Sends a request to name. See Peer.request.

The outcome is unroutable when name has no connection. During the handshake of a connection the call waits.

RAISES DESCRIPTION
ValueError

An empty key, a timeout out of range, or a key and body above the largest length.

PeerClosed

aclose was called.

Source code in src/rulfo/_server.py
async def request(
    self,
    name: str,
    key: str,
    body: bytes = b"",
    *,
    timeout: float,  # noqa: ASYNC109 -- the deadline that goes on the wire
) -> Result:
    """Sends a request to ``name``. See ``Peer.request``.

    The outcome is ``unroutable`` when ``name`` has no connection. During the handshake of a
    connection the call waits.

    Raises:
        ValueError: An empty key, a timeout out of range, or a key and body above the
            largest length.
        PeerClosed: ``aclose`` was called.
    """
    if self._closed:
        raise PeerClosed
    party = self._parties.get(name)
    if party is None:
        check_request(key, body, self.config.max_length)
        timeout_ms(timeout)
        return Result(Outcome.UNROUTABLE, ())
    return await party.peer.request(key, body, timeout=timeout)
request_copy async
request_copy(
    name: str,
    request_id: bytes,
    key: str,
    body: bytes = b"",
    *,
    deadline_ms: int,
    sent_before: bool,
) -> Result

Sends to name a request whose id and deadline the caller chose.

See Peer.request_copy. With sent_before true the call also waits for a name that has not connected yet.

RAISES DESCRIPTION
ValueError

As Peer.request_copy.

CallError

As Peer.request_copy.

PeerClosed

aclose was called.

Source code in src/rulfo/_server.py
async def request_copy(  # noqa: PLR0913
    self,
    name: str,
    request_id: bytes,
    key: str,
    body: bytes = b"",
    *,
    deadline_ms: int,
    sent_before: bool,
) -> Result:
    """Sends to ``name`` a request whose id and deadline the caller chose.

    See ``Peer.request_copy``. With ``sent_before`` true the call also waits for a name that
    has not connected yet.

    Raises:
        ValueError: As ``Peer.request_copy``.
        CallError: As ``Peer.request_copy``.
        PeerClosed: ``aclose`` was called.
    """
    if self._closed:
        raise PeerClosed
    party = self._party(name)
    try:
        return await party.peer.request_copy(
            request_id, key, body, deadline_ms=deadline_ms, sent_before=sent_before
        )
    finally:
        if party.serving == 0 and party.peer.idle and self._parties.get(name) is party:
            del self._parties[name]
aclose async
aclose() -> None

Closes every Peer. If this call is cancelled, call it again.

Source code in src/rulfo/_server.py
async def aclose(self) -> None:
    """Closes every ``Peer``. If this call is cancelled, call it again."""
    self._closed = True
    # One at a time, in this task: a handler that calls this must not be waited for.
    for name, party in list(self._parties.items()):
        await party.peer.aclose()
        self._parties.pop(name, None)

PeerState

The state for one remote party: its open requests, the ids it sent and the bytes to send.

It does no I/O and reads no clock. Every now and deadline is in milliseconds on one clock that never goes back, does not jump and counts the time the machine is suspended.

For each connection call connected, send what data_to_send returns after every call, pass what arrives to receive, call poll at next_time, and call disconnected when the connection ends or after a Closed event. Keep the object for the next one: one PeerState stands for one remote party, and a second one for the same party would run a repeated request again.

It sends open requests again after a reconnect, and sends stored replies again when the other side asks, without events.

Source code in src/rulfo/_state.py
class PeerState:
    """The state for one remote party: its open requests, the ids it sent and the bytes to send.

    It does no I/O and reads no clock. Every ``now`` and deadline is in milliseconds on one clock
    that never goes back, does not jump and counts the time the machine is suspended.

    For each connection call ``connected``, send what ``data_to_send`` returns after every call,
    pass what arrives to ``receive``, call ``poll`` at ``next_time``, and call ``disconnected``
    when the connection ends or after a ``Closed`` event. Keep the object for the next one: one
    ``PeerState`` stands for one remote party, and a second one for the same party would run a
    repeated request again.

    It sends open requests again after a reconnect, and sends stored replies again when the other
    side asks, without events.
    """

    def __init__(self, config: Config | None = None) -> None:
        self.config = config or Config()
        settings = _config(self.config)
        size = lib.rf_peer_size(settings)
        if size == 0:
            msg = f"a setting is out of range: {self.config}"
            raise ValueError(msg)
        memory = lib.malloc(size)
        if memory == ffi.NULL:
            raise MemoryError
        self._memory = ffi.gc(memory, lib.free, size)
        made = ffi.new("rf_peer **")
        status = lib.rf_peer_init(self._memory, size, settings, made)
        if status != lib.RF_OK:
            raise _fail(status)
        self._peer = made[0]
        self._header = ffi.new("uint8_t[]", lib.RF_HEADER_SIZE)
        self._event = ffi.new("rf_event *")
        self._in = bytearray()
        self._out = bytearray()
        self._ready = False
        self._open: dict[bytes, _Open] = {}
        self._taken: dict[bytes, _Taken] = {}
        self._stored = 0
        self._free_at: list[tuple[int, bytes]] = []  # a heap of (deadline, id) with stored replies

    @property
    def ready(self) -> bool:
        """Whether the connection can carry a request."""
        return self._ready

    @property
    def open_requests(self) -> int:
        """Requests of this side without an outcome."""
        return len(self._open)

    @property
    def idle(self) -> bool:
        """No open request and no kept id: the object can be dropped without running one twice."""
        return not self._open and not self._taken

    @property
    def unsent(self) -> int:
        """Bytes that ``data_to_send`` would return."""
        return len(self._out)

    @property
    def open_bytes(self) -> int:
        """Bytes of the keys and bodies kept to send open requests again, with their headers."""
        return sum(
            lib.RF_HEADER_SIZE + len(kept.key) + len(kept.body) for kept in self._open.values()
        )

    @property
    def stored_bytes(self) -> int:
        """Memory counted for replies kept to be sent again."""
        return self._stored

    def connected(self, now: int) -> None:
        """Starts a connection. Bytes of an earlier one are dropped."""
        self._reset()
        lib.rf_connected(self._peer, now)
        self._flush()

    def disconnected(self) -> None:
        """Ends the connection. Requests, ids and stored replies are kept."""
        lib.rf_disconnected(self._peer)
        self._reset()

    def receive(self, data: bytes, now: int) -> list[Event]:
        """Reads bytes from the other side, cut anywhere, and returns what happened."""
        events: list[Event] = []
        self._in += data
        buffer = ffi.from_buffer("uint8_t[]", self._in)
        used = ffi.new("size_t *")
        offset = 0
        try:
            while True:
                length = len(self._in) - offset
                status = lib.rf_input(self._peer, buffer + offset, length, now, used, self._event)
                offset += used[0]
                self._handle(now, events)
                self._flush()
                if status not in (lib.RF_OK, lib.RF_WOULD_BLOCK):
                    break
        finally:
            ffi.release(buffer)
            del self._in[:offset]
        if status != lib.RF_NEED_MORE:
            self._in.clear()  # a protocol error, or no connection: nothing more is read
        events += self.poll(now)
        return events

    def poll(self, now: int) -> list[Event]:
        """Returns what is due at ``now``: expired requests and a handshake that took too long."""
        events: list[Event] = []
        while True:
            lib.rf_poll(self._peer, now, self._event)
            if self._event.kind == lib.RF_EV_NONE:
                break
            self._handle(now, events)
            self._flush()
        # Past the deadline the requester drops every reply: the stored ones have no use.
        while self._free_at and self._free_at[0][0] <= now:
            _, request_id = heapq.heappop(self._free_at)
            taken = self._taken.get(request_id)
            if taken is not None and taken.deadline <= now:
                self._unstore(taken)
        return events

    def next_time(self) -> int | None:
        """When to call ``poll`` next. A time that has passed means now. None: nothing is due."""
        core = lib.rf_next_time(self._peer)
        while self._free_at:
            deadline, request_id = self._free_at[0]
            taken = self._taken.get(request_id)
            if taken is not None and taken.replies is not None and taken.deadline == deadline:
                return min(core, deadline)
            heapq.heappop(self._free_at)
        return None if core == _NEVER else core

    def data_to_send(self) -> bytes:
        """All bytes that wait, in the order they go on the wire."""
        data = bytes(self._out)
        self._out.clear()
        return data

    def request(  # noqa: PLR0913
        self,
        request_id: bytes,
        key: str,
        body: bytes,
        deadline: int,
        now: int,
        *,
        sent_before: bool = False,
    ) -> None:
        """Sends a request. Its outcome comes later as ``Ended``, once.

        Args:
            request_id: 16 bytes that no other request uses.
            key: Which handler runs it. Not empty.
            body: The bytes for the handler.
            deadline: When the request expires.
            now: The time of this call.
            sent_before: An earlier copy of this id was sent, for example by another process,
                and no end arrived.

        Raises:
            ValueError: A key or a length that the wire format refuses.
            CallError: The connection cannot be used, the deadline has passed, too many requests
                are open, or the id is open.
        """
        if request_id in self._open:
            raise CallError(_STATUS[lib.RF_ERR_STATE])
        kept = _Open(key.encode(), _copy(body), deadline)
        status = self._send_request(request_id, kept, now, repeat=sent_before)
        if status != lib.RF_OK:
            raise _fail(status)
        self._open[request_id] = kept

    def abandon(self, request_id: bytes) -> None:
        """Stops waiting for a request: no event is given for it. It may still run.

        Does nothing when the request is not open. Do not use the id again.
        """
        lib.rf_abandon(self._peer, _id(request_id)[0])
        self._open.pop(request_id, None)

    def reply(self, request_id: bytes, body: bytes, *, error: bool = False) -> None:
        """Sends one reply to a received request, or only stores it when there is no connection.

        Raises:
            ValueError: A body longer than the wire format or ``max_length`` allows.
            CallError: The id is not known, or the request has ended.
        """
        ident = _id(request_id)
        kept = _copy(body)
        flags = lib.RF_REPLY_ERROR if error else 0
        status = self._write(
            lambda header: lib.rf_reply(self._peer, ident[0], len(kept), flags, header), kept
        )
        if status not in (lib.RF_OK, lib.RF_OFFLINE):
            raise _fail(status)
        self._store(request_id, flags, kept)

    def end(self, request_id: bytes) -> None:
        """Ends a received request: the requester gets ``completed``.

        Raises:
            CallError: The id is not known, or the request has ended.
        """
        ident = _id(request_id)
        status = self._write(lambda header: lib.rf_end(self._peer, ident[0], header))
        if status not in (lib.RF_OK, lib.RF_OFFLINE):
            raise _fail(status)

    def give_up(self, request_id: bytes) -> None:
        """Closes a received request that did not finish. Nothing is sent, now or on a repeat.

        The requester gets ``expired``: the request may have run in part.

        Raises:
            CallError: The id is not known, or the request has ended.
        """
        self._flush()
        status = lib.rf_end(self._peer, _id(request_id)[0], self._header)
        if status not in (lib.RF_OK, lib.RF_OFFLINE):
            raise _fail(status)
        taken = self._taken.get(request_id)
        if taken is not None:
            self._unstore(taken)

    def refuse(self, request_id: bytes, *, no_handler: bool = False) -> None:
        """Refuses a received request before its first reply, instead of running it.

        The refusal is not sent for a request that was sent again, or whose connection ended.

        Raises:
            CallError: The id is not known, or a reply or the end was sent.
        """
        ident = _id(request_id)
        flag = lib.RF_END_NO_HANDLER if no_handler else lib.RF_END_BUSY
        status = self._write(lambda header: lib.rf_refuse(self._peer, ident[0], flag, header))
        if status not in (lib.RF_OK, lib.RF_DROPPED):
            raise _fail(status)
        self._drop_taken(request_id)

    def _reset(self) -> None:
        self._ready = False
        self._in.clear()
        self._out.clear()

    def _flush(self) -> None:
        """Moves the frames the core made behind the bytes that already wait."""
        chunk = ffi.new("uint8_t[]", 256)
        while count := lib.rf_output(self._peer, chunk, len(chunk)):
            self._out += ffi.buffer(chunk, count)

    def _write(self, call: Callable[[_CData], int], *parts: bytes) -> int:
        """Makes a core call that writes a header, and queues the header and ``parts`` on OK."""
        self._flush()  # the core wants its own frames before this header
        status = call(self._header)
        if status == lib.RF_OK:
            self._out += ffi.buffer(self._header)
            for part in parts:
                self._out += part
        return status

    def _send_request(self, request_id: bytes, kept: _Open, now: int, *, repeat: bool) -> int:
        ident = _id(request_id)
        key = ffi.from_buffer("uint8_t[]", kept.key)
        wire_key = ffi.new("rf_bytes *", {"ptr": key, "len": len(kept.key)})
        return self._write(
            lambda header: lib.rf_request(
                self._peer,
                ident[0],
                wire_key[0],
                len(kept.body),
                kept.deadline,
                repeat,
                now,
                header,
            ),
            kept.key,
            kept.body,
        )

    def _handle(self, now: int, events: list[Event]) -> None:
        """Acts on the event of the core: gives it to the caller, or answers it here."""
        event = self._event
        kind = event.kind
        if kind == lib.RF_EV_NONE:
            return
        request_id = bytes(event.id.bytes)
        if kind == lib.RF_EV_READY:
            self._ready = True
            events.append(Ready())
        elif kind == lib.RF_EV_CLOSE:
            self._ready = False
            self._out.clear()
            events.append(Closed(_STATUS[event.status]))
        elif kind == lib.RF_EV_REPLY:
            error = bool(event.flags & lib.RF_REPLY_ERROR)
            events.append(ReplyReceived(request_id, event.number, _bytes(event.body), error))
        elif kind == lib.RF_EV_OUTCOME:
            self._open.pop(request_id, None)
            events.append(Ended(request_id, _OUTCOMES[event.outcome], event.number))
        elif kind == lib.RF_EV_RESEND:
            status = self._send_request(request_id, self._open[request_id], now, repeat=True)
            if status not in (lib.RF_OK, lib.RF_ERR_EXPIRED):
                raise _fail(status)
        elif kind == lib.RF_EV_REQUEST:
            self._take(request_id, event.deadline)
            events.append(
                RequestReceived(
                    request_id,
                    _bytes(event.key).decode(),
                    _bytes(event.body),
                    event.deadline,
                    bool(event.flags & lib.RF_REQUEST_REPEAT),
                )
            )
        elif kind == lib.RF_EV_REPEAT:
            self._send_again(request_id)
        else:
            self._drop_taken(request_id)  # RF_EV_FORGOT

    def _take(self, request_id: bytes, deadline: int) -> None:
        storing = self.config.replay_bytes > 0
        self._taken[request_id] = _Taken(deadline, [] if storing else None)

    def _store(self, request_id: bytes, flags: int, body: bytes) -> None:
        taken = self._taken[request_id]
        if taken.replies is None:
            return
        cost = lib.RF_HEADER_SIZE + len(body)
        if (
            taken.size + cost > self.config.replay_bytes_per_request
            or self._stored + cost > self.config.replay_bytes
        ):
            # A replay starts at reply 0, so a part of the replies is of no use.
            self._unstore(taken)
            return
        if not taken.replies:  # the first stored reply: there is something to free later
            heapq.heappush(self._free_at, (taken.deadline, request_id))
        taken.replies.append((flags, body))
        taken.size += cost
        self._stored += cost

    def _unstore(self, taken: _Taken) -> None:
        self._stored -= taken.size
        taken.size = 0
        taken.replies = None

    def _drop_taken(self, request_id: bytes) -> None:
        taken = self._taken.pop(request_id, None)
        if taken is not None:
            self._unstore(taken)

    def _send_again(self, request_id: bytes) -> None:
        """Sends every stored reply and the end, or nothing when they are not stored."""
        taken = self._taken.get(request_id)
        if taken is None or taken.replies is None:
            return
        ident = _id(request_id)
        for number, (flags, body) in enumerate(taken.replies):
            status = self._write(
                lambda header, number=number, flags=flags, body=body: lib.rf_reply_again(
                    self._peer, ident[0], number, len(body), flags, header
                ),
                body,
            )
            if status != lib.RF_OK:
                raise _fail(status)
        status = self._write(lambda header: lib.rf_end_again(self._peer, ident[0], header))
        if status not in (lib.RF_OK, lib.RF_ERR_STATE):  # ERR_STATE: not ended yet
            raise _fail(status)
ready property
ready: bool

Whether the connection can carry a request.

open_requests property
open_requests: int

Requests of this side without an outcome.

idle property
idle: bool

No open request and no kept id: the object can be dropped without running one twice.

unsent property
unsent: int

Bytes that data_to_send would return.

open_bytes property
open_bytes: int

Bytes of the keys and bodies kept to send open requests again, with their headers.

stored_bytes property
stored_bytes: int

Memory counted for replies kept to be sent again.

connected
connected(now: int) -> None

Starts a connection. Bytes of an earlier one are dropped.

Source code in src/rulfo/_state.py
def connected(self, now: int) -> None:
    """Starts a connection. Bytes of an earlier one are dropped."""
    self._reset()
    lib.rf_connected(self._peer, now)
    self._flush()
disconnected
disconnected() -> None

Ends the connection. Requests, ids and stored replies are kept.

Source code in src/rulfo/_state.py
def disconnected(self) -> None:
    """Ends the connection. Requests, ids and stored replies are kept."""
    lib.rf_disconnected(self._peer)
    self._reset()
receive
receive(data: bytes, now: int) -> list[Event]

Reads bytes from the other side, cut anywhere, and returns what happened.

Source code in src/rulfo/_state.py
def receive(self, data: bytes, now: int) -> list[Event]:
    """Reads bytes from the other side, cut anywhere, and returns what happened."""
    events: list[Event] = []
    self._in += data
    buffer = ffi.from_buffer("uint8_t[]", self._in)
    used = ffi.new("size_t *")
    offset = 0
    try:
        while True:
            length = len(self._in) - offset
            status = lib.rf_input(self._peer, buffer + offset, length, now, used, self._event)
            offset += used[0]
            self._handle(now, events)
            self._flush()
            if status not in (lib.RF_OK, lib.RF_WOULD_BLOCK):
                break
    finally:
        ffi.release(buffer)
        del self._in[:offset]
    if status != lib.RF_NEED_MORE:
        self._in.clear()  # a protocol error, or no connection: nothing more is read
    events += self.poll(now)
    return events
poll
poll(now: int) -> list[Event]

Returns what is due at now: expired requests and a handshake that took too long.

Source code in src/rulfo/_state.py
def poll(self, now: int) -> list[Event]:
    """Returns what is due at ``now``: expired requests and a handshake that took too long."""
    events: list[Event] = []
    while True:
        lib.rf_poll(self._peer, now, self._event)
        if self._event.kind == lib.RF_EV_NONE:
            break
        self._handle(now, events)
        self._flush()
    # Past the deadline the requester drops every reply: the stored ones have no use.
    while self._free_at and self._free_at[0][0] <= now:
        _, request_id = heapq.heappop(self._free_at)
        taken = self._taken.get(request_id)
        if taken is not None and taken.deadline <= now:
            self._unstore(taken)
    return events
next_time
next_time() -> int | None

When to call poll next. A time that has passed means now. None: nothing is due.

Source code in src/rulfo/_state.py
def next_time(self) -> int | None:
    """When to call ``poll`` next. A time that has passed means now. None: nothing is due."""
    core = lib.rf_next_time(self._peer)
    while self._free_at:
        deadline, request_id = self._free_at[0]
        taken = self._taken.get(request_id)
        if taken is not None and taken.replies is not None and taken.deadline == deadline:
            return min(core, deadline)
        heapq.heappop(self._free_at)
    return None if core == _NEVER else core
data_to_send
data_to_send() -> bytes

All bytes that wait, in the order they go on the wire.

Source code in src/rulfo/_state.py
def data_to_send(self) -> bytes:
    """All bytes that wait, in the order they go on the wire."""
    data = bytes(self._out)
    self._out.clear()
    return data
request
request(
    request_id: bytes,
    key: str,
    body: bytes,
    deadline: int,
    now: int,
    *,
    sent_before: bool = False,
) -> None

Sends a request. Its outcome comes later as Ended, once.

PARAMETER DESCRIPTION
request_id

16 bytes that no other request uses.

TYPE: bytes

key

Which handler runs it. Not empty.

TYPE: str

body

The bytes for the handler.

TYPE: bytes

deadline

When the request expires.

TYPE: int

now

The time of this call.

TYPE: int

sent_before

An earlier copy of this id was sent, for example by another process, and no end arrived.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError

A key or a length that the wire format refuses.

CallError

The connection cannot be used, the deadline has passed, too many requests are open, or the id is open.

Source code in src/rulfo/_state.py
def request(  # noqa: PLR0913
    self,
    request_id: bytes,
    key: str,
    body: bytes,
    deadline: int,
    now: int,
    *,
    sent_before: bool = False,
) -> None:
    """Sends a request. Its outcome comes later as ``Ended``, once.

    Args:
        request_id: 16 bytes that no other request uses.
        key: Which handler runs it. Not empty.
        body: The bytes for the handler.
        deadline: When the request expires.
        now: The time of this call.
        sent_before: An earlier copy of this id was sent, for example by another process,
            and no end arrived.

    Raises:
        ValueError: A key or a length that the wire format refuses.
        CallError: The connection cannot be used, the deadline has passed, too many requests
            are open, or the id is open.
    """
    if request_id in self._open:
        raise CallError(_STATUS[lib.RF_ERR_STATE])
    kept = _Open(key.encode(), _copy(body), deadline)
    status = self._send_request(request_id, kept, now, repeat=sent_before)
    if status != lib.RF_OK:
        raise _fail(status)
    self._open[request_id] = kept
abandon
abandon(request_id: bytes) -> None

Stops waiting for a request: no event is given for it. It may still run.

Does nothing when the request is not open. Do not use the id again.

Source code in src/rulfo/_state.py
def abandon(self, request_id: bytes) -> None:
    """Stops waiting for a request: no event is given for it. It may still run.

    Does nothing when the request is not open. Do not use the id again.
    """
    lib.rf_abandon(self._peer, _id(request_id)[0])
    self._open.pop(request_id, None)
reply
reply(
    request_id: bytes, body: bytes, *, error: bool = False
) -> None

Sends one reply to a received request, or only stores it when there is no connection.

RAISES DESCRIPTION
ValueError

A body longer than the wire format or max_length allows.

CallError

The id is not known, or the request has ended.

Source code in src/rulfo/_state.py
def reply(self, request_id: bytes, body: bytes, *, error: bool = False) -> None:
    """Sends one reply to a received request, or only stores it when there is no connection.

    Raises:
        ValueError: A body longer than the wire format or ``max_length`` allows.
        CallError: The id is not known, or the request has ended.
    """
    ident = _id(request_id)
    kept = _copy(body)
    flags = lib.RF_REPLY_ERROR if error else 0
    status = self._write(
        lambda header: lib.rf_reply(self._peer, ident[0], len(kept), flags, header), kept
    )
    if status not in (lib.RF_OK, lib.RF_OFFLINE):
        raise _fail(status)
    self._store(request_id, flags, kept)
end
end(request_id: bytes) -> None

Ends a received request: the requester gets completed.

RAISES DESCRIPTION
CallError

The id is not known, or the request has ended.

Source code in src/rulfo/_state.py
def end(self, request_id: bytes) -> None:
    """Ends a received request: the requester gets ``completed``.

    Raises:
        CallError: The id is not known, or the request has ended.
    """
    ident = _id(request_id)
    status = self._write(lambda header: lib.rf_end(self._peer, ident[0], header))
    if status not in (lib.RF_OK, lib.RF_OFFLINE):
        raise _fail(status)
give_up
give_up(request_id: bytes) -> None

Closes a received request that did not finish. Nothing is sent, now or on a repeat.

The requester gets expired: the request may have run in part.

RAISES DESCRIPTION
CallError

The id is not known, or the request has ended.

Source code in src/rulfo/_state.py
def give_up(self, request_id: bytes) -> None:
    """Closes a received request that did not finish. Nothing is sent, now or on a repeat.

    The requester gets ``expired``: the request may have run in part.

    Raises:
        CallError: The id is not known, or the request has ended.
    """
    self._flush()
    status = lib.rf_end(self._peer, _id(request_id)[0], self._header)
    if status not in (lib.RF_OK, lib.RF_OFFLINE):
        raise _fail(status)
    taken = self._taken.get(request_id)
    if taken is not None:
        self._unstore(taken)
refuse
refuse(
    request_id: bytes, *, no_handler: bool = False
) -> None

Refuses a received request before its first reply, instead of running it.

The refusal is not sent for a request that was sent again, or whose connection ended.

RAISES DESCRIPTION
CallError

The id is not known, or a reply or the end was sent.

Source code in src/rulfo/_state.py
def refuse(self, request_id: bytes, *, no_handler: bool = False) -> None:
    """Refuses a received request before its first reply, instead of running it.

    The refusal is not sent for a request that was sent again, or whose connection ended.

    Raises:
        CallError: The id is not known, or a reply or the end was sent.
    """
    ident = _id(request_id)
    flag = lib.RF_END_NO_HANDLER if no_handler else lib.RF_END_BUSY
    status = self._write(lambda header: lib.rf_refuse(self._peer, ident[0], flag, header))
    if status not in (lib.RF_OK, lib.RF_DROPPED):
        raise _fail(status)
    self._drop_taken(request_id)

StreamTransport

A connection of asyncio streams: TCP and unix sockets.

Source code in src/rulfo/_transport.py
class StreamTransport:
    """A connection of asyncio streams: TCP and unix sockets."""

    def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
        self._reader = reader
        self._writer = writer

    async def send(self, data: bytes) -> None:
        self._writer.write(data)
        await self._writer.drain()

    async def recv(self) -> bytes:
        return await self._reader.read(_CHUNK)

    async def close(self) -> None:
        self._writer.close()
        try:
            async with asyncio.timeout(_CLOSE_SECONDS):
                with contextlib.suppress(OSError):  # the connection broke: it is closed
                    await self._writer.wait_closed()
        except TimeoutError:  # the other side reads nothing: drop the waiting bytes
            self._writer.transport.abort()

Transport

Bases: Protocol

One connection. The cuts between chunks have no meaning.

Source code in src/rulfo/_transport.py
class Transport(Protocol):
    """One connection. The cuts between chunks have no meaning."""

    async def send(self, data: bytes) -> None:
        """Sends all of ``data``, at most 64 KiB. Returns when the transport can take more."""
        ...

    async def recv(self) -> bytes:
        """The next bytes that arrived, or ``b""`` when the connection has ended."""
        ...

    async def close(self) -> None:
        """Closes the connection."""
        ...
send async
send(data: bytes) -> None

Sends all of data, at most 64 KiB. Returns when the transport can take more.

Source code in src/rulfo/_transport.py
async def send(self, data: bytes) -> None:
    """Sends all of ``data``, at most 64 KiB. Returns when the transport can take more."""
    ...
recv async
recv() -> bytes

The next bytes that arrived, or b"" when the connection has ended.

Source code in src/rulfo/_transport.py
async def recv(self) -> bytes:
    """The next bytes that arrived, or ``b""`` when the connection has ended."""
    ...
close async
close() -> None

Closes the connection.

Source code in src/rulfo/_transport.py
async def close(self) -> None:
    """Closes the connection."""
    ...

Busy

Bases: RulfoError

Raised by a handler, before its first reply, to refuse the request. It did not run.

Source code in src/rulfo/_types.py
class Busy(RulfoError):  # noqa: N818
    """Raised by a handler, before its first reply, to refuse the request. It did not run."""

CallError

Bases: RulfoError

A call that is not valid now. status is the name of the core status.

Source code in src/rulfo/_types.py
class CallError(RulfoError):
    """A call that is not valid now. ``status`` is the name of the core status."""

    def __init__(self, status: str) -> None:
        super().__init__(status)
        self.status = status

Closed dataclass

The core ends the connection: close the transport and call disconnected.

Source code in src/rulfo/_types.py
@dataclass(frozen=True, slots=True)
class Closed:
    """The core ends the connection: close the transport and call ``disconnected``."""

    status: str

Config dataclass

The settings of one peer. Times are in seconds.

PARAMETER DESCRIPTION
max_length

Largest key plus body accepted.

TYPE: int DEFAULT: 16 * _MIB

handshake

Longest wait for the other side after a connection starts.

TYPE: float DEFAULT: 5.0

keep

How long a request id is kept after its deadline. Not below handshake.

TYPE: float DEFAULT: 60.0

max_requests

Open requests this side can have.

TYPE: int DEFAULT: 64

max_ids

Request ids this side keeps as the replier. New requests above max_ids / (deadline + keep) per second are refused as busy.

TYPE: int DEFAULT: 4096

max_deadline

A request with a deadline further away is refused as busy.

TYPE: float DEFAULT: 3600.0

replay_bytes

Memory for sent replies, to send them again after a reconnect. 0 stores none.

TYPE: int DEFAULT: 16 * _MIB

replay_bytes_per_request

The same for one request. A request that goes over stores none.

TYPE: int DEFAULT: _MIB

max_running

Handlers that run at once. Above it a request is refused as busy.

TYPE: int DEFAULT: 64

send_buffer

request and reply wait while more bytes than this are not yet sent.

TYPE: int DEFAULT: _MIB

Source code in src/rulfo/_types.py
@dataclass(frozen=True, slots=True)
class Config:
    """The settings of one peer. Times are in seconds.

    Args:
        max_length: Largest key plus body accepted.
        handshake: Longest wait for the other side after a connection starts.
        keep: How long a request id is kept after its deadline. Not below ``handshake``.
        max_requests: Open requests this side can have.
        max_ids: Request ids this side keeps as the replier. New requests above
            ``max_ids / (deadline + keep)`` per second are refused as busy.
        max_deadline: A request with a deadline further away is refused as busy.
        replay_bytes: Memory for sent replies, to send them again after a reconnect. 0 stores none.
        replay_bytes_per_request: The same for one request. A request that goes over stores none.
        max_running: Handlers that run at once. Above it a request is refused as busy.
        send_buffer: ``request`` and ``reply`` wait while more bytes than this are not yet sent.
    """

    max_length: int = 16 * _MIB
    handshake: float = 5.0
    keep: float = 60.0
    max_requests: int = 64
    max_ids: int = 4096
    max_deadline: float = 3600.0
    replay_bytes: int = 16 * _MIB
    replay_bytes_per_request: int = _MIB
    max_running: int = 64
    send_buffer: int = _MIB

Ended dataclass

A request of this side ended with outcome after replies replies.

Source code in src/rulfo/_types.py
@dataclass(frozen=True, slots=True)
class Ended:
    """A request of this side ended with ``outcome`` after ``replies`` replies."""

    id: bytes
    outcome: Outcome
    replies: int

NotCompleted

Bases: RulfoError

The request has another outcome than completed.

Source code in src/rulfo/_types.py
class NotCompleted(RulfoError):  # noqa: N818
    """The request has another outcome than ``completed``."""

    def __init__(self, result: Result) -> None:
        super().__init__(result.outcome.value)
        self.result = result

Outcome

Bases: Enum

How a request ended.

Source code in src/rulfo/_types.py
class Outcome(enum.Enum):
    """How a request ended."""

    COMPLETED = "completed"
    """The handler ran and every reply it sent arrived."""
    BUSY = "busy"
    """Refused. It did not run."""
    EXPIRED = "expired"
    """The deadline passed first. It may have run."""
    UNROUTABLE = "unroutable"
    """No handler for the key, or no connection to send it on. It did not run."""
COMPLETED class-attribute instance-attribute
COMPLETED = 'completed'

The handler ran and every reply it sent arrived.

BUSY class-attribute instance-attribute
BUSY = 'busy'

Refused. It did not run.

EXPIRED class-attribute instance-attribute
EXPIRED = 'expired'

The deadline passed first. It may have run.

UNROUTABLE class-attribute instance-attribute
UNROUTABLE = 'unroutable'

No handler for the key, or no connection to send it on. It did not run.

Overloaded

Bases: RulfoError

The other side takes too little of what is sent to it: the connection was ended.

Source code in src/rulfo/_types.py
class Overloaded(RulfoError):  # noqa: N818
    """The other side takes too little of what is sent to it: the connection was ended."""

PeerClosed

Bases: RulfoError

The peer was closed.

Source code in src/rulfo/_types.py
class PeerClosed(RulfoError):  # noqa: N818
    """The peer was closed."""

ProtocolError

Bases: RulfoError

The other side broke the wire format. status is the name of the core status.

Source code in src/rulfo/_types.py
class ProtocolError(RulfoError):
    """The other side broke the wire format. ``status`` is the name of the core status."""

    def __init__(self, status: str) -> None:
        super().__init__(status)
        self.status = status

Ready dataclass

The connection can be used.

Source code in src/rulfo/_types.py
@dataclass(frozen=True, slots=True)
class Ready:
    """The connection can be used."""

RemoteError

Bases: RulfoError

The handler replied with an error.

Source code in src/rulfo/_types.py
class RemoteError(RulfoError):
    """The handler replied with an error."""

Reply dataclass

One reply. error marks a reply that reports a failure of the handler.

Source code in src/rulfo/_types.py
@dataclass(frozen=True, slots=True)
class Reply:
    """One reply. ``error`` marks a reply that reports a failure of the handler."""

    number: int
    body: bytes
    error: bool

ReplyReceived dataclass

A reply to a request of this side.

Source code in src/rulfo/_types.py
@dataclass(frozen=True, slots=True)
class ReplyReceived:
    """A reply to a request of this side."""

    id: bytes
    number: int
    body: bytes
    error: bool

RequestReceived dataclass

A request to run. Each one needs end, refuse or give_up.

deadline is in milliseconds on this side's clock. repeat means that the requester sent it before and this side does not know the id: a process that ran earlier may have run it.

Source code in src/rulfo/_types.py
@dataclass(frozen=True, slots=True)
class RequestReceived:
    """A request to run. Each one needs ``end``, ``refuse`` or ``give_up``.

    ``deadline`` is in milliseconds on this side's clock. ``repeat`` means that the requester
    sent it before and this side does not know the id: a process that ran earlier may have run it.
    """

    id: bytes
    key: str
    body: bytes
    deadline: int
    repeat: bool

Result dataclass

The outcome of a request and the replies that arrived.

Source code in src/rulfo/_types.py
@dataclass(frozen=True, slots=True)
class Result:
    """The outcome of a request and the replies that arrived."""

    outcome: Outcome
    replies: tuple[Reply, ...]

    def one(self) -> bytes:
        """The body of the only reply of a completed request.

        Raises:
            NotCompleted: The outcome is not ``completed``.
            RemoteError: The reply is an error reply.
            ValueError: The request completed with no reply or with more than one.
        """
        if self.outcome is not Outcome.COMPLETED:
            raise NotCompleted(self)
        if len(self.replies) != 1:
            msg = f"expected one reply, got {len(self.replies)}"
            raise ValueError(msg)
        reply = self.replies[0]
        if reply.error:
            raise RemoteError(reply.body.decode(errors="replace"))
        return reply.body
one
one() -> bytes

The body of the only reply of a completed request.

RAISES DESCRIPTION
NotCompleted

The outcome is not completed.

RemoteError

The reply is an error reply.

ValueError

The request completed with no reply or with more than one.

Source code in src/rulfo/_types.py
def one(self) -> bytes:
    """The body of the only reply of a completed request.

    Raises:
        NotCompleted: The outcome is not ``completed``.
        RemoteError: The reply is an error reply.
        ValueError: The request completed with no reply or with more than one.
    """
    if self.outcome is not Outcome.COMPLETED:
        raise NotCompleted(self)
    if len(self.replies) != 1:
        msg = f"expected one reply, got {len(self.replies)}"
        raise ValueError(msg)
    reply = self.replies[0]
    if reply.error:
        raise RemoteError(reply.body.decode(errors="replace"))
    return reply.body

RulfoError

Bases: Exception

The base of the errors of rulfo.

Source code in src/rulfo/_types.py
class RulfoError(Exception):
    """The base of the errors of rulfo."""

rulfo.testing

Helpers for the tests of a program that uses rulfo.

memory_pair

memory_pair() -> tuple[Transport, Transport]

Two transports connected to each other in memory. Closing one ends both.

Source code in src/rulfo/testing.py
def memory_pair() -> tuple[Transport, Transport]:
    """Two transports connected to each other in memory. Closing one ends both."""
    there: asyncio.Queue[bytes] = asyncio.Queue()
    back: asyncio.Queue[bytes] = asyncio.Queue()
    return _MemoryTransport(back, there), _MemoryTransport(there, back)