flpit 0.4.2.dev10__py3-none-any.whl → 0.4.2.dev12__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 +16 -3
- flpit/json/_msgspec.py +38 -2
- flpit/json/_native.py +1 -1
- flpit/task.py +218 -76
- {flpit-0.4.2.dev10.dist-info → flpit-0.4.2.dev12.dist-info}/METADATA +27 -21
- {flpit-0.4.2.dev10.dist-info → flpit-0.4.2.dev12.dist-info}/RECORD +9 -9
- {flpit-0.4.2.dev10.dist-info → flpit-0.4.2.dev12.dist-info}/WHEEL +0 -0
- {flpit-0.4.2.dev10.dist-info → flpit-0.4.2.dev12.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
|
@@ -468,6 +468,8 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
468
468
|
|
|
469
469
|
Evaluation stops as soon as the result is known.
|
|
470
470
|
"""
|
|
471
|
+
if predicate is None:
|
|
472
|
+
raise PredicateNoneError()
|
|
471
473
|
if predicate is not _SENTINEL:
|
|
472
474
|
return builtins.any(map(predicate, self))
|
|
473
475
|
|
|
@@ -489,6 +491,8 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
489
491
|
Returns True for an empty sequence.
|
|
490
492
|
Evaluation stops at the first element that fails the predicate.
|
|
491
493
|
"""
|
|
494
|
+
if predicate is None:
|
|
495
|
+
raise PredicateNoneError()
|
|
492
496
|
return builtins.all(map(predicate, self))
|
|
493
497
|
|
|
494
498
|
def concat(self, second: Iterable[TItem]) -> "FlpIt[TItem]":
|
|
@@ -1455,7 +1459,7 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
1455
1459
|
if key_selector is None:
|
|
1456
1460
|
raise SelectorNoneError()
|
|
1457
1461
|
if element_selector is None:
|
|
1458
|
-
raise
|
|
1462
|
+
raise ElementSelectorNoneError()
|
|
1459
1463
|
|
|
1460
1464
|
result: dict[Any, Any] = {}
|
|
1461
1465
|
for item in self:
|
|
@@ -1556,8 +1560,9 @@ class FlpIt[TItem](Iterable[TItem]):
|
|
|
1556
1560
|
def when_all[R](self: FlpIt[Task[R]]) -> Task[list[R]]:
|
|
1557
1561
|
"""
|
|
1558
1562
|
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
|
-
|
|
1563
|
+
form of ``Task.when_all`` (.NET ``Task.WhenAll``). Enumerating the query starts it in full. If tasks fail, ``result()``
|
|
1564
|
+
and ``await`` raise the first failure in query order; ``exception()`` and ``wait()`` give an
|
|
1565
|
+
``AggregateError`` with all of them.
|
|
1561
1566
|
An empty query gives an empty list.
|
|
1562
1567
|
"""
|
|
1563
1568
|
from flpit.task import Task
|
|
@@ -1835,6 +1840,9 @@ class FlpList[TItem](Collection[TItem]):
|
|
|
1835
1840
|
return item in self.__list.data
|
|
1836
1841
|
|
|
1837
1842
|
def exists(self, predicate: Callable[[TItem], bool]) -> bool:
|
|
1843
|
+
if predicate is None:
|
|
1844
|
+
raise PredicateNoneError()
|
|
1845
|
+
|
|
1838
1846
|
return any(predicate(item) for item in self.__list.data)
|
|
1839
1847
|
|
|
1840
1848
|
def find(self, predicate: Callable[[TItem], bool]) -> TItem | None:
|
|
@@ -1952,6 +1960,8 @@ class FlpList[TItem](Collection[TItem]):
|
|
|
1952
1960
|
) -> bool:
|
|
1953
1961
|
if predicate is _SENTINEL:
|
|
1954
1962
|
return len(self.__list.data) > 0
|
|
1963
|
+
if predicate is None:
|
|
1964
|
+
raise PredicateNoneError()
|
|
1955
1965
|
|
|
1956
1966
|
return any(predicate(item) for item in self.__list.data)
|
|
1957
1967
|
|
|
@@ -1959,6 +1969,9 @@ class FlpList[TItem](Collection[TItem]):
|
|
|
1959
1969
|
self,
|
|
1960
1970
|
predicate: Callable[[TItem], bool],
|
|
1961
1971
|
) -> bool:
|
|
1972
|
+
if predicate is None:
|
|
1973
|
+
raise PredicateNoneError()
|
|
1974
|
+
|
|
1962
1975
|
return all(predicate(item) for item in self.__list.data)
|
|
1963
1976
|
|
|
1964
1977
|
def append(self, element: TItem) -> FlpIt[TItem]:
|
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)
|
|
@@ -313,7 +317,7 @@ class _WorkerInfo:
|
|
|
313
317
|
# This thread's CPU-time clock, where the platform has one (Linux, BSDs; not macOS
|
|
314
318
|
# or Windows): it barely moves while the thread waits, and moves while it computes.
|
|
315
319
|
self.cpu_clock: int | None = None
|
|
316
|
-
getcpuclockid =
|
|
320
|
+
getcpuclockid = _thread_cpu_clock_id
|
|
317
321
|
if getcpuclockid is not None:
|
|
318
322
|
try:
|
|
319
323
|
self.cpu_clock = getcpuclockid(threading.get_ident())
|
|
@@ -321,6 +325,12 @@ class _WorkerInfo:
|
|
|
321
325
|
pass
|
|
322
326
|
|
|
323
327
|
|
|
328
|
+
# The CPU clocks the pool's gate reads (module level, so tests can stand in for another platform).
|
|
329
|
+
# Per-thread clocks exist on Linux and the BSDs, not on macOS or Windows.
|
|
330
|
+
_thread_cpu_clock_id: Callable[[int], int] | None = getattr(time, "pthread_getcpuclockid", None)
|
|
331
|
+
_process_time: Callable[[], float] = time.process_time
|
|
332
|
+
|
|
333
|
+
|
|
324
334
|
def _cpu_capacity() -> float:
|
|
325
335
|
"""CPU cores Python code can use at once: 1 with the GIL, all of them without."""
|
|
326
336
|
if getattr(sys, "_is_gil_enabled", lambda: True)():
|
|
@@ -896,7 +906,13 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
896
906
|
# and a task only gets its own attribute when it assigns one: a Task is created
|
|
897
907
|
# for every unit of work, and each attribute stored in __init__ costs time.
|
|
898
908
|
_result: Any = None
|
|
909
|
+
# The exception result() and await raise: the first failure, as .NET's GetAwaiter().GetResult().
|
|
899
910
|
_exception: BaseException | None = None
|
|
911
|
+
# Every failure when there were several (when_all, TaskCompletionSource.set_exception of an
|
|
912
|
+
# iterable), in order; _exception is the first of them. None: _exception is the only one.
|
|
913
|
+
_inner_exceptions: tuple[Exception, ...] | None = None
|
|
914
|
+
# What exception() returns once built (.NET Task.Exception returns the same instance each time).
|
|
915
|
+
_aggregate: AggregateError | None = None
|
|
900
916
|
_continuations: list[Callable[[Task[Any]], Any]] | None = None
|
|
901
917
|
_done_event: threading.Event | None = None
|
|
902
918
|
_work: tuple[Any, tuple[Any, ...], dict[str, Any]] | None = None
|
|
@@ -1092,6 +1108,11 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1092
1108
|
``Task.run_inline`` to start it on the calling thread instead.
|
|
1093
1109
|
"""
|
|
1094
1110
|
task = cls._create(work, args, kwargs, token, pass_token, creation_options)
|
|
1111
|
+
if token is not None and token.is_cancellation_requested:
|
|
1112
|
+
# .NET: a task created with a cancelled token is Canceled at once, without being queued.
|
|
1113
|
+
_close_if_coroutine(work)
|
|
1114
|
+
task._finish(_CANCELLED, exception=_task_canceled(task, f"{task.name} cancelled before start", token))
|
|
1115
|
+
return task
|
|
1095
1116
|
if creation_options and creation_options & _LONG_RUNNING:
|
|
1096
1117
|
task._runtime._submit_long_running(task, work, args, kwargs)
|
|
1097
1118
|
else:
|
|
@@ -1219,6 +1240,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1219
1240
|
if is_coroutine:
|
|
1220
1241
|
cast(Any, work).close()
|
|
1221
1242
|
raise TypeError("args/kwargs/pass_token cannot be supplied with an awaitable instance")
|
|
1243
|
+
elif work is None:
|
|
1244
|
+
raise ArgumentNullError("function") # .NET ArgumentNullException; a TypeError, as before
|
|
1222
1245
|
elif not callable(work):
|
|
1223
1246
|
raise TypeError("Task.run() expects an awaitable or a callable")
|
|
1224
1247
|
if token is not None and not isinstance(token, CancellationToken):
|
|
@@ -1259,8 +1282,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1259
1282
|
Accepts Task instances and raw awaitables (including coroutine objects)
|
|
1260
1283
|
as positional arguments or in one iterable. Raw awaitables are scheduled
|
|
1261
1284
|
automatically. Child tasks are not cancelled if this
|
|
1262
|
-
aggregate task is cancelled.
|
|
1263
|
-
|
|
1285
|
+
aggregate task is cancelled. If children fail, ``result()`` and ``await``
|
|
1286
|
+
raise the first failure in argument order and ``exception()`` / ``wait()``
|
|
1287
|
+
give an ``AggregateError`` with all of them, as with .NET ``Task.WhenAll``;
|
|
1288
|
+
a failure wins over a cancellation.
|
|
1264
1289
|
If there are no tasks, the result is an empty list.
|
|
1265
1290
|
"""
|
|
1266
1291
|
normalized = _normalize_tasks(tasks, allow_empty=True)
|
|
@@ -1309,11 +1334,58 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1309
1334
|
queried fluently and iterated with ``async for``.
|
|
1310
1335
|
"""
|
|
1311
1336
|
from flpit.core.async_linq import async_flpit # async_linq imports this module
|
|
1337
|
+
# .NET validates the arguments at the call, not when the stream is first iterated.
|
|
1338
|
+
if len(tasks) == 1 and tasks[0] is None:
|
|
1339
|
+
raise ArgumentNullError("tasks")
|
|
1340
|
+
if len(tasks) == 1 and not isinstance(tasks[0], Task) and not inspect.isawaitable(tasks[0]):
|
|
1341
|
+
tasks = tuple(tasks[0])
|
|
1342
|
+
if any(task is None for task in tasks):
|
|
1343
|
+
raise ArgumentError("The tasks argument included a null value. (Parameter 'tasks')")
|
|
1312
1344
|
return async_flpit(_collect_each)(tasks)
|
|
1313
1345
|
|
|
1314
1346
|
collect = when_each
|
|
1315
1347
|
"""Alias of :meth:`when_each`."""
|
|
1316
1348
|
|
|
1349
|
+
@classmethod
|
|
1350
|
+
def from_result[R](cls, result: R) -> "Task[R]":
|
|
1351
|
+
"""A task that has already completed successfully with ``result`` (.NET ``Task.FromResult``).
|
|
1352
|
+
|
|
1353
|
+
Every call returns a new task.
|
|
1354
|
+
"""
|
|
1355
|
+
source: TaskCompletionSource[R] = TaskCompletionSource()
|
|
1356
|
+
source.set_result(result)
|
|
1357
|
+
return source.task
|
|
1358
|
+
|
|
1359
|
+
@classmethod
|
|
1360
|
+
def from_exception(cls, exception: Exception) -> "Task[Any]":
|
|
1361
|
+
"""A task that has already failed with ``exception`` (.NET ``Task.FromException``).
|
|
1362
|
+
|
|
1363
|
+
The task is failed, not cancelled, even for an ``OperationCanceledError``, as in .NET.
|
|
1364
|
+
"""
|
|
1365
|
+
if exception is None:
|
|
1366
|
+
raise ArgumentNullError("exception")
|
|
1367
|
+
if not isinstance(exception, Exception):
|
|
1368
|
+
raise TypeError(f"exception must be an Exception, not {type(exception).__name__}")
|
|
1369
|
+
source: TaskCompletionSource[Any] = TaskCompletionSource()
|
|
1370
|
+
source.set_exception(exception)
|
|
1371
|
+
return source.task
|
|
1372
|
+
|
|
1373
|
+
@classmethod
|
|
1374
|
+
def from_canceled(cls, token: CancellationToken) -> "Task[Any]":
|
|
1375
|
+
"""A task that has already been cancelled with ``token`` (.NET ``Task.FromCanceled``).
|
|
1376
|
+
|
|
1377
|
+
``token`` must have had cancellation requested; otherwise ``ArgumentOutOfRangeError``.
|
|
1378
|
+
"""
|
|
1379
|
+
if not isinstance(token, CancellationToken):
|
|
1380
|
+
raise TypeError("token must be a CancellationToken")
|
|
1381
|
+
if not token.is_cancellation_requested:
|
|
1382
|
+
raise ArgumentOutOfRangeError(
|
|
1383
|
+
"cancellationToken", "The cancellation token must have had cancellation requested.")
|
|
1384
|
+
# .NET: the task carries the token as its CancellationToken, and the TaskCanceledException's.
|
|
1385
|
+
task: Task[Any] = cls._promise(_get_runtime(), token=token)
|
|
1386
|
+
task._finish(_CANCELLED, exception=_task_canceled(task, "A task was canceled.", token))
|
|
1387
|
+
return task
|
|
1388
|
+
|
|
1317
1389
|
@classmethod
|
|
1318
1390
|
def delay(
|
|
1319
1391
|
cls,
|
|
@@ -1438,6 +1510,10 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1438
1510
|
def result(self) -> T:
|
|
1439
1511
|
"""Block the calling thread until completion and return/raise the result.
|
|
1440
1512
|
|
|
1513
|
+
Raises like ``await`` and .NET's ``task.GetAwaiter().GetResult()``, not like ``Task.Result``:
|
|
1514
|
+
the task's first failure as it is (not inside an ``AggregateError``), or its cancellation.
|
|
1515
|
+
``exception()`` and ``wait()`` report every failure.
|
|
1516
|
+
|
|
1441
1517
|
As with .NET's ``Task.Result`` this also blocks when called from inside
|
|
1442
1518
|
a task. Two things keep that from starving the pool:
|
|
1443
1519
|
|
|
@@ -1475,7 +1551,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1475
1551
|
|
|
1476
1552
|
Like .NET ``Task.Wait`` and unlike ``result()``, a faulted or canceled task raises
|
|
1477
1553
|
``AggregateError`` (a canceled task contributes a ``TaskCanceledError``). A cancelled
|
|
1478
|
-
``token`` raises ``OperationCanceledError``; it does not cancel the task.
|
|
1554
|
+
``token`` raises ``OperationCanceledError``; it does not cancel the task. A
|
|
1555
|
+
``KeyboardInterrupt`` or ``SystemExit`` from the task is raised as it is.
|
|
1479
1556
|
``wait(token)`` is accepted as the token-only overload.
|
|
1480
1557
|
"""
|
|
1481
1558
|
if isinstance(timeout, CancellationToken):
|
|
@@ -1491,7 +1568,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1491
1568
|
if self._state is _CANCELLED:
|
|
1492
1569
|
token.throw_if_cancellation_requested()
|
|
1493
1570
|
if self._state is not _SUCCEEDED:
|
|
1494
|
-
|
|
1571
|
+
_raise_aggregate(_exceptions_of(self))
|
|
1495
1572
|
return True
|
|
1496
1573
|
|
|
1497
1574
|
def _internal_wait(self, seconds: float | None, token: CancellationToken) -> bool:
|
|
@@ -1533,7 +1610,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1533
1610
|
if exception_seen or any(task._state is _CANCELLED for task in items):
|
|
1534
1611
|
if not exception_seen:
|
|
1535
1612
|
token.throw_if_cancellation_requested()
|
|
1536
|
-
|
|
1613
|
+
_raise_aggregate([error for task in items for error in _exceptions_of(task)])
|
|
1537
1614
|
return True
|
|
1538
1615
|
|
|
1539
1616
|
@classmethod
|
|
@@ -1649,6 +1726,15 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1649
1726
|
return follower
|
|
1650
1727
|
|
|
1651
1728
|
def exception(self) -> BaseException | None:
|
|
1729
|
+
"""Wait for completion; the task's failures as one ``AggregateError`` (.NET ``Task.Exception``).
|
|
1730
|
+
|
|
1731
|
+
``None`` if the task succeeded. A failed task gives an ``AggregateError`` with every failure in
|
|
1732
|
+
order, also when there is only one: ``result()`` and ``await`` raise the first of them, this
|
|
1733
|
+
holds all of them. The same instance is returned each time. Two exceptions to the .NET contract:
|
|
1734
|
+
a cancelled task raises its cancellation (.NET returns null; Python's
|
|
1735
|
+
``asyncio.Future.exception()`` raises too), and a ``KeyboardInterrupt`` or ``SystemExit`` from
|
|
1736
|
+
the task is returned as it is, never inside an ``AggregateError``.
|
|
1737
|
+
"""
|
|
1652
1738
|
if self._state is _PENDING:
|
|
1653
1739
|
self._wait()
|
|
1654
1740
|
if self._state is _CANCELLED:
|
|
@@ -1658,7 +1744,16 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1658
1744
|
raise error
|
|
1659
1745
|
finally:
|
|
1660
1746
|
del error
|
|
1661
|
-
|
|
1747
|
+
error = self._exception
|
|
1748
|
+
if error is None or not isinstance(error, Exception):
|
|
1749
|
+
return error
|
|
1750
|
+
aggregate = self._aggregate
|
|
1751
|
+
if aggregate is None:
|
|
1752
|
+
with self._lock:
|
|
1753
|
+
aggregate = self._aggregate
|
|
1754
|
+
if aggregate is None:
|
|
1755
|
+
aggregate = self._aggregate = AggregateError(_faults_of(self))
|
|
1756
|
+
return aggregate
|
|
1662
1757
|
|
|
1663
1758
|
def _wait(self) -> None:
|
|
1664
1759
|
state = _thread_state
|
|
@@ -1731,7 +1826,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1731
1826
|
_close_if_coroutine(target)
|
|
1732
1827
|
self._finish(
|
|
1733
1828
|
_CANCELLED,
|
|
1734
|
-
exception=
|
|
1829
|
+
exception=_task_canceled(self, f"{self.name} cancelled before start", token),
|
|
1735
1830
|
)
|
|
1736
1831
|
return
|
|
1737
1832
|
|
|
@@ -1835,7 +1930,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1835
1930
|
def _cancellation_exception(self) -> OperationCanceledError:
|
|
1836
1931
|
if isinstance(self._exception, OperationCanceledError):
|
|
1837
1932
|
return self._exception
|
|
1838
|
-
return
|
|
1933
|
+
return _task_canceled(self, f"{self.name} was cancelled")
|
|
1839
1934
|
|
|
1840
1935
|
def __await__(self) -> Generator[Any, T, T]:
|
|
1841
1936
|
"""Await the task from flpit code or from an asyncio coroutine.
|
|
@@ -1919,8 +2014,12 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1919
2014
|
state: str,
|
|
1920
2015
|
result: Any = None,
|
|
1921
2016
|
exception: BaseException | None = None,
|
|
2017
|
+
inner_exceptions: tuple[Exception, ...] | None = None,
|
|
1922
2018
|
) -> bool:
|
|
1923
|
-
"""Complete the task. Exactly one caller wins; the others get False.
|
|
2019
|
+
"""Complete the task. Exactly one caller wins; the others get False.
|
|
2020
|
+
|
|
2021
|
+
``inner_exceptions``: every failure when there are several; ``exception`` is the first.
|
|
2022
|
+
"""
|
|
1924
2023
|
with self._lock:
|
|
1925
2024
|
if self._state is not _PENDING:
|
|
1926
2025
|
return False
|
|
@@ -1930,6 +2029,8 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
1930
2029
|
self._result = result
|
|
1931
2030
|
if exception is not None:
|
|
1932
2031
|
self._exception = exception
|
|
2032
|
+
if inner_exceptions is not None:
|
|
2033
|
+
self._inner_exceptions = inner_exceptions
|
|
1933
2034
|
# Published last: lock-free readers check the state first.
|
|
1934
2035
|
self._state = state
|
|
1935
2036
|
continuations = self._continuations
|
|
@@ -2013,9 +2114,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
2013
2114
|
_close_if_coroutine(target)
|
|
2014
2115
|
self._finish(
|
|
2015
2116
|
_CANCELLED,
|
|
2016
|
-
exception=
|
|
2017
|
-
f"{self.name} cancelled before start", token=token
|
|
2018
|
-
),
|
|
2117
|
+
exception=_task_canceled(self, f"{self.name} cancelled before start", token),
|
|
2019
2118
|
)
|
|
2020
2119
|
return
|
|
2021
2120
|
|
|
@@ -2112,7 +2211,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
2112
2211
|
if self._cancel_requested:
|
|
2113
2212
|
self._cancel_requested = False
|
|
2114
2213
|
if not isinstance(error, OperationCanceledError):
|
|
2115
|
-
error =
|
|
2214
|
+
error = _task_canceled(self, f"{self.name} cancelled")
|
|
2116
2215
|
else:
|
|
2117
2216
|
# Finished from outside (shutdown) while it was not ours.
|
|
2118
2217
|
self._coroutine = None
|
|
@@ -2213,14 +2312,14 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
2213
2312
|
if operation is not None:
|
|
2214
2313
|
runtime = self._runtime
|
|
2215
2314
|
runtime._release_wait(operation)
|
|
2216
|
-
self._next_exception =
|
|
2315
|
+
self._next_exception = _task_canceled(self, f"{self.name} cancelled")
|
|
2217
2316
|
runtime._enqueue_task(self)
|
|
2218
2317
|
elif finish:
|
|
2219
2318
|
if work is not None:
|
|
2220
2319
|
_close_if_coroutine(work[0])
|
|
2221
2320
|
self._finish(
|
|
2222
2321
|
_CANCELLED,
|
|
2223
|
-
exception=
|
|
2322
|
+
exception=_task_canceled(self, f"{self.name} cancelled"),
|
|
2224
2323
|
)
|
|
2225
2324
|
return False
|
|
2226
2325
|
|
|
@@ -2234,7 +2333,7 @@ class Task(Generic[T], metaclass=_TaskMeta):
|
|
|
2234
2333
|
runtime = self._runtime
|
|
2235
2334
|
if operation is not None:
|
|
2236
2335
|
runtime._release_wait(operation)
|
|
2237
|
-
self._finish(_CANCELLED, exception=
|
|
2336
|
+
self._finish(_CANCELLED, exception=_task_canceled(self, "runtime shutting down"))
|
|
2238
2337
|
with self._lock:
|
|
2239
2338
|
if self._running:
|
|
2240
2339
|
# A worker is inside a step; it cleans up when the step returns.
|
|
@@ -2407,21 +2506,45 @@ def _tasks_argument(tasks: tuple[Any, ...]) -> list[Task[Any]]:
|
|
|
2407
2506
|
return items
|
|
2408
2507
|
|
|
2409
2508
|
|
|
2410
|
-
def _exceptions_of(task: Task[Any]) -> list[
|
|
2411
|
-
"""A completed task's exceptions as .NET ``Task.Exception.InnerExceptions`` lists them.
|
|
2509
|
+
def _exceptions_of(task: Task[Any]) -> list[BaseException]:
|
|
2510
|
+
"""A completed task's exceptions as .NET ``Task.Exception.InnerExceptions`` lists them.
|
|
2511
|
+
|
|
2512
|
+
A ``KeyboardInterrupt`` or ``SystemExit`` from the task body is returned as it is:
|
|
2513
|
+
``_raise_aggregate`` raises it instead of hiding it in an ``AggregateError``.
|
|
2514
|
+
"""
|
|
2412
2515
|
if task._state is _CANCELLED:
|
|
2413
2516
|
cancellation = task._cancellation_exception()
|
|
2414
2517
|
if isinstance(cancellation, TaskCanceledError) and cancellation.task is task:
|
|
2415
2518
|
return [cancellation]
|
|
2416
2519
|
return [TaskCanceledError(task, inner_exception=None, token=cancellation.token)]
|
|
2417
|
-
|
|
2418
|
-
if error is None or task._state is not _FAILED:
|
|
2520
|
+
if task._state is not _FAILED or task._exception is None:
|
|
2419
2521
|
return []
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2522
|
+
return list(_faults_of(task))
|
|
2523
|
+
|
|
2524
|
+
|
|
2525
|
+
def _faults_of(task: Task[Any]) -> tuple[Any, ...]:
|
|
2526
|
+
"""Every failure of a failed task, in order (one, unless it recorded several)."""
|
|
2527
|
+
inner = task._inner_exceptions
|
|
2528
|
+
return inner if inner is not None else (task._exception,)
|
|
2529
|
+
|
|
2530
|
+
|
|
2531
|
+
def _raise_aggregate(errors: list[BaseException]) -> NoReturn:
|
|
2532
|
+
"""Raise ``errors`` as one ``AggregateError`` (.NET ``Wait``/``WaitAll``).
|
|
2533
|
+
|
|
2534
|
+
A ``KeyboardInterrupt``/``SystemExit`` among them is raised as it is: inside an
|
|
2535
|
+
``AggregateError`` (an ``Exception``), ``except Exception`` would swallow it.
|
|
2536
|
+
"""
|
|
2537
|
+
for error in errors:
|
|
2538
|
+
if not isinstance(error, Exception):
|
|
2539
|
+
raise error
|
|
2540
|
+
raise AggregateError(cast(list[Exception], errors))
|
|
2541
|
+
|
|
2542
|
+
|
|
2543
|
+
def _task_canceled(task: Task[Any], message: str, token: CancellationToken | None = None) -> TaskCanceledError:
|
|
2544
|
+
"""The ``TaskCanceledError`` a task records when it is cancelled without an exception of its own."""
|
|
2545
|
+
error = TaskCanceledError(message, token=token)
|
|
2546
|
+
error.task = task
|
|
2547
|
+
return error
|
|
2425
2548
|
|
|
2426
2549
|
|
|
2427
2550
|
def _block_until(
|
|
@@ -2636,54 +2759,48 @@ class TaskCompletionSource(Generic[T]):
|
|
|
2636
2759
|
def _normalize_exceptions(
|
|
2637
2760
|
error: Exception | Iterable[Exception],
|
|
2638
2761
|
) -> tuple[Exception, ...] | Exception:
|
|
2762
|
+
# .NET: ArgumentNullException for a null exception or list, ArgumentException for an empty list or a
|
|
2763
|
+
# null element. ArgumentError is a TypeError, as these always were except the empty list (ValueError).
|
|
2639
2764
|
if isinstance(error, Exception):
|
|
2640
2765
|
return error
|
|
2641
2766
|
if error is None:
|
|
2642
|
-
raise
|
|
2767
|
+
raise ArgumentNullError("exception")
|
|
2643
2768
|
if isinstance(error, (str, bytes, bytearray)):
|
|
2644
|
-
raise
|
|
2769
|
+
raise ArgumentError("exception must be an Exception or iterable of Exceptions")
|
|
2645
2770
|
try:
|
|
2646
2771
|
exceptions = tuple(error)
|
|
2647
2772
|
except TypeError as exc:
|
|
2648
|
-
raise
|
|
2773
|
+
raise ArgumentError("exception must be an Exception or iterable of Exceptions") from exc
|
|
2649
2774
|
if not exceptions:
|
|
2650
|
-
raise
|
|
2775
|
+
raise ArgumentError("The tasks argument contains no exceptions. (Parameter 'exceptions')")
|
|
2651
2776
|
if not all(isinstance(item, Exception) for item in exceptions):
|
|
2652
|
-
raise
|
|
2777
|
+
raise ArgumentError("The exceptions collection included at least one null element. (Parameter 'exceptions')")
|
|
2653
2778
|
return exceptions
|
|
2654
2779
|
|
|
2655
2780
|
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):
|
|
2781
|
+
if not self.try_set_exception(error):
|
|
2663
2782
|
raise InvalidStateError("TaskCompletionSource task has already completed")
|
|
2664
2783
|
|
|
2665
2784
|
def try_set_exception(self, error: Exception | Iterable[Exception]) -> bool:
|
|
2785
|
+
# .NET TrySetException(IEnumerable): await raises the first, Task.Exception holds all.
|
|
2666
2786
|
normalized = self._normalize_exceptions(error)
|
|
2667
|
-
|
|
2668
|
-
normalized
|
|
2669
|
-
|
|
2670
|
-
|
|
2787
|
+
if isinstance(normalized, Exception):
|
|
2788
|
+
return self._try_complete(Task.FAILED, exception=normalized)
|
|
2789
|
+
return self._try_complete(
|
|
2790
|
+
Task.FAILED,
|
|
2791
|
+
exception=normalized[0],
|
|
2792
|
+
inner_exceptions=normalized if len(normalized) > 1 else None,
|
|
2671
2793
|
)
|
|
2672
|
-
return self._try_complete(Task.FAILED, exception=exception)
|
|
2673
2794
|
|
|
2674
2795
|
def set_canceled(self, token: CancellationToken | None = None) -> None:
|
|
2675
2796
|
self._validate_token(token)
|
|
2676
|
-
cancellation =
|
|
2677
|
-
"The task was canceled.", token=token
|
|
2678
|
-
)
|
|
2797
|
+
cancellation = _task_canceled(self._task, "The task was canceled.", token)
|
|
2679
2798
|
if not self._try_complete(Task.CANCELLED, exception=cancellation):
|
|
2680
2799
|
raise InvalidStateError("TaskCompletionSource task has already completed")
|
|
2681
2800
|
|
|
2682
2801
|
def try_set_canceled(self, token: CancellationToken | None = None) -> bool:
|
|
2683
2802
|
self._validate_token(token)
|
|
2684
|
-
cancellation =
|
|
2685
|
-
"The task was canceled.", token=token
|
|
2686
|
-
)
|
|
2803
|
+
cancellation = _task_canceled(self._task, "The task was canceled.", token)
|
|
2687
2804
|
return self._try_complete(Task.CANCELLED, exception=cancellation)
|
|
2688
2805
|
|
|
2689
2806
|
@staticmethod
|
|
@@ -2702,18 +2819,20 @@ class TaskCompletionSource(Generic[T]):
|
|
|
2702
2819
|
|
|
2703
2820
|
def _validate_completed_task(self, source: "flpit.task.Task[Any] | None") -> None:
|
|
2704
2821
|
if source is None:
|
|
2705
|
-
raise
|
|
2822
|
+
raise ArgumentNullError("completedTask")
|
|
2706
2823
|
if not isinstance(source, Task):
|
|
2707
2824
|
raise TypeError("completed_task must be a Task instance")
|
|
2708
2825
|
if not source.done():
|
|
2709
|
-
raise
|
|
2826
|
+
raise ArgumentError("The provided task must have already completed. (Parameter 'completedTask')")
|
|
2710
2827
|
|
|
2711
2828
|
def _try_copy_task(self, source: "flpit.task.Task[Any]") -> bool:
|
|
2712
2829
|
if source._state == Task.SUCCEEDED:
|
|
2713
2830
|
return self._try_complete(Task.SUCCEEDED, result=source._result)
|
|
2714
2831
|
if source._state == Task.FAILED:
|
|
2715
2832
|
assert source._exception is not None
|
|
2716
|
-
return self._try_complete(
|
|
2833
|
+
return self._try_complete(
|
|
2834
|
+
Task.FAILED, exception=source._exception, inner_exceptions=source._inner_exceptions,
|
|
2835
|
+
)
|
|
2717
2836
|
if source._state == Task.CANCELLED:
|
|
2718
2837
|
return self._try_complete(
|
|
2719
2838
|
Task.CANCELLED,
|
|
@@ -2729,11 +2848,12 @@ class TaskCompletionSource(Generic[T]):
|
|
|
2729
2848
|
*,
|
|
2730
2849
|
result: Any = None,
|
|
2731
2850
|
exception: Exception | BaseException | None = None,
|
|
2851
|
+
inner_exceptions: tuple[Exception, ...] | None = None,
|
|
2732
2852
|
) -> bool:
|
|
2733
2853
|
# Safe from any thread and never blocks: the task's own lock decides
|
|
2734
2854
|
# the winner and its continuations are handed to the pool, so the
|
|
2735
2855
|
# caller of set_result() does not end up running awaiting coroutines.
|
|
2736
|
-
return self._task._finish(state, result=result, exception=exception)
|
|
2856
|
+
return self._task._finish(state, result=result, exception=exception, inner_exceptions=inner_exceptions)
|
|
2737
2857
|
|
|
2738
2858
|
|
|
2739
2859
|
async def _collect_each(tasks: tuple[Any, ...]) -> AsyncGenerator[Task[Any], None]:
|
|
@@ -2780,6 +2900,8 @@ def _normalize_tasks(items: tuple[Any, ...], *, allow_empty: bool) -> tuple[Task
|
|
|
2780
2900
|
coroutine objects supplied to this call are closed so Python does not emit
|
|
2781
2901
|
"coroutine was never awaited" warnings for rejected inputs.
|
|
2782
2902
|
"""
|
|
2903
|
+
if len(items) == 1 and items[0] is None:
|
|
2904
|
+
raise ArgumentNullError("tasks") # .NET Task.WhenAll((Task[])null)
|
|
2783
2905
|
# A single awaitable is one operation, not an iterable of operations.
|
|
2784
2906
|
if (
|
|
2785
2907
|
len(items) == 1
|
|
@@ -2794,7 +2916,7 @@ def _normalize_tasks(items: tuple[Any, ...], *, allow_empty: bool) -> tuple[Task
|
|
|
2794
2916
|
pass
|
|
2795
2917
|
|
|
2796
2918
|
if not items and not allow_empty:
|
|
2797
|
-
raise
|
|
2919
|
+
raise ArgumentError("The tasks argument contains no tasks. (Parameter 'tasks')")
|
|
2798
2920
|
|
|
2799
2921
|
def close_raw_coroutines(values: tuple[Any, ...]) -> None:
|
|
2800
2922
|
seen: set[int] = set()
|
|
@@ -2808,6 +2930,9 @@ def _normalize_tasks(items: tuple[Any, ...], *, allow_empty: bool) -> tuple[Task
|
|
|
2808
2930
|
|
|
2809
2931
|
# Validate everything before scheduling anything, avoiding partial starts
|
|
2810
2932
|
# when the caller accidentally mixes a coroutine with a non-awaitable.
|
|
2933
|
+
if any(item is None for item in items):
|
|
2934
|
+
close_raw_coroutines(items)
|
|
2935
|
+
raise ArgumentError("The tasks argument included a null value. (Parameter 'tasks')")
|
|
2811
2936
|
invalid = [item for item in items if not isinstance(item, Task) and not inspect.isawaitable(item)]
|
|
2812
2937
|
if invalid:
|
|
2813
2938
|
close_raw_coroutines(items)
|
|
@@ -2872,20 +2997,24 @@ class _WhenAll:
|
|
|
2872
2997
|
if self._remaining:
|
|
2873
2998
|
return
|
|
2874
2999
|
tasks = self._tasks
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
3000
|
+
# .NET Task.WhenAll: faulted wins over canceled; the aggregate holds every failure of every
|
|
3001
|
+
# child in order (a child's own several failures included), await/result raise the first.
|
|
3002
|
+
failures = [error for child in tasks if child._state is _FAILED for error in _faults_of(child)]
|
|
3003
|
+
if failures:
|
|
3004
|
+
interrupt = next((error for error in failures if not isinstance(error, Exception)), None)
|
|
3005
|
+
if interrupt is not None: # KeyboardInterrupt/SystemExit: never inside an AggregateError
|
|
3006
|
+
self._promise._finish(_FAILED, exception=interrupt)
|
|
3007
|
+
else:
|
|
3008
|
+
self._promise._finish(
|
|
3009
|
+
_FAILED,
|
|
3010
|
+
exception=failures[0],
|
|
3011
|
+
inner_exceptions=tuple(failures) if len(failures) > 1 else None,
|
|
3012
|
+
)
|
|
2883
3013
|
elif any(child._state is _CANCELLED for child in tasks):
|
|
2884
|
-
self._promise
|
|
3014
|
+
promise = self._promise
|
|
3015
|
+
promise._finish(
|
|
2885
3016
|
_CANCELLED,
|
|
2886
|
-
exception=
|
|
2887
|
-
"One or more tasks passed to Task.when_all() were cancelled"
|
|
2888
|
-
),
|
|
3017
|
+
exception=_task_canceled(promise, "One or more tasks passed to Task.when_all() were cancelled"),
|
|
2889
3018
|
)
|
|
2890
3019
|
else:
|
|
2891
3020
|
self._promise._finish(_SUCCEEDED, result=[child._result for child in tasks])
|
|
@@ -3436,12 +3565,13 @@ def _spin_count() -> int:
|
|
|
3436
3565
|
class _Stall:
|
|
3437
3566
|
"""The gate's view of one worker's current item: since when, and its CPU time then."""
|
|
3438
3567
|
|
|
3439
|
-
__slots__ = ("items", "ticks", "since", "cpu")
|
|
3568
|
+
__slots__ = ("items", "ticks", "since", "cpu", "process_cpu")
|
|
3440
3569
|
|
|
3441
3570
|
def __init__(self, info: _WorkerInfo) -> None:
|
|
3442
3571
|
self.items = info.items
|
|
3443
3572
|
self.ticks = 0
|
|
3444
3573
|
self.since = time.monotonic()
|
|
3574
|
+
self.process_cpu = _process_time()
|
|
3445
3575
|
self.cpu: float | None = None
|
|
3446
3576
|
if info.cpu_clock is not None:
|
|
3447
3577
|
try:
|
|
@@ -3505,6 +3635,10 @@ class _WorkerPool:
|
|
|
3505
3635
|
# A stalled worker whose own CPU clock moved less than this share of the time it has been
|
|
3506
3636
|
# on its item is waiting (it measures 0.000; computing ones get a share even when contended).
|
|
3507
3637
|
_WAITING_CPU_SHARE: Final = 0.02
|
|
3638
|
+
# Without per-thread CPU clocks (macOS, Windows) the process's CPU decides, measured over at
|
|
3639
|
+
# least this long: Windows' process_time() moves in 15.625 ms steps, so a shorter sample reads
|
|
3640
|
+
# 0 while a worker computes, and one tick is too short to average out scheduling noise.
|
|
3641
|
+
_FALLBACK_WINDOW: Final = 0.1
|
|
3508
3642
|
|
|
3509
3643
|
def __init__(
|
|
3510
3644
|
self,
|
|
@@ -3762,7 +3896,7 @@ class _WorkerPool:
|
|
|
3762
3896
|
last = self._completed
|
|
3763
3897
|
starvation_due = time.monotonic() + self._starvation_interval()
|
|
3764
3898
|
stalls: dict[_WorkerInfo, _Stall] = {}
|
|
3765
|
-
cpu_then =
|
|
3899
|
+
cpu_then = _process_time()
|
|
3766
3900
|
wall_then = time.monotonic()
|
|
3767
3901
|
tick = self._GATE_TICK
|
|
3768
3902
|
while True:
|
|
@@ -3775,7 +3909,7 @@ class _WorkerPool:
|
|
|
3775
3909
|
if not items:
|
|
3776
3910
|
break
|
|
3777
3911
|
signal.set()
|
|
3778
|
-
cpu_now =
|
|
3912
|
+
cpu_now = _process_time()
|
|
3779
3913
|
now = time.monotonic()
|
|
3780
3914
|
cores_used = (cpu_now - cpu_then) / max(now - wall_then, 1e-6)
|
|
3781
3915
|
cpu_then, wall_then = cpu_now, now
|
|
@@ -3870,8 +4004,13 @@ class _WorkerPool:
|
|
|
3870
4004
|
waiting += 1
|
|
3871
4005
|
else:
|
|
3872
4006
|
return waiting
|
|
3873
|
-
# No per-thread CPU clocks here: decide from the CPU the process used
|
|
3874
|
-
|
|
4007
|
+
# No per-thread CPU clocks here: decide from the CPU the process used while the workers
|
|
4008
|
+
# were stalled, over at least _FALLBACK_WINDOW. Until then they count as computing.
|
|
4009
|
+
oldest = min((record for _, record in stalled), key=lambda record: record.since)
|
|
4010
|
+
window = now - oldest.since
|
|
4011
|
+
if window < self._FALLBACK_WINDOW:
|
|
4012
|
+
return 0
|
|
4013
|
+
if (_process_time() - oldest.process_cpu) / window >= self._CPU_SATURATED * min(self._capacity, workers):
|
|
3875
4014
|
return 0
|
|
3876
4015
|
return len(stalled)
|
|
3877
4016
|
|
|
@@ -4540,16 +4679,19 @@ def asyncio_task[**P, T](
|
|
|
4540
4679
|
A ``CancellationToken`` passed as an argument also cancels the call, as in .NET: the asyncio
|
|
4541
4680
|
task is cancelled and the returned Task ends cancelled.
|
|
4542
4681
|
|
|
4543
|
-
Loop-bound objects that should be reused across calls (clients, connection pools)
|
|
4544
|
-
a ``
|
|
4682
|
+
Loop-bound objects that should be reused across calls (clients, connection pools) are kept
|
|
4683
|
+
one per loop: a parameter annotated ``Loop[T]`` (``flpit.asyncio_bridge``) receives the
|
|
4684
|
+
``provide()``-d ``T`` of the loop the call runs on, and an object that outlives the call can
|
|
4685
|
+
hold a ``PerLoop[T]`` and read ``.current``.
|
|
4545
4686
|
"""
|
|
4687
|
+
cache: list[Any] = []
|
|
4546
4688
|
|
|
4547
4689
|
@functools.wraps(async_function)
|
|
4548
4690
|
def wrapper(*args: P.args, **kwargs: P.kwargs) -> Task[T]:
|
|
4549
|
-
from .asyncio_bridge import
|
|
4691
|
+
from .asyncio_bridge import _call_asyncio_task # imports asyncio on first use only
|
|
4550
4692
|
|
|
4551
4693
|
token = next((value for value in (*args, *kwargs.values()) if isinstance(value, CancellationToken)), None)
|
|
4552
|
-
return
|
|
4694
|
+
return _call_asyncio_task(async_function, args, kwargs, token, cache)
|
|
4553
4695
|
|
|
4554
4696
|
return wrapper
|
|
4555
4697
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: flpit
|
|
3
|
-
Version: 0.4.2.
|
|
3
|
+
Version: 0.4.2.dev12
|
|
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/
|
|
@@ -153,7 +153,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
153
153
|
| │ ├── test_first.py | 8 |
|
|
154
154
|
| │ ├── test_first_or_default.py | 8 |
|
|
155
155
|
| │ ├── test_full_join.py | 11 |
|
|
156
|
-
| │ ├── test_group_by.py |
|
|
156
|
+
| │ ├── test_group_by.py | 6 |
|
|
157
157
|
| │ ├── test_group_join.py | 9 |
|
|
158
158
|
| │ ├── test_index.py | 8 |
|
|
159
159
|
| │ ├── test_intersect.py | 12 |
|
|
@@ -162,9 +162,9 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
162
162
|
| │ ├── test_last_or_default.py | 8 |
|
|
163
163
|
| │ ├── test_left_join.py | 10 |
|
|
164
164
|
| │ ├── test_max.py | 11 |
|
|
165
|
-
| │ ├── test_max_by.py |
|
|
165
|
+
| │ ├── test_max_by.py | 12 |
|
|
166
166
|
| │ ├── test_min.py | 11 |
|
|
167
|
-
| │ ├── test_min_by.py |
|
|
167
|
+
| │ ├── test_min_by.py | 12 |
|
|
168
168
|
| │ ├── test_of_type.py | 5 |
|
|
169
169
|
| │ ├── test_order_by.py | 18 |
|
|
170
170
|
| │ ├── test_prepend.py | 19 |
|
|
@@ -198,7 +198,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
198
198
|
| │ ├── test_rendezvous_channel.py | 104 |
|
|
199
199
|
| │ └── test_unbounded_channel.py | 338 |
|
|
200
200
|
| ├── concurrent/ | |
|
|
201
|
-
| │ ├── test_concurrent_bag.py |
|
|
201
|
+
| │ ├── test_concurrent_bag.py | 131 |
|
|
202
202
|
| │ ├── test_concurrent_dictionary.py | 56 |
|
|
203
203
|
| │ ├── test_concurrent_dictionary_generic.py | 1236 |
|
|
204
204
|
| │ ├── test_concurrent_queue.py | 130 |
|
|
@@ -214,7 +214,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
214
214
|
| │ ├── test_chunk.py | 22 |
|
|
215
215
|
| │ ├── test_concat.py | 64 |
|
|
216
216
|
| │ ├── test_contains.py | 108 |
|
|
217
|
-
| │ ├── test_count.py |
|
|
217
|
+
| │ ├── test_count.py | 64 |
|
|
218
218
|
| │ ├── test_default_if_empty.py | 37 |
|
|
219
219
|
| │ ├── test_distinct.py | 87 |
|
|
220
220
|
| │ ├── test_element_at.py | 43 |
|
|
@@ -222,7 +222,7 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
222
222
|
| │ ├── test_first.py | 29 |
|
|
223
223
|
| │ ├── test_first_or_default.py | 50 |
|
|
224
224
|
| │ ├── test_full_join.py | 37 |
|
|
225
|
-
| │ ├── test_generic_list.py |
|
|
225
|
+
| │ ├── test_generic_list.py | 87 |
|
|
226
226
|
| │ ├── test_group_by.py | 23 |
|
|
227
227
|
| │ ├── test_group_join.py | 53 |
|
|
228
228
|
| │ ├── test_index.py | 6 |
|
|
@@ -231,23 +231,23 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
231
231
|
| │ ├── test_last.py | 29 |
|
|
232
232
|
| │ ├── test_last_or_default.py | 45 |
|
|
233
233
|
| │ ├── test_left_join.py | 47 |
|
|
234
|
-
| │ ├── test_max.py |
|
|
235
|
-
| │ ├── test_min.py |
|
|
234
|
+
| │ ├── test_max.py | 1098 |
|
|
235
|
+
| │ ├── test_min.py | 966 |
|
|
236
236
|
| │ ├── test_of_type.py | 38 |
|
|
237
|
-
| │ ├── test_order_by.py |
|
|
238
|
-
| │ ├── test_order_descending_by.py |
|
|
237
|
+
| │ ├── test_order_by.py | 104 |
|
|
238
|
+
| │ ├── test_order_descending_by.py | 46 |
|
|
239
239
|
| │ ├── test_reverse.py | 35 |
|
|
240
|
-
| │ ├── test_select.py |
|
|
240
|
+
| │ ├── test_select.py | 143 |
|
|
241
241
|
| │ ├── test_select_many.py | 85 |
|
|
242
242
|
| │ ├── test_single.py | 34 |
|
|
243
243
|
| │ ├── test_single_or_default.py | 48 |
|
|
244
|
-
| │ ├── test_skip.py |
|
|
244
|
+
| │ ├── test_skip.py | 77 |
|
|
245
245
|
| │ ├── test_skip_last.py | 1221 |
|
|
246
|
-
| │ ├── test_sum.py |
|
|
247
|
-
| │ ├── test_take.py |
|
|
246
|
+
| │ ├── test_sum.py | 154 |
|
|
247
|
+
| │ ├── test_take.py | 73 |
|
|
248
248
|
| │ ├── test_take_last.py | 1221 |
|
|
249
|
-
| │ ├── test_then_by.py |
|
|
250
|
-
| │ ├── test_then_descending_by.py |
|
|
249
|
+
| │ ├── test_then_by.py | 38 |
|
|
250
|
+
| │ ├── test_then_descending_by.py | 32 |
|
|
251
251
|
| │ ├── test_to_dictionary.py | 32 |
|
|
252
252
|
| │ ├── test_to_list.py | 40 |
|
|
253
253
|
| │ ├── test_to_lookup.py | 26 |
|
|
@@ -255,20 +255,26 @@ Distributed under the MIT License. See `LICENSE` for more information.
|
|
|
255
255
|
| │ ├── test_where.py | 76 |
|
|
256
256
|
| │ └── test_zip.py | 101 |
|
|
257
257
|
| ├── task/ | |
|
|
258
|
+
| │ ├── test_aggregate_exception.py | 1 |
|
|
258
259
|
| │ ├── test_cancellation.py | 69 |
|
|
259
|
-
| │ ├──
|
|
260
|
+
| │ ├── test_method_coverage.py | 30 |
|
|
261
|
+
| │ ├── test_method_coverage_when_all.py | 13 |
|
|
262
|
+
| │ ├── test_operation_canceled_exception.py | 0 |
|
|
263
|
+
| │ ├── test_task_canceled_exception.py | 1 |
|
|
264
|
+
| │ ├── test_task_completion_source.py | 25 |
|
|
265
|
+
| │ ├── test_task_completion_source_tresult.py | 5 |
|
|
260
266
|
| │ ├── test_task_continue_with.py | 15 |
|
|
261
267
|
| │ ├── test_task_continue_with_func_and_action.py | 16 |
|
|
262
268
|
| │ ├── test_task_continue_with_func_and_action_args.py | 20 |
|
|
263
269
|
| │ ├── test_task_factory.py | 3 |
|
|
264
|
-
| │ ├── test_task_rt.py |
|
|
265
|
-
| │ ├── test_task_rt_core.py |
|
|
270
|
+
| │ ├── test_task_rt.py | 7 |
|
|
271
|
+
| │ ├── test_task_rt_core.py | 32 |
|
|
266
272
|
| │ └── test_task_wait_all_any.py | 62 |
|
|
267
273
|
| └── threading/ | |
|
|
268
274
|
| ├── test_semaphore_slim.py | 39 |
|
|
269
275
|
| ├── test_semaphore_slim_cancellation.py | 4 |
|
|
270
276
|
| └── test_thread_local.py | 15 |
|
|
271
277
|
--------------------------------------------------------------------------------
|
|
272
|
-
| GRAND TOTALS |
|
|
278
|
+
| GRAND TOTALS | 10848 |
|
|
273
279
|
================================================================================
|
|
274
280
|
```
|
|
@@ -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=yfTKlZ1boIW12JJCzPF6dArTVemfoXn8PNu_gl8EAjo,195918
|
|
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=Mk3nzcCLDgwfCGoiFoxtZNuudb-hH72c8aubF64jgzg,90431
|
|
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.dev12.dist-info/METADATA,sha256=swRkw5gKuQMjWgRUtlOWd9-bmgl4wVIlrieBU6uTcEw,19930
|
|
25
|
+
flpit-0.4.2.dev12.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
26
|
+
flpit-0.4.2.dev12.dist-info/licenses/LICENSE,sha256=bi5Vg_YP3Oq3jaOMQT4b7WZu0NfBcZr-nRyOExUKJrQ,1063
|
|
27
|
+
flpit-0.4.2.dev12.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|