flpit 0.4.2.dev9__py3-none-any.whl → 0.4.2.dev11__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.
flpit/asyncio_bridge.py CHANGED
@@ -23,7 +23,10 @@ calling more asyncio code stays on its loop), otherwise to the least busy of the
23
23
  ("power of two choices"). Loops are created on demand, up to ``configure(loops=...)``.
24
24
 
25
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.
26
+ are kept one per loop and closed with the loop. Register them with ``provide()`` and take them as
27
+ a ``Loop[T]`` parameter of an ``@asyncio_task`` function, or hold a ``PerLoop[T]`` in an object that
28
+ lives longer than a call (a singleton) and read ``.current`` on the loop. ``warm=True`` creates the
29
+ value on every pool loop before the loop takes work.
27
30
 
28
31
  Strand loops drive asyncio's ``BaseEventLoop._run_once`` and replace two private hooks
29
32
  (``_write_to_self``, the selector's wait); the thread backend needs none of that and is the
@@ -35,23 +38,25 @@ import asyncio
35
38
  import atexit
36
39
  import concurrent.futures
37
40
  import contextvars
41
+ import inspect
38
42
  import os
39
43
  import random
40
44
  import select
41
45
  import selectors
42
46
  import sys
43
47
  import threading
48
+ import typing
44
49
  import weakref
45
50
  from asyncio import events
46
51
  from collections import deque
47
52
  from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine
48
- from typing import Any, Generic, TypeVar, cast, override
53
+ from typing import Annotated, Any, Final, Generic, TypeAlias, TypeVar, cast, get_args, get_origin, override
49
54
 
50
55
  from . import task as _task
51
56
  from .task import CancellationToken, OperationCanceledError, Task, TaskCompletionSource
52
57
  from .threading import ThreadPool
53
58
 
54
- __all__ = ["LoopLocal", "configure", "run_asyncio", "shutdown"]
59
+ __all__ = ["Loop", "LoopLocal", "LoopStartError", "PerLoop", "configure", "injected", "provide", "run_asyncio", "shutdown"]
55
60
 
56
61
  T = TypeVar("T")
57
62
 
@@ -380,6 +385,8 @@ class _LoopPool:
380
385
  loop = self._new_loop()
381
386
  loops.append(loop)
382
387
  self.load[loop] = 1
388
+ # Queued before the caller queues its work, so the warm-up gate exists first.
389
+ loop.call_soon_threadsafe(_begin_warm, loop, self, None)
383
390
  return loop
384
391
 
385
392
  def release(self, loop: asyncio.AbstractEventLoop) -> None:
@@ -387,6 +394,25 @@ class _LoopPool:
387
394
  if loop in self.load:
388
395
  self.load[loop] -= 1
389
396
 
397
+ def retire(self, loop: asyncio.AbstractEventLoop) -> None:
398
+ """Take ``loop`` out of service (its start failed) and close it once its work has ended."""
399
+ with self.lock:
400
+ if loop not in self.load:
401
+ return
402
+ self.loops.remove(loop)
403
+ del self.load[loop]
404
+ runner = next((r for r in self.threads if r.loop is loop), None)
405
+ if runner is not None:
406
+ self.threads.remove(runner)
407
+
408
+ def close(_state: Any) -> None:
409
+ _close_loop(loop, 1.0)
410
+ if runner is not None:
411
+ runner.stop()
412
+ runner.loop.close()
413
+
414
+ ThreadPool.queue(close, None)
415
+
390
416
  def _new_loop(self) -> asyncio.AbstractEventLoop:
391
417
  if self.backend == "strands":
392
418
  if self.reactor is None:
@@ -576,6 +602,13 @@ def _start(loop: asyncio.AbstractEventLoop, pool: _LoopPool | None, coroutine: C
576
602
  run = _Run(loop, pool, source, token)
577
603
  if token is not None:
578
604
  run.registration = token.register(run.on_cancel)
605
+ gate: asyncio.Task[None] | None = getattr(loop, _GATE, None)
606
+ if gate is not None:
607
+ if gate.done() and not gate.cancelled() and gate.exception() is None:
608
+ if getattr(loop, _GATE, None) is gate:
609
+ setattr(loop, _GATE, None)
610
+ else:
611
+ coroutine = _after_gate(gate, coroutine)
579
612
  task = loop.create_task(coroutine, context=context)
580
613
  run.task = task
581
614
  task.add_done_callback(run.finish)
@@ -679,6 +712,276 @@ async def _dispose_loop_locals(loop: asyncio.AbstractEventLoop) -> None:
679
712
  _task._LOG.exception("closing a LoopLocal value failed")
680
713
 
681
714
 
715
+ # ---------------------------------------------------------------------------
716
+ # PerLoop, provide() and Loop[T] parameters
717
+ # ---------------------------------------------------------------------------
718
+
719
+ class LoopStartError(RuntimeError):
720
+ """A ``warm=True`` value could not be created on a new loop; the loop was taken out of service."""
721
+
722
+
723
+ #: Attribute of a pool loop holding the asyncio task that warms it (None once warm).
724
+ _GATE: Final = "_flpit_warm_gate"
725
+ _warm_per_loops: weakref.WeakSet[PerLoop[Any]] = weakref.WeakSet()
726
+ _warm_lock = threading.Lock()
727
+
728
+
729
+ def _begin_warm(loop: asyncio.AbstractEventLoop, pool: _LoopPool, per_loops: list[PerLoop[Any]] | None) -> None:
730
+ """On ``loop``: start creating the warm values; work started meanwhile waits for them."""
731
+ if per_loops is None:
732
+ with _warm_lock:
733
+ per_loops = list(_warm_per_loops)
734
+ if not per_loops:
735
+ return
736
+ previous: asyncio.Task[None] | None = getattr(loop, _GATE, None)
737
+ setattr(loop, _GATE, loop.create_task(_warm(loop, pool, per_loops, previous)))
738
+
739
+
740
+ async def _warm(loop: asyncio.AbstractEventLoop, pool: _LoopPool, per_loops: list[PerLoop[Any]],
741
+ previous: asyncio.Task[None] | None) -> None:
742
+ if previous is not None:
743
+ await previous
744
+ for per_loop in per_loops:
745
+ if per_loop._closed:
746
+ continue
747
+ try:
748
+ await per_loop.get()
749
+ except Exception as error:
750
+ pool.retire(loop)
751
+ raise LoopStartError(f"creating the per-loop value {per_loop!r} on a new asyncio loop failed") from error
752
+
753
+
754
+ async def _after_gate(gate: asyncio.Task[None], coroutine: Coroutine[Any, Any, T]) -> T:
755
+ try:
756
+ await asyncio.shield(gate)
757
+ except BaseException:
758
+ coroutine.close()
759
+ raise
760
+ return await coroutine
761
+
762
+
763
+ class PerLoop(LoopLocal[T]):
764
+ """One ``T`` per asyncio event loop, for objects that live longer than a call.
765
+
766
+ Hold a ``PerLoop`` where the object itself must not be held: a singleton built once cannot
767
+ keep a loop-bound client (it would use the client of the loop it was built on), but it can
768
+ keep the ``PerLoop`` and read ``current`` in each call:
769
+
770
+ ```python
771
+ clients = PerLoop(lambda: httpx.AsyncClient(timeout=10), warm=True)
772
+
773
+ class GitHubApi:
774
+ def __init__(self, clients: PerLoop[httpx.AsyncClient]) -> None:
775
+ self._clients = clients
776
+
777
+ @asyncio_task
778
+ async def repo(self, name: str) -> dict:
779
+ return (await self._clients.current.get(f"/repos/{name}")).json()
780
+ ```
781
+
782
+ ``factory`` may be a plain function or an ``async def``. With ``warm=True`` the value is created
783
+ on each pool loop when the loop starts, before it takes work, so ``current`` never creates one
784
+ during a call; a factory that fails there fails the work waiting for that loop with
785
+ ``LoopStartError`` and the loop is replaced. ``close()`` closes the values on every loop.
786
+ """
787
+
788
+ def __init__(self, factory: Callable[[], T | Awaitable[T]], *, warm: bool = False) -> None:
789
+ super().__init__(factory)
790
+ self.warm = warm
791
+ self._closed = False
792
+ if warm:
793
+ with _warm_lock:
794
+ _warm_per_loops.add(self)
795
+ pool = _pool
796
+ if pool is not None:
797
+ with pool.lock:
798
+ loops = list(pool.loops)
799
+ only: list[PerLoop[Any]] = [self]
800
+ for loop in loops:
801
+ try:
802
+ loop.call_soon_threadsafe(_begin_warm, loop, pool, only)
803
+ except RuntimeError:
804
+ pass # closed meanwhile
805
+
806
+ @property
807
+ def current(self) -> T:
808
+ """The value of the loop running on this thread; created now if it does not exist yet.
809
+
810
+ Raises ``RuntimeError`` outside asyncio code. An async factory cannot run here: with
811
+ ``warm=True`` the value exists on every pool loop; elsewhere use ``await per_loop.get()``.
812
+ """
813
+ if self._closed:
814
+ raise RuntimeError(f"{self!r} is closed")
815
+ loop = self._loop()
816
+ values = self._values
817
+ if loop in values:
818
+ return values[loop]
819
+ created = self._factory()
820
+ if asyncio.iscoroutine(created) or isinstance(created, asyncio.Future):
821
+ if asyncio.iscoroutine(created):
822
+ created.close()
823
+ raise RuntimeError(f"{self!r} has an async factory and no value on this loop yet: "
824
+ "create it with warm=True, or use 'await per_loop.get()'")
825
+ value = cast(T, created)
826
+ values[loop] = value
827
+ return value
828
+
829
+ @override
830
+ async def get(self) -> T:
831
+ if self._closed:
832
+ raise RuntimeError(f"{self!r} is closed")
833
+ return await super().get()
834
+
835
+ def close(self, timeout: float = 5.0) -> None:
836
+ """Close the value of every loop (``aclose()`` or ``close()``, on its loop) and stop creating new ones."""
837
+ self._closed = True
838
+ with _warm_lock:
839
+ _warm_per_loops.discard(self)
840
+ with _providers_lock:
841
+ for service_type, registered in list(_providers.items()):
842
+ if registered is self:
843
+ del _providers[service_type]
844
+ running = events._get_running_loop()
845
+ pending: list[concurrent.futures.Future[None]] = []
846
+ for loop, value in list(self._values.items()):
847
+ self._values.pop(loop, None)
848
+ if loop.is_closed():
849
+ continue
850
+ if loop is running:
851
+ loop.create_task(_close_value(value)) # cannot wait for our own loop
852
+ continue
853
+ try:
854
+ pending.append(asyncio.run_coroutine_threadsafe(_close_value(value), loop))
855
+ except RuntimeError:
856
+ pass # the loop closed meanwhile
857
+ if pending:
858
+ done, _ = concurrent.futures.wait(pending, timeout=timeout)
859
+ for future in done:
860
+ if future.exception() is not None:
861
+ _task._LOG.error("closing a PerLoop value failed", exc_info=future.exception())
862
+
863
+ async def aclose(self) -> None:
864
+ """``close()`` without blocking the awaiting coroutine's thread."""
865
+ await Task.run(self.close)
866
+
867
+ @override
868
+ def __repr__(self) -> str:
869
+ name = getattr(self._factory, "__qualname__", None) or repr(self._factory)
870
+ return f"PerLoop({name})"
871
+
872
+
873
+ class _LoopParameter:
874
+ __slots__ = ()
875
+
876
+ @override
877
+ def __repr__(self) -> str:
878
+ return "Loop"
879
+
880
+
881
+ _LOOP_PARAMETER: Final = _LoopParameter()
882
+
883
+ Loop: TypeAlias = Annotated[T, _LOOP_PARAMETER]
884
+ """A parameter of an ``@asyncio_task`` function that receives the ``provide()``-d ``T`` of the loop the call runs on.
885
+
886
+ ```python
887
+ asyncio_bridge.provide(httpx.AsyncClient, lambda: httpx.AsyncClient(timeout=10), warm=True)
888
+
889
+ @asyncio_task
890
+ async def fetch(url: str, client: Loop[httpx.AsyncClient] = injected) -> dict:
891
+ return (await client.get(url)).json()
892
+
893
+ data = await fetch("https://...")
894
+ ```
895
+
896
+ The caller does not pass it (``= injected`` tells type checkers so); a value the caller does pass wins.
897
+ """
898
+
899
+
900
+ class _Injected:
901
+ __slots__ = ()
902
+
903
+ @override
904
+ def __repr__(self) -> str:
905
+ return "injected"
906
+
907
+
908
+ injected: Final[Any] = _Injected()
909
+ """Default for a ``Loop[T]`` parameter: the bridge fills it in, the caller does not pass it."""
910
+
911
+ _providers: dict[Any, PerLoop[Any]] = {}
912
+ _owned_providers: weakref.WeakSet[PerLoop[Any]] = weakref.WeakSet()
913
+ _providers_lock = threading.Lock()
914
+
915
+
916
+ def provide(service_type: type[T], source: Callable[[], T | Awaitable[T]] | PerLoop[T], *,
917
+ warm: bool = False) -> PerLoop[T]:
918
+ """Make ``Loop[service_type]`` parameters of ``@asyncio_task`` functions receive one value per loop.
919
+
920
+ ``source`` is a factory (plain or ``async def``; ``warm`` as for ``PerLoop``) or an existing
921
+ ``PerLoop``, which stays the caller's to close. Providing a type again replaces the provider;
922
+ values created by a replaced factory are closed. Returns the ``PerLoop`` in use.
923
+ """
924
+ if isinstance(source, PerLoop):
925
+ per_loop = cast(PerLoop[T], source)
926
+ else:
927
+ per_loop = PerLoop(source, warm=warm)
928
+ _owned_providers.add(per_loop)
929
+ with _providers_lock:
930
+ replaced = _providers.get(service_type)
931
+ _providers[service_type] = per_loop
932
+ if replaced is not None and replaced is not per_loop and replaced in _owned_providers:
933
+ ThreadPool.queue(lambda: replaced.close())
934
+ return per_loop
935
+
936
+
937
+ def _provider(service_type: Any) -> PerLoop[Any]:
938
+ per_loop = _providers.get(service_type)
939
+ if per_loop is None:
940
+ name = getattr(service_type, "__qualname__", repr(service_type))
941
+ raise LookupError(f"no per-loop value is provided for {name}: "
942
+ f"call asyncio_bridge.provide({name}, factory) at startup")
943
+ return per_loop
944
+
945
+
946
+ def _loop_parameters(function: Callable[..., Any]) -> tuple[inspect.Signature, tuple[tuple[str, Any], ...]] | None:
947
+ """The signature and the ``Loop[T]`` parameters of ``function``, or None if it has none."""
948
+ try:
949
+ hints = typing.get_type_hints(function, include_extras=True)
950
+ except Exception as error:
951
+ raw = getattr(function, "__annotations__", {})
952
+ if not any("Loop[" in str(annotation) for annotation in raw.values()):
953
+ return None
954
+ raise TypeError(f"cannot read the annotations of {function.__qualname__} "
955
+ f"to find its Loop[...] parameters: {error}") from error
956
+ found = tuple(
957
+ (name, get_args(hint)[0]) for name, hint in hints.items()
958
+ if get_origin(hint) is Annotated and any(m is _LOOP_PARAMETER for m in hint.__metadata__)
959
+ )
960
+ return (inspect.signature(function), found) if found else None
961
+
962
+
963
+ def _call_asyncio_task(function: Callable[..., Awaitable[T]], args: tuple[Any, ...], kwargs: dict[str, Any],
964
+ token: CancellationToken | None, cache: list[Any]) -> Task[T]:
965
+ """One call of an ``@asyncio_task`` function: fill its ``Loop[T]`` parameters on the loop, run it."""
966
+ if not cache:
967
+ cache.append(_loop_parameters(function))
968
+ plan = cache[0]
969
+ if plan is None:
970
+ return run_asyncio(function(*args, **kwargs), token=token)
971
+ signature, parameters = plan
972
+ bound = signature.bind_partial(*args, **kwargs) # wrong arguments fail here, in the caller
973
+ missing = [(name, service_type) for name, service_type in parameters
974
+ if bound.arguments.get(name, injected) is injected]
975
+ return run_asyncio(_with_loop_values(function, bound, missing), token=token)
976
+
977
+
978
+ async def _with_loop_values(function: Callable[..., Awaitable[T]], bound: inspect.BoundArguments,
979
+ missing: list[tuple[str, Any]]) -> T:
980
+ for name, service_type in missing:
981
+ bound.arguments[name] = await _provider(service_type).get()
982
+ return await function(*bound.args, **bound.kwargs)
983
+
984
+
682
985
  # ---------------------------------------------------------------------------
683
986
  # Lifecycle hooks
684
987
  # ---------------------------------------------------------------------------
flpit/core/linq.py CHANGED
@@ -1556,8 +1556,9 @@ class FlpIt[TItem](Iterable[TItem]):
1556
1556
  def when_all[R](self: FlpIt[Task[R]]) -> Task[list[R]]:
1557
1557
  """
1558
1558
  A task that completes with the results of all tasks of this query, in query order. The query
1559
- form of ``Task.when_all`` (.NET ``Task.WhenAll``). Enumerating the query starts it in full. If a task fails the
1560
- exception is re-raised; if several fail, ``TaskAggregateError`` carries all of them.
1559
+ form of ``Task.when_all`` (.NET ``Task.WhenAll``). Enumerating the query starts it in full. If tasks fail, ``result()``
1560
+ and ``await`` raise the first failure in query order; ``exception()`` and ``wait()`` give an
1561
+ ``AggregateError`` with all of them.
1561
1562
  An empty query gives an empty list.
1562
1563
  """
1563
1564
  from flpit.task import Task
flpit/json/_msgspec.py CHANGED
@@ -253,7 +253,8 @@ def _struct_fields(
253
253
  definitions.append(spec)
254
254
 
255
255
  # 2. Process properties automatically
256
- for name, value in vars(info.source).items():
256
+ # A snapshot: msgspec stores its type cache on the class, so another thread may add to this dict meanwhile.
257
+ for name, value in vars(info.source).copy().items():
257
258
  if isinstance(value, property) and name not in dataclass_fields:
258
259
  # Extract the type annotation directly from the getter function signature
259
260
  if value.fset is not None:
@@ -300,7 +301,7 @@ def _register_forward_refs(
300
301
  def _behavior_namespace(source: type) -> dict[str, Any]:
301
302
  return {
302
303
  name: value
303
- for name, value in vars(source).items()
304
+ for name, value in vars(source).copy().items()
304
305
  if (
305
306
  not name.startswith("__")
306
307
  and (callable(value) or isinstance(value, property))
@@ -423,6 +424,8 @@ def _make_hook(tp: Any) -> typing.Callable[[Any], Any]:
423
424
  # struct side of a registered collection: a validated plain list
424
425
  as_list: Any = list[item]
425
426
 
427
+ _ensure_type_info(as_list)
428
+
426
429
  def wire(obj: Any) -> Any:
427
430
  if type(obj) is not list:
428
431
  if _not_array(obj):
@@ -439,6 +442,7 @@ def _make_hook(tp: Any) -> typing.Callable[[Any], Any]:
439
442
  else typing.cast(Any, collection.base)[item])
440
443
  # Items coming from the struct side were validated already; plain values need no second pass.
441
444
  reuse = collection.base is list and item in _PLAIN_ITEMS
445
+ _ensure_type_info(base)
442
446
 
443
447
  def dataclass_side(obj: Any) -> Any:
444
448
  # Lists here come from decoded structs (msgspec validated them); plain items need no second pass.
@@ -504,8 +508,37 @@ def _enc_hook(obj: Any) -> Any:
504
508
  raise NotImplementedError(f"flpit.json: cannot serialize {type(obj).__qualname__}")
505
509
 
506
510
 
511
+ _type_info_ready: set[Any] = set()
512
+ _type_info_lock = threading.Lock()
513
+
514
+
515
+ def _ensure_type_info(tp: Any) -> None:
516
+ """Have msgspec build its information for ``tp`` (and the types in it) on one thread, before first use.
517
+
518
+ msgspec builds that information lazily, on a type's first decode or convert, and caches it on the type.
519
+ On free-threaded Python, threads using a type for the first time at once can crash the interpreter (a
520
+ segmentation fault in msgspec._core, msgspec 0.22): one thread reads the information while another is
521
+ still building it. Once it is complete, concurrent use is safe. So the first use of each type runs here,
522
+ under a lock; afterwards this is one set lookup.
523
+ """
524
+ try:
525
+ if tp in _type_info_ready:
526
+ return
527
+ except TypeError: # unhashable: nothing to remember it by; msgspec does not cache it on a type either
528
+ return
529
+ with _type_info_lock:
530
+ if tp in _type_info_ready:
531
+ return
532
+ try:
533
+ msgspec.json.Decoder(type=tp, dec_hook=_dec_hook)
534
+ except (TypeError, ValueError):
535
+ pass # not a type msgspec handles itself: the conversion goes through the hooks
536
+ _type_info_ready.add(tp)
537
+
538
+
507
539
  @lru_cache(maxsize=256)
508
540
  def _get_decoder(wire_type: Any):
541
+ _ensure_type_info(wire_type)
509
542
  return msgspec.json.Decoder(type=wire_type, dec_hook=_dec_hook)
510
543
 
511
544
 
@@ -535,6 +568,7 @@ class Backend:
535
568
  if jso.native:
536
569
  return parsed
537
570
 
571
+ _ensure_type_info(target)
538
572
  result = msgspec.convert(
539
573
  parsed,
540
574
  target,
@@ -567,6 +601,7 @@ class Backend:
567
601
  jso = JsonSerializerOptions()
568
602
 
569
603
  wire_type = wire_type_for(target, jso)
604
+ _ensure_type_info(wire_type)
570
605
  try:
571
606
  wire_obj = msgspec.convert(data, wire_type, from_attributes=True, dec_hook=_dec_hook)
572
607
  return _JSON_ENCODER.encode(wire_obj)
@@ -599,6 +634,7 @@ class Backend:
599
634
 
600
635
  first = True
601
636
  wire_type = wire_type_for(target, jso)
637
+ _ensure_type_info(wire_type)
602
638
 
603
639
  write(b"[")
604
640
 
flpit/json/_native.py CHANGED
@@ -270,7 +270,7 @@ def _class_layout(cls: type, jso: JsonSerializerOptions) -> tuple[list[_FieldSpe
270
270
 
271
271
  field_names = {f.name for f in dataclasses.fields(cls)}
272
272
  properties: list[_PropertySpec] = []
273
- for name, value in vars(cls).items():
273
+ for name, value in vars(cls).copy().items():
274
274
  if not isinstance(value, property) or name in field_names:
275
275
  continue
276
276
  if value.fset is not None: