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/context.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
"""Services: Tag, Reference, Context, provide. Built on the kernel's update_context.
|
|
2
|
+
|
|
3
|
+
class Users(Tag[UserRepo], key="app/Users"): ... # the key is the identity; R gains Users
|
|
4
|
+
repo = yield from Users() # Effect[UserRepo, Never, Users]
|
|
5
|
+
provide(Users.context(impl))(program) # removes Users from program's R
|
|
6
|
+
|
|
7
|
+
Effect v4: Context.ts (Service, Reference), internal/effect.ts:2379-2397 (provideContext).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from collections.abc import Callable, Generator, Mapping
|
|
14
|
+
from types import MappingProxyType
|
|
15
|
+
from typing import Any, ClassVar, Generic, Never, Self, TypeVar, cast, final, overload
|
|
16
|
+
|
|
17
|
+
from .core import ContextMap, Effect, WithFiber, die, succeed, update_context
|
|
18
|
+
from .fiber import Fiber, RootRunner, SchedulerService
|
|
19
|
+
|
|
20
|
+
T_contra = TypeVar("T_contra", contravariant=True)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MissingService(Exception):
|
|
24
|
+
"""A tag was read with no service provided: a defect, since the types should prevent it."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, tag: type[Tag[Any]]) -> None:
|
|
27
|
+
super().__init__("Service not found" + (f": {tag.key}" if tag.key else ""))
|
|
28
|
+
self.tag = tag
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Tag[S]:
|
|
32
|
+
"""Subclass once per service: ``class Users(Tag[UserRepo], key="app/Users"): ...``.
|
|
33
|
+
|
|
34
|
+
The explicit ``key`` string is the runtime identity, as Effect v4's
|
|
35
|
+
``Context.Service("app/Users")`` (Context.ts:256-262): two declarations with one key read and
|
|
36
|
+
replace the same service. The class stays the static R. A concrete tag can't be subclassed:
|
|
37
|
+
R is covariant, and a parent tag's context would type-check against a child tag's request
|
|
38
|
+
under another key. ``__init_subclass__`` enforces both rules; there is no default key.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
__slots__ = ()
|
|
42
|
+
key: ClassVar[str]
|
|
43
|
+
|
|
44
|
+
def __init_subclass__(cls, *, key: str | None = None, **kwargs: Any) -> None:
|
|
45
|
+
super().__init_subclass__(**kwargs)
|
|
46
|
+
for base in cls.__bases__:
|
|
47
|
+
if issubclass(base, Tag) and base.__module__ != __name__: # Tag, Reference are roots
|
|
48
|
+
raise TypeError(f"{cls.__name__}: tag {base.__name__} is concrete; subclass Tag")
|
|
49
|
+
if cls.__module__ == __name__:
|
|
50
|
+
return
|
|
51
|
+
if not isinstance(key, str): # also catches key=1 from types.new_class
|
|
52
|
+
raise TypeError(f"{cls.__name__}: declare its key, class {cls.__name__}(..., key=...)")
|
|
53
|
+
cls.key = key
|
|
54
|
+
|
|
55
|
+
def __iter__(self) -> Generator[Effect[S, Never, Self], Any, S]:
|
|
56
|
+
return (yield from self.use())
|
|
57
|
+
|
|
58
|
+
def use(self) -> Effect[S, Never, Self]:
|
|
59
|
+
key = type(self)
|
|
60
|
+
return WithFiber(lambda fiber: key._find(fiber.context))
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def _find(cls, context: ContextMap) -> Effect[S, Never, Never]:
|
|
64
|
+
key = cls.key
|
|
65
|
+
return succeed(context[key]) if key in context else die(MissingService(cls))
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def context(cls, service: S) -> Context[Self]:
|
|
69
|
+
"""The context holding just this service. Combine with ``|``; the right side wins."""
|
|
70
|
+
if cls.__module__ == __name__:
|
|
71
|
+
raise TypeError(f"subclass {cls.__name__} per service, then call .context on it")
|
|
72
|
+
return Context({cls.key: service}, _TOKEN)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Reference[S](Tag[S]):
|
|
76
|
+
"""A service with a default, so using it never adds to R. Define ``default``.
|
|
77
|
+
|
|
78
|
+
The default is built on first use and kept on the class: one value for every fiber and
|
|
79
|
+
every run, until a provide overrides it (Effect v4 Context.ts:1091-1096). A raising default
|
|
80
|
+
is a defect and is not kept, so the next use calls it again.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
__slots__ = ()
|
|
84
|
+
_default_value: ClassVar[Any]
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def default(cls) -> S:
|
|
88
|
+
raise NotImplementedError(f"{cls.__name__} must define default()")
|
|
89
|
+
|
|
90
|
+
def __iter__(self) -> Generator[Effect[S, Never, Never], Any, S]:
|
|
91
|
+
return (yield from self.use())
|
|
92
|
+
|
|
93
|
+
def use(self) -> Effect[S, Never, Never]:
|
|
94
|
+
key = type(self)
|
|
95
|
+
return WithFiber(lambda fiber: key._find(fiber.context))
|
|
96
|
+
|
|
97
|
+
@classmethod
|
|
98
|
+
def _find(cls, context: ContextMap) -> Effect[S, Never, Never]:
|
|
99
|
+
if cls.key in context:
|
|
100
|
+
return succeed(context[cls.key])
|
|
101
|
+
# per declaration, not per key (Context.ts:1091-1096)
|
|
102
|
+
if "_default_value" not in cls.__dict__: # own dict: a cache is never inherited
|
|
103
|
+
cls._default_value = cls.default()
|
|
104
|
+
return succeed(cls._default_value)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@final
|
|
108
|
+
class _Token:
|
|
109
|
+
__slots__ = ()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
_TOKEN = _Token()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _equal_values(left: Any, right: Any, path: set[tuple[int, int]]) -> bool:
|
|
116
|
+
"""Equal.ts:186-238: identity, NaN, and coinductive container comparison.
|
|
117
|
+
|
|
118
|
+
Python lists/tuples and dict values recurse; other service objects retain their Python
|
|
119
|
+
equality protocol. Path assumptions are local to this comparison, never cached globally.
|
|
120
|
+
"""
|
|
121
|
+
if left is right:
|
|
122
|
+
return True
|
|
123
|
+
if type(left) in (int, float) and type(right) in (int, float):
|
|
124
|
+
return bool(left == right) or (
|
|
125
|
+
isinstance(left, float)
|
|
126
|
+
and isinstance(right, float)
|
|
127
|
+
and math.isnan(left)
|
|
128
|
+
and math.isnan(right)
|
|
129
|
+
)
|
|
130
|
+
if type(left) is not type(right):
|
|
131
|
+
return False
|
|
132
|
+
pair = (id(left), id(right))
|
|
133
|
+
if pair in path:
|
|
134
|
+
return True
|
|
135
|
+
path.add(pair)
|
|
136
|
+
try:
|
|
137
|
+
if isinstance(left, (list, tuple)):
|
|
138
|
+
a, b = cast(list[Any] | tuple[Any, ...], left), cast(list[Any] | tuple[Any, ...], right)
|
|
139
|
+
return len(a) == len(b) and all(
|
|
140
|
+
_equal_values(x, y, path) for x, y in zip(a, b, strict=True)
|
|
141
|
+
)
|
|
142
|
+
if isinstance(left, dict):
|
|
143
|
+
a_map, b_map = cast(dict[Any, Any], left), cast(dict[Any, Any], right)
|
|
144
|
+
return len(a_map) == len(b_map) and all(
|
|
145
|
+
key in b_map and _equal_values(value, b_map[key], path)
|
|
146
|
+
for key, value in a_map.items()
|
|
147
|
+
)
|
|
148
|
+
return bool(left == right)
|
|
149
|
+
finally:
|
|
150
|
+
path.remove(pair)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@final
|
|
154
|
+
class Context(Generic[T_contra]):
|
|
155
|
+
"""Services for the tags in T, built only by ``Users.context(impl)`` and ``a | b``.
|
|
156
|
+
|
|
157
|
+
So a ``Context[Users]`` always holds a Users service, which is what lets ``provide`` take
|
|
158
|
+
Users out of R. Contravariant: one holding more tags stands in for one holding fewer.
|
|
159
|
+
"""
|
|
160
|
+
|
|
161
|
+
__slots__ = ("_services",)
|
|
162
|
+
|
|
163
|
+
def __init__(self, services: dict[str, Any], token: _Token) -> None:
|
|
164
|
+
if token is not _TOKEN:
|
|
165
|
+
raise TypeError("build a Context with Users.context(impl), not Context(...)")
|
|
166
|
+
self._services: Mapping[str, Any] = MappingProxyType(services)
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def services(self) -> Mapping[str, Any]:
|
|
170
|
+
"""Services by key string, in insertion order."""
|
|
171
|
+
return self._services
|
|
172
|
+
|
|
173
|
+
@staticmethod
|
|
174
|
+
def empty() -> Context[Never]:
|
|
175
|
+
"""The context with no services: one shared, immutable instance (Context.ts:744-745)."""
|
|
176
|
+
return _EMPTY
|
|
177
|
+
|
|
178
|
+
def __or__[T, T2](self: Context[T], other: Context[T2]) -> Context[T | T2]:
|
|
179
|
+
# an empty side returns the other one itself (Context.ts:1192-1193). Only empty() is
|
|
180
|
+
# empty (every other context is built from a tag), so the empty side's T is Never.
|
|
181
|
+
if not self.services:
|
|
182
|
+
return cast(Context[T | T2], other)
|
|
183
|
+
if not other.services:
|
|
184
|
+
return cast(Context[T | T2], self)
|
|
185
|
+
return Context({**self.services, **other.services}, _TOKEN)
|
|
186
|
+
|
|
187
|
+
def __eq__(self, other: object) -> bool:
|
|
188
|
+
"""Same keys, equal values, in any order; only another Context (Context.ts:637-645).
|
|
189
|
+
Values use identity, NaN and recursive container equality, then Python object equality."""
|
|
190
|
+
if not isinstance(other, Context):
|
|
191
|
+
return False
|
|
192
|
+
mine, theirs = self.services, cast(Context[Any], other).services
|
|
193
|
+
return len(mine) == len(theirs) and all(
|
|
194
|
+
k in theirs and _equal_values(v, theirs[k], set()) for k, v in mine.items()
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def __hash__(self) -> int:
|
|
198
|
+
return len(self.services) # the size, as upstream (Context.ts:646-648)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
_EMPTY: Context[Never] = Context({}, _TOKEN)
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@final
|
|
205
|
+
class provide[T]:
|
|
206
|
+
"""``provide(ctx)(program)``: run program with ctx's services added to the current ones.
|
|
207
|
+
|
|
208
|
+
Removes ctx's tags from R. Python has no ``Exclude``, so two overloads cover it: R is
|
|
209
|
+
covered by T (result R is Never), or R is a union that names T's tags (the rest stays).
|
|
210
|
+
Anything else, such as a bare type variable, keeps its requirement.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
__slots__ = ("_ctx",)
|
|
214
|
+
|
|
215
|
+
def __init__(self, ctx: Context[T]) -> None:
|
|
216
|
+
self._ctx = ctx
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def ctx(self) -> Context[T]:
|
|
220
|
+
return self._ctx
|
|
221
|
+
|
|
222
|
+
# exact match first: matching `T | R` against plain `T` would leave R unsolved
|
|
223
|
+
@overload
|
|
224
|
+
def __call__[A, E](self, eff: Effect[A, E, T]) -> Effect[A, E, Never]: ...
|
|
225
|
+
@overload
|
|
226
|
+
def __call__[A, E, R](self, eff: Effect[A, E, T | R]) -> Effect[A, E, R]: ...
|
|
227
|
+
def __call__(self, eff: Effect[Any, Any, Any]) -> Effect[Any, Any, Any]:
|
|
228
|
+
services = self.ctx.services
|
|
229
|
+
return update_context(eff, lambda old: {**old, **services})
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@final
|
|
233
|
+
class run_fork_with[R]:
|
|
234
|
+
"""Start roots with requirements supplied by this Context (effect.ts:5773-5777).
|
|
235
|
+
|
|
236
|
+
R is fixed by construction, so calling the runner cannot infer away a missing service.
|
|
237
|
+
The raw-map runner stays in the kernel; callers use this typed boundary.
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
__slots__ = ("_ctx",)
|
|
241
|
+
|
|
242
|
+
def __init__(self, ctx: Context[R]) -> None:
|
|
243
|
+
self._ctx = ctx
|
|
244
|
+
|
|
245
|
+
def __call__[A, E](
|
|
246
|
+
self,
|
|
247
|
+
eff: Effect[A, E, R],
|
|
248
|
+
*,
|
|
249
|
+
scheduler: SchedulerService | None = None,
|
|
250
|
+
uninterruptible: bool = False,
|
|
251
|
+
on_fiber_start: Callable[[Fiber[Any, Any]], object] | None = None,
|
|
252
|
+
) -> Fiber[A, E]:
|
|
253
|
+
return RootRunner(self._ctx.services)(
|
|
254
|
+
eff,
|
|
255
|
+
scheduler=scheduler,
|
|
256
|
+
uninterruptible=uninterruptible,
|
|
257
|
+
on_fiber_start=on_fiber_start,
|
|
258
|
+
)
|