Coverage for core / src / sensorkit / backend / request.py: 98%
295 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
1# SPDX-License-Identifier: Apache-2.0
2from __future__ import annotations
4import asyncio
5import contextlib
6import functools
7import uuid
8from abc import ABC, abstractmethod
9from collections.abc import Awaitable, Coroutine, Generator
10from dataclasses import dataclass
11from datetime import UTC, datetime, timedelta
12from typing import Any, Callable, ClassVar, Literal, cast, final, override
14from loguru import logger
15from pydantic import BaseModel
17from sensorkit.backend.base import (
18 Backend,
19 RemoteRequestError,
20 RequestResponseContext,
21 StreamContext,
22)
23from sensorkit.backend.event import Event, EventMultiplexer
24from sensorkit.common.aio import cleanup_future, scoped_waiter
26type ReplyState = Literal["accepted", "rejected", "succeeded", "failed"]
29class CallRequest[P: BaseModel | None = Any](BaseModel):
30 """The envelope a call is sent in.
32 Carries when the call was sent alongside the caller's message, so the message model holds only
33 application data. A handler rejects a call it cannot answer within the caller's reply budget.
34 Peer clocks must agree within the reply margin.
36 Left unparametrized, the message is kept as plain JSON data.
37 """
38 sent_at: datetime
39 """When the caller sent the call."""
40 message: P | None = None
41 """The caller's message, where the request declares one."""
43 def age(self) -> float:
44 """Return the seconds since the caller sent the call."""
45 return (datetime.now(UTC) - self.sent_at).total_seconds()
48class CallReply[R: BaseModel | None = Any](BaseModel):
49 """The direct reply to a call.
51 Carries the state of the call alongside the handler's response, so the response model holds
52 only application data. A simple request succeeds or fails in its reply. A long-running request
53 is accepted or rejected in its reply, and reports its outcome on the entity event stream.
55 Left unparametrized, the response is kept as plain JSON data.
56 """
57 call_id: uuid.UUID
58 """Identifies the call, and matches the events a long-running call publishes."""
59 state: ReplyState
60 """Where the call stands once the handler has replied."""
61 response: R | None = None
62 """The handler's response, where it gave one."""
63 reason: str | None = None
64 """Why the call was rejected or failed."""
65 details: str | None = None
66 """Diagnostic detail for a failed call, such as the handler's traceback."""
69class Call[R: BaseModel | None, V: BaseModel | None = R](Awaitable[V]):
70 """An invocation of a simple request.
72 Args:
73 context: The request context of the entity serving the request.
74 name: The request name.
75 message: The caller's message, a model or plain JSON data.
76 response_type: The type expected in the reply.
77 """
79 def __init__(
80 self,
81 context: RequestResponseContext,
82 name: str,
83 message: Any,
84 response_type: type[R] | None,
85 ):
86 self._context = context
87 self._name = name
88 self._message = message
89 self._sent = False
90 self._reply_type: type[CallReply[R]] = CallReply[response_type]
91 self._future: asyncio.Future[V] = asyncio.get_running_loop().create_future()
92 self._got_response = False
93 self.response: R | None = None
95 self._future.add_done_callback(cleanup_future)
97 @final
98 async def _invoke(self, expected: ReplyState) -> CallReply[R]:
99 if self._sent:
100 raise RuntimeError("Call has already been sent")
102 self._sent = True
104 # Stamp the call as it is sent, so no wait before sending counts against its age.
105 request = CallRequest(sent_at=datetime.now(UTC), message=self._message)
106 recv = await self._context.invoke(self._name, request.model_dump_json().encode())
108 reply = self._reply_type.model_validate_json(recv)
109 self.response = reply.response
110 self._got_response = True
112 match reply.state:
113 case "failed":
114 raise RemoteRequestError(reply.reason, details=reply.details)
115 case "rejected":
116 raise CallRejected(
117 f"call rejected: {reply.reason}" if reply.reason else "call rejected"
118 )
119 case state if state != expected:
120 raise CallError(f"unexpected {state} reply")
122 return reply
124 async def invoke(self):
125 """Send the request and populate the future with the response.
127 Raises:
128 ReplyTimeout: if no reply arrives within the reply budget.
129 """
130 try:
131 await self._invoke("succeeded")
132 self._future.set_result(cast(V, self.response))
133 return self.response
134 except BaseException as e:
135 self._future.set_exception(e)
136 raise
138 async def wait(self):
139 """Wait until the call's future is resolved."""
140 await self._future
142 def get_future(self) -> asyncio.Future[V]:
143 """Return the underlying future resolving to the call's final result."""
144 return self._future
146 def done(self):
147 """Return True if the call has completed (success or error)."""
148 return self._future.done()
150 def result(self) -> V:
151 """Return the call result, raising if the call has not completed or raised."""
152 return self._future.result()
154 async def run_to_completion(self) -> V:
155 """Invoke the call if not already sent, then await and return the final result."""
156 if not self._got_response:
157 await self.invoke()
159 await self._future
160 return self._future.result()
162 @override
163 def __await__(self) -> Generator[Any, None, V]:
164 return self.run_to_completion().__await__()
167type HandlerFunc[P: BaseModel | None, R: BaseModel | None] = Callable[[P], Coroutine[Any, Any, R]]
168"""A simple request handler. A request that declares no message types it as None."""
171class CallHandler[P: BaseModel | None]:
172 """Adapts a request handler to the backend's bytes in, bytes out contract.
174 Every call gets a reply, including one whose handler raised. A request with no message type
175 passes None, keeping every handler the same arity. A call that arrives too late to be answered
176 within its caller's reply budget is rejected without running the handler.
177 """
179 def __init__(
180 self,
181 message: type[P] | None,
182 run: Callable[..., Awaitable[CallReply]],
183 ):
184 self._message = message
185 self._request_type: type[CallRequest] = CallRequest[message] if message else CallRequest
187 # Simple and long-running requests share this class, differing only in the runner bound.
188 self._run = run
190 async def __call__(self, payload: bytes) -> bytes:
191 call_id = uuid.uuid1()
193 try:
194 request = self._request_type.model_validate_json(payload)
196 if (age := request.age()) > Backend.REPLY_TIMEOUT - Backend.REPLY_MARGIN:
197 logger.warning(f"Rejecting call received {age:.1f} s after it was sent")
198 reply = CallReply(
199 call_id=call_id, state="rejected", reason="call arrived too late"
200 )
201 else:
202 reply = await self._run(call_id, request.message if self._message else None)
204 # The caller has stopped waiting, so anything the handler started runs unobserved.
205 if (age := request.age()) > Backend.REPLY_TIMEOUT:
206 logger.warning(f"Replying to call {call_id} {age:.1f} s after it was sent")
207 except Exception as e:
208 logger.opt(exception=e).debug(f"Call {call_id} failed in its handler")
209 error = RemoteRequestError.from_exception(e)
211 reply = CallReply(
212 call_id=call_id,
213 state="failed",
214 reason=str(error),
215 details=error.details,
216 )
218 return reply.model_dump_json().encode()
221async def run_call[R: BaseModel | None](
222 func: HandlerFunc[Any, R],
223 call_id: uuid.UUID,
224 message: BaseModel | None,
225) -> CallReply[R]:
226 """Run a simple handler func and return the reply carrying its response."""
227 return CallReply(call_id=call_id, state="succeeded", response=await func(message))
230class CallEvent(Event):
231 """An event that occurs in the context of a long-running request."""
232 call_id: uuid.UUID
233 call_state: Literal["running", "success", "failure"] = "running"
234 good_until: datetime | None
235 payload: Any = None
238class LongCall[R: BaseModel | None, V: BaseModel | None](Call[R, V]):
239 """A Call extension that supports long-running requests."""
241 FIRST_EVENT_TIMEOUT: ClassVar[float] = 10.0
242 """Seconds a caller waits for the first event of an accepted long-running call."""
244 def __init__(
245 self,
246 context: RequestResponseContext,
247 name: str,
248 message: Any,
249 response_type: type[R] | None,
250 result_type: type[V] | None,
251 event_mux: EventMultiplexer,
252 ):
253 super().__init__(context, name, message, response_type)
254 self._result_type = result_type
255 self._event_mux = event_mux
256 self._task: asyncio.Task[V] | None = None
258 @override
259 async def run_to_completion(self) -> V:
260 """Invoke the call if not already sent, then await and return the final result.
262 Leaves no local work running on any exit, including cancellation. The request itself is
263 not retracted, so a handler that accepted it keeps running it.
264 """
265 try:
266 return await super().run_to_completion()
267 finally:
268 # Cancelling the caller cancels the future but not the event task, which would keep its
269 # queue until the peer's lease lapses. A second cancellation during this wait leaves
270 # the task already cancelled, so it still ends on its next step.
271 if self._task is not None and not self._task.done():
272 self._task.cancel()
273 await asyncio.wait({self._task})
275 @override
276 async def invoke(self):
277 # Consume the event stream.
278 context = contextlib.ExitStack()
279 queue = context.enter_context(self._event_mux.event_queue(CallEvent))
281 try:
282 await self._event_mux.wait_ready()
284 # Execute the initial request-response communication.
285 reply = await self._invoke("accepted")
286 except (asyncio.CancelledError, Exception) as e:
287 context.close()
288 self._future.set_exception(e)
289 raise
291 # Start a background task to receive response progress and end events.
292 started = asyncio.Event()
294 self._task = asyncio.create_task(
295 self._await_response_events(
296 context,
297 queue,
298 reply.call_id,
299 started,
300 )
301 )
303 def long_call_done(t: asyncio.Task):
304 # Note we must check the task exception even if the future is already done to avoid
305 # leaks and warnings.
306 if t.cancelled():
307 self._future.cancel()
308 elif err := t.exception():
309 if not self._future.done():
310 self._future.set_exception(err)
311 elif not self._future.done():
312 self._future.set_result(t.result())
314 self._task.add_done_callback(long_call_done)
316 # Wait until the first event is received or the task ends for some reason, whichever
317 # comes first.
318 async with scoped_waiter(started.wait()) as wait:
319 await asyncio.wait(
320 [wait, self._task],
321 return_when=asyncio.FIRST_COMPLETED,
322 )
324 return self.response
326 async def _await_response_events(
327 self,
328 context: contextlib.ExitStack,
329 queue: asyncio.Queue[Event],
330 response_id: uuid.UUID,
331 started: asyncio.Event,
332 ) -> V:
333 timeout = self.FIRST_EVENT_TIMEOUT
335 with context:
336 while True:
337 async with asyncio.timeout(timeout):
338 # Consume the next matching ResponseEvent.
339 event = await queue.get()
340 queue.task_done()
342 if not isinstance(event, CallEvent) or event.call_id != response_id:
343 continue
345 match event.call_state:
346 case "success":
347 return cast(
348 V,
349 self._result_type.model_validate(event.payload)
350 if self._result_type is not None
351 else None
352 )
353 case "failure":
354 raise CallError(f"response failed: {event.payload}")
356 # Signal that at least one matching response event has been received.
357 started.set()
359 # Figure the next timeout. This relies on peer clock synchronization.
360 timeout = (event.good_until - datetime.now(UTC)).total_seconds()
362 # Unreachable.
363 raise RuntimeError
366type LongHandlerFunc[P: BaseModel | None, R: BaseModel | None, V: BaseModel | None] = (
367 Callable[[P, CallContext[V, R]], Coroutine[Any, Any, None]]
368)
369"""A long-running request handler."""
371type RequestHandlerFunc[P: BaseModel | None, R: BaseModel | None, V: BaseModel | None] = (
372 HandlerFunc[P, R] | LongHandlerFunc[P, R, V]
373)
374"""Any handler shape a request may be declared with."""
377class CallContext[V: BaseModel | None, R: BaseModel | None = None]:
378 """Context for an incoming long-running request currently being handled."""
380 def __init__(self, call_id: uuid.UUID, stream: StreamContext):
381 self.call_id = call_id
382 self._stream = stream
383 self.reply: asyncio.Future[CallReply[R]] = asyncio.get_running_loop().create_future()
384 self.finalized = False
385 """Whether the call ended by rejection or a published end event."""
387 @property
388 def responded(self) -> bool:
389 """Whether the handler has accepted or rejected the call."""
390 return self.reply.done()
392 def accept(self, *, response: R | None = None):
393 """Accept the call and send the initial response, allowing progress events to follow."""
394 self._respond(CallReply(call_id=self.call_id, state="accepted", response=response))
396 def reject(self, *, response: R | None = None, reason: str | None = None):
397 """Reject the call, ending it without further events.
399 Args:
400 response: The initial response, for a caller that needs it despite the rejection.
401 reason: Why the call was rejected.
402 """
403 self._respond(
404 CallReply(call_id=self.call_id, state="rejected", response=response, reason=reason)
405 )
406 self.finalized = True
408 def _respond(self, reply: CallReply[R]):
409 if self.responded:
410 raise HandlerResponseError(responded=True)
412 self.reply.set_result(reply)
414 async def progress(self, ttl: float):
415 """Emit a progress event, extending the caller's deadline by ttl seconds."""
416 if not self.responded:
417 raise HandlerResponseError(responded=False)
419 await self._call_event(
420 CallEvent(
421 call_id=self.call_id,
422 call_state="running",
423 good_until=datetime.now(UTC) + timedelta(seconds=ttl),
424 )
425 )
427 async def progress_from_task(self, task: asyncio.Task, *, cadence: float, ttl: float):
428 """Emit progress events at the given cadence until task completes, then await the task."""
429 done = None
430 fs = [task]
432 while not done:
433 await self.progress(ttl)
434 done, _ = await asyncio.wait(fs, timeout=cadence)
436 # Raise if the task raised.
437 await task
439 async def succeed(self, *, result: V):
440 """Emit a success event carrying the final result, completing the long-running call."""
441 if not self.responded:
442 raise HandlerResponseError(responded=False)
444 await self._call_event(
445 CallEvent(
446 call_id=self.call_id,
447 call_state="success",
448 good_until=None,
449 payload=result,
450 ),
451 finalize=True,
452 )
454 async def fail(self, reason: str | None = None):
455 """Emit a failure event, completing the long-running call in a failed state."""
456 if not self.responded:
457 raise HandlerResponseError(responded=False)
459 await self._call_event(
460 CallEvent(
461 call_id=self.call_id,
462 call_state="failure",
463 good_until=None,
464 payload=reason,
465 ),
466 finalize=True,
467 )
469 async def _call_event(self, event: CallEvent, finalize: bool = False):
470 if self.finalized:
471 raise HandlerError("Call has already been finalized")
473 await self._stream.publish_event(event.model_dump_json().encode())
475 # An unpublished end event leaves the call open for another. One that failed may still have
476 # been delivered, so callers act on the first end event they receive.
477 if finalize:
478 self.finalized = True
481_pending_failures: set[asyncio.Task] = set()
482"""Failure tasks for abandoned calls, held so the event loop cannot collect them early."""
485def _failure_task_done(task: asyncio.Task):
486 if not task.cancelled() and (error := task.exception()):
487 logger.debug(f"Could not fail abandoned call: {error}")
489 _pending_failures.discard(task)
492# TODO: Fold finalization into the handler coroutine so this callback and its detached task go
493# away. That also closes the race where a task the handler spawned finalizes between the
494# check here and the failure task running. The handler task still needs an owner after
495# that, so teardown can fail in flight calls rather than drop them, and a handler that is
496# cancelled after accepting stops leaving its caller to time out on the event stream.
497def _fail_abandoned_call(context: CallContext[Any, Any], handler_task: asyncio.Task):
498 """Fail a call whose handler exited without finalizing it.
500 The handler task's exception is always retrieved, even when the call is already settled,
501 so that asyncio does not report it as never retrieved.
502 """
503 if handler_task.cancelled():
504 return
506 error = handler_task.exception()
508 if context.finalized:
509 if error is not None:
510 logger.debug(f"Exception raised after call was finalized: {error}")
512 return
514 reason = None if error is None else str(error)
515 suffix = "" if reason is None else f" with error {reason}"
517 logger.debug(f"Failing unfinalized call handler{suffix}")
518 task = asyncio.create_task(context.fail(reason))
520 _pending_failures.add(task)
521 task.add_done_callback(_failure_task_done)
524async def run_long_call[R: BaseModel | None, V: BaseModel | None](
525 func: LongHandlerFunc[Any, R, V],
526 stream: StreamContext,
527 call_id: uuid.UUID,
528 message: BaseModel | None,
529) -> CallReply[R]:
530 """Run a long-running handler func and return the reply for the caller.
532 The handler keeps running after this returns, publishing progress and end events to the
533 entity event stream until the call is finalized.
535 Raises:
536 HandlerResponseError: if the handler returned without accepting or rejecting.
537 """
538 # Create the call context object and run the call handler func.
539 context: CallContext[V, R] = CallContext(call_id, stream)
540 handler_task = asyncio.create_task(func(message, context))
542 # Wait for the handler to reply or exit, whichever comes first.
543 await asyncio.wait(
544 [
545 handler_task,
546 context.reply,
547 ],
548 return_when=asyncio.FIRST_COMPLETED,
549 )
551 if not context.responded:
552 # The handler exited without accepting or rejecting. The caller has no call id to follow
553 # events by, so the error goes back on the reply. A cancelled handler has no exception of
554 # its own to report.
555 if not handler_task.cancelled() and (error := handler_task.exception()):
556 raise error
558 raise HandlerResponseError(responded=False)
560 # Once the handler has replied, anything that ends the call is reported on the event stream,
561 # including the handler exiting without finalizing it.
562 handler_task.add_done_callback(functools.partial(_fail_abandoned_call, context))
563 return context.reply.result()
566class CallError(Exception):
567 """Raised to a caller when a call is rejected or fails."""
570class CallRejected(CallError):
571 """The remote handler explicitly rejected the call."""
574class HandlerError(Exception):
575 """Raised when a request handler is declared or used in an invalid state."""
578class HandlerResponseError(HandlerError):
579 def __init__(self, *, responded: bool):
580 self.responded = responded
581 problem = "has already called" if responded else "did not call"
582 super().__init__(f"Call handler {problem} `accept` or `reject`")
585@dataclass(frozen=True, eq=False)
586class RequestBase[P: BaseModel | None, R: BaseModel | None, V: BaseModel | None](ABC):
587 """A declaration of a callable request.
589 Use `declare_request` or `declare_long_request` to build one, rather than constructing it
590 directly.
591 """
592 name: str
593 """The name of the request."""
594 message: type[P] | None
595 """The type expected to be sent in the request call."""
596 response: type[R] | None
597 """The type expected to be received in the call reply."""
598 result: type[V] | None
599 """The type a caller receives once the call completes."""
601 @abstractmethod
602 def create_handler(
603 self,
604 func: RequestHandlerFunc[P, R, V],
605 stream: StreamContext | None = None,
606 ) -> CallHandler[P]:
607 """Build the backend callback for this request.
609 Args:
610 func: The handler to run for each incoming call.
611 stream: The entity event stream, required for a long-running request.
612 """
614 @abstractmethod
615 def create_call(
616 self,
617 context: RequestResponseContext,
618 message: P | None = None,
619 event_mux: EventMultiplexer | None = None,
620 ) -> Call[R, V]:
621 """Build a call of this request, sent once invoked.
623 Args:
624 context: The request context of the entity serving the request.
625 message: The message to send, for a request that declares one.
626 event_mux: The serving entity's events, required for a long-running request.
627 """
630class Request[P: BaseModel | None, R: BaseModel | None](RequestBase[P, R, R]):
631 """A request that its handler answers immediately, with a response that is the whole result."""
633 @override
634 def create_handler(
635 self,
636 func: RequestHandlerFunc[P, R, R],
637 stream: StreamContext | None = None,
638 ) -> CallHandler[P]:
639 return CallHandler(self.message, functools.partial(run_call, func))
641 @override
642 def create_call(
643 self,
644 context: RequestResponseContext,
645 message: P | None = None,
646 event_mux: EventMultiplexer | None = None,
647 ) -> Call[R, R]:
648 return Call(context, self.name, message, self.response)
651class LongRequest[P: BaseModel | None, R: BaseModel | None, V: BaseModel | None](
652 RequestBase[P, R, V]
653):
654 """A request that keeps running after its handler replies, reporting its result as an event."""
656 @override
657 def create_handler(
658 self,
659 func: RequestHandlerFunc[P, R, V],
660 stream: StreamContext | None = None,
661 ) -> CallHandler[P]:
662 """Build the backend callback for this request.
664 Args:
665 func: The handler to run for each incoming call.
666 stream: The entity event stream the handler reports on.
668 Raises:
669 HandlerError: if no event stream is given.
670 """
671 if stream is None:
672 raise HandlerError("Long-running request requires an event stream")
674 return CallHandler(self.message, functools.partial(run_long_call, func, stream))
676 @override
677 def create_call(
678 self,
679 context: RequestResponseContext,
680 message: P | None = None,
681 event_mux: EventMultiplexer | None = None,
682 ) -> Call[R, V]:
683 """Build a call of this request, sent once invoked.
685 Args:
686 context: The request context of the entity serving the request.
687 message: The message to send, for a request that declares one.
688 event_mux: The serving entity's events, which report the call's progress and result.
690 Raises:
691 ValueError: if no event multiplexer is given.
692 """
693 if event_mux is None:
694 raise ValueError("Long-running request requires an event multiplexer")
696 return LongCall(context, self.name, message, self.response, self.result, event_mux)
699def declare_request[R: BaseModel | None = None, P: BaseModel | None = None](
700 name: str,
701 *,
702 message: type[P] | None = None,
703 response: type[R] | None = None,
704) -> Request[P, R]:
705 """Declare a request that its handler answers immediately.
707 The response is the whole result, so a caller awaiting the call receives it directly. Omit
708 the message for a request that carries no arguments, and the response for one that reports
709 nothing back.
711 Args:
712 name: The request name, unique among the requests served by one entity.
713 message: The type sent by the caller.
714 response: The type returned by the handler.
715 """
716 return Request(name, message, response, response)
719def declare_long_request[
720 V: BaseModel | None = None,
721 R: BaseModel | None = None,
722 P: BaseModel | None = None,
723](
724 name: str,
725 *,
726 message: type[P] | None = None,
727 response: type[R] | None = None,
728 result: type[V] | None = None,
729) -> LongRequest[P, R, V]:
730 """Declare a request that keeps running after it replies.
732 The handler accepts or rejects the call immediately, then reports progress and its final
733 result on the entity event stream. A caller awaiting the call receives the result, while
734 the response carries whatever the handler needs to report up front.
736 Args:
737 name: The request name, unique among the requests served by one entity.
738 message: The type sent by the caller.
739 response: The type the handler replies with when it accepts or rejects the call.
740 result: The type carried by the success event, for a request that reports one.
741 """
742 return LongRequest(name, message, response, result)