flpit-stoop 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,105 @@
1
+ """stoop: a FastAPI-style web framework on the flpit Task runtime, served by Granian.
2
+
3
+ A *stoop* is the falcon's high-speed dive: Granian's Rust runtime hands each
4
+ request straight to flpit's thread pool (the Kestrel execution model), with no
5
+ asyncio event loop in between.
6
+ """
7
+ from importlib.metadata import PackageNotFoundError
8
+ from importlib.metadata import version as _version
9
+
10
+ from flpit.task import CancellationToken, OperationCanceledError, Task
11
+
12
+ from .app import Stoop
13
+ from .binding import RequestValidationError
14
+ from .di import (
15
+ FromKeyedServices,
16
+ Invocation,
17
+ Lifetime,
18
+ ServiceCollection,
19
+ ServiceProvider,
20
+ ServiceScope,
21
+ )
22
+ from .forms import FormData, UploadFile
23
+ from .hosting import BackgroundService, HealthCheckResult, HealthStatus
24
+ from .http import (
25
+ DEFAULT_MAX_BODY_SIZE,
26
+ DEFAULT_MIN_BODY_RATE,
27
+ UNLIMITED,
28
+ EventStreamResponse,
29
+ FileResponse,
30
+ HTMLResponse,
31
+ HTTPException,
32
+ JSONResponse,
33
+ MinDataRate,
34
+ PayloadTooLargeError,
35
+ PlainTextResponse,
36
+ ProblemDetails,
37
+ RedirectResponse,
38
+ Request,
39
+ RequestTimeoutError,
40
+ Response,
41
+ Results,
42
+ ServerSentEvent,
43
+ StreamingResponse,
44
+ )
45
+ from .middleware import ConcurrencyLimiter, CORSMiddleware, ServerTimingMiddleware
46
+ from .params import Body, Cookie, File, Form, FromServices, Header, Path, Query
47
+ from .routing import Router
48
+ from .websocket import WebSocket, WebSocketDisconnect
49
+
50
+ try:
51
+ __version__ = _version("flpit-stoop")
52
+ except PackageNotFoundError: # running from a source tree without installation
53
+ __version__ = "0.0.0"
54
+
55
+ __all__ = [
56
+ "Stoop",
57
+ "Router",
58
+ "Request",
59
+ "Response",
60
+ "JSONResponse",
61
+ "PlainTextResponse",
62
+ "HTMLResponse",
63
+ "RedirectResponse",
64
+ "FileResponse",
65
+ "StreamingResponse",
66
+ "EventStreamResponse",
67
+ "ServerSentEvent",
68
+ "Results",
69
+ "HTTPException",
70
+ "PayloadTooLargeError",
71
+ "UNLIMITED",
72
+ "DEFAULT_MAX_BODY_SIZE",
73
+ "MinDataRate",
74
+ "DEFAULT_MIN_BODY_RATE",
75
+ "RequestTimeoutError",
76
+ "ProblemDetails",
77
+ "RequestValidationError",
78
+ "Path",
79
+ "Query",
80
+ "Header",
81
+ "Cookie",
82
+ "Body",
83
+ "Form",
84
+ "File",
85
+ "UploadFile",
86
+ "FormData",
87
+ "FromServices",
88
+ "FromKeyedServices",
89
+ "ServiceCollection",
90
+ "ServiceProvider",
91
+ "ServiceScope",
92
+ "Lifetime",
93
+ "Invocation",
94
+ "WebSocket",
95
+ "WebSocketDisconnect",
96
+ "BackgroundService",
97
+ "HealthCheckResult",
98
+ "HealthStatus",
99
+ "CORSMiddleware",
100
+ "ConcurrencyLimiter",
101
+ "ServerTimingMiddleware",
102
+ "CancellationToken",
103
+ "OperationCanceledError",
104
+ "Task",
105
+ ]
flpit/stoop/_io.py ADDED
@@ -0,0 +1,407 @@
1
+ """Bridges between Granian's Rust awaitables and flpit coroutines.
2
+
3
+ Granian hands Python *future-like* objects (``PyFutureAwaitable``) for anything
4
+ that completes later: reading a request body, ``client_disconnect()``, WebSocket
5
+ ``accept()`` / ``receive()``. They speak the asyncio future protocol and report
6
+ completion by calling ``loop.call_soon_threadsafe(callback, future)`` on the
7
+ event loop Granian was given.
8
+
9
+ flpit coroutines cannot await those directly (the flpit runtime only accepts
10
+ its own operations), so every Granian awaitable goes through an ``IOBridge``:
11
+
12
+ * ``DirectBridge`` is used by the loop-free host. There Granian's "event loop"
13
+ is ``FlpitLoop``, a shim whose ``call_soon*`` run the callback right away on
14
+ the Rust thread that completed the I/O. The callback completes a flpit
15
+ ``TaskCompletionSource``, which queues the awaiting coroutine on the pool.
16
+ No asyncio loop is involved at any point.
17
+ * ``LoopBridge`` is used by the standard RSGI app (``app.__rsgi__``) running
18
+ under a real asyncio loop: callbacks are registered from the loop thread.
19
+
20
+ Awaitables that are already complete (Granian returns those for cheap,
21
+ synchronous operations such as ``send_bytes`` on a stream) are unwrapped
22
+ inline without creating a task.
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import asyncio
27
+ import sysconfig
28
+ import threading
29
+ from queue import Empty, SimpleQueue
30
+ from typing import Any
31
+
32
+ from flpit.task import TaskCompletionSource
33
+
34
+ __all__ = ["IOBridge", "DirectBridge", "LoopBridge", "FlpitLoop", "Ready", "TransportError", "OWNER"]
35
+
36
+
37
+ class TransportError(ConnectionError):
38
+ """A Granian I/O operation failed (client gone, transport closed, read cancelled...).
39
+
40
+ ``kind`` is the name of Granian's original exception type.
41
+ """
42
+
43
+ def __init__(self, kind: str, message: str) -> None:
44
+ self.kind = kind
45
+ super().__init__(f"{kind}: {message}" if message else kind)
46
+
47
+
48
+ def _fresh(error: BaseException) -> BaseException:
49
+ """A new exception equivalent to one that came out of a Granian object.
50
+
51
+ Granian's Rust objects keep a reference to the exceptions they raise, and Python's garbage
52
+ collector cannot see that reference. If that same exception object travelled on, its
53
+ traceback would point at our frames, those frames at the Rust object, and the Rust object
54
+ back at the exception: a cycle the GC never frees, which kept every request with a failed
55
+ write alive (with its Granian connection and buffers). A fresh exception never links our
56
+ frames to an object Rust holds.
57
+ """
58
+ # The original has already picked up a traceback through our frames on its way out; Rust keeps
59
+ # the original, so cut its links to our frames as well.
60
+ error.__traceback__ = None
61
+ error.__context__ = None
62
+ error.__cause__ = None
63
+ if isinstance(error, StopAsyncIteration):
64
+ return StopAsyncIteration(*error.args)
65
+ return TransportError(type(error).__name__, str(error))
66
+
67
+
68
+ class Ready:
69
+ """An awaitable whose outcome is already known; awaiting it never suspends."""
70
+
71
+ __slots__ = ("value", "error")
72
+
73
+ def __init__(self, value: Any = None, error: BaseException | None = None) -> None:
74
+ self.value = value
75
+ self.error = error
76
+
77
+ def __await__(self):
78
+ if self.error is not None:
79
+ raise self.error
80
+ return self.value
81
+ yield # pragma: no cover - makes this a generator
82
+
83
+
84
+ def _drain(awaitable: Any) -> Ready:
85
+ """Run a Granian awaitable that completes without suspending (Empty/Done/Err awaitables)."""
86
+ try:
87
+ iterator = awaitable.__await__()
88
+ while True:
89
+ next(iterator)
90
+ except StopIteration as stop:
91
+ return Ready(stop.value)
92
+ except BaseException as error: # noqa: BLE001 - re-raised in the awaiting coroutine
93
+ return Ready(error=_fresh(error))
94
+
95
+
96
+ class _Settle:
97
+ """One-shot done-callback for a Granian future.
98
+
99
+ Granian keeps its callbacks after they fire, and Rust references are invisible to
100
+ the GC: holding the source past settling would pin source -> task -> exception ->
101
+ traceback -> frames -> the future itself, an uncollectable cycle. So let go first.
102
+ """
103
+
104
+ __slots__ = ("source",)
105
+
106
+ def __init__(self, source: TaskCompletionSource[Any]) -> None:
107
+ self.source: TaskCompletionSource[Any] | None = source
108
+
109
+ def __call__(self, future: Any) -> None:
110
+ source, self.source = self.source, None
111
+ if source is None:
112
+ return
113
+ try:
114
+ source.try_set_result(future.result())
115
+ except BaseException as error: # noqa: BLE001
116
+ fresh = _fresh(error)
117
+ source.try_set_exception(fresh if isinstance(fresh, Exception) else RuntimeError(repr(fresh)))
118
+
119
+
120
+ class IOBridge:
121
+ """Turns a Granian awaitable into something a flpit coroutine can await."""
122
+
123
+ __slots__ = ()
124
+
125
+ def wait(self, awaitable: Any) -> Any: # pragma: no cover - interface
126
+ raise NotImplementedError
127
+
128
+ def cancel(self, awaitable: Any) -> None: # pragma: no cover - interface
129
+ raise NotImplementedError
130
+
131
+
132
+ def on_complete(self, awaitable: Any, callback: Any) -> None: # pragma: no cover - interface
133
+ """Call ``callback()`` when ``awaitable`` completes (any outcome)."""
134
+ raise NotImplementedError
135
+
136
+ def call(self, function: Any, *args: Any) -> None: # pragma: no cover - interface
137
+ """Invoke a Granian protocol method that must run where Granian expects it."""
138
+ raise NotImplementedError
139
+
140
+
141
+ class DirectBridge(IOBridge):
142
+ __slots__ = ()
143
+
144
+ def wait(self, awaitable: Any) -> Any:
145
+ add_done_callback = getattr(awaitable, "add_done_callback", None)
146
+ if add_done_callback is None:
147
+ return _drain(awaitable)
148
+ if awaitable.done():
149
+ try:
150
+ return Ready(awaitable.result())
151
+ except BaseException as error: # noqa: BLE001
152
+ return Ready(error=_fresh(error))
153
+ source: TaskCompletionSource[Any] = TaskCompletionSource()
154
+ add_done_callback(_Settle(source))
155
+ return source.task
156
+
157
+ def cancel(self, awaitable: Any) -> None:
158
+ cancel = getattr(awaitable, "cancel", None)
159
+ if cancel is not None:
160
+ cancel()
161
+
162
+ def on_complete(self, awaitable: Any, callback: Any) -> None:
163
+ add_done_callback = getattr(awaitable, "add_done_callback", None)
164
+ if add_done_callback is None:
165
+ callback()
166
+ else:
167
+ add_done_callback(lambda _future: callback())
168
+
169
+ def call(self, function: Any, *args: Any) -> None:
170
+ function(*args)
171
+
172
+
173
+ DIRECT = DirectBridge()
174
+
175
+
176
+ class LoopBridge(IOBridge):
177
+ """Bridge for awaitables bound to a running asyncio loop (standard RSGI mode)."""
178
+
179
+ __slots__ = ("loop",)
180
+
181
+ def __init__(self, loop: Any) -> None:
182
+ self.loop = loop
183
+
184
+ def wait(self, awaitable: Any) -> Any:
185
+ add_done_callback = getattr(awaitable, "add_done_callback", None)
186
+ if add_done_callback is None:
187
+ return _drain(awaitable)
188
+ if awaitable.done():
189
+ try:
190
+ return Ready(awaitable.result())
191
+ except BaseException as error: # noqa: BLE001
192
+ return Ready(error=_fresh(error))
193
+ source: TaskCompletionSource[Any] = TaskCompletionSource()
194
+ # Granian's future must only be touched from its loop thread.
195
+ self.loop.call_soon_threadsafe(add_done_callback, _Settle(source))
196
+ return source.task
197
+
198
+ def cancel(self, awaitable: Any) -> None:
199
+ cancel = getattr(awaitable, "cancel", None)
200
+ if cancel is not None:
201
+ self.loop.call_soon_threadsafe(cancel)
202
+
203
+ def on_complete(self, awaitable: Any, callback: Any) -> None:
204
+ add_done_callback = getattr(awaitable, "add_done_callback", None)
205
+ if add_done_callback is None:
206
+ callback()
207
+ else:
208
+ self.loop.call_soon_threadsafe(add_done_callback, lambda _future: callback())
209
+
210
+ def call(self, function: Any, *args: Any) -> None:
211
+ # Under the embedded (single-threaded tokio) runtime, work Granian spawns from a
212
+ # foreign thread is only picked up on the next I/O event; run it on the loop thread.
213
+ self.loop.call_soon_threadsafe(function, *args)
214
+
215
+
216
+ class _Future:
217
+ """A thread-safe future in asyncio's shape, for Granian builds that create futures on the loop.
218
+
219
+ On Linux and macOS Granian brings its own future type (``PyFutureAwaitable``) and only calls
220
+ ``call_soon*`` on the loop. The Windows build asks the loop for ``create_future()`` instead and
221
+ completes it later from a Rust thread through ``call_soon_threadsafe(future.set_result, value)``.
222
+ ``DirectBridge.wait`` then treats it like any other Granian future.
223
+ """
224
+
225
+ __slots__ = ("_loop", "_lock", "_state", "_value", "_callbacks", "_asyncio_future_blocking")
226
+
227
+ _PENDING, _DONE, _CANCELLED = 0, 1, 2
228
+
229
+ def __init__(self, loop: Any) -> None:
230
+ self._loop = loop
231
+ self._lock = threading.Lock()
232
+ self._state = self._PENDING
233
+ self._value: Any = None
234
+ self._callbacks: list[tuple[Any, Any]] = []
235
+ self._asyncio_future_blocking = False # asyncio's protocol for awaiting a future from a task
236
+
237
+ def get_loop(self) -> Any:
238
+ return self._loop
239
+
240
+ def done(self) -> bool:
241
+ return self._state != self._PENDING
242
+
243
+ def cancelled(self) -> bool:
244
+ return self._state == self._CANCELLED
245
+
246
+ def result(self) -> Any:
247
+ if self._state == self._CANCELLED:
248
+ raise asyncio.CancelledError()
249
+ if self._state == self._PENDING:
250
+ raise asyncio.InvalidStateError("Result is not ready.")
251
+ if isinstance(self._value, BaseException):
252
+ raise self._value
253
+ return self._value
254
+
255
+ def exception(self) -> BaseException | None:
256
+ if self._state == self._CANCELLED:
257
+ raise asyncio.CancelledError()
258
+ if self._state == self._PENDING:
259
+ raise asyncio.InvalidStateError("Exception is not set.")
260
+ return self._value if isinstance(self._value, BaseException) else None
261
+
262
+ def _settle(self, state: int, value: Any) -> bool:
263
+ with self._lock:
264
+ if self._state != self._PENDING:
265
+ return False # already settled: a completion racing a cancel loses quietly
266
+ self._state, self._value = state, value
267
+ callbacks, self._callbacks = self._callbacks, []
268
+ for callback, context in callbacks:
269
+ self._loop.call_soon_threadsafe(callback, self, context=context)
270
+ return True
271
+
272
+ def set_result(self, value: Any) -> None:
273
+ self._settle(self._DONE, value)
274
+
275
+ def set_exception(self, error: BaseException) -> None:
276
+ self._settle(self._DONE, error() if isinstance(error, type) else error)
277
+
278
+ def cancel(self, msg: Any = None) -> bool:
279
+ return self._settle(self._CANCELLED, None)
280
+
281
+ def add_done_callback(self, callback: Any, *, context: Any = None) -> None:
282
+ with self._lock:
283
+ if self._state == self._PENDING:
284
+ self._callbacks.append((callback, context))
285
+ return
286
+ self._loop.call_soon_threadsafe(callback, self, context=context)
287
+
288
+ def remove_done_callback(self, callback: Any) -> int:
289
+ with self._lock:
290
+ before = len(self._callbacks)
291
+ self._callbacks = [(c, ctx) for c, ctx in self._callbacks if c != callback]
292
+ return before - len(self._callbacks)
293
+
294
+ def __await__(self):
295
+ if not self.done():
296
+ self._asyncio_future_blocking = True
297
+ yield self
298
+ return self.result()
299
+
300
+ __iter__ = __await__
301
+
302
+
303
+ class FlpitLoop:
304
+ """The 'event loop' handed to Granian by the direct host.
305
+
306
+ Granian calls ``call_soon`` / ``call_soon_threadsafe`` on it, to deliver completions
307
+ of its future-like objects, and on Windows also ``create_future``. The callbacks registered by
308
+ ``DirectBridge`` are non-blocking (they complete a flpit task), so they run
309
+ inline on the calling Rust thread; the awaiting coroutine itself resumes
310
+ on the flpit pool.
311
+ """
312
+
313
+ __slots__ = ("_on_error",)
314
+
315
+ def __init__(self, on_error: Any = None) -> None:
316
+ self._on_error = on_error
317
+
318
+ def call_soon_threadsafe(self, callback: Any, *args: Any, context: Any = None) -> None:
319
+ try:
320
+ if context is not None:
321
+ context.run(callback, *args)
322
+ else:
323
+ callback(*args)
324
+ except BaseException as error: # noqa: BLE001 - never let a callback kill a Rust thread
325
+ if self._on_error is not None:
326
+ self._on_error(error)
327
+
328
+ call_soon = call_soon_threadsafe
329
+
330
+ def create_future(self) -> _Future:
331
+ return _Future(self)
332
+
333
+ def is_running(self) -> bool:
334
+ return True
335
+
336
+ def is_closed(self) -> bool:
337
+ return False
338
+
339
+
340
+ class _Owner:
341
+ """A thread that owns Granian objects whose *deallocation* has an effect.
342
+
343
+ Granian ends a streamed response body when its transport object is freed; there is
344
+ no explicit close. On free-threaded CPython, a reference taken on the creating
345
+ thread and dropped on another one is handed back to the creating thread, which
346
+ frees the object only the next time it runs Python code. A parked flpit worker
347
+ may not do that for many seconds, leaving the client waiting for the end of the
348
+ body. So such objects are created here, and ``release()`` wakes this thread after
349
+ the last reference is gone, which frees them immediately. A periodic wake bounds
350
+ whatever is released without a ``release()`` call (an aborted stream, say).
351
+ """
352
+
353
+ interval = 1.0
354
+
355
+ def __init__(self) -> None:
356
+ self._queue: SimpleQueue[Any] = SimpleQueue()
357
+ self._lock = threading.Lock()
358
+ self._thread: threading.Thread | None = None
359
+
360
+ def create(self, function: Any, *args: Any) -> tuple[Any, list[Any]]:
361
+ """Call ``function(*args)`` on the owner thread.
362
+
363
+ Returns a task that completes when the call is done, and a list that then
364
+ holds the result: the caller pops it, so no task or frame keeps it alive.
365
+ """
366
+ if self._thread is None:
367
+ self._start()
368
+ source: TaskCompletionSource[None] = TaskCompletionSource()
369
+ holder: list[Any] = []
370
+ self._queue.put((function, args, holder, source))
371
+ return source.task, holder
372
+
373
+ def release(self) -> None:
374
+ """Wake the owner thread: references dropped elsewhere are freed now."""
375
+ self._queue.put(None)
376
+
377
+ def _start(self) -> None:
378
+ with self._lock:
379
+ if self._thread is None:
380
+ thread = threading.Thread(target=self._run, name="stoop-owner", daemon=True)
381
+ thread.start()
382
+ self._thread = thread
383
+
384
+ def _run(self) -> None:
385
+ get = self._queue.get
386
+ interval = self.interval
387
+ while True:
388
+ try:
389
+ item = get(timeout=interval)
390
+ except Empty:
391
+ continue # running bytecode is what frees objects handed back to this thread
392
+ if item is None:
393
+ continue
394
+ function, args, holder, source = item
395
+ del item
396
+ try:
397
+ holder.append(function(*args))
398
+ except BaseException as error: # noqa: BLE001 - reported to the caller
399
+ fresh = _fresh(error)
400
+ source.try_set_exception(fresh if isinstance(fresh, Exception) else RuntimeError(repr(fresh)))
401
+ else:
402
+ source.try_set_result(None)
403
+ del function, args, holder, source
404
+
405
+
406
+ #: Only needed where objects are freed by their owning thread (free-threaded builds).
407
+ OWNER: _Owner | None = _Owner() if sysconfig.get_config_var("Py_GIL_DISABLED") else None