flpit 0.4.2.dev7__py3-none-any.whl → 0.4.2.dev8__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,705 @@
1
+ """asyncio libraries on the flpit runtime: a pool of standard asyncio event loops.
2
+
3
+ Provisional: the API of this module may change in 0.5. Prefer a library's sync client where one
4
+ exists (``httpx.Client``, psycopg's ``ConnectionPool``): it is written for threads and can be shared.
5
+
6
+ asyncio libraries (httpx, asyncpg, redis.asyncio, aiohttp, ...) need two things: a running
7
+ event loop on the thread that runs their code, and loop affinity (a connection pool, lock or
8
+ future created on one loop is only used on that loop). This module provides both without
9
+ giving up flpit's threads:
10
+
11
+ * **Strand loops** (Linux, the default there): each loop is an ordinary
12
+ ``asyncio.SelectorEventLoop`` - asyncio's own transports, sockets, timers and executor
13
+ hooks - but nobody calls ``run_forever()``. When a loop has work, one flpit work item runs
14
+ its iterations; iterations of the same loop never overlap, so each loop is a serialized
15
+ queue on the flpit pool (Kestrel's IOQueue model). One reactor thread waits on a master
16
+ epoll holding every loop's own epoll descriptor and wakes the loop that has I/O; timers go
17
+ to flpit's timer queue. A loop costs no thread, and loops run in parallel on the pool.
18
+ * **Thread loops** (other platforms, or ``configure(backend="threads")``): one dedicated
19
+ thread per loop running ``run_forever()``. Public asyncio API only.
20
+
21
+ Work goes to the loop already running on the calling thread when there is one (asyncio code
22
+ calling more asyncio code stays on its loop), otherwise to the least busy of the pool's loops
23
+ ("power of two choices"). Loops are created on demand, up to ``configure(loops=...)``.
24
+
25
+ Loop-bound objects that should outlive one call (an ``httpx.AsyncClient``, an asyncpg pool)
26
+ belong in a ``LoopLocal``: one value per loop, created on first use, closed with the loop.
27
+
28
+ Strand loops drive asyncio's ``BaseEventLoop._run_once`` and replace two private hooks
29
+ (``_write_to_self``, the selector's wait); the thread backend needs none of that and is the
30
+ fallback if a Python release changes those internals.
31
+ """
32
+ from __future__ import annotations
33
+
34
+ import asyncio
35
+ import atexit
36
+ import concurrent.futures
37
+ import contextvars
38
+ import os
39
+ import random
40
+ import select
41
+ import selectors
42
+ import sys
43
+ import threading
44
+ import weakref
45
+ from asyncio import events
46
+ from collections import deque
47
+ from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine
48
+ from typing import Any, Generic, TypeVar, cast, override
49
+
50
+ from . import task as _task
51
+ from .task import CancellationToken, OperationCanceledError, Task, TaskCompletionSource
52
+ from .threading import ThreadPool
53
+
54
+ __all__ = ["LoopLocal", "configure", "run_asyncio", "shutdown"]
55
+
56
+ T = TypeVar("T")
57
+
58
+ #: Iterations one drive runs before it yields its pool worker to other work.
59
+ _MAX_ITERATIONS_PER_DRIVE = 64
60
+
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Default executor: run_in_executor(None, ...) and getaddrinfo on the flpit pool
64
+ # ---------------------------------------------------------------------------
65
+
66
+ class _PoolExecutor(concurrent.futures.ThreadPoolExecutor):
67
+ """``concurrent.futures`` interface over the flpit pool (asyncio's default executor here).
68
+
69
+ A ``ThreadPoolExecutor`` subclass only because ``set_default_executor`` requires one; it
70
+ never starts threads of its own.
71
+ """
72
+
73
+ def __init__(self) -> None:
74
+ super().__init__(max_workers=1, thread_name_prefix="unused")
75
+
76
+ @override
77
+ def submit[**P, R](
78
+ self, fn: Callable[P, R], /, *args: P.args, **kwargs: P.kwargs
79
+ ) -> concurrent.futures.Future[R]:
80
+ future: concurrent.futures.Future[R] = concurrent.futures.Future()
81
+
82
+ def run(_state: Any) -> None:
83
+ if not future.set_running_or_notify_cancel():
84
+ return
85
+ try:
86
+ result = fn(*args, **kwargs)
87
+ except BaseException as error: # noqa: BLE001 - delivered to the waiter
88
+ future.set_exception(error)
89
+ else:
90
+ future.set_result(result)
91
+
92
+ ThreadPool.queue(run, None)
93
+ return future
94
+
95
+ @override
96
+ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None:
97
+ pass # the flpit pool outlives the loops
98
+
99
+
100
+ _POOL_EXECUTOR = _PoolExecutor()
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # Strand loops
105
+ # ---------------------------------------------------------------------------
106
+
107
+ if hasattr(selectors, "EpollSelector"):
108
+ class _NonBlockingSelector(selectors.EpollSelector):
109
+ """The loop's own selector never waits: the reactor thread does the waiting."""
110
+
111
+ @override
112
+ def select(self, timeout: float | None = None) -> list[tuple[selectors.SelectorKey, int]]:
113
+ return super().select(0)
114
+
115
+
116
+ class _Reactor:
117
+ """One thread for every strand loop: waits on a master epoll of the loops' epoll descriptors.
118
+
119
+ Each loop is registered one-shot (EPOLLONESHOT) and re-armed after the loop's iterations
120
+ ran, so a loop with pending I/O is woken once, not on every poll.
121
+ """
122
+
123
+ def __init__(self) -> None:
124
+ self._epoll = select.epoll()
125
+ self._loops: dict[int, _StrandLoop] = {}
126
+ self._lock = threading.Lock()
127
+ self._wakeup_read, self._wakeup_write = os.pipe()
128
+ os.set_blocking(self._wakeup_read, False)
129
+ self._epoll.register(self._wakeup_read, select.EPOLLIN)
130
+ self._stopping = False
131
+ self._thread = threading.Thread(target=self._run, name="Task-asyncio-reactor", daemon=True)
132
+ self._thread.start()
133
+
134
+ def add(self, loop: _StrandLoop) -> None:
135
+ fd = loop._selector.fileno()
136
+ with self._lock:
137
+ self._loops[fd] = loop
138
+ self._epoll.register(fd, select.EPOLLIN | select.EPOLLONESHOT)
139
+
140
+ def rearm(self, loop: _StrandLoop) -> None:
141
+ try:
142
+ self._epoll.modify(loop._selector.fileno(), select.EPOLLIN | select.EPOLLONESHOT)
143
+ except (OSError, ValueError):
144
+ pass # closed meanwhile
145
+
146
+ def remove(self, loop: _StrandLoop) -> None:
147
+ fd = loop._selector.fileno()
148
+ with self._lock:
149
+ self._loops.pop(fd, None)
150
+ try:
151
+ self._epoll.unregister(fd)
152
+ except (OSError, ValueError):
153
+ pass
154
+
155
+ def stop(self) -> None:
156
+ self._stopping = True
157
+ os.write(self._wakeup_write, b"x")
158
+ self._thread.join(5)
159
+ self._epoll.close()
160
+ os.close(self._wakeup_read)
161
+ os.close(self._wakeup_write)
162
+
163
+ def _run(self) -> None:
164
+ poll = self._epoll.poll
165
+ while not self._stopping:
166
+ try:
167
+ ready = poll()
168
+ except InterruptedError:
169
+ continue
170
+ for fd, _events in ready:
171
+ if fd == self._wakeup_read:
172
+ try:
173
+ os.read(self._wakeup_read, 64)
174
+ except BlockingIOError:
175
+ pass
176
+ continue
177
+ with self._lock:
178
+ loop = self._loops.get(fd)
179
+ if loop is not None:
180
+ loop._wake()
181
+
182
+
183
+ class _StrandLoop(asyncio.SelectorEventLoop):
184
+ """A standard selector event loop whose iterations run as flpit work items, never two at once."""
185
+
186
+ # asyncio internals this backend uses (CPython's BaseEventLoop / BaseSelectorEventLoop; not in
187
+ # typeshed). Kept to this one class; the threads backend needs none of them.
188
+ _selector: selectors.EpollSelector # always a _NonBlockingSelector
189
+ _ready: deque[asyncio.Handle]
190
+ _scheduled: list[asyncio.TimerHandle]
191
+ _thread_id: int | None
192
+ _run_once: Callable[[], None]
193
+ _asyncgen_firstiter_hook: Callable[[AsyncGenerator[Any, Any]], None]
194
+ _asyncgen_finalizer_hook: Callable[[AsyncGenerator[Any, Any]], None]
195
+
196
+ def __init__(self, reactor: _Reactor) -> None:
197
+ # Set before BaseEventLoop.__init__, which already calls overridden methods.
198
+ self._reactor = reactor
199
+ self._guard = threading.Lock()
200
+ self._queued = False # a drive is queued or running
201
+ self._again = False # woken while driving: iterate once more
202
+ self._timer: Any = None
203
+ self._timer_at: float | None = None
204
+ self._loop_closing = True # not running (and never driven) until fully set up
205
+ super().__init__(_NonBlockingSelector())
206
+ self.set_default_executor(_POOL_EXECUTOR)
207
+ reactor.add(self)
208
+ self._loop_closing = False
209
+ if self._ready:
210
+ self._wake()
211
+
212
+ # -- waking ----------------------------------------------------------------------------------
213
+
214
+ def _wake(self) -> None:
215
+ with self._guard:
216
+ if self._loop_closing:
217
+ return
218
+ if self._queued:
219
+ self._again = True
220
+ return
221
+ self._queued = True
222
+ ThreadPool.queue(self._drive, None)
223
+
224
+ def _write_to_self(self) -> None:
225
+ # call_soon_threadsafe from another thread. A strand isn't blocked in select(), so
226
+ # schedule it directly instead of writing to the self-pipe (and going through the reactor).
227
+ self._wake()
228
+
229
+ @override
230
+ def call_soon(self, callback: Callable[..., Any], *args: Any, context: contextvars.Context | None = None) -> Any:
231
+ handle = super().call_soon(callback, *args, context=context)
232
+ if events._get_running_loop() is not self:
233
+ self._wake() # scheduled outside an iteration (setup code on this loop's behalf)
234
+ return handle
235
+
236
+ @override
237
+ def is_running(self) -> bool:
238
+ # Logically running while it accepts work, although nobody calls run_forever().
239
+ return not (self._loop_closing or self.is_closed())
240
+
241
+ # -- driving ---------------------------------------------------------------------------------
242
+
243
+ def _drive(self, _state: Any) -> None:
244
+ hooks = sys.get_asyncgen_hooks()
245
+ previous = events._get_running_loop()
246
+ # asyncio's async-generator hooks for this loop while its code runs (pool workers carry
247
+ # flpit's; an abandoned asyncio generator must be closed on its loop, not by flpit).
248
+ sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook, finalizer=self._asyncgen_finalizer_hook)
249
+ events._set_running_loop(self)
250
+ self._thread_id = threading.get_ident()
251
+ requeue = False
252
+ next_timer: float | None = None
253
+ try:
254
+ iterations = 0
255
+ while not self.is_closed():
256
+ try:
257
+ self._run_once()
258
+ except (KeyboardInterrupt, SystemExit):
259
+ # asyncio re-raises these from the task that raised them, to stop run_forever().
260
+ # The task has already failed with it and its Task reports it to whoever waits;
261
+ # the loop serves its other work on.
262
+ pass
263
+ iterations += 1
264
+ with self._guard:
265
+ if not (self._ready or self._again):
266
+ # Read while this is still the only drive; the next may start right after.
267
+ scheduled = self._scheduled
268
+ next_timer = scheduled[0].when() if scheduled else None
269
+ self._queued = False
270
+ break
271
+ self._again = False
272
+ if iterations >= _MAX_ITERATIONS_PER_DRIVE:
273
+ requeue = True # yield the worker; continue in a fresh work item
274
+ break
275
+ finally:
276
+ self._thread_id = None
277
+ events._set_running_loop(previous)
278
+ sys.set_asyncgen_hooks(*hooks)
279
+ if self.is_closed():
280
+ return
281
+ if requeue:
282
+ ThreadPool.queue(self._drive, None)
283
+ return
284
+ self._reactor.rearm(self)
285
+ if next_timer is not None:
286
+ self._arm_timer(next_timer)
287
+
288
+ def _arm_timer(self, when: float) -> None:
289
+ with self._guard:
290
+ if self._loop_closing or (self._timer_at is not None and self._timer_at <= when):
291
+ return # an earlier (or the same) wake-up is already armed
292
+ if self._timer is not None:
293
+ self._timer.cancel()
294
+ self._timer_at = when
295
+ self._timer = _task._timers.schedule(max(0.0, when - self.time()), self._on_timer)
296
+
297
+ def _on_timer(self) -> None:
298
+ with self._guard:
299
+ self._timer = None
300
+ self._timer_at = None
301
+ self._wake()
302
+
303
+ @override
304
+ def close(self) -> None:
305
+ if self.is_closed():
306
+ return
307
+ with self._guard:
308
+ self._loop_closing = True # no more drives get queued
309
+ if self._timer is not None:
310
+ self._timer.cancel()
311
+ self._timer = None
312
+ # A drive may still be finishing on a pool worker (it completed the last task).
313
+ deadline = self.time() + 5.0
314
+ while True:
315
+ with self._guard:
316
+ if not self._queued:
317
+ break
318
+ if self.time() > deadline:
319
+ break
320
+ threading.Event().wait(0.001)
321
+ self._reactor.remove(self)
322
+ super().close()
323
+
324
+
325
+ # ---------------------------------------------------------------------------
326
+ # Thread loops (fallback backend)
327
+ # ---------------------------------------------------------------------------
328
+
329
+ class _ThreadLoop:
330
+ """A standard event loop on a dedicated thread (public asyncio API only)."""
331
+
332
+ def __init__(self) -> None:
333
+ self.loop = asyncio.new_event_loop()
334
+ self.loop.set_default_executor(_POOL_EXECUTOR)
335
+ self.thread = threading.Thread(target=self._serve, name="Task-asyncio-loop", daemon=True)
336
+ self.thread.start()
337
+
338
+ def _serve(self) -> None:
339
+ while True:
340
+ try:
341
+ self.loop.run_forever()
342
+ return # stopped by stop()
343
+ except (KeyboardInterrupt, SystemExit):
344
+ continue # raised out of one task (which failed with it); serve on, as strands do
345
+
346
+ def stop(self) -> None:
347
+ self.loop.call_soon_threadsafe(self.loop.stop)
348
+ self.thread.join(5)
349
+
350
+
351
+ # ---------------------------------------------------------------------------
352
+ # The pool of loops
353
+ # ---------------------------------------------------------------------------
354
+
355
+ def _default_count() -> int:
356
+ counter = getattr(os, "process_cpu_count", None) or os.cpu_count
357
+ return max(1, counter() or 1)
358
+
359
+
360
+ class _LoopPool:
361
+ def __init__(self, count: int, backend: str) -> None:
362
+ self.count = count
363
+ self.backend = backend
364
+ self.loops: list[asyncio.AbstractEventLoop] = []
365
+ self.load: dict[asyncio.AbstractEventLoop, int] = {}
366
+ self.lock = threading.Lock()
367
+ self.reactor: _Reactor | None = None
368
+ self.threads: list[_ThreadLoop] = []
369
+
370
+ def acquire(self) -> asyncio.AbstractEventLoop:
371
+ """The loop for a new piece of work: two random loops, the less busy one, or a new loop."""
372
+ with self.lock:
373
+ loops = self.loops
374
+ if loops:
375
+ a, b = (random.choice(loops), random.choice(loops)) if len(loops) > 1 else (loops[0], loops[0])
376
+ loop = a if self.load[a] <= self.load[b] else b
377
+ if self.load[loop] == 0 or len(loops) >= self.count:
378
+ self.load[loop] += 1
379
+ return loop
380
+ loop = self._new_loop()
381
+ loops.append(loop)
382
+ self.load[loop] = 1
383
+ return loop
384
+
385
+ def release(self, loop: asyncio.AbstractEventLoop) -> None:
386
+ with self.lock:
387
+ if loop in self.load:
388
+ self.load[loop] -= 1
389
+
390
+ def _new_loop(self) -> asyncio.AbstractEventLoop:
391
+ if self.backend == "strands":
392
+ if self.reactor is None:
393
+ self.reactor = _Reactor()
394
+ return _StrandLoop(self.reactor)
395
+ runner = _ThreadLoop()
396
+ self.threads.append(runner)
397
+ return runner.loop
398
+
399
+ def close(self, timeout: float) -> None:
400
+ empty: list[asyncio.AbstractEventLoop] = []
401
+ with self.lock:
402
+ loops, self.loops = self.loops, empty
403
+ self.load.clear()
404
+ for loop in loops:
405
+ _close_loop(loop, timeout)
406
+ for runner in self.threads:
407
+ runner.stop()
408
+ runner.loop.close()
409
+ self.threads.clear()
410
+ if self.reactor is not None:
411
+ self.reactor.stop()
412
+ self.reactor = None
413
+
414
+
415
+ def _close_loop(loop: asyncio.AbstractEventLoop, timeout: float) -> None:
416
+ """Cancel what still runs on ``loop``, close its LoopLocal values and async generators, close it."""
417
+
418
+ async def wind_down() -> None:
419
+ current = asyncio.current_task()
420
+ tasks = [t for t in asyncio.all_tasks(loop) if t is not current]
421
+ for running in tasks:
422
+ running.cancel()
423
+ if tasks:
424
+ await asyncio.wait(tasks, timeout=timeout)
425
+ await _dispose_loop_locals(loop)
426
+ await loop.shutdown_asyncgens()
427
+
428
+ if loop.is_closed():
429
+ return
430
+ try:
431
+ asyncio.run_coroutine_threadsafe(wind_down(), loop).result(timeout + 1)
432
+ except BaseException: # noqa: BLE001 - shutting down regardless
433
+ pass
434
+ if isinstance(loop, _StrandLoop):
435
+ loop.close()
436
+
437
+
438
+ _DEFAULT_BACKEND = "strands" if hasattr(select, "epoll") else "threads"
439
+ _config: dict[str, Any] = {"loops": None, "backend": _DEFAULT_BACKEND}
440
+ _pool: _LoopPool | None = None
441
+ _pool_lock = threading.Lock()
442
+
443
+
444
+ def configure(*, loops: int | None = None, backend: str | None = None) -> None:
445
+ """Set the number of loops (default: the CPU count) and the backend before first use.
446
+
447
+ ``backend`` is ``"strands"`` (loops as serialized queues on the flpit pool; Linux) or
448
+ ``"threads"`` (one thread per loop; any platform). Changing either after loops exist
449
+ takes effect after ``shutdown()``.
450
+ """
451
+ if loops is not None and loops < 1:
452
+ raise ValueError("loops must be at least 1")
453
+ if backend is not None:
454
+ if backend not in ("strands", "threads"):
455
+ raise ValueError("backend must be 'strands' or 'threads'")
456
+ if backend == "strands" and not hasattr(select, "epoll"):
457
+ raise ValueError("the strands backend needs epoll (Linux); use 'threads'")
458
+ with _pool_lock:
459
+ if loops is not None:
460
+ _config["loops"] = loops
461
+ if backend is not None:
462
+ _config["backend"] = backend
463
+
464
+
465
+ def _get_pool() -> _LoopPool:
466
+ global _pool
467
+ pool = _pool
468
+ if pool is None:
469
+ with _pool_lock:
470
+ pool = _pool
471
+ if pool is None:
472
+ pool = _pool = _LoopPool(_config["loops"] or _default_count(), _config["backend"])
473
+ return pool
474
+
475
+
476
+ def shutdown(timeout: float = 5.0) -> None:
477
+ """Cancel work still running on the loops, close their LoopLocal values and the loops.
478
+
479
+ Called by ``Task.shutdown`` and at interpreter exit. Later work creates new loops.
480
+ """
481
+ global _pool
482
+ with _pool_lock:
483
+ pool, _pool = _pool, None
484
+ if pool is not None:
485
+ pool.close(timeout)
486
+
487
+
488
+ # ---------------------------------------------------------------------------
489
+ # Running asyncio code as a flpit Task
490
+ # ---------------------------------------------------------------------------
491
+
492
+ def run_asyncio(awaitable: Awaitable[T], *, token: CancellationToken | None = None) -> Task[T]:
493
+ """Run asyncio code on an event loop and return a flpit Task for its outcome.
494
+
495
+ The loop is the one already running on this thread, if any; otherwise a loop of the pool.
496
+ The coroutine starts in a copy of the caller's context (``AsyncLocal`` values flow in).
497
+
498
+ ``token`` cancels it: a cancelled token cancels the asyncio task (its ``finally`` blocks
499
+ run) and the returned Task ends cancelled; an already cancelled token starts nothing.
500
+ asyncio code that catches the cancellation and returns normally completes normally.
501
+ """
502
+ source: TaskCompletionSource[T] = TaskCompletionSource()
503
+ if token is not None and token.is_cancellation_requested:
504
+ if asyncio.iscoroutine(awaitable):
505
+ awaitable.close()
506
+ source.set_canceled(token)
507
+ return source.task
508
+ coroutine = awaitable if asyncio.iscoroutine(awaitable) else _await(awaitable)
509
+ context = contextvars.copy_context()
510
+ running = events._get_running_loop()
511
+ if running is not None:
512
+ _start(running, None, coroutine, context, source, token)
513
+ else:
514
+ pool = _get_pool()
515
+ loop = pool.acquire()
516
+ loop.call_soon_threadsafe(_start, loop, pool, coroutine, context, source, token)
517
+ return source.task
518
+
519
+
520
+ async def _await(awaitable: Awaitable[T]) -> T:
521
+ return await awaitable
522
+
523
+
524
+ class _Run:
525
+ """One asyncio task started for run_asyncio: its token registration and completion."""
526
+
527
+ __slots__ = ("loop", "pool", "source", "token", "registration", "task", "cancel_requested")
528
+
529
+ def __init__(self, loop: asyncio.AbstractEventLoop, pool: _LoopPool | None,
530
+ source: TaskCompletionSource[Any], token: CancellationToken | None) -> None:
531
+ self.loop = loop
532
+ self.pool = pool
533
+ self.source = source
534
+ self.token = token
535
+ self.registration: Any = None
536
+ self.task: asyncio.Task[Any] | None = None
537
+ self.cancel_requested = False
538
+
539
+ def on_cancel(self) -> None:
540
+ try:
541
+ self.loop.call_soon_threadsafe(self._cancel)
542
+ except RuntimeError:
543
+ pass # the loop is closed
544
+
545
+ def _cancel(self) -> None:
546
+ if self.task is None:
547
+ self.cancel_requested = True
548
+ else:
549
+ self.task.cancel()
550
+
551
+ def finish(self, task: asyncio.Task[Any]) -> None:
552
+ registration, self.registration = self.registration, None
553
+ if registration is not None:
554
+ registration.dispose()
555
+ if self.pool is not None:
556
+ self.pool.release(self.loop)
557
+ source, token = self.source, self.token
558
+ if task.cancelled():
559
+ source.try_set_canceled(token)
560
+ return
561
+ error = task.exception()
562
+ if error is None:
563
+ source.try_set_result(task.result())
564
+ elif isinstance(error, OperationCanceledError):
565
+ source.try_set_canceled(token if token is not None and token.is_cancellation_requested else None)
566
+ elif isinstance(error, Exception):
567
+ source.try_set_exception(error)
568
+ else:
569
+ # KeyboardInterrupt, SystemExit or another BaseException: the Task fails with it, as a
570
+ # flpit coroutine that raises it does (TaskCompletionSource only accepts Exceptions).
571
+ source._try_complete(Task.FAILED, exception=error)
572
+
573
+
574
+ def _start(loop: asyncio.AbstractEventLoop, pool: _LoopPool | None, coroutine: Coroutine[Any, Any, Any],
575
+ context: contextvars.Context, source: TaskCompletionSource[Any], token: CancellationToken | None) -> None:
576
+ run = _Run(loop, pool, source, token)
577
+ if token is not None:
578
+ run.registration = token.register(run.on_cancel)
579
+ task = loop.create_task(coroutine, context=context)
580
+ run.task = task
581
+ task.add_done_callback(run.finish)
582
+ if run.cancel_requested:
583
+ task.cancel()
584
+
585
+
586
+ # ---------------------------------------------------------------------------
587
+ # LoopLocal
588
+ # ---------------------------------------------------------------------------
589
+
590
+ _loop_locals: weakref.WeakSet[LoopLocal[Any]] = weakref.WeakSet()
591
+
592
+
593
+ class LoopLocal(Generic[T]):
594
+ """One value per asyncio event loop, created on first use on that loop.
595
+
596
+ For loop-bound objects that should outlive one call: an ``httpx.AsyncClient``, an asyncpg
597
+ pool, an asyncio lock. ``factory`` may be a plain function or an ``async def``; read the
598
+ value with ``await local.get()`` (works for both) or ``local.value`` (plain factories, or
599
+ once created). When the bridge closes one of its loops, the loop's value is closed too:
600
+ ``await value.aclose()`` if it has one, else ``value.close()``.
601
+
602
+ Example:
603
+ ```python
604
+ clients = LoopLocal(httpx.AsyncClient)
605
+
606
+ @asyncio_task
607
+ async def fetch(url: str) -> dict:
608
+ client = await clients.get()
609
+ return (await client.get(url)).json()
610
+ ```
611
+ """
612
+
613
+ def __init__(self, factory: Callable[[], T | Awaitable[T]]) -> None:
614
+ self._factory = factory
615
+ self._values: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, T] = weakref.WeakKeyDictionary()
616
+ _loop_locals.add(self)
617
+
618
+ @staticmethod
619
+ def _loop() -> asyncio.AbstractEventLoop:
620
+ loop = events._get_running_loop()
621
+ if loop is None:
622
+ raise RuntimeError("LoopLocal is only available in code running on an asyncio event loop")
623
+ return loop
624
+
625
+ @property
626
+ def value(self) -> T:
627
+ loop = self._loop()
628
+ values = self._values
629
+ if loop in values:
630
+ return values[loop]
631
+ created = self._factory()
632
+ if asyncio.iscoroutine(created):
633
+ created.close()
634
+ raise TypeError("this LoopLocal has an async factory: use 'await local.get()'")
635
+ value = cast(T, created)
636
+ values[loop] = value
637
+ return value
638
+
639
+ async def get(self) -> T:
640
+ loop = self._loop()
641
+ values = self._values
642
+ if loop in values:
643
+ return values[loop]
644
+ created = self._factory()
645
+ if asyncio.iscoroutine(created) or isinstance(created, asyncio.Future):
646
+ value = cast(T, await created)
647
+ else:
648
+ value = cast(T, created)
649
+ if loop in values: # created by another task of this loop meanwhile
650
+ await _close_value(value)
651
+ return values[loop]
652
+ values[loop] = value
653
+ return value
654
+
655
+ def has_value(self) -> bool:
656
+ """Whether a value exists for the loop running on this thread."""
657
+ loop = events._get_running_loop()
658
+ return loop is not None and loop in self._values
659
+
660
+
661
+ async def _close_value(value: object) -> None:
662
+ """``await value.aclose()`` if it has one, else ``value.close()`` (awaited if it returns a coroutine)."""
663
+ closer = getattr(value, "aclose", None) or getattr(value, "close", None)
664
+ if closer is None:
665
+ return
666
+ result = closer()
667
+ if asyncio.iscoroutine(result):
668
+ await result
669
+
670
+
671
+ async def _dispose_loop_locals(loop: asyncio.AbstractEventLoop) -> None:
672
+ for local in list(_loop_locals):
673
+ if loop not in local._values:
674
+ continue
675
+ value = local._values.pop(loop)
676
+ try:
677
+ await _close_value(value)
678
+ except Exception: # noqa: BLE001 - one value's close must not keep the others open
679
+ _task._LOG.exception("closing a LoopLocal value failed")
680
+
681
+
682
+ # ---------------------------------------------------------------------------
683
+ # Lifecycle hooks
684
+ # ---------------------------------------------------------------------------
685
+
686
+ def _reset_after_fork() -> None:
687
+ # Only the forking thread exists in the child: the reactor and loop threads are gone.
688
+ global _pool
689
+ _pool = None
690
+
691
+
692
+ if hasattr(os, "register_at_fork"):
693
+ os.register_at_fork(after_in_child=_reset_after_fork)
694
+
695
+
696
+ def _shutdown_at_exit() -> None:
697
+ try:
698
+ shutdown(timeout=0.5)
699
+ except BaseException: # noqa: BLE001 - interpreter exit goes on
700
+ _task._LOG.exception("Error during asyncio bridge shutdown")
701
+
702
+
703
+ # Registered after flpit.task's handler (this module imports it first), so it runs before the
704
+ # runtime stops: the loops' remaining work still needs the pool.
705
+ atexit.register(_shutdown_at_exit)
flpit/task.py CHANGED
@@ -1364,6 +1364,9 @@ class Task(Generic[T], metaclass=_TaskMeta):
1364
1364
  if grace_timeout < 0 or worker_timeout < 0:
1365
1365
  raise ValueError("shutdown timeouts must be >= 0")
1366
1366
  global _runtime
1367
+ bridge = sys.modules.get("flpit.asyncio_bridge")
1368
+ if bridge is not None:
1369
+ bridge.shutdown(timeout=grace_timeout) # its loops still need the pool to wind down
1367
1370
  with _runtime_lock:
1368
1371
  runtime = _runtime
1369
1372
  if runtime is None:
@@ -4112,23 +4115,28 @@ def await_using[**P, T](
4112
4115
  def asyncio_task[**P, T](
4113
4116
  async_function: Callable[P, Awaitable[T]]
4114
4117
  ) -> Callable[P, Task[T]]:
4115
- """
4116
- | Wraps async functions with a dependency on asyncio to be compatible with Task.run(coro)
4118
+ """Make every call of an ``async def`` that needs asyncio start a Task on an asyncio event loop.
4117
4119
 
4118
- Use with caution as this transfers execution control to an isolated asyncio loop runner.
4119
- """
4120
- import asyncio
4120
+ For code that depends on asyncio, such as ``httpx.AsyncClient`` or asyncpg. Each call runs on
4121
+ the asyncio loop already running on the calling thread, if any, otherwise on one of the
4122
+ pool's shared loops (see ``flpit.asyncio_bridge``): no loop is created per call, and no pool
4123
+ worker is blocked while the call waits for I/O.
4124
+
4125
+ A ``CancellationToken`` passed as an argument also cancels the call, as in .NET: the asyncio
4126
+ task is cancelled and the returned Task ends cancelled.
4121
4127
 
4122
- async def _await(awaitable: Awaitable[T]) -> T:
4123
- return await awaitable
4128
+ Loop-bound objects that should be reused across calls (clients, connection pools) belong in
4129
+ a ``LoopLocal`` (``flpit.asyncio_bridge.LoopLocal``): one per loop.
4130
+ """
4124
4131
 
4125
4132
  @functools.wraps(async_function)
4126
- def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
4127
- with asyncio.Runner() as runner:
4128
- # Call the function with its arguments to generate the awaitable instance
4129
- return runner.run(_await(async_function(*args, **kwargs)))
4133
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Task[T]:
4134
+ from .asyncio_bridge import run_asyncio # imports asyncio on first use only
4135
+
4136
+ token = next((value for value in (*args, *kwargs.values()) if isinstance(value, CancellationToken)), None)
4137
+ return run_asyncio(async_function(*args, **kwargs), token=token)
4130
4138
 
4131
- return task(wrapper)
4139
+ return wrapper
4132
4140
 
4133
4141
 
4134
4142
  class _SyncBridge:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: flpit
3
- Version: 0.4.2.dev7
3
+ Version: 0.4.2.dev8
4
4
  Summary: Fluent LINQ for Python — flip your iterables
5
5
  Project-URL: Homepage, https://github.com/riemar/flpit
6
6
  Project-URL: Documentation, https://riemar.github.io/flpit/
@@ -1,11 +1,12 @@
1
1
  flp/__init__.py,sha256=reAHhZtYt0f2LHeIYJbklta6Vatr6yeQCL1R-9TTyY0,688
2
2
  flpit/__init__.py,sha256=BJh2_YMsC9G9ognk8DytyBlW4qTHAe_ql_gycf6MAhA,2608
3
+ flpit/asyncio_bridge.py,sha256=cZ91tGvh2l9KAy67d04KxP2LNTH0YhFblYqLIAy5BCI,27553
3
4
  flpit/channels.py,sha256=LuJ25ReLff2eagQAoNUvOuhLCbrBDT2nwncFXafUFUc,46800
4
5
  flpit/concurrent.py,sha256=HZueI_zSTX9ozwmxwrn7_HSrxT4VL3CKoDbKQRqAKLA,32211
5
6
  flpit/csv.py,sha256=QMG8AxYR32i4I_lD1KL284OXdScN6vjjgusvnqw2q-A,25862
6
7
  flpit/flp.py,sha256=WaZnrtYdxwEOJUEBv_hXg8Uwm81h8kcH64pjDh8oJhU,1527
7
8
  flpit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
- flpit/task.py,sha256=REvC_OWFrtJLsn6VqXmTPOZooVP5wiiw62_TCjoiBlw,168041
9
+ flpit/task.py,sha256=p1T0GVu8mxVGdPLMvfLEt7dK0Lya-MoPytD1sIirH9U,168771
9
10
  flpit/threading.py,sha256=MeWwOI2DSejmwiivSL1IVGx0US-FEsgcNRjFWdwdcSg,37236
10
11
  flpit/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
12
  flpit/core/_grouping.py,sha256=QZNdNqXx4fcRsnun4nwkGKnst63Y10Q-rYBevof7Abw,954
@@ -20,7 +21,7 @@ flpit/json/__init__.py,sha256=7U7-KaxLbQybqmNTqDf4U54Njhac2ep5gxPEaavR7hA,4625
20
21
  flpit/json/_core.py,sha256=IhLM116xW4jI4gg3-QmRGptVr5pHRY7X7aicm8TmO3Y,13445
21
22
  flpit/json/_msgspec.py,sha256=19NB98R1tftz8LYY_2QriWo9d4Syii4f7QW_s8vWL2s,20124
22
23
  flpit/json/_native.py,sha256=E_Ro3rXTCKDpb6jicBOYU9fzOJch6ZJkLqsKJNXAsTg,39974
23
- flpit-0.4.2.dev7.dist-info/METADATA,sha256=QDp_Lc5rZXJQneHiFMmfceGtv6t4EaRndKJLSJPlfpQ,19395
24
- flpit-0.4.2.dev7.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
25
- flpit-0.4.2.dev7.dist-info/licenses/LICENSE,sha256=bi5Vg_YP3Oq3jaOMQT4b7WZu0NfBcZr-nRyOExUKJrQ,1063
26
- flpit-0.4.2.dev7.dist-info/RECORD,,
24
+ flpit-0.4.2.dev8.dist-info/METADATA,sha256=TohtpnCtXFUvu9av3-30zzkTmmuPgbz8g_yH5l7cctc,19395
25
+ flpit-0.4.2.dev8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
26
+ flpit-0.4.2.dev8.dist-info/licenses/LICENSE,sha256=bi5Vg_YP3Oq3jaOMQT4b7WZu0NfBcZr-nRyOExUKJrQ,1063
27
+ flpit-0.4.2.dev8.dist-info/RECORD,,