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/logger.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Logger: leveled log lines through the fiber's loggers. A header-only subset.
|
|
2
|
+
|
|
3
|
+
yield from log_warning("disk low", pct) # [12:00:00.000] WARN (#3): disk low 9
|
|
4
|
+
provide(MinimumLogLevel.context("Debug"))(program) # let Debug lines through
|
|
5
|
+
provide(CurrentLoggers.context((make(fn),)))(program) # replace the loggers
|
|
6
|
+
|
|
7
|
+
The default logger writes ``[HH:MM:SS.mmm] LEVEL (#fiber):`` then the messages, as separate
|
|
8
|
+
arguments, to the fiber's Console (``console.error`` when ``LogToStderr``). The time is the fiber
|
|
9
|
+
Clock's, in local time, as upstream's ``Date``. Not ported: spans, annotations, cause rendering,
|
|
10
|
+
the tracer logger, the pretty and JSON loggers. Effect v4: internal/effect.ts:6594-6634,
|
|
11
|
+
:6725-6760, :6810-6813, :6984-7003; internal/references.ts:56-58.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import math
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Callable, Generator
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any, Literal, Never, final
|
|
21
|
+
|
|
22
|
+
from .clock import Clock
|
|
23
|
+
from .console import Console, ConsoleService
|
|
24
|
+
from .context import Reference
|
|
25
|
+
from .core import ContextMap, Effect, WithFiber, fiber_id, gen, succeed
|
|
26
|
+
|
|
27
|
+
type Severity = Literal["Fatal", "Error", "Warn", "Info", "Debug", "Trace"]
|
|
28
|
+
type LogLevel = Severity | Literal["All", "None"]
|
|
29
|
+
|
|
30
|
+
_ORDER: dict[LogLevel, float] = { # logLevelToOrder, :6594-6613 (Number.MIN/MAX_SAFE_INTEGER)
|
|
31
|
+
"All": -(2**53 - 1),
|
|
32
|
+
"Fatal": 50_000,
|
|
33
|
+
"Error": 40_000,
|
|
34
|
+
"Warn": 30_000,
|
|
35
|
+
"Info": 20_000,
|
|
36
|
+
"Debug": 10_000,
|
|
37
|
+
"Trace": 0,
|
|
38
|
+
"None": 2**53 - 1,
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def is_greater_than(self: LogLevel, that: LogLevel) -> bool:
|
|
43
|
+
"""isLogLevelGreaterThan (:6615-6619)."""
|
|
44
|
+
return _ORDER[self] > _ORDER[that]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class MinimumLogLevel(Reference[LogLevel], key="effect/References/MinimumLogLevel"):
|
|
48
|
+
"""Levels below this are skipped. Default "Info" (internal/references.ts:56-58)."""
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def default(cls) -> LogLevel:
|
|
52
|
+
return "Info"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class LogToStderr(Reference[bool], key="effect/Logger/LogToStderr"):
|
|
56
|
+
"""When true the default logger writes with ``console.error``. Default False (:6633)."""
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def default(cls) -> bool:
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@final
|
|
64
|
+
@dataclass(frozen=True, slots=True)
|
|
65
|
+
class LogOptions:
|
|
66
|
+
"""What a logger gets. ``fiber_id`` stands in for upstream's fiber (INVARIANTS B3);
|
|
67
|
+
``context`` is that fiber's services, for loggers that read a Reference such as Console."""
|
|
68
|
+
|
|
69
|
+
log_level: Severity
|
|
70
|
+
message: tuple[object, ...]
|
|
71
|
+
fiber_id: int
|
|
72
|
+
time_millis: float
|
|
73
|
+
context: ContextMap
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@final
|
|
77
|
+
class Logger:
|
|
78
|
+
"""A logger: ``make(fn)`` wraps a function of LogOptions. Identity is what dedups it."""
|
|
79
|
+
|
|
80
|
+
__slots__ = ("_log",)
|
|
81
|
+
|
|
82
|
+
def __init__(self, log: Callable[[LogOptions], object]) -> None:
|
|
83
|
+
self._log = log
|
|
84
|
+
|
|
85
|
+
def log(self, options: LogOptions) -> None:
|
|
86
|
+
self._log(options)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def make(log: Callable[[LogOptions], object]) -> Logger:
|
|
90
|
+
"""Logger.make: a logger that calls ``log`` for every line that passes the minimum."""
|
|
91
|
+
return Logger(log)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def format_time(millis: float) -> str:
|
|
95
|
+
"""``HH:MM:SS.mmm`` in local time, as defaultDateFormat (:6810-6813) over ``new Date(millis)``:
|
|
96
|
+
the time is truncated toward zero, and outside Date's range (non-finite, or more than 8.64e15
|
|
97
|
+
from the epoch) every field is NaN."""
|
|
98
|
+
if not math.isfinite(millis) or abs(millis) > 8.64e15:
|
|
99
|
+
return "NaN:NaN:NaN.NaN"
|
|
100
|
+
seconds, ms = divmod(int(millis), 1000)
|
|
101
|
+
t = time.localtime(seconds)
|
|
102
|
+
return f"{t.tm_hour:02}:{t.tm_min:02}:{t.tm_sec:02}.{ms:03}"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _default_log(options: LogOptions) -> None:
|
|
106
|
+
"""defaultLogger (:6984-7003), header only."""
|
|
107
|
+
context = options.context
|
|
108
|
+
console: ConsoleService = context.get(Console.key, Console.default())
|
|
109
|
+
to_stderr: bool = context.get(LogToStderr.key, LogToStderr.default())
|
|
110
|
+
header = (
|
|
111
|
+
f"[{format_time(options.time_millis)}] {options.log_level.upper()} (#{options.fiber_id}):"
|
|
112
|
+
)
|
|
113
|
+
(console.error if to_stderr else console.log)(header, *options.message)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
default_logger: Logger = Logger(_default_log)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class CurrentLoggers(Reference[tuple[Logger, ...]], key="effect/Logger/CurrentLoggers"):
|
|
120
|
+
"""The loggers each line goes to. A logger listed twice logs once, at its first place, as
|
|
121
|
+
upstream's ``Set`` (:6626-6631). Default: the default logger alone (no tracer logger)."""
|
|
122
|
+
|
|
123
|
+
@classmethod
|
|
124
|
+
def default(cls) -> tuple[Logger, ...]:
|
|
125
|
+
return (default_logger,)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def log_with_level(level: Severity) -> Callable[..., Effect[None, Never, Never]]:
|
|
129
|
+
"""``log_with_level("Warn")("a", 1)``: log at ``level`` unless the minimum is above it, with
|
|
130
|
+
the fiber Clock's time read once per line (logWithLevel, :6725-6760)."""
|
|
131
|
+
|
|
132
|
+
@gen
|
|
133
|
+
def log(*message: object) -> Generator[Effect[Any, Never, Never], Any]:
|
|
134
|
+
if is_greater_than((yield from MinimumLogLevel()), level):
|
|
135
|
+
return
|
|
136
|
+
loggers = yield from CurrentLoggers()
|
|
137
|
+
if not loggers:
|
|
138
|
+
return
|
|
139
|
+
fid = yield from fiber_id
|
|
140
|
+
clock = yield from Clock()
|
|
141
|
+
context = yield from WithFiber(lambda fiber: succeed(fiber.context))
|
|
142
|
+
options = LogOptions(level, message, fid, clock.current_time_millis_unsafe(), context)
|
|
143
|
+
for logger in dict.fromkeys(loggers): # each once, first registration first, as a Set
|
|
144
|
+
logger.log(options)
|
|
145
|
+
|
|
146
|
+
return log
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
log_warning = log_with_level("Warn")
|
|
150
|
+
"""Effect.logWarning."""
|
|
151
|
+
|
|
152
|
+
__all__ = [
|
|
153
|
+
"CurrentLoggers",
|
|
154
|
+
"LogLevel",
|
|
155
|
+
"LogOptions",
|
|
156
|
+
"LogToStderr",
|
|
157
|
+
"Logger",
|
|
158
|
+
"MinimumLogLevel",
|
|
159
|
+
"Severity",
|
|
160
|
+
"default_logger",
|
|
161
|
+
"format_time",
|
|
162
|
+
"is_greater_than",
|
|
163
|
+
"log_warning",
|
|
164
|
+
"log_with_level",
|
|
165
|
+
"make",
|
|
166
|
+
]
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""ManagedRuntime: build a Layer once, run effects with its services, dispose it once.
|
|
2
|
+
|
|
3
|
+
Effect v4 289a53f7, packages/effect/src/ManagedRuntime.ts:325-474 (``make``). Line references
|
|
4
|
+
below are to that file unless they name another one.
|
|
5
|
+
|
|
6
|
+
rt = ManagedRuntime.make(Users.layer)
|
|
7
|
+
users = await rt.run(Users().use()) # the first request builds the layer
|
|
8
|
+
await rt.dispose() # closes the layer and interrupts managed fibers
|
|
9
|
+
|
|
10
|
+
State, all owned by the runtime:
|
|
11
|
+
|
|
12
|
+
- ``scope`` (sequential) with two children forked at construction: ``_layer_scope`` holds the
|
|
13
|
+
layer's resources, ``_fiber_scope`` (parallel) holds one finalizer per running managed fiber,
|
|
14
|
+
so closing ``scope`` interrupts and awaits those fibers, then releases the layer (:332-334).
|
|
15
|
+
- ``_managed`` / ``_disposing``: WeakSets of fibers (:338-339). A managed fiber (or one of its
|
|
16
|
+
descendants) that disposes the runtime returns at once instead of awaiting its own close;
|
|
17
|
+
a disposing fiber that starts a request is not added to ``_fiber_scope`` (:340-346).
|
|
18
|
+
- ``_build_fiber``: the one layer build, started by the first request (:361-383).
|
|
19
|
+
- ``_disposed``: set by the one disposer that claims disposal; every other disposer awaits it.
|
|
20
|
+
|
|
21
|
+
Adaptations: Promise runners are async methods over ``await_exit`` (runPromiseExitWith,
|
|
22
|
+
internal/effect.ts:5854-5866); there is no sync or callback runner and no AbortSignal, so
|
|
23
|
+
``run_sync*``, ``run_callback`` and ``signal`` are not ported. ``die`` takes an exception, so the
|
|
24
|
+
disposal defect is ``RuntimeError("ManagedRuntime disposed")`` where upstream dies with the bare
|
|
25
|
+
string (:418). ``Symbol.asyncDispose`` is ``async with``.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import weakref
|
|
31
|
+
from collections.abc import Callable
|
|
32
|
+
from typing import Any, Never, Self, final
|
|
33
|
+
|
|
34
|
+
from .context import Context, Reference, provide, run_fork_with
|
|
35
|
+
from .core import (
|
|
36
|
+
Effect,
|
|
37
|
+
Exit,
|
|
38
|
+
Success,
|
|
39
|
+
WithFiber,
|
|
40
|
+
die,
|
|
41
|
+
ensuring,
|
|
42
|
+
succeed,
|
|
43
|
+
sync,
|
|
44
|
+
uninterruptible_mask,
|
|
45
|
+
)
|
|
46
|
+
from .deferred import Deferred
|
|
47
|
+
from .fiber import (
|
|
48
|
+
DEFAULT_SCHEDULER,
|
|
49
|
+
Fiber,
|
|
50
|
+
SchedulerService,
|
|
51
|
+
await_exit,
|
|
52
|
+
run,
|
|
53
|
+
run_exit,
|
|
54
|
+
run_fork,
|
|
55
|
+
)
|
|
56
|
+
from .layer import Layer, MemoMap
|
|
57
|
+
from .scheduler import Scheduler
|
|
58
|
+
from .scope import Closeable, Scope, run_in
|
|
59
|
+
|
|
60
|
+
_VOID: Effect[None, Never, Never] = succeed(None)
|
|
61
|
+
_DISPOSED = "ManagedRuntime disposed"
|
|
62
|
+
|
|
63
|
+
type _Hook = Callable[[Fiber[Any, Any]], object] # RunOptions.onFiberStart
|
|
64
|
+
type _Restore = Callable[[Effect[None, Never, Never]], Effect[None, Never, Never]]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class _DisposingRuntimes( # :250-262, not exported upstream either
|
|
68
|
+
Reference[frozenset["ManagedRuntime[Any, Any]"]],
|
|
69
|
+
key="effect/ManagedRuntime/DisposingRuntimes",
|
|
70
|
+
):
|
|
71
|
+
"""The runtimes whose disposal the current fiber is running. A disposal adds its runtime to
|
|
72
|
+
the set it inherits, so a finalizer that disposes another runtime still belongs to the outer
|
|
73
|
+
disposals. Not provided to the layer build: a layer shared through a MemoMap keeps the build
|
|
74
|
+
context of the runtime that built it, which may not be the one disposing it."""
|
|
75
|
+
|
|
76
|
+
__slots__ = ()
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
def default(cls) -> frozenset[ManagedRuntime[Any, Any]]:
|
|
80
|
+
return frozenset()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@final
|
|
84
|
+
class ManagedRuntime[R, ER]:
|
|
85
|
+
"""A Layer built on first use; runs effects needing R, and fails them with ER if the build
|
|
86
|
+
fails. Contravariant in R and covariant in ER, as upstream ``ManagedRuntime<in R, out ER>``."""
|
|
87
|
+
|
|
88
|
+
__slots__ = (
|
|
89
|
+
"_build_fiber",
|
|
90
|
+
"_cached_context",
|
|
91
|
+
"_context_effect",
|
|
92
|
+
"_disposed",
|
|
93
|
+
"_disposing",
|
|
94
|
+
"_fiber_scope",
|
|
95
|
+
"_layer",
|
|
96
|
+
"_layer_scope",
|
|
97
|
+
"_managed",
|
|
98
|
+
"dispose_effect",
|
|
99
|
+
"memo_map",
|
|
100
|
+
"scope",
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def __init__(self, layer: Layer[R, ER, Never], memo_map: MemoMap | None) -> None:
|
|
104
|
+
self.memo_map: MemoMap = memo_map if memo_map is not None else Layer.make_memo_map_unsafe()
|
|
105
|
+
self.scope: Closeable = Scope.make_unsafe("sequential")
|
|
106
|
+
self._layer_scope = Scope.fork_unsafe(self.scope, "sequential")
|
|
107
|
+
self._fiber_scope = Scope.fork_unsafe(self.scope, "parallel")
|
|
108
|
+
# Fibers started by the runtime, the build included, are interrupted and awaited by its
|
|
109
|
+
# disposal, so they and their children must not wait for it (:335-339).
|
|
110
|
+
self._managed: weakref.WeakSet[Fiber[Any, Any]] = weakref.WeakSet()
|
|
111
|
+
self._disposing: weakref.WeakSet[Fiber[Any, Any]] = weakref.WeakSet()
|
|
112
|
+
self._layer = layer
|
|
113
|
+
self._build_fiber: Fiber[Context[R], ER] | None = None
|
|
114
|
+
self._disposed: Deferred[None, Never] | None = None
|
|
115
|
+
self._cached_context: Context[R] | None = None
|
|
116
|
+
self._context_effect: Effect[Context[R], ER, Never] = WithFiber(
|
|
117
|
+
lambda fiber: self._request_context(fiber)
|
|
118
|
+
)
|
|
119
|
+
# The decision, the mask and the claim are one step: uninterruptible_mask calls its body
|
|
120
|
+
# inside the op that masks (core.py uninterruptible_mask), as withFiber +
|
|
121
|
+
# fiberEnterUninterruptibleUnsafe do upstream (:401, :410-411). An interrupt that lands
|
|
122
|
+
# before that op leaves the runtime unclaimed.
|
|
123
|
+
self.dispose_effect: Effect[None, Never, Never] = WithFiber(
|
|
124
|
+
lambda fiber: uninterruptible_mask(lambda restore: self._dispose(fiber, restore))
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
@staticmethod
|
|
128
|
+
def make[R2, ER2](
|
|
129
|
+
layer: Layer[R2, ER2, Never], *, memo_map: MemoMap | None = None
|
|
130
|
+
) -> ManagedRuntime[R2, ER2]:
|
|
131
|
+
"""make, :325-331. Nothing is built until the first request."""
|
|
132
|
+
return ManagedRuntime(layer, memo_map)
|
|
133
|
+
|
|
134
|
+
# -- read-only views (upstream fields; read-only here so R stays contravariant) -------------
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def cached_context(self) -> Context[R] | None:
|
|
138
|
+
"""The built context once the build succeeded, until disposal claims (:364-369, :419)."""
|
|
139
|
+
return self._cached_context
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def context_effect(self) -> Effect[Context[R], ER, Never]:
|
|
143
|
+
"""Join (or start) the build; after disposal, a defect (:361-383, :418)."""
|
|
144
|
+
return self._context_effect
|
|
145
|
+
|
|
146
|
+
# -- start hooks (:340-358, :372-378) ---------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
def _on_fiber_start(self, fiber: Fiber[Any, Any]) -> None:
|
|
149
|
+
self._managed.add(fiber)
|
|
150
|
+
if fiber in self._disposing:
|
|
151
|
+
return
|
|
152
|
+
run_in(fiber, self._fiber_scope)
|
|
153
|
+
|
|
154
|
+
def _on_build_start(self, fiber: Fiber[Any, Any]) -> None:
|
|
155
|
+
# Unlike requests, the build joins fiberScope even if it disposed the runtime, so
|
|
156
|
+
# disposal still interrupts it (:373-377).
|
|
157
|
+
self._managed.add(fiber)
|
|
158
|
+
run_in(fiber, self._fiber_scope)
|
|
159
|
+
|
|
160
|
+
def _merge(self, hook: _Hook | None) -> _Hook:
|
|
161
|
+
"""mergeRunOptions, :347-358: the runtime's hook first, then the caller's."""
|
|
162
|
+
if hook is None:
|
|
163
|
+
return self._on_fiber_start
|
|
164
|
+
user = hook
|
|
165
|
+
|
|
166
|
+
def both(fiber: Fiber[Any, Any]) -> None:
|
|
167
|
+
self._on_fiber_start(fiber)
|
|
168
|
+
user(fiber)
|
|
169
|
+
|
|
170
|
+
return both
|
|
171
|
+
|
|
172
|
+
# -- contextEffect (:361-383) -----------------------------------------------------------------
|
|
173
|
+
|
|
174
|
+
def _request_context(self, fiber: Fiber[Any, Any]) -> Effect[Context[R], ER, Never]:
|
|
175
|
+
build = self._build_fiber
|
|
176
|
+
if build is None:
|
|
177
|
+
# A local function, not a method: a method taking Context[R] would make pyright
|
|
178
|
+
# infer R invariant (private attributes are left out of variance inference).
|
|
179
|
+
def cache(context: Context[R]) -> Context[R]: # :364-369
|
|
180
|
+
self._cached_context = context
|
|
181
|
+
return context
|
|
182
|
+
|
|
183
|
+
scheduler: SchedulerService = fiber.context.get(Scheduler.key, DEFAULT_SCHEDULER)
|
|
184
|
+
built = Layer.build_with_memo_map(self._layer, self.memo_map, self._layer_scope)
|
|
185
|
+
build = self._build_fiber = run_fork(
|
|
186
|
+
built.flat_map(lambda context: sync(lambda: cache(context))),
|
|
187
|
+
scheduler=scheduler, # fiber.cache.scheduler, :372
|
|
188
|
+
on_fiber_start=self._on_build_start,
|
|
189
|
+
)
|
|
190
|
+
return build.await_().flat_map(_flatten)
|
|
191
|
+
|
|
192
|
+
# -- disposeEffect (:401-424) -----------------------------------------------------------------
|
|
193
|
+
|
|
194
|
+
def _dispose(self, fiber: Fiber[Any, Any], restore: _Restore) -> Effect[None, Never, Never]:
|
|
195
|
+
inherited: frozenset[ManagedRuntime[Any, Any]] = fiber.context.get(
|
|
196
|
+
_DisposingRuntimes.key, _DisposingRuntimes.default()
|
|
197
|
+
)
|
|
198
|
+
done = self._disposed
|
|
199
|
+
if done is not None:
|
|
200
|
+
if self in inherited: # a finalizer of this disposal (:403)
|
|
201
|
+
return _VOID
|
|
202
|
+
current: Fiber[Any, Any] | None = fiber
|
|
203
|
+
while current is not None: # a managed fiber, which the close awaits (:404-406)
|
|
204
|
+
if current in self._managed:
|
|
205
|
+
return _VOID
|
|
206
|
+
current = current.parent
|
|
207
|
+
return restore(done.await_()) # waiters stay interruptible (:407)
|
|
208
|
+
# Once `disposed` is set the close must run, or later calls would wait forever (:409).
|
|
209
|
+
done = self._disposed = Deferred[None, Never].make_unsafe()
|
|
210
|
+
# Closing fiberScope interrupts and awaits every managed fiber. Exempt the disposing
|
|
211
|
+
# fiber and its ancestors, which would otherwise await themselves (:412-417).
|
|
212
|
+
current = fiber
|
|
213
|
+
while current is not None:
|
|
214
|
+
self._disposing.add(current)
|
|
215
|
+
Scope.remove_finalizer_unsafe(self._fiber_scope, current)
|
|
216
|
+
current = current.parent
|
|
217
|
+
self._context_effect = die(RuntimeError(_DISPOSED)) # :418
|
|
218
|
+
self._cached_context = None # :419
|
|
219
|
+
disposing = _DisposingRuntimes.context(inherited | {self})
|
|
220
|
+
return provide(disposing)(Scope.close(self.scope, _EXIT_VOID)).pipe(
|
|
221
|
+
ensuring(done.done(_EXIT_VOID)) # :420-423
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
# -- runners (:390-400, :425-474) -------------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
def _provided[A, E](self, effect: Effect[A, E, R]) -> Effect[A, E | ER, Never]:
|
|
227
|
+
"""provide, :466-474. Reads ``context_effect`` now, as upstream reads it at call time."""
|
|
228
|
+
return self._context_effect.flat_map(lambda context: provide(context)(effect))
|
|
229
|
+
|
|
230
|
+
def run_fork[A, E](
|
|
231
|
+
self,
|
|
232
|
+
effect: Effect[A, E, R],
|
|
233
|
+
*,
|
|
234
|
+
scheduler: SchedulerService | None = None,
|
|
235
|
+
uninterruptible: bool = False,
|
|
236
|
+
on_fiber_start: _Hook | None = None,
|
|
237
|
+
) -> Fiber[A, E | ER]:
|
|
238
|
+
"""runFork, :425-429: over the cached context once built, else through the build."""
|
|
239
|
+
hook = self._merge(on_fiber_start)
|
|
240
|
+
cached = self._cached_context
|
|
241
|
+
if cached is None:
|
|
242
|
+
return run_fork(
|
|
243
|
+
self._provided(effect),
|
|
244
|
+
scheduler=scheduler,
|
|
245
|
+
uninterruptible=uninterruptible,
|
|
246
|
+
on_fiber_start=hook,
|
|
247
|
+
)
|
|
248
|
+
return run_fork_with(cached)(
|
|
249
|
+
effect, scheduler=scheduler, uninterruptible=uninterruptible, on_fiber_start=hook
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
async def run_exit[A, E](
|
|
253
|
+
self,
|
|
254
|
+
effect: Effect[A, E, R],
|
|
255
|
+
*,
|
|
256
|
+
scheduler: SchedulerService | None = None,
|
|
257
|
+
uninterruptible: bool = False,
|
|
258
|
+
on_fiber_start: _Hook | None = None,
|
|
259
|
+
) -> Exit[A, E | ER]:
|
|
260
|
+
"""runPromiseExit, :450-454: the request fiber's own Exit, through an observer.
|
|
261
|
+
Cancelling the awaiting task interrupts that fiber (``await_exit``)."""
|
|
262
|
+
fiber = self.run_fork(
|
|
263
|
+
effect,
|
|
264
|
+
scheduler=scheduler,
|
|
265
|
+
uninterruptible=uninterruptible,
|
|
266
|
+
on_fiber_start=on_fiber_start,
|
|
267
|
+
)
|
|
268
|
+
return await await_exit(fiber)
|
|
269
|
+
|
|
270
|
+
async def run[A, E](
|
|
271
|
+
self,
|
|
272
|
+
effect: Effect[A, E, R],
|
|
273
|
+
*,
|
|
274
|
+
scheduler: SchedulerService | None = None,
|
|
275
|
+
uninterruptible: bool = False,
|
|
276
|
+
on_fiber_start: _Hook | None = None,
|
|
277
|
+
) -> A:
|
|
278
|
+
"""runPromise, :455-461: the value, or the squashed cause raised."""
|
|
279
|
+
exit_ = await self.run_exit(
|
|
280
|
+
effect,
|
|
281
|
+
scheduler=scheduler,
|
|
282
|
+
uninterruptible=uninterruptible,
|
|
283
|
+
on_fiber_start=on_fiber_start,
|
|
284
|
+
)
|
|
285
|
+
if isinstance(exit_, Success):
|
|
286
|
+
return exit_.value
|
|
287
|
+
raise exit_.cause.squash()
|
|
288
|
+
|
|
289
|
+
async def context(self) -> Context[R]:
|
|
290
|
+
"""context, :390-394: the cached context, or ``context_effect`` run as an unmanaged
|
|
291
|
+
root (no runtime hook)."""
|
|
292
|
+
cached = self._cached_context
|
|
293
|
+
if cached is not None:
|
|
294
|
+
return cached
|
|
295
|
+
exit_ = await run_exit(self._context_effect)
|
|
296
|
+
if isinstance(exit_, Success):
|
|
297
|
+
return exit_.value
|
|
298
|
+
raise exit_.cause.squash()
|
|
299
|
+
|
|
300
|
+
async def dispose(self) -> None:
|
|
301
|
+
"""dispose, :395-397: ``dispose_effect`` as an unmanaged root."""
|
|
302
|
+
await run(self.dispose_effect)
|
|
303
|
+
|
|
304
|
+
async def __aenter__(self) -> Self:
|
|
305
|
+
return self
|
|
306
|
+
|
|
307
|
+
async def __aexit__(self, *_: object) -> None:
|
|
308
|
+
"""Symbol.asyncDispose, :398-400."""
|
|
309
|
+
await self.dispose()
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
_EXIT_VOID: Exit[None, Never] = Success(None)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _flatten[A, E](exit_: Exit[A, E]) -> Effect[A, E, Never]:
|
|
316
|
+
"""Effect.flatten over Fiber.await: continue as the build ended (:382)."""
|
|
317
|
+
return exit_
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def is_managed_runtime(value: object) -> bool:
|
|
321
|
+
"""isManagedRuntime, :51."""
|
|
322
|
+
return isinstance(value, ManagedRuntime)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
__all__ = ["ManagedRuntime", "is_managed_runtime"]
|
peffect/option.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Option: a value that may be absent, with presence carried by a wrapper, not by the value.
|
|
2
|
+
|
|
3
|
+
Pinned Effect v4 Option.ts:266-385 and internal/option.ts:28-100: `some(a)` is `Some(a)`,
|
|
4
|
+
`none()` is `None`. `Some(None)` is present, so a computation returning None stays
|
|
5
|
+
distinguishable from no result. Only construction, the value and structural equality are ported.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import final
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@final
|
|
14
|
+
class Some[A]:
|
|
15
|
+
"""A present value. Equal and hashed by value, like internal/option.ts:32-39. Covariant like
|
|
16
|
+
upstream's `Some<out A>` (Option.ts:133): the value is a read-only property and the instance
|
|
17
|
+
rejects every write, so a Some[int] is a Some[object]. A frozen dataclass would type `value`
|
|
18
|
+
as a mutable field and make A invariant."""
|
|
19
|
+
|
|
20
|
+
__slots__ = ("_value",)
|
|
21
|
+
__match_args__ = ("value",)
|
|
22
|
+
|
|
23
|
+
def __init__(self, value: A) -> None:
|
|
24
|
+
object.__setattr__(self, "_value", value)
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def value(self) -> A:
|
|
28
|
+
return self._value
|
|
29
|
+
|
|
30
|
+
def __setattr__(self, name: str, value: object) -> None:
|
|
31
|
+
raise AttributeError(f"Some is immutable: cannot set {name!r}")
|
|
32
|
+
|
|
33
|
+
def __delattr__(self, name: str) -> None:
|
|
34
|
+
raise AttributeError(f"Some is immutable: cannot delete {name!r}")
|
|
35
|
+
|
|
36
|
+
def _key(self) -> object:
|
|
37
|
+
"""The value as `object`: comparable across differently parameterized Somes."""
|
|
38
|
+
return self._value
|
|
39
|
+
|
|
40
|
+
def __eq__(self, other: object) -> bool:
|
|
41
|
+
return isinstance(other, Some) and bool(self._key() == other._key())
|
|
42
|
+
|
|
43
|
+
def __hash__(self) -> int:
|
|
44
|
+
return hash((Some, self._value))
|
|
45
|
+
|
|
46
|
+
def __repr__(self) -> str:
|
|
47
|
+
return f"Some({self._value!r})"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
type Option[A] = Some[A] | None
|
peffect/pull.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""The completion prefix of Effect v4 Pull, pinned at 289a53f7.
|
|
2
|
+
|
|
3
|
+
Done is an ordinary typed failure, so a pull is already an Effect. This module
|
|
4
|
+
ports only the predicates, filter, terminal conversion and handler needed by
|
|
5
|
+
Queue. It does not claim the remaining Pull surface or introduce a wrapper type.
|
|
6
|
+
|
|
7
|
+
Python adaptation: filter_done uses Exit[Done[L], E] where upstream uses
|
|
8
|
+
Result<Done<L>, Cause<E>>. Its Failure contains the remaining Cause unchanged.
|
|
9
|
+
Exact-Done-first overloads express ExcludeDone at the public boundary; the
|
|
10
|
+
filter implementation works on object-typed reasons and narrows actual values.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from typing import Never, TypeIs, overload
|
|
15
|
+
|
|
16
|
+
from .cause import Cause, Die, Done, Fail, Interrupt, is_done
|
|
17
|
+
from .core import Effect, Exit, Failure, Success, fail
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@overload
|
|
21
|
+
def done() -> Effect[Never, Done[None], Never]: ...
|
|
22
|
+
@overload
|
|
23
|
+
def done[L](value: L) -> Effect[Never, Done[L], Never]: ...
|
|
24
|
+
def done(value: object = None) -> Effect[Never, Done[object], Never]:
|
|
25
|
+
"""Fail with normal completion (internal/core.ts:765-767)."""
|
|
26
|
+
return fail(Done(value))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def is_done_failure(reason: Fail[object] | Die | Interrupt) -> TypeIs[Fail[Done[object]]]:
|
|
30
|
+
"""Pull.ts:213-215: a Done value in Die is not a completion failure."""
|
|
31
|
+
return isinstance(reason, Fail) and is_done(reason.error)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def is_done_cause(cause: Cause[object]) -> bool:
|
|
35
|
+
"""Pull.ts:195: true even when Done was merged with another failure."""
|
|
36
|
+
return any(is_done_failure(reason) for reason in cause.reasons)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@overload
|
|
40
|
+
def filter_done(cause: Cause[Never]) -> Exit[Never, Never]: ...
|
|
41
|
+
@overload
|
|
42
|
+
def filter_done[L = Never](cause: Cause[Done[L]]) -> Exit[Done[L], Never]: ...
|
|
43
|
+
@overload
|
|
44
|
+
def filter_done[E, L = Never](cause: Cause[E | Done[L]]) -> Exit[Done[L], E]: ...
|
|
45
|
+
def filter_done(cause: Cause[object]) -> Exit[Done[object], object]:
|
|
46
|
+
"""Pull.ts:238-256: recover Done only without other non-interrupt reasons."""
|
|
47
|
+
found: Done[object] | None = None
|
|
48
|
+
remaining: list[Fail[object] | Die | Interrupt] = []
|
|
49
|
+
has_failure = False
|
|
50
|
+
for reason in cause.reasons:
|
|
51
|
+
if is_done_failure(reason):
|
|
52
|
+
if found is None:
|
|
53
|
+
found = reason.error
|
|
54
|
+
else:
|
|
55
|
+
remaining.append(reason)
|
|
56
|
+
if not isinstance(reason, Interrupt):
|
|
57
|
+
has_failure = True
|
|
58
|
+
if found is None:
|
|
59
|
+
return Failure(cause)
|
|
60
|
+
if has_failure:
|
|
61
|
+
return Failure(Cause(tuple(remaining)))
|
|
62
|
+
return Success(found)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@overload
|
|
66
|
+
def done_exit_from_cause(cause: Cause[Never]) -> Exit[Never, Never]: ...
|
|
67
|
+
@overload
|
|
68
|
+
def done_exit_from_cause[L = Never](cause: Cause[Done[L]]) -> Exit[L, Never]: ...
|
|
69
|
+
@overload
|
|
70
|
+
def done_exit_from_cause[E, L = Never](cause: Cause[E | Done[L]]) -> Exit[L, E]: ...
|
|
71
|
+
def done_exit_from_cause(cause: Cause[object]) -> Exit[object, object]:
|
|
72
|
+
"""Pull.ts:354-357: expose the leftover or the filtered failure cause."""
|
|
73
|
+
result = filter_done(cause)
|
|
74
|
+
if isinstance(result, Failure):
|
|
75
|
+
return result
|
|
76
|
+
return Success(result.value.value)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@overload
|
|
80
|
+
def catch_done[L, E2, R](
|
|
81
|
+
effect: Effect[Never, Done[L], R], handler: Callable[[L], Effect[Never, E2, R]]
|
|
82
|
+
) -> Effect[Never, E2, R]: ...
|
|
83
|
+
@overload
|
|
84
|
+
def catch_done[A, L, R, B, E2](
|
|
85
|
+
effect: Effect[A, Done[L], R], handler: Callable[[L], Effect[B, E2, R]]
|
|
86
|
+
) -> Effect[A | B, E2, R]: ...
|
|
87
|
+
@overload
|
|
88
|
+
def catch_done[E, L, R, E2](
|
|
89
|
+
effect: Effect[Never, E | Done[L], R], handler: Callable[[L], Effect[Never, E2, R]]
|
|
90
|
+
) -> Effect[Never, E | E2, R]: ...
|
|
91
|
+
@overload
|
|
92
|
+
def catch_done[A, E, L, R, B, E2](
|
|
93
|
+
effect: Effect[A, E | Done[L], R], handler: Callable[[L], Effect[B, E2, R]]
|
|
94
|
+
) -> Effect[A | B, E | E2, R]: ...
|
|
95
|
+
def catch_done[A, E, L, R, B, E2](
|
|
96
|
+
effect: Effect[A, E | Done[L], R], handler: Callable[[L], Effect[B, E2, R]]
|
|
97
|
+
) -> Effect[A | B, E | E2, R]:
|
|
98
|
+
"""Pull.ts:165-177: handle leftover completion, preserving real failures."""
|
|
99
|
+
|
|
100
|
+
def recover(cause: Cause[E | Done[L]]) -> Effect[B, E | E2, R]:
|
|
101
|
+
result = filter_done(cause)
|
|
102
|
+
if isinstance(result, Failure):
|
|
103
|
+
return result
|
|
104
|
+
return handler(result.value.value)
|
|
105
|
+
|
|
106
|
+
return effect.catch_cause(recover)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
__all__ = [
|
|
110
|
+
"catch_done",
|
|
111
|
+
"done",
|
|
112
|
+
"done_exit_from_cause",
|
|
113
|
+
"filter_done",
|
|
114
|
+
"is_done_cause",
|
|
115
|
+
"is_done_failure",
|
|
116
|
+
]
|
peffect/py.typed
ADDED
|
File without changes
|