flpit 0.4.2.dev10__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 +306 -3
- flpit/core/linq.py +3 -2
- flpit/json/_msgspec.py +38 -2
- flpit/json/_native.py +1 -1
- flpit/task.py +196 -70
- {flpit-0.4.2.dev10.dist-info → flpit-0.4.2.dev11.dist-info}/METADATA +1 -1
- {flpit-0.4.2.dev10.dist-info → flpit-0.4.2.dev11.dist-info}/RECORD +9 -9
- {flpit-0.4.2.dev10.dist-info → flpit-0.4.2.dev11.dist-info}/WHEEL +0 -0
- {flpit-0.4.2.dev10.dist-info → flpit-0.4.2.dev11.dist-info}/licenses/LICENSE +0 -0
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
|
-
|
|
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
|
|
1560
|
-
|
|
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
|
-
|
|
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:
|
flpit/task.py
CHANGED
|
@@ -66,7 +66,7 @@ from collections.abc import AsyncGenerator, Generator
|
|
|
66
66
|
from dataclasses import dataclass
|
|
67
67
|
from itertools import count
|
|
68
68
|
from types import AsyncGeneratorType, CoroutineType, FunctionType, MethodType
|
|
69
|
-
from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, cast, Iterable, Final, overload, override
|
|
69
|
+
from typing import TYPE_CHECKING, Any, Generic, NoReturn, Protocol, TypeVar, cast, Iterable, Final, overload, override
|
|
70
70
|
import functools
|
|
71
71
|
from functools import wraps
|
|
72
72
|
from collections.abc import Awaitable, Callable, Coroutine
|
|
@@ -142,9 +142,13 @@ class AggregateError(Exception):
|
|
|
142
142
|
exceptions: Iterable[Exception],
|
|
143
143
|
message: str = "One or more errors occurred.",
|
|
144
144
|
) -> None:
|
|
145
|
+
if exceptions is None:
|
|
146
|
+
raise ArgumentNullError("innerExceptions") # .NET ArgumentNullException; a TypeError, as before
|
|
145
147
|
self.exceptions = tuple(exceptions)
|
|
146
148
|
if not self.exceptions:
|
|
147
149
|
raise ValueError("exceptions must contain at least one exception")
|
|
150
|
+
if any(error is None for error in self.exceptions):
|
|
151
|
+
raise ArgumentError("An element of innerExceptions was null. (Parameter 'innerExceptions')")
|
|
148
152
|
if not all(isinstance(error, Exception) for error in self.exceptions):
|
|
149
153
|
raise TypeError("exceptions must contain Exception instances")
|
|
150
154
|
super().__init__(message)
|
|
@@ -896,7 +900,13 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
896
900
|
# and a task only gets its own attribute when it assigns one: a Task is created
|
|
897
901
|
# for every unit of work, and each attribute stored in __init__ costs time.
|
|
898
902
|
_result: Any = None
|
|
903
|
+
# The exception result() and await raise: the first failure, as .NET's GetAwaiter().GetResult().
|
|
899
904
|
_exception: BaseException | None = None
|
|
905
|
+
# Every failure when there were several (when_all, TaskCompletionSource.set_exception of an
|
|
906
|
+
# iterable), in order; _exception is the first of them. None: _exception is the only one.
|
|
907
|
+
_inner_exceptions: tuple[Exception, ...] | None = None
|
|
908
|
+
# What exception() returns once built (.NET Task.Exception returns the same instance each time).
|
|
909
|
+
_aggregate: AggregateError | None = None
|
|
900
910
|
_continuations: list[Callable[[Task[Any]], Any]] | None = None
|
|
901
911
|
_done_event: threading.Event | None = None
|
|
902
912
|
_work: tuple[Any, tuple[Any, ...], dict[str, Any]] | None = None
|
|
@@ -1092,6 +1102,11 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1092
1102
|
``Task.run_inline`` to start it on the calling thread instead.
|
|
1093
1103
|
"""
|
|
1094
1104
|
task = cls._create(work, args, kwargs, token, pass_token, creation_options)
|
|
1105
|
+
if token is not None and token.is_cancellation_requested:
|
|
1106
|
+
# .NET: a task created with a cancelled token is Canceled at once, without being queued.
|
|
1107
|
+
_close_if_coroutine(work)
|
|
1108
|
+
task._finish(_CANCELLED, exception=_task_canceled(task, f"{task.name} cancelled before start", token))
|
|
1109
|
+
return task
|
|
1095
1110
|
if creation_options and creation_options & _LONG_RUNNING:
|
|
1096
1111
|
task._runtime._submit_long_running(task, work, args, kwargs)
|
|
1097
1112
|
else:
|
|
@@ -1219,6 +1234,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1219
1234
|
if is_coroutine:
|
|
1220
1235
|
cast(Any, work).close()
|
|
1221
1236
|
raise TypeError("args/kwargs/pass_token cannot be supplied with an awaitable instance")
|
|
1237
|
+
elif work is None:
|
|
1238
|
+
raise ArgumentNullError("function") # .NET ArgumentNullException; a TypeError, as before
|
|
1222
1239
|
elif not callable(work):
|
|
1223
1240
|
raise TypeError("Task.run() expects an awaitable or a callable")
|
|
1224
1241
|
if token is not None and not isinstance(token, CancellationToken):
|
|
@@ -1259,8 +1276,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1259
1276
|
Accepts Task instances and raw awaitables (including coroutine objects)
|
|
1260
1277
|
as positional arguments or in one iterable. Raw awaitables are scheduled
|
|
1261
1278
|
automatically. Child tasks are not cancelled if this
|
|
1262
|
-
aggregate task is cancelled.
|
|
1263
|
-
|
|
1279
|
+
aggregate task is cancelled. If children fail, ``result()`` and ``await``
|
|
1280
|
+
raise the first failure in argument order and ``exception()`` / ``wait()``
|
|
1281
|
+
give an ``AggregateError`` with all of them, as with .NET ``Task.WhenAll``;
|
|
1282
|
+
a failure wins over a cancellation.
|
|
1264
1283
|
If there are no tasks, the result is an empty list.
|
|
1265
1284
|
"""
|
|
1266
1285
|
normalized = _normalize_tasks(tasks, allow_empty=True)
|
|
@@ -1309,11 +1328,58 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1309
1328
|
queried fluently and iterated with ``async for``.
|
|
1310
1329
|
"""
|
|
1311
1330
|
from flpit.core.async_linq import async_flpit # async_linq imports this module
|
|
1331
|
+
# .NET validates the arguments at the call, not when the stream is first iterated.
|
|
1332
|
+
if len(tasks) == 1 and tasks[0] is None:
|
|
1333
|
+
raise ArgumentNullError("tasks")
|
|
1334
|
+
if len(tasks) == 1 and not isinstance(tasks[0], Task) and not inspect.isawaitable(tasks[0]):
|
|
1335
|
+
tasks = tuple(tasks[0])
|
|
1336
|
+
if any(task is None for task in tasks):
|
|
1337
|
+
raise ArgumentError("The tasks argument included a null value. (Parameter 'tasks')")
|
|
1312
1338
|
return async_flpit(_collect_each)(tasks)
|
|
1313
1339
|
|
|
1314
1340
|
collect = when_each
|
|
1315
1341
|
"""Alias of :meth:`when_each`."""
|
|
1316
1342
|
|
|
1343
|
+
@classmethod
|
|
1344
|
+
def from_result[R](cls, result: R) -> "Task[R]":
|
|
1345
|
+
"""A task that has already completed successfully with ``result`` (.NET ``Task.FromResult``).
|
|
1346
|
+
|
|
1347
|
+
Every call returns a new task.
|
|
1348
|
+
"""
|
|
1349
|
+
source: TaskCompletionSource[R] = TaskCompletionSource()
|
|
1350
|
+
source.set_result(result)
|
|
1351
|
+
return source.task
|
|
1352
|
+
|
|
1353
|
+
@classmethod
|
|
1354
|
+
def from_exception(cls, exception: Exception) -> "Task[Any]":
|
|
1355
|
+
"""A task that has already failed with ``exception`` (.NET ``Task.FromException``).
|
|
1356
|
+
|
|
1357
|
+
The task is failed, not cancelled, even for an ``OperationCanceledError``, as in .NET.
|
|
1358
|
+
"""
|
|
1359
|
+
if exception is None:
|
|
1360
|
+
raise ArgumentNullError("exception")
|
|
1361
|
+
if not isinstance(exception, Exception):
|
|
1362
|
+
raise TypeError(f"exception must be an Exception, not {type(exception).__name__}")
|
|
1363
|
+
source: TaskCompletionSource[Any] = TaskCompletionSource()
|
|
1364
|
+
source.set_exception(exception)
|
|
1365
|
+
return source.task
|
|
1366
|
+
|
|
1367
|
+
@classmethod
|
|
1368
|
+
def from_canceled(cls, token: CancellationToken) -> "Task[Any]":
|
|
1369
|
+
"""A task that has already been cancelled with ``token`` (.NET ``Task.FromCanceled``).
|
|
1370
|
+
|
|
1371
|
+
``token`` must have had cancellation requested; otherwise ``ArgumentOutOfRangeError``.
|
|
1372
|
+
"""
|
|
1373
|
+
if not isinstance(token, CancellationToken):
|
|
1374
|
+
raise TypeError("token must be a CancellationToken")
|
|
1375
|
+
if not token.is_cancellation_requested:
|
|
1376
|
+
raise ArgumentOutOfRangeError(
|
|
1377
|
+
"cancellationToken", "The cancellation token must have had cancellation requested.")
|
|
1378
|
+
# .NET: the task carries the token as its CancellationToken, and the TaskCanceledException's.
|
|
1379
|
+
task: Task[Any] = cls._promise(_get_runtime(), token=token)
|
|
1380
|
+
task._finish(_CANCELLED, exception=_task_canceled(task, "A task was canceled.", token))
|
|
1381
|
+
return task
|
|
1382
|
+
|
|
1317
1383
|
@classmethod
|
|
1318
1384
|
def delay(
|
|
1319
1385
|
cls,
|
|
@@ -1438,6 +1504,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1438
1504
|
def result(self) -> T:
|
|
1439
1505
|
"""Block the calling thread until completion and return/raise the result.
|
|
1440
1506
|
|
|
1507
|
+
Raises like ``await`` and .NET's ``task.GetAwaiter().GetResult()``, not like ``Task.Result``:
|
|
1508
|
+
the task's first failure as it is (not inside an ``AggregateError``), or its cancellation.
|
|
1509
|
+
``exception()`` and ``wait()`` report every failure.
|
|
1510
|
+
|
|
1441
1511
|
As with .NET's ``Task.Result`` this also blocks when called from inside
|
|
1442
1512
|
a task. Two things keep that from starving the pool:
|
|
1443
1513
|
|
|
@@ -1475,7 +1545,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1475
1545
|
|
|
1476
1546
|
Like .NET ``Task.Wait`` and unlike ``result()``, a faulted or canceled task raises
|
|
1477
1547
|
``AggregateError`` (a canceled task contributes a ``TaskCanceledError``). A cancelled
|
|
1478
|
-
``token`` raises ``OperationCanceledError``; it does not cancel the task.
|
|
1548
|
+
``token`` raises ``OperationCanceledError``; it does not cancel the task. A
|
|
1549
|
+
``KeyboardInterrupt`` or ``SystemExit`` from the task is raised as it is.
|
|
1479
1550
|
``wait(token)`` is accepted as the token-only overload.
|
|
1480
1551
|
"""
|
|
1481
1552
|
if isinstance(timeout, CancellationToken):
|
|
@@ -1491,7 +1562,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1491
1562
|
if self._state is _CANCELLED:
|
|
1492
1563
|
token.throw_if_cancellation_requested()
|
|
1493
1564
|
if self._state is not _SUCCEEDED:
|
|
1494
|
-
|
|
1565
|
+
_raise_aggregate(_exceptions_of(self))
|
|
1495
1566
|
return True
|
|
1496
1567
|
|
|
1497
1568
|
def _internal_wait(self, seconds: float | None, token: CancellationToken) -> bool:
|
|
@@ -1533,7 +1604,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1533
1604
|
if exception_seen or any(task._state is _CANCELLED for task in items):
|
|
1534
1605
|
if not exception_seen:
|
|
1535
1606
|
token.throw_if_cancellation_requested()
|
|
1536
|
-
|
|
1607
|
+
_raise_aggregate([error for task in items for error in _exceptions_of(task)])
|
|
1537
1608
|
return True
|
|
1538
1609
|
|
|
1539
1610
|
@classmethod
|
|
@@ -1649,6 +1720,15 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1649
1720
|
return follower
|
|
1650
1721
|
|
|
1651
1722
|
def exception(self) -> BaseException | None:
|
|
1723
|
+
"""Wait for completion; the task's failures as one ``AggregateError`` (.NET ``Task.Exception``).
|
|
1724
|
+
|
|
1725
|
+
``None`` if the task succeeded. A failed task gives an ``AggregateError`` with every failure in
|
|
1726
|
+
order, also when there is only one: ``result()`` and ``await`` raise the first of them, this
|
|
1727
|
+
holds all of them. The same instance is returned each time. Two exceptions to the .NET contract:
|
|
1728
|
+
a cancelled task raises its cancellation (.NET returns null; Python's
|
|
1729
|
+
``asyncio.Future.exception()`` raises too), and a ``KeyboardInterrupt`` or ``SystemExit`` from
|
|
1730
|
+
the task is returned as it is, never inside an ``AggregateError``.
|
|
1731
|
+
"""
|
|
1652
1732
|
if self._state is _PENDING:
|
|
1653
1733
|
self._wait()
|
|
1654
1734
|
if self._state is _CANCELLED:
|
|
@@ -1658,7 +1738,16 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1658
1738
|
raise error
|
|
1659
1739
|
finally:
|
|
1660
1740
|
del error
|
|
1661
|
-
|
|
1741
|
+
error = self._exception
|
|
1742
|
+
if error is None or not isinstance(error, Exception):
|
|
1743
|
+
return error
|
|
1744
|
+
aggregate = self._aggregate
|
|
1745
|
+
if aggregate is None:
|
|
1746
|
+
with self._lock:
|
|
1747
|
+
aggregate = self._aggregate
|
|
1748
|
+
if aggregate is None:
|
|
1749
|
+
aggregate = self._aggregate = AggregateError(_faults_of(self))
|
|
1750
|
+
return aggregate
|
|
1662
1751
|
|
|
1663
1752
|
def _wait(self) -> None:
|
|
1664
1753
|
state = _thread_state
|
|
@@ -1731,7 +1820,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1731
1820
|
_close_if_coroutine(target)
|
|
1732
1821
|
self._finish(
|
|
1733
1822
|
_CANCELLED,
|
|
1734
|
-
exception=
|
|
1823
|
+
exception=_task_canceled(self, f"{self.name} cancelled before start", token),
|
|
1735
1824
|
)
|
|
1736
1825
|
return
|
|
1737
1826
|
|
|
@@ -1835,7 +1924,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1835
1924
|
def _cancellation_exception(self) -> OperationCanceledError:
|
|
1836
1925
|
if isinstance(self._exception, OperationCanceledError):
|
|
1837
1926
|
return self._exception
|
|
1838
|
-
return
|
|
1927
|
+
return _task_canceled(self, f"{self.name} was cancelled")
|
|
1839
1928
|
|
|
1840
1929
|
def __await__(self) -> Generator[Any, T, T]:
|
|
1841
1930
|
"""Await the task from flpit code or from an asyncio coroutine.
|
|
@@ -1919,8 +2008,12 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1919
2008
|
state: str,
|
|
1920
2009
|
result: Any = None,
|
|
1921
2010
|
exception: BaseException | None = None,
|
|
2011
|
+
inner_exceptions: tuple[Exception, ...] | None = None,
|
|
1922
2012
|
) -> bool:
|
|
1923
|
-
"""Complete the task. Exactly one caller wins; the others get False.
|
|
2013
|
+
"""Complete the task. Exactly one caller wins; the others get False.
|
|
2014
|
+
|
|
2015
|
+
``inner_exceptions``: every failure when there are several; ``exception`` is the first.
|
|
2016
|
+
"""
|
|
1924
2017
|
with self._lock:
|
|
1925
2018
|
if self._state is not _PENDING:
|
|
1926
2019
|
return False
|
|
@@ -1930,6 +2023,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1930
2023
|
self._result = result
|
|
1931
2024
|
if exception is not None:
|
|
1932
2025
|
self._exception = exception
|
|
2026
|
+
if inner_exceptions is not None:
|
|
2027
|
+
self._inner_exceptions = inner_exceptions
|
|
1933
2028
|
# Published last: lock-free readers check the state first.
|
|
1934
2029
|
self._state = state
|
|
1935
2030
|
continuations = self._continuations
|
|
@@ -2013,9 +2108,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
2013
2108
|
_close_if_coroutine(target)
|
|
2014
2109
|
self._finish(
|
|
2015
2110
|
_CANCELLED,
|
|
2016
|
-
exception=
|
|
2017
|
-
f"{self.name} cancelled before start", token=token
|
|
2018
|
-
),
|
|
2111
|
+
exception=_task_canceled(self, f"{self.name} cancelled before start", token),
|
|
2019
2112
|
)
|
|
2020
2113
|
return
|
|
2021
2114
|
|
|
@@ -2112,7 +2205,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
2112
2205
|
if self._cancel_requested:
|
|
2113
2206
|
self._cancel_requested = False
|
|
2114
2207
|
if not isinstance(error, OperationCanceledError):
|
|
2115
|
-
error =
|
|
2208
|
+
error = _task_canceled(self, f"{self.name} cancelled")
|
|
2116
2209
|
else:
|
|
2117
2210
|
# Finished from outside (shutdown) while it was not ours.
|
|
2118
2211
|
self._coroutine = None
|
|
@@ -2213,14 +2306,14 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
2213
2306
|
if operation is not None:
|
|
2214
2307
|
runtime = self._runtime
|
|
2215
2308
|
runtime._release_wait(operation)
|
|
2216
|
-
self._next_exception =
|
|
2309
|
+
self._next_exception = _task_canceled(self, f"{self.name} cancelled")
|
|
2217
2310
|
runtime._enqueue_task(self)
|
|
2218
2311
|
elif finish:
|
|
2219
2312
|
if work is not None:
|
|
2220
2313
|
_close_if_coroutine(work[0])
|
|
2221
2314
|
self._finish(
|
|
2222
2315
|
_CANCELLED,
|
|
2223
|
-
exception=
|
|
2316
|
+
exception=_task_canceled(self, f"{self.name} cancelled"),
|
|
2224
2317
|
)
|
|
2225
2318
|
return False
|
|
2226
2319
|
|
|
@@ -2234,7 +2327,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
2234
2327
|
runtime = self._runtime
|
|
2235
2328
|
if operation is not None:
|
|
2236
2329
|
runtime._release_wait(operation)
|
|
2237
|
-
self._finish(_CANCELLED, exception=
|
|
2330
|
+
self._finish(_CANCELLED, exception=_task_canceled(self, "runtime shutting down"))
|
|
2238
2331
|
with self._lock:
|
|
2239
2332
|
if self._running:
|
|
2240
2333
|
# A worker is inside a step; it cleans up when the step returns.
|
|
@@ -2407,21 +2500,45 @@ def _tasks_argument(tasks: tuple[Any, ...]) -> list[Task[Any]]:
|
|
|
2407
2500
|
return items
|
|
2408
2501
|
|
|
2409
2502
|
|
|
2410
|
-
def _exceptions_of(task: Task[Any]) -> list[
|
|
2411
|
-
"""A completed task's exceptions as .NET ``Task.Exception.InnerExceptions`` lists them.
|
|
2503
|
+
def _exceptions_of(task: Task[Any]) -> list[BaseException]:
|
|
2504
|
+
"""A completed task's exceptions as .NET ``Task.Exception.InnerExceptions`` lists them.
|
|
2505
|
+
|
|
2506
|
+
A ``KeyboardInterrupt`` or ``SystemExit`` from the task body is returned as it is:
|
|
2507
|
+
``_raise_aggregate`` raises it instead of hiding it in an ``AggregateError``.
|
|
2508
|
+
"""
|
|
2412
2509
|
if task._state is _CANCELLED:
|
|
2413
2510
|
cancellation = task._cancellation_exception()
|
|
2414
2511
|
if isinstance(cancellation, TaskCanceledError) and cancellation.task is task:
|
|
2415
2512
|
return [cancellation]
|
|
2416
2513
|
return [TaskCanceledError(task, inner_exception=None, token=cancellation.token)]
|
|
2417
|
-
|
|
2418
|
-
if error is None or task._state is not _FAILED:
|
|
2514
|
+
if task._state is not _FAILED or task._exception is None:
|
|
2419
2515
|
return []
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2516
|
+
return list(_faults_of(task))
|
|
2517
|
+
|
|
2518
|
+
|
|
2519
|
+
def _faults_of(task: Task[Any]) -> tuple[Any, ...]:
|
|
2520
|
+
"""Every failure of a failed task, in order (one, unless it recorded several)."""
|
|
2521
|
+
inner = task._inner_exceptions
|
|
2522
|
+
return inner if inner is not None else (task._exception,)
|
|
2523
|
+
|
|
2524
|
+
|
|
2525
|
+
def _raise_aggregate(errors: list[BaseException]) -> NoReturn:
|
|
2526
|
+
"""Raise ``errors`` as one ``AggregateError`` (.NET ``Wait``/``WaitAll``).
|
|
2527
|
+
|
|
2528
|
+
A ``KeyboardInterrupt``/``SystemExit`` among them is raised as it is: inside an
|
|
2529
|
+
``AggregateError`` (an ``Exception``), ``except Exception`` would swallow it.
|
|
2530
|
+
"""
|
|
2531
|
+
for error in errors:
|
|
2532
|
+
if not isinstance(error, Exception):
|
|
2533
|
+
raise error
|
|
2534
|
+
raise AggregateError(cast(list[Exception], errors))
|
|
2535
|
+
|
|
2536
|
+
|
|
2537
|
+
def _task_canceled(task: Task[Any], message: str, token: CancellationToken | None = None) -> TaskCanceledError:
|
|
2538
|
+
"""The ``TaskCanceledError`` a task records when it is cancelled without an exception of its own."""
|
|
2539
|
+
error = TaskCanceledError(message, token=token)
|
|
2540
|
+
error.task = task
|
|
2541
|
+
return error
|
|
2425
2542
|
|
|
2426
2543
|
|
|
2427
2544
|
def _block_until(
|
|
@@ -2636,54 +2753,48 @@ class TaskCompletionSource(Generic[T]):
|
|
|
2636
2753
|
def _normalize_exceptions(
|
|
2637
2754
|
error: Exception | Iterable[Exception],
|
|
2638
2755
|
) -> tuple[Exception, ...] | Exception:
|
|
2756
|
+
# .NET: ArgumentNullException for a null exception or list, ArgumentException for an empty list or a
|
|
2757
|
+
# null element. ArgumentError is a TypeError, as these always were except the empty list (ValueError).
|
|
2639
2758
|
if isinstance(error, Exception):
|
|
2640
2759
|
return error
|
|
2641
2760
|
if error is None:
|
|
2642
|
-
raise
|
|
2761
|
+
raise ArgumentNullError("exception")
|
|
2643
2762
|
if isinstance(error, (str, bytes, bytearray)):
|
|
2644
|
-
raise
|
|
2763
|
+
raise ArgumentError("exception must be an Exception or iterable of Exceptions")
|
|
2645
2764
|
try:
|
|
2646
2765
|
exceptions = tuple(error)
|
|
2647
2766
|
except TypeError as exc:
|
|
2648
|
-
raise
|
|
2767
|
+
raise ArgumentError("exception must be an Exception or iterable of Exceptions") from exc
|
|
2649
2768
|
if not exceptions:
|
|
2650
|
-
raise
|
|
2769
|
+
raise ArgumentError("The tasks argument contains no exceptions. (Parameter 'exceptions')")
|
|
2651
2770
|
if not all(isinstance(item, Exception) for item in exceptions):
|
|
2652
|
-
raise
|
|
2771
|
+
raise ArgumentError("The exceptions collection included at least one null element. (Parameter 'exceptions')")
|
|
2653
2772
|
return exceptions
|
|
2654
2773
|
|
|
2655
2774
|
def set_exception(self, error: Exception | Iterable[Exception]) -> None:
|
|
2656
|
-
|
|
2657
|
-
exception = (
|
|
2658
|
-
normalized
|
|
2659
|
-
if isinstance(normalized, Exception)
|
|
2660
|
-
else AggregateError(normalized)
|
|
2661
|
-
)
|
|
2662
|
-
if not self._try_complete(Task.FAILED, exception=exception):
|
|
2775
|
+
if not self.try_set_exception(error):
|
|
2663
2776
|
raise InvalidStateError("TaskCompletionSource task has already completed")
|
|
2664
2777
|
|
|
2665
2778
|
def try_set_exception(self, error: Exception | Iterable[Exception]) -> bool:
|
|
2779
|
+
# .NET TrySetException(IEnumerable): await raises the first, Task.Exception holds all.
|
|
2666
2780
|
normalized = self._normalize_exceptions(error)
|
|
2667
|
-
|
|
2668
|
-
normalized
|
|
2669
|
-
|
|
2670
|
-
|
|
2781
|
+
if isinstance(normalized, Exception):
|
|
2782
|
+
return self._try_complete(Task.FAILED, exception=normalized)
|
|
2783
|
+
return self._try_complete(
|
|
2784
|
+
Task.FAILED,
|
|
2785
|
+
exception=normalized[0],
|
|
2786
|
+
inner_exceptions=normalized if len(normalized) > 1 else None,
|
|
2671
2787
|
)
|
|
2672
|
-
return self._try_complete(Task.FAILED, exception=exception)
|
|
2673
2788
|
|
|
2674
2789
|
def set_canceled(self, token: CancellationToken | None = None) -> None:
|
|
2675
2790
|
self._validate_token(token)
|
|
2676
|
-
cancellation =
|
|
2677
|
-
"The task was canceled.", token=token
|
|
2678
|
-
)
|
|
2791
|
+
cancellation = _task_canceled(self._task, "The task was canceled.", token)
|
|
2679
2792
|
if not self._try_complete(Task.CANCELLED, exception=cancellation):
|
|
2680
2793
|
raise InvalidStateError("TaskCompletionSource task has already completed")
|
|
2681
2794
|
|
|
2682
2795
|
def try_set_canceled(self, token: CancellationToken | None = None) -> bool:
|
|
2683
2796
|
self._validate_token(token)
|
|
2684
|
-
cancellation =
|
|
2685
|
-
"The task was canceled.", token=token
|
|
2686
|
-
)
|
|
2797
|
+
cancellation = _task_canceled(self._task, "The task was canceled.", token)
|
|
2687
2798
|
return self._try_complete(Task.CANCELLED, exception=cancellation)
|
|
2688
2799
|
|
|
2689
2800
|
@staticmethod
|
|
@@ -2702,18 +2813,20 @@ class TaskCompletionSource(Generic[T]):
|
|
|
2702
2813
|
|
|
2703
2814
|
def _validate_completed_task(self, source: "flpit.task.Task[Any] | None") -> None:
|
|
2704
2815
|
if source is None:
|
|
2705
|
-
raise
|
|
2816
|
+
raise ArgumentNullError("completedTask")
|
|
2706
2817
|
if not isinstance(source, Task):
|
|
2707
2818
|
raise TypeError("completed_task must be a Task instance")
|
|
2708
2819
|
if not source.done():
|
|
2709
|
-
raise
|
|
2820
|
+
raise ArgumentError("The provided task must have already completed. (Parameter 'completedTask')")
|
|
2710
2821
|
|
|
2711
2822
|
def _try_copy_task(self, source: "flpit.task.Task[Any]") -> bool:
|
|
2712
2823
|
if source._state == Task.SUCCEEDED:
|
|
2713
2824
|
return self._try_complete(Task.SUCCEEDED, result=source._result)
|
|
2714
2825
|
if source._state == Task.FAILED:
|
|
2715
2826
|
assert source._exception is not None
|
|
2716
|
-
return self._try_complete(
|
|
2827
|
+
return self._try_complete(
|
|
2828
|
+
Task.FAILED, exception=source._exception, inner_exceptions=source._inner_exceptions,
|
|
2829
|
+
)
|
|
2717
2830
|
if source._state == Task.CANCELLED:
|
|
2718
2831
|
return self._try_complete(
|
|
2719
2832
|
Task.CANCELLED,
|
|
@@ -2729,11 +2842,12 @@ class TaskCompletionSource(Generic[T]):
|
|
|
2729
2842
|
*,
|
|
2730
2843
|
result: Any = None,
|
|
2731
2844
|
exception: Exception | BaseException | None = None,
|
|
2845
|
+
inner_exceptions: tuple[Exception, ...] | None = None,
|
|
2732
2846
|
) -> bool:
|
|
2733
2847
|
# Safe from any thread and never blocks: the task's own lock decides
|
|
2734
2848
|
# the winner and its continuations are handed to the pool, so the
|
|
2735
2849
|
# caller of set_result() does not end up running awaiting coroutines.
|
|
2736
|
-
return self._task._finish(state, result=result, exception=exception)
|
|
2850
|
+
return self._task._finish(state, result=result, exception=exception, inner_exceptions=inner_exceptions)
|
|
2737
2851
|
|
|
2738
2852
|
|
|
2739
2853
|
async def _collect_each(tasks: tuple[Any, ...]) -> AsyncGenerator[Task[Any], None]:
|
|
@@ -2780,6 +2894,8 @@ def _normalize_tasks(items: tuple[Any, ...], *, allow_empty: bool) -> tuple[Task
|
|
|
2780
2894
|
coroutine objects supplied to this call are closed so Python does not emit
|
|
2781
2895
|
"coroutine was never awaited" warnings for rejected inputs.
|
|
2782
2896
|
"""
|
|
2897
|
+
if len(items) == 1 and items[0] is None:
|
|
2898
|
+
raise ArgumentNullError("tasks") # .NET Task.WhenAll((Task[])null)
|
|
2783
2899
|
# A single awaitable is one operation, not an iterable of operations.
|
|
2784
2900
|
if (
|
|
2785
2901
|
len(items) == 1
|
|
@@ -2794,7 +2910,7 @@ def _normalize_tasks(items: tuple[Any, ...], *, allow_empty: bool) -> tuple[Task
|
|
|
2794
2910
|
pass
|
|
2795
2911
|
|
|
2796
2912
|
if not items and not allow_empty:
|
|
2797
|
-
raise
|
|
2913
|
+
raise ArgumentError("The tasks argument contains no tasks. (Parameter 'tasks')")
|
|
2798
2914
|
|
|
2799
2915
|
def close_raw_coroutines(values: tuple[Any, ...]) -> None:
|
|
2800
2916
|
seen: set[int] = set()
|
|
@@ -2808,6 +2924,9 @@ def _normalize_tasks(items: tuple[Any, ...], *, allow_empty: bool) -> tuple[Task
|
|
|
2808
2924
|
|
|
2809
2925
|
# Validate everything before scheduling anything, avoiding partial starts
|
|
2810
2926
|
# when the caller accidentally mixes a coroutine with a non-awaitable.
|
|
2927
|
+
if any(item is None for item in items):
|
|
2928
|
+
close_raw_coroutines(items)
|
|
2929
|
+
raise ArgumentError("The tasks argument included a null value. (Parameter 'tasks')")
|
|
2811
2930
|
invalid = [item for item in items if not isinstance(item, Task) and not inspect.isawaitable(item)]
|
|
2812
2931
|
if invalid:
|
|
2813
2932
|
close_raw_coroutines(items)
|
|
@@ -2872,20 +2991,24 @@ class _WhenAll:
|
|
|
2872
2991
|
if self._remaining:
|
|
2873
2992
|
return
|
|
2874
2993
|
tasks = self._tasks
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2994
|
+
# .NET Task.WhenAll: faulted wins over canceled; the aggregate holds every failure of every
|
|
2995
|
+
# child in order (a child's own several failures included), await/result raise the first.
|
|
2996
|
+
failures = [error for child in tasks if child._state is _FAILED for error in _faults_of(child)]
|
|
2997
|
+
if failures:
|
|
2998
|
+
interrupt = next((error for error in failures if not isinstance(error, Exception)), None)
|
|
2999
|
+
if interrupt is not None: # KeyboardInterrupt/SystemExit: never inside an AggregateError
|
|
3000
|
+
self._promise._finish(_FAILED, exception=interrupt)
|
|
3001
|
+
else:
|
|
3002
|
+
self._promise._finish(
|
|
3003
|
+
_FAILED,
|
|
3004
|
+
exception=failures[0],
|
|
3005
|
+
inner_exceptions=tuple(failures) if len(failures) > 1 else None,
|
|
3006
|
+
)
|
|
2883
3007
|
elif any(child._state is _CANCELLED for child in tasks):
|
|
2884
|
-
self._promise
|
|
3008
|
+
promise = self._promise
|
|
3009
|
+
promise._finish(
|
|
2885
3010
|
_CANCELLED,
|
|
2886
|
-
exception=
|
|
2887
|
-
"One or more tasks passed to Task.when_all() were cancelled"
|
|
2888
|
-
),
|
|
3011
|
+
exception=_task_canceled(promise, "One or more tasks passed to Task.when_all() were cancelled"),
|
|
2889
3012
|
)
|
|
2890
3013
|
else:
|
|
2891
3014
|
self._promise._finish(_SUCCEEDED, result=[child._result for child in tasks])
|
|
@@ -4540,16 +4663,19 @@ def asyncio_task[**P, T](
|
|
|
4540
4663
|
A ``CancellationToken`` passed as an argument also cancels the call, as in .NET: the asyncio
|
|
4541
4664
|
task is cancelled and the returned Task ends cancelled.
|
|
4542
4665
|
|
|
4543
|
-
Loop-bound objects that should be reused across calls (clients, connection pools)
|
|
4544
|
-
a ``
|
|
4666
|
+
Loop-bound objects that should be reused across calls (clients, connection pools) are kept
|
|
4667
|
+
one per loop: a parameter annotated ``Loop[T]`` (``flpit.asyncio_bridge``) receives the
|
|
4668
|
+
``provide()``-d ``T`` of the loop the call runs on, and an object that outlives the call can
|
|
4669
|
+
hold a ``PerLoop[T]`` and read ``.current``.
|
|
4545
4670
|
"""
|
|
4671
|
+
cache: list[Any] = []
|
|
4546
4672
|
|
|
4547
4673
|
@functools.wraps(async_function)
|
|
4548
4674
|
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Task[T]:
|
|
4549
|
-
from .asyncio_bridge import
|
|
4675
|
+
from .asyncio_bridge import _call_asyncio_task # imports asyncio on first use only
|
|
4550
4676
|
|
|
4551
4677
|
token = next((value for value in (*args, *kwargs.values()) if isinstance(value, CancellationToken)), None)
|
|
4552
|
-
return
|
|
4678
|
+
return _call_asyncio_task(async_function, args, kwargs, token, cache)
|
|
4553
4679
|
|
|
4554
4680
|
return wrapper
|
|
4555
4681
|
|
|
@@ -1,12 +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=
|
|
3
|
+
flpit/asyncio_bridge.py,sha256=BKeOntFmVepIu7Fu0Z5JO0KCYYOYr4YeMgOaRtHIcQI,40061
|
|
4
4
|
flpit/channels.py,sha256=LuJ25ReLff2eagQAoNUvOuhLCbrBDT2nwncFXafUFUc,46800
|
|
5
5
|
flpit/concurrent.py,sha256=HZueI_zSTX9ozwmxwrn7_HSrxT4VL3CKoDbKQRqAKLA,32211
|
|
6
6
|
flpit/csv.py,sha256=QMG8AxYR32i4I_lD1KL284OXdScN6vjjgusvnqw2q-A,25862
|
|
7
7
|
flpit/flp.py,sha256=WaZnrtYdxwEOJUEBv_hXg8Uwm81h8kcH64pjDh8oJhU,1527
|
|
8
8
|
flpit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
-
flpit/task.py,sha256=
|
|
9
|
+
flpit/task.py,sha256=yY7yMc4Yioy-5o-Fd74geU4BF0Xg7HZVF1U0ud8Ghkc,194908
|
|
10
10
|
flpit/threading.py,sha256=MeWwOI2DSejmwiivSL1IVGx0US-FEsgcNRjFWdwdcSg,37236
|
|
11
11
|
flpit/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
12
|
flpit/core/_grouping.py,sha256=QZNdNqXx4fcRsnun4nwkGKnst63Y10Q-rYBevof7Abw,954
|
|
@@ -16,12 +16,12 @@ flpit/core/_lookup.py,sha256=v_FC9anm6OpbQqj3DmNwOW4ppxDZY9VY5MybAvsHJsk,1641
|
|
|
16
16
|
flpit/core/_zip.py,sha256=lz5cbHcVV12UNyaOtrUd5jz-v_XI5xEp24KbnhAQZq8,259
|
|
17
17
|
flpit/core/async_linq.py,sha256=OlqpZJQASJuzoaPM2Mg6ejMR8rzeU53oBiFtas_ey4k,81749
|
|
18
18
|
flpit/core/comparers.py,sha256=XH3OuTHqhcc3of8dsMtbyggv1EuL6qZBOwiB3YEaKvQ,3030
|
|
19
|
-
flpit/core/linq.py,sha256=
|
|
19
|
+
flpit/core/linq.py,sha256=UInHjKiNWF-H4eDJLFCHqa-nWNHk30qc0EKBwrCGxZY,90077
|
|
20
20
|
flpit/json/__init__.py,sha256=7U7-KaxLbQybqmNTqDf4U54Njhac2ep5gxPEaavR7hA,4625
|
|
21
21
|
flpit/json/_core.py,sha256=IhLM116xW4jI4gg3-QmRGptVr5pHRY7X7aicm8TmO3Y,13445
|
|
22
|
-
flpit/json/_msgspec.py,sha256=
|
|
23
|
-
flpit/json/_native.py,sha256=
|
|
24
|
-
flpit-0.4.2.
|
|
25
|
-
flpit-0.4.2.
|
|
26
|
-
flpit-0.4.2.
|
|
27
|
-
flpit-0.4.2.
|
|
22
|
+
flpit/json/_msgspec.py,sha256=RJKHXT3928G-E7JKn8VwGf__FCeNB4OrJzVyQ6W5uxY,21682
|
|
23
|
+
flpit/json/_native.py,sha256=AmfJZbT8vR67a6To1zUBG70oa0xWCPEqjUmQUnA99-0,39981
|
|
24
|
+
flpit-0.4.2.dev11.dist-info/METADATA,sha256=4G6sMsfkULZzTuxyNUOhtd6mJZaSSOdR7ePCvucsRQA,19396
|
|
25
|
+
flpit-0.4.2.dev11.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
26
|
+
flpit-0.4.2.dev11.dist-info/licenses/LICENSE,sha256=bi5Vg_YP3Oq3jaOMQT4b7WZu0NfBcZr-nRyOExUKJrQ,1063
|
|
27
|
+
flpit-0.4.2.dev11.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|