peffect 0.1.2__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.
- peffect/__init__.py +223 -0
- peffect/cause.py +177 -0
- peffect/clock.py +130 -0
- peffect/console.py +99 -0
- peffect/context.py +258 -0
- peffect/core.py +1273 -0
- peffect/deferred.py +99 -0
- peffect/duration.py +497 -0
- peffect/fiber.py +1082 -0
- peffect/latch.py +120 -0
- peffect/layer.py +789 -0
- peffect/logger.py +166 -0
- peffect/managed_runtime.py +325 -0
- peffect/option.py +50 -0
- peffect/pull.py +116 -0
- peffect/py.typed +0 -0
- peffect/queue.py +670 -0
- peffect/ref.py +133 -0
- peffect/resources.py +113 -0
- peffect/scheduler.py +55 -0
- peffect/scope.py +394 -0
- peffect/semaphore.py +255 -0
- peffect/synchronized_ref.py +183 -0
- peffect/testing/__init__.py +7 -0
- peffect/testing/_clock.py +453 -0
- peffect/testing/_console.py +105 -0
- peffect/timeout.py +67 -0
- peffect-0.1.2.dist-info/METADATA +6 -0
- peffect-0.1.2.dist-info/RECORD +30 -0
- peffect-0.1.2.dist-info/WHEEL +4 -0
peffect/ref.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""A mutable cell read and written by effects; each operation is one synchronous step.
|
|
2
|
+
|
|
3
|
+
Pinned Effect v4 src/Ref.ts. Every operation is `Effect.sync` of a body that reads the cell,
|
|
4
|
+
calls the user function, and assigns, so no other fiber can run between the read and the write
|
|
5
|
+
of one operation. A user function that raises is a defect of that sync step and assigns nothing
|
|
6
|
+
(each body computes before it assigns). Upstream's data-first/data-last duals only select the
|
|
7
|
+
receiver and are not separate API; the Pipeable/Inspectable protocol and toJSON are not ported.
|
|
8
|
+
|
|
9
|
+
Upstream stores a MutableRef in `self.ref` and reads `self.ref.current`; MutableRef is not
|
|
10
|
+
ported, so the cell is the `current` slot itself. Option is `Some[A] | None`: an update applies
|
|
11
|
+
when the function returns a `Some`, including `Some(None)` (Ref.ts tests `_tag === "Some"`).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from typing import Never, final
|
|
18
|
+
|
|
19
|
+
from .core import Effect, sync
|
|
20
|
+
from .option import Option
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@final
|
|
24
|
+
class Ref[A]:
|
|
25
|
+
"""A cell of A. Invariant in A: it is both read and written (Ref.ts `Ref<in out A>`)."""
|
|
26
|
+
|
|
27
|
+
__slots__ = ("current",)
|
|
28
|
+
|
|
29
|
+
def __init__(self, value: A) -> None:
|
|
30
|
+
self.current: A = value
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def make_unsafe(cls, value: A) -> Ref[A]:
|
|
34
|
+
"""Allocate a cell synchronously (Ref.ts makeUnsafe)."""
|
|
35
|
+
return cls(value)
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def make(cls, value: A) -> Effect[Ref[A], Never, Never]:
|
|
39
|
+
"""A fresh cell each time this effect runs (Ref.ts make)."""
|
|
40
|
+
return sync(lambda: cls(value))
|
|
41
|
+
|
|
42
|
+
def get_unsafe(self) -> A:
|
|
43
|
+
"""Read the cell synchronously (Ref.ts getUnsafe)."""
|
|
44
|
+
return self.current
|
|
45
|
+
|
|
46
|
+
def get(self) -> Effect[A, Never, Never]:
|
|
47
|
+
return sync(self.get_unsafe)
|
|
48
|
+
|
|
49
|
+
def set(self, value: A) -> Effect[None, Never, Never]:
|
|
50
|
+
def go() -> None:
|
|
51
|
+
self.current = value
|
|
52
|
+
|
|
53
|
+
return sync(go)
|
|
54
|
+
|
|
55
|
+
def get_and_set(self, value: A) -> Effect[A, Never, Never]:
|
|
56
|
+
def go() -> A:
|
|
57
|
+
current = self.current
|
|
58
|
+
self.current = value
|
|
59
|
+
return current
|
|
60
|
+
|
|
61
|
+
return sync(go)
|
|
62
|
+
|
|
63
|
+
def set_and_get(self, value: A) -> Effect[A, Never, Never]:
|
|
64
|
+
def go() -> A:
|
|
65
|
+
self.current = value
|
|
66
|
+
return value
|
|
67
|
+
|
|
68
|
+
return sync(go)
|
|
69
|
+
|
|
70
|
+
def get_and_update(self, f: Callable[[A], A]) -> Effect[A, Never, Never]:
|
|
71
|
+
def go() -> A:
|
|
72
|
+
current = self.current
|
|
73
|
+
self.current = f(current)
|
|
74
|
+
return current
|
|
75
|
+
|
|
76
|
+
return sync(go)
|
|
77
|
+
|
|
78
|
+
def get_and_update_some(self, pf: Callable[[A], Option[A]]) -> Effect[A, Never, Never]:
|
|
79
|
+
def go() -> A:
|
|
80
|
+
current = self.current
|
|
81
|
+
option = pf(current)
|
|
82
|
+
if option is not None:
|
|
83
|
+
self.current = option.value
|
|
84
|
+
return current
|
|
85
|
+
|
|
86
|
+
return sync(go)
|
|
87
|
+
|
|
88
|
+
def modify[B](self, f: Callable[[A], tuple[B, A]]) -> Effect[B, Never, Never]:
|
|
89
|
+
def go() -> B:
|
|
90
|
+
b, a = f(self.current)
|
|
91
|
+
self.current = a
|
|
92
|
+
return b
|
|
93
|
+
|
|
94
|
+
return sync(go)
|
|
95
|
+
|
|
96
|
+
def modify_some[B](self, pf: Callable[[A], tuple[B, Option[A]]]) -> Effect[B, Never, Never]:
|
|
97
|
+
"""Ref.ts modifySome: modify, keeping the value when the option is None."""
|
|
98
|
+
|
|
99
|
+
def f(value: A) -> tuple[B, A]:
|
|
100
|
+
b, option = pf(value)
|
|
101
|
+
return b, (value if option is None else option.value)
|
|
102
|
+
|
|
103
|
+
return self.modify(f)
|
|
104
|
+
|
|
105
|
+
def update(self, f: Callable[[A], A]) -> Effect[None, Never, Never]:
|
|
106
|
+
def go() -> None:
|
|
107
|
+
self.current = f(self.current)
|
|
108
|
+
|
|
109
|
+
return sync(go)
|
|
110
|
+
|
|
111
|
+
def update_and_get(self, f: Callable[[A], A]) -> Effect[A, Never, Never]:
|
|
112
|
+
def go() -> A:
|
|
113
|
+
self.current = value = f(self.current)
|
|
114
|
+
return value
|
|
115
|
+
|
|
116
|
+
return sync(go)
|
|
117
|
+
|
|
118
|
+
def update_some(self, f: Callable[[A], Option[A]]) -> Effect[None, Never, Never]:
|
|
119
|
+
def go() -> None:
|
|
120
|
+
option = f(self.current)
|
|
121
|
+
if option is not None:
|
|
122
|
+
self.current = option.value
|
|
123
|
+
|
|
124
|
+
return sync(go)
|
|
125
|
+
|
|
126
|
+
def update_some_and_get(self, pf: Callable[[A], Option[A]]) -> Effect[A, Never, Never]:
|
|
127
|
+
def go() -> A:
|
|
128
|
+
option = pf(self.current)
|
|
129
|
+
if option is not None:
|
|
130
|
+
self.current = option.value
|
|
131
|
+
return self.current
|
|
132
|
+
|
|
133
|
+
return sync(go)
|
peffect/resources.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Scoped resources, composed from the public kernel and Scope APIs.
|
|
2
|
+
|
|
3
|
+
Effect v4 internal/effect.ts:4240-4269 (acquireRelease, addFinalizer) and :4502-4515
|
|
4
|
+
(acquireUseRelease), pinned at 289a53f7. Only acquireRelease's default, masked acquisition
|
|
5
|
+
mode is supported; its optional interruptible acquisition mode is not ported.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from typing import Any, Never, cast, overload
|
|
12
|
+
|
|
13
|
+
from .core import (
|
|
14
|
+
ContextMap,
|
|
15
|
+
Effect,
|
|
16
|
+
Exit,
|
|
17
|
+
WithFiber,
|
|
18
|
+
on_exit,
|
|
19
|
+
suspend,
|
|
20
|
+
uninterruptible,
|
|
21
|
+
uninterruptible_mask,
|
|
22
|
+
update_context,
|
|
23
|
+
)
|
|
24
|
+
from .scope import Scope, ScopeService, scope
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _provide_captured[A, E, R](
|
|
28
|
+
eff: Effect[A, E, R], context: ContextMap
|
|
29
|
+
) -> Effect[A, E, Never]:
|
|
30
|
+
# The enclosing resource API requires R at capture time. All its services are supplied
|
|
31
|
+
# here, so the registered finalizer has no outstanding requirement. Like provide's
|
|
32
|
+
# overloads, this discharges R only after installing its services; update_context alone
|
|
33
|
+
# deliberately preserves R. Captured services win, as upstream provideContext does.
|
|
34
|
+
return cast(Effect[A, E, Never], update_context(eff, lambda old: {**old, **context}))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def acquire_release[A, E = Never, R = Never, R2 = Never](
|
|
38
|
+
acquire: Effect[A, E, R],
|
|
39
|
+
release: Callable[[A, Exit[Any, Any]], Effect[Any, Never, R2]],
|
|
40
|
+
) -> Effect[A, E, R | R2 | Scope]:
|
|
41
|
+
"""Acquire masked and register release before interruption can resume.
|
|
42
|
+
|
|
43
|
+
Release receives the scope's closing Exit and runs with the services captured here.
|
|
44
|
+
A failed acquisition registers nothing. Requires Scope and both callbacks' services.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def captured(context: ContextMap) -> Effect[A, E, R | R2 | Scope]:
|
|
48
|
+
def in_scope(s: ScopeService) -> Effect[A, E, R]:
|
|
49
|
+
return acquire.flat_map(
|
|
50
|
+
lambda a: Scope.add_finalizer_exit(
|
|
51
|
+
s, lambda ex: _provide_captured(release(a, ex), context)
|
|
52
|
+
).as_(a)
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
return uninterruptible(scope.flat_map(in_scope))
|
|
56
|
+
|
|
57
|
+
return WithFiber(lambda fiber: captured(fiber.context))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def add_finalizer[R = Never](
|
|
61
|
+
finalizer: Callable[[Exit[Any, Any]], Effect[None, Never, R]],
|
|
62
|
+
) -> Effect[None, Never, R | Scope]:
|
|
63
|
+
"""Register a finalizer in the current Scope, capturing its required services now."""
|
|
64
|
+
|
|
65
|
+
def register(s: ScopeService, context: ContextMap) -> Effect[None, Never, R]:
|
|
66
|
+
return Scope.add_finalizer_exit(s, lambda ex: _provide_captured(finalizer(ex), context))
|
|
67
|
+
|
|
68
|
+
return scope.flat_map(lambda s: WithFiber(lambda fiber: register(s, fiber.context)))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# Pyright loses an all-Never union across free function type parameters. As in
|
|
72
|
+
# provide/scoped, cover the exact empty channels before the general union signature.
|
|
73
|
+
@overload
|
|
74
|
+
def acquire_use_release[Resource, A](
|
|
75
|
+
acquire: Effect[Resource, Never, Never],
|
|
76
|
+
use: Callable[[Resource], Effect[A, Never, Never]],
|
|
77
|
+
release: Callable[[Resource, Exit[A, Never]], Effect[None, Never, Never]],
|
|
78
|
+
) -> Effect[A, Never, Never]: ...
|
|
79
|
+
@overload
|
|
80
|
+
def acquire_use_release[Resource, A, E, E2, E3](
|
|
81
|
+
acquire: Effect[Resource, E, Never],
|
|
82
|
+
use: Callable[[Resource], Effect[A, E2, Never]],
|
|
83
|
+
release: Callable[[Resource, Exit[A, E2]], Effect[None, E3, Never]],
|
|
84
|
+
) -> Effect[A, E | E2 | E3, Never]: ...
|
|
85
|
+
@overload
|
|
86
|
+
def acquire_use_release[Resource, A, R, R2, R3](
|
|
87
|
+
acquire: Effect[Resource, Never, R],
|
|
88
|
+
use: Callable[[Resource], Effect[A, Never, R2]],
|
|
89
|
+
release: Callable[[Resource, Exit[A, Never]], Effect[None, Never, R3]],
|
|
90
|
+
) -> Effect[A, Never, R | R2 | R3]: ...
|
|
91
|
+
@overload
|
|
92
|
+
def acquire_use_release[Resource, A, E, R, E2, R2, E3, R3](
|
|
93
|
+
acquire: Effect[Resource, E, R],
|
|
94
|
+
use: Callable[[Resource], Effect[A, E2, R2]],
|
|
95
|
+
release: Callable[[Resource, Exit[A, E2]], Effect[None, E3, R3]],
|
|
96
|
+
) -> Effect[A, E | E2 | E3, R | R2 | R3]: ...
|
|
97
|
+
def acquire_use_release[
|
|
98
|
+
Resource, A, E = Never, R = Never, E2 = Never, R2 = Never, E3 = Never, R3 = Never
|
|
99
|
+
](
|
|
100
|
+
acquire: Effect[Resource, E, R],
|
|
101
|
+
use: Callable[[Resource], Effect[A, E2, R2]],
|
|
102
|
+
release: Callable[[Resource, Exit[A, E2]], Effect[None, E3, R3]],
|
|
103
|
+
) -> Effect[A, E | E2 | E3, R | R2 | R3]:
|
|
104
|
+
"""Acquire and release masked; use inherits the caller's interruption status.
|
|
105
|
+
|
|
106
|
+
The use callback is suspended beneath the exit handler, so a thrown callback still
|
|
107
|
+
releases the acquired resource. Release errors join the use failure through on_exit.
|
|
108
|
+
"""
|
|
109
|
+
return uninterruptible_mask(
|
|
110
|
+
lambda restore: acquire.flat_map(
|
|
111
|
+
lambda a: suspend(lambda: restore(use(a))).pipe(on_exit(lambda ex: release(a, ex)))
|
|
112
|
+
)
|
|
113
|
+
)
|
peffect/scheduler.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Scheduler: when a fiber yields, and where its queued steps run.
|
|
2
|
+
|
|
3
|
+
provide(MaxOpsBeforeYield.context(256))(program) # yield more often
|
|
4
|
+
provide(Scheduler.context(MixedScheduler("sync")))(p) # replace the scheduler
|
|
5
|
+
with_dispatcher(lambda d: sync(lambda: d.flush())) # reach the fiber's dispatcher
|
|
6
|
+
|
|
7
|
+
All three are References, so using them never adds to R. The kernel (fiber.py) reads them by
|
|
8
|
+
key on every context change. Effect v4: Scheduler.ts, internal/effect.ts:567-570, :794-828.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from .context import Reference
|
|
14
|
+
from .fiber import (
|
|
15
|
+
DEFAULT_SCHEDULER,
|
|
16
|
+
MixedScheduler,
|
|
17
|
+
SchedulerDispatcher,
|
|
18
|
+
SchedulerService,
|
|
19
|
+
with_dispatcher,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Scheduler(Reference[SchedulerService], key="effect/Scheduler"):
|
|
24
|
+
"""The fiber's scheduler. Default: the shared MixedScheduler (Scheduler.ts:82-85)."""
|
|
25
|
+
|
|
26
|
+
@classmethod
|
|
27
|
+
def default(cls) -> SchedulerService:
|
|
28
|
+
return DEFAULT_SCHEDULER
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class MaxOpsBeforeYield(Reference[int], key="effect/Scheduler/MaxOpsBeforeYield"):
|
|
32
|
+
"""Ops a fiber runs before MixedScheduler yields it. Default 2048 (Scheduler.ts:294-297)."""
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def default(cls) -> int:
|
|
36
|
+
return 2048
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class PreventSchedulerYield(Reference[bool], key="effect/Scheduler/PreventSchedulerYield"):
|
|
40
|
+
"""When true, the run loop never asks should_yield. Default False (Scheduler.ts:321-324)."""
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def default(cls) -> bool:
|
|
44
|
+
return False
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"MaxOpsBeforeYield",
|
|
49
|
+
"MixedScheduler",
|
|
50
|
+
"PreventSchedulerYield",
|
|
51
|
+
"Scheduler",
|
|
52
|
+
"SchedulerDispatcher",
|
|
53
|
+
"SchedulerService",
|
|
54
|
+
"with_dispatcher",
|
|
55
|
+
]
|
peffect/scope.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
"""Scope: a lifetime that runs its finalizers, newest first, when it closes.
|
|
2
|
+
|
|
3
|
+
s = yield from Scope.make()
|
|
4
|
+
yield from Scope.add_finalizer(s, release) # runs when s closes
|
|
5
|
+
yield from Scope.close(s, Success(None)) # finalizers run masked, get the Exit
|
|
6
|
+
|
|
7
|
+
scoped(body) # body reads its Scope with `scope`
|
|
8
|
+
|
|
9
|
+
A finalizer added to a closed scope runs at once with the exit it closed with. A child made by
|
|
10
|
+
``Scope.fork`` closes with its parent and leaves the parent when it closes first.
|
|
11
|
+
|
|
12
|
+
Effect v4: Scope.ts, internal/effect.ts:4024-4215 (scopeClose ... scoped). Upstream's
|
|
13
|
+
``Scope.use`` (scopeUse) is not ported: on this Tag ``Scope().use()`` is the service lookup
|
|
14
|
+
every Tag has, the same effect as ``scope``.
|
|
15
|
+
|
|
16
|
+
A ``"parallel"`` scope with several finalizers starts each one, newest first, in its own daemon
|
|
17
|
+
fiber that inherits the closing fiber's mask, then waits for all of them; empty and
|
|
18
|
+
one-finalizer closes take the common path, as upstream's do.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from collections.abc import Callable, Generator
|
|
24
|
+
from typing import Any, Final, Literal, Never, Protocol, final, overload
|
|
25
|
+
|
|
26
|
+
from .cause import Cause, Die, Fail, Interrupt
|
|
27
|
+
from .context import Tag, provide
|
|
28
|
+
from .core import (
|
|
29
|
+
Effect,
|
|
30
|
+
Exit,
|
|
31
|
+
Failure,
|
|
32
|
+
Success,
|
|
33
|
+
WithFiber,
|
|
34
|
+
exit_,
|
|
35
|
+
gen,
|
|
36
|
+
on_exit,
|
|
37
|
+
succeed,
|
|
38
|
+
suspend,
|
|
39
|
+
sync,
|
|
40
|
+
uninterruptible,
|
|
41
|
+
update_context,
|
|
42
|
+
)
|
|
43
|
+
from .fiber import Fiber, await_all, fork_daemon, fork_in_owner, run_in_owner
|
|
44
|
+
|
|
45
|
+
type Strategy = Literal["sequential", "parallel"]
|
|
46
|
+
type Finalizer = Callable[[Exit[Any, Any]], Effect[Any, Never, Never]]
|
|
47
|
+
|
|
48
|
+
VOID: Effect[None, Never, Never] = succeed(None)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# -- state (Scope.ts:103-195) ---------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@final
|
|
55
|
+
class Empty:
|
|
56
|
+
"""Open, no finalizers. Removing the last finalizer comes back here."""
|
|
57
|
+
|
|
58
|
+
__slots__ = ()
|
|
59
|
+
tag: Final = "Empty"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@final
|
|
63
|
+
class Open:
|
|
64
|
+
"""Open with finalizers: the first is kept inline, a second moves both into the dict."""
|
|
65
|
+
|
|
66
|
+
__slots__ = ("finalizer", "finalizer_key", "finalizers")
|
|
67
|
+
tag: Final = "Open"
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
finalizer_key: object | None,
|
|
72
|
+
finalizer: Finalizer | None,
|
|
73
|
+
finalizers: dict[object, Finalizer] | None,
|
|
74
|
+
) -> None:
|
|
75
|
+
self.finalizer_key = finalizer_key
|
|
76
|
+
self.finalizer = finalizer
|
|
77
|
+
self.finalizers = finalizers
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@final
|
|
81
|
+
class Closed:
|
|
82
|
+
"""Closing has started (finalizers may still be running); ``exit`` is what it closed with."""
|
|
83
|
+
|
|
84
|
+
__slots__ = ("exit",)
|
|
85
|
+
tag: Final = "Closed"
|
|
86
|
+
|
|
87
|
+
def __init__(self, exit_: Exit[Any, Any]) -> None:
|
|
88
|
+
self.exit: Final = exit_
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
type State = Empty | Open | Closed
|
|
92
|
+
|
|
93
|
+
_EMPTY: Final = Empty() # constScopeEmpty
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class ScopeService(Protocol):
|
|
97
|
+
"""What ``scope`` hands out (Scope.ts:47-52): no ``close``, that needs a Closeable."""
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def strategy(self) -> Strategy: ...
|
|
101
|
+
@property
|
|
102
|
+
def parent(self) -> ScopeService | None: ...
|
|
103
|
+
|
|
104
|
+
state: State
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@final
|
|
108
|
+
class Closeable:
|
|
109
|
+
"""A scope its maker can close (Scope.ts:77-79). Made by ``Scope.make``/``make_unsafe``/
|
|
110
|
+
``fork``/``fork_unsafe``."""
|
|
111
|
+
|
|
112
|
+
__slots__ = ("_parent", "_strategy", "state")
|
|
113
|
+
|
|
114
|
+
def __init__(self, strategy: Strategy, parent: ScopeService | None) -> None:
|
|
115
|
+
self._strategy: Final = strategy
|
|
116
|
+
self._parent: Final = parent
|
|
117
|
+
self.state: State = _EMPTY
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def strategy(self) -> Strategy:
|
|
121
|
+
return self._strategy
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def parent(self) -> ScopeService | None:
|
|
125
|
+
return self._parent
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# -- internals (internal/effect.ts) ---------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _add_finalizer_unsafe(scope: ScopeService, key: object, finalizer: Finalizer) -> None:
|
|
132
|
+
"""scopeAddFinalizerUnsafe, :4143-4159. A Closed scope is left alone."""
|
|
133
|
+
state = scope.state
|
|
134
|
+
if isinstance(state, Empty):
|
|
135
|
+
scope.state = Open(key, finalizer, None)
|
|
136
|
+
elif isinstance(state, Open):
|
|
137
|
+
if state.finalizer is not None:
|
|
138
|
+
state.finalizers = {state.finalizer_key: state.finalizer, key: finalizer}
|
|
139
|
+
state.finalizer_key = None
|
|
140
|
+
state.finalizer = None
|
|
141
|
+
elif state.finalizers is not None:
|
|
142
|
+
state.finalizers[key] = finalizer
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _remove_finalizer_unsafe(scope: ScopeService, key: object) -> None:
|
|
146
|
+
"""scopeRemoveFinalizerUnsafe, :4159-4172."""
|
|
147
|
+
state = scope.state
|
|
148
|
+
if not isinstance(state, Open):
|
|
149
|
+
return
|
|
150
|
+
if state.finalizer_key is key:
|
|
151
|
+
scope.state = _EMPTY
|
|
152
|
+
elif state.finalizers is not None:
|
|
153
|
+
state.finalizers.pop(key, None)
|
|
154
|
+
if not state.finalizers:
|
|
155
|
+
scope.state = _EMPTY
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _run_finalizer(finalizer: Finalizer, exit_: Exit[Any, Any]) -> Effect[Any, Never, Never]:
|
|
159
|
+
"""runFinalizer, :4058-4067: a finalizer that raises becomes its defect."""
|
|
160
|
+
try:
|
|
161
|
+
return finalizer(exit_)
|
|
162
|
+
except Exception as e:
|
|
163
|
+
return Failure(Cause.die(e))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _as_void_all(exits: list[Exit[Any, Never]]) -> Exit[None, Never]:
|
|
167
|
+
"""exitAsVoidAll, :2221-2234: every failure's reasons, in order, kept as they are (no
|
|
168
|
+
merging of equal reasons, no defect election)."""
|
|
169
|
+
reasons: list[Fail[Any] | Die | Interrupt] = []
|
|
170
|
+
for ex in exits:
|
|
171
|
+
if isinstance(ex, Failure):
|
|
172
|
+
reasons.extend(ex.cause.reasons)
|
|
173
|
+
return Failure(Cause(tuple(reasons))) if reasons else Success(None)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@gen
|
|
177
|
+
def _close_finalizers(
|
|
178
|
+
strategy: Strategy, finalizers: dict[object, Finalizer], closed_with: Exit[Any, Any]
|
|
179
|
+
) -> Generator[Effect[Any, Never, Never], Any]:
|
|
180
|
+
"""scopeCloseFinalizers, :4077-4101: newest first. Sequential runs each to its Exit in turn;
|
|
181
|
+
parallel starts each in a daemon fiber with the closing fiber's mask, then awaits them all,
|
|
182
|
+
skipping the closing fiber's own `run_in`/`fork_in` finalizer, which would wait for itself."""
|
|
183
|
+
exits: list[Exit[Any, Never]] = []
|
|
184
|
+
fibers: list[Fiber[Any, Never]] = []
|
|
185
|
+
closing: Fiber[Any, Any] = yield from WithFiber(_succeed_with)
|
|
186
|
+
for key, finalizer in reversed(list(finalizers.items())):
|
|
187
|
+
if strategy == "sequential":
|
|
188
|
+
ex: Exit[Any, Never] = yield from exit_(_run_finalizer(finalizer, closed_with))
|
|
189
|
+
exits.append(ex)
|
|
190
|
+
elif key is not closing:
|
|
191
|
+
fiber: Fiber[Any, Never] = yield from fork_daemon(
|
|
192
|
+
_run_finalizer(finalizer, closed_with),
|
|
193
|
+
start_immediately=True,
|
|
194
|
+
uninterruptible="inherit",
|
|
195
|
+
)
|
|
196
|
+
fibers.append(fiber)
|
|
197
|
+
if fibers:
|
|
198
|
+
exits = yield from await_all(fibers)
|
|
199
|
+
yield from _as_void_all(exits)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _succeed_with[T](value: T) -> Effect[T, Never, Never]:
|
|
203
|
+
return succeed(value)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _fiber_finalizer(fiber: Fiber[Any, Any]) -> Finalizer:
|
|
207
|
+
"""fiberScopeFinalizer, :5690-5693: interrupt and await the fiber, unless it is the one
|
|
208
|
+
running the close."""
|
|
209
|
+
return lambda _: WithFiber(lambda current: VOID if current is fiber else fiber.interrupt())
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@final
|
|
213
|
+
class _ScopeOwner:
|
|
214
|
+
"""The kernel's FiberOwner over a Scope: the fiber's finalizer is keyed by the fiber."""
|
|
215
|
+
|
|
216
|
+
__slots__ = ("_scope",)
|
|
217
|
+
|
|
218
|
+
def __init__(self, scope: ScopeService) -> None:
|
|
219
|
+
self._scope: Final = scope
|
|
220
|
+
|
|
221
|
+
def is_closed(self) -> bool:
|
|
222
|
+
return isinstance(self._scope.state, Closed)
|
|
223
|
+
|
|
224
|
+
def attach(self, fiber: Fiber[Any, Any]) -> None:
|
|
225
|
+
_add_finalizer_unsafe(self._scope, fiber, _fiber_finalizer(fiber))
|
|
226
|
+
|
|
227
|
+
def detach(self, fiber: Fiber[Any, Any]) -> None:
|
|
228
|
+
_remove_finalizer_unsafe(self._scope, fiber)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _void_if_none(eff: Effect[Any, Never, Never] | None) -> Effect[Any, Never, Never]:
|
|
232
|
+
return VOID if eff is None else eff
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# -- the API (Scope.ts) ---------------------------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class Scope(Tag[ScopeService], key="effect/Scope"): # internal/effect.ts:4030
|
|
239
|
+
"""The Scope service (scopeTag), and the Scope module's functions."""
|
|
240
|
+
|
|
241
|
+
__slots__ = ()
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
def make_unsafe(strategy: Strategy = "sequential") -> Closeable:
|
|
245
|
+
"""scopeMakeUnsafe, :4180-4192."""
|
|
246
|
+
return Closeable(strategy, None)
|
|
247
|
+
|
|
248
|
+
@staticmethod
|
|
249
|
+
def make(strategy: Strategy = "sequential") -> Effect[Closeable, Never, Never]:
|
|
250
|
+
return sync(lambda: Scope.make_unsafe(strategy))
|
|
251
|
+
|
|
252
|
+
@staticmethod
|
|
253
|
+
def add_finalizer_unsafe(scope: ScopeService, key: object, finalizer: Finalizer) -> None:
|
|
254
|
+
"""Synchronously register ownership; a closed scope is left alone.
|
|
255
|
+
|
|
256
|
+
Python plumbing for Layer's atomic observer registration. Matches the upstream
|
|
257
|
+
internal scopeAddFinalizerUnsafe (:4143-4159), rather than late-add execution.
|
|
258
|
+
"""
|
|
259
|
+
_add_finalizer_unsafe(scope, key, finalizer)
|
|
260
|
+
|
|
261
|
+
@staticmethod
|
|
262
|
+
def remove_finalizer_unsafe(scope: ScopeService, key: object) -> None:
|
|
263
|
+
"""scopeRemoveFinalizerUnsafe (:4159-4172): drop the finalizer added under ``key``."""
|
|
264
|
+
_remove_finalizer_unsafe(scope, key)
|
|
265
|
+
|
|
266
|
+
@staticmethod
|
|
267
|
+
def add_finalizer_exit(scope: ScopeService, finalizer: Finalizer) -> Effect[None, Never, Never]:
|
|
268
|
+
"""scopeAddFinalizerExit, :4123-4134: on a closed scope the finalizer runs now, with the
|
|
269
|
+
exit the scope closed with."""
|
|
270
|
+
|
|
271
|
+
def add() -> Effect[None, Never, Never]:
|
|
272
|
+
state = scope.state
|
|
273
|
+
if isinstance(state, Closed):
|
|
274
|
+
return finalizer(state.exit)
|
|
275
|
+
_add_finalizer_unsafe(scope, object(), finalizer)
|
|
276
|
+
return VOID
|
|
277
|
+
|
|
278
|
+
return suspend(add)
|
|
279
|
+
|
|
280
|
+
@staticmethod
|
|
281
|
+
def add_finalizer(
|
|
282
|
+
scope: ScopeService, finalizer: Effect[Any, Never, Never]
|
|
283
|
+
) -> Effect[None, Never, Never]:
|
|
284
|
+
return Scope.add_finalizer_exit(scope, lambda _: finalizer)
|
|
285
|
+
|
|
286
|
+
@staticmethod
|
|
287
|
+
def close_unsafe(scope: Closeable, exit_: Exit[Any, Any]) -> Effect[None, Never, Never] | None:
|
|
288
|
+
"""scopeCloseUnsafe, :4040-4056. Marks the scope Closed and leaves its parent, then gives
|
|
289
|
+
the finalizers' effect (None when there is nothing to run). A second close gives None."""
|
|
290
|
+
state = scope.state
|
|
291
|
+
if isinstance(state, Closed):
|
|
292
|
+
return None
|
|
293
|
+
scope.state = Closed(exit_)
|
|
294
|
+
if scope.parent is not None:
|
|
295
|
+
_remove_finalizer_unsafe(scope.parent, scope)
|
|
296
|
+
if isinstance(state, Empty):
|
|
297
|
+
return None
|
|
298
|
+
if state.finalizer is not None:
|
|
299
|
+
return _run_finalizer(state.finalizer, exit_)
|
|
300
|
+
finalizers = state.finalizers
|
|
301
|
+
assert finalizers is not None # Open holds the inline finalizer or the dict
|
|
302
|
+
if len(finalizers) == 1:
|
|
303
|
+
return _run_finalizer(next(iter(finalizers.values())), exit_)
|
|
304
|
+
return _close_finalizers(scope.strategy, finalizers, exit_)
|
|
305
|
+
|
|
306
|
+
@staticmethod
|
|
307
|
+
def close(scope: Closeable, exit_: Exit[Any, Any]) -> Effect[None, Never, Never]:
|
|
308
|
+
"""scopeClose, :4033-4038: masked first, so the finalizers run uninterruptibly."""
|
|
309
|
+
return uninterruptible(suspend(lambda: _void_if_none(Scope.close_unsafe(scope, exit_))))
|
|
310
|
+
|
|
311
|
+
@staticmethod
|
|
312
|
+
def fork_unsafe(scope: ScopeService, strategy: Strategy = "sequential") -> Closeable:
|
|
313
|
+
"""scopeForkUnsafe, :4110-4121: a child of a closed scope starts closed, with its exit."""
|
|
314
|
+
child = Closeable(strategy, scope)
|
|
315
|
+
if isinstance(scope.state, Closed):
|
|
316
|
+
child.state = scope.state
|
|
317
|
+
return child
|
|
318
|
+
_add_finalizer_unsafe(scope, child, lambda ex: Scope.close(child, ex))
|
|
319
|
+
return child
|
|
320
|
+
|
|
321
|
+
@staticmethod
|
|
322
|
+
def fork(
|
|
323
|
+
scope: ScopeService, strategy: Strategy = "sequential"
|
|
324
|
+
) -> Effect[Closeable, Never, Never]:
|
|
325
|
+
return sync(lambda: Scope.fork_unsafe(scope, strategy))
|
|
326
|
+
|
|
327
|
+
@staticmethod
|
|
328
|
+
def provide(scope: ScopeService) -> provide[Scope]:
|
|
329
|
+
"""provideScope: run an effect with this scope as its Scope service."""
|
|
330
|
+
return provide(Scope.context(scope))
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def run_in[A, E](fiber: Fiber[A, E], scope: ScopeService) -> Fiber[A, E]:
|
|
334
|
+
"""Fiber.runIn: interrupt ``fiber`` when ``scope`` closes (at once if it has), and return
|
|
335
|
+
it. Registering again makes it the newest finalizer. Does not wait for the fiber."""
|
|
336
|
+
return run_in_owner(fiber, _ScopeOwner(scope))
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def fork_in[A, E, R](
|
|
340
|
+
eff: Effect[A, E, R],
|
|
341
|
+
scope: ScopeService,
|
|
342
|
+
*,
|
|
343
|
+
start_immediately: bool = False,
|
|
344
|
+
uninterruptible: bool | Literal["inherit"] = False,
|
|
345
|
+
) -> Effect[Fiber[A, E], Never, R]:
|
|
346
|
+
"""Effect.forkIn: run ``eff`` in a daemon fiber that ``scope`` interrupts when it closes.
|
|
347
|
+
On a closed scope the work never runs and the fiber is interrupted."""
|
|
348
|
+
return fork_in_owner(
|
|
349
|
+
eff,
|
|
350
|
+
_ScopeOwner(scope),
|
|
351
|
+
start_immediately=start_immediately,
|
|
352
|
+
uninterruptible=uninterruptible,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
scope: Effect[ScopeService, Never, Scope] = Scope().use()
|
|
357
|
+
"""Effect.scope: the Scope service in context (internal/effect.ts:4192)."""
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def fork_scoped[A, E, R](
|
|
361
|
+
eff: Effect[A, E, R],
|
|
362
|
+
*,
|
|
363
|
+
start_immediately: bool = False,
|
|
364
|
+
uninterruptible: bool | Literal["inherit"] = False,
|
|
365
|
+
) -> Effect[Fiber[A, E], Never, R | Scope]:
|
|
366
|
+
"""Effect.forkScoped: ``fork_in`` the Scope in context (internal/effect.ts:5742-5765). The
|
|
367
|
+
fiber outlives the fiber that forked it and is interrupted when that Scope closes."""
|
|
368
|
+
return scope.flat_map(
|
|
369
|
+
lambda s: fork_in(
|
|
370
|
+
eff, s, start_immediately=start_immediately, uninterruptible=uninterruptible
|
|
371
|
+
)
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
# exact match first, as context.provide: matching `Scope | R` against `Scope` leaves R unsolved
|
|
376
|
+
@overload
|
|
377
|
+
def scoped[A, E](eff: Effect[A, E, Scope]) -> Effect[A, E, Never]: ...
|
|
378
|
+
@overload
|
|
379
|
+
def scoped[A, E, R](eff: Effect[A, E, Scope | R]) -> Effect[A, E, R]: ...
|
|
380
|
+
def scoped(eff: Effect[Any, Any, Any]) -> Effect[Any, Any, Any]:
|
|
381
|
+
"""Run ``eff`` with a new Scope, closed with ``eff``'s exit when it ends.
|
|
382
|
+
|
|
383
|
+
Effect v4 scoped (:4204-4215) installs the Scope and its exit handler in one step; here the
|
|
384
|
+
handler (``on_exit``) is in place before the context changes, and the context goes back
|
|
385
|
+
(update_context's frame) before the scope closes, so finalizers run without the Scope.
|
|
386
|
+
"""
|
|
387
|
+
|
|
388
|
+
def install() -> Effect[Any, Any, Any]:
|
|
389
|
+
s = Scope.make_unsafe()
|
|
390
|
+
return on_exit(lambda ex: _void_if_none(Scope.close_unsafe(s, ex)))(
|
|
391
|
+
update_context(eff, lambda old: {**old, Scope.key: s})
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
return suspend(install)
|