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
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"""TestClock: a Clock whose time moves only when the test moves it.
|
|
2
|
+
|
|
3
|
+
provide_layer(TestClock.layer())(program) # Clock and Scheduler for the program
|
|
4
|
+
yield from fork(sleep("1 hour").flat_map(...))
|
|
5
|
+
yield from TestClock.adjust("1 hour") # wakes the sleeper, waits for it to settle
|
|
6
|
+
|
|
7
|
+
Sleeps register a deadline and park; ``adjust`` and ``set_time`` wake every deadline they pass,
|
|
8
|
+
in time order, moving the clock to each deadline first. After each wake the clock waits until
|
|
9
|
+
the dispatcher tasks the wake scheduled have run (the layer's tracking scheduler counts them),
|
|
10
|
+
or ``warning_delay`` of live time, then prints a busy warning and goes on. A sleep on a clock
|
|
11
|
+
nobody advances prints a warning after ``warning_delay``, through the live Console and live
|
|
12
|
+
Clock; ``adjust``, ``set_time`` and closing the clock's Scope stop it.
|
|
13
|
+
|
|
14
|
+
Effect v4: src/testing/TestClock.ts. Adaptations: ``copy.copy`` of a clock shares its state
|
|
15
|
+
(upstream's own-arrow methods survive a spread); ``repr`` stands in for ``toJSON``; a Clock that
|
|
16
|
+
is a TestClock (or a copy) is its own way back to the live clock, where upstream keeps a WeakMap
|
|
17
|
+
of the clocks ``make`` built; ``test_clock_with`` dies with a TypeError on another Clock, where
|
|
18
|
+
upstream casts.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import math
|
|
24
|
+
from collections.abc import Callable, Generator
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from typing import Any, ClassVar, Literal, Never, Protocol, final
|
|
27
|
+
|
|
28
|
+
from ..clock import Clock, ClockService, sleep
|
|
29
|
+
from ..console import Console, ConsoleService
|
|
30
|
+
from ..core import (
|
|
31
|
+
Effect,
|
|
32
|
+
async_,
|
|
33
|
+
die,
|
|
34
|
+
gen,
|
|
35
|
+
succeed,
|
|
36
|
+
suspend,
|
|
37
|
+
sync,
|
|
38
|
+
update_context,
|
|
39
|
+
yield_now,
|
|
40
|
+
)
|
|
41
|
+
from ..duration import Duration, Input, from_input_unsafe, to_millis, to_nanos_unsafe
|
|
42
|
+
from ..fiber import Fiber, SchedulerDispatcher, SchedulerService, fork
|
|
43
|
+
from ..latch import Latch
|
|
44
|
+
from ..layer import Layer
|
|
45
|
+
from ..logger import log_warning
|
|
46
|
+
from ..resources import acquire_use_release, add_finalizer
|
|
47
|
+
from ..scheduler import Scheduler
|
|
48
|
+
from ..scope import Scope
|
|
49
|
+
from ..semaphore import Semaphore
|
|
50
|
+
from ..timeout import timeout_or_else
|
|
51
|
+
|
|
52
|
+
WARNING_MESSAGE = (
|
|
53
|
+
"A test is using time, but is not advancing the test clock, which may result in the test "
|
|
54
|
+
"hanging. Use TestClock.adjust to manually advance the time."
|
|
55
|
+
)
|
|
56
|
+
BUSY_WARNING_MESSAGE = (
|
|
57
|
+
"A fiber woken by the test clock is still running without suspending, so the test clock "
|
|
58
|
+
"stopped waiting for it. Sleeps it starts later may be scheduled relative to a later time."
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
type _Void = Effect[None, Never, Never]
|
|
62
|
+
type _Warning = Literal["start", "done"] | Fiber[None, Never]
|
|
63
|
+
"""TestClock.ts WarningState: Start, Pending (the warning fiber), Done."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class TestClockService(ClockService, Protocol):
|
|
67
|
+
"""A Clock the test drives (TestClock.ts `TestClock`)."""
|
|
68
|
+
|
|
69
|
+
def adjust(self, duration: Input) -> _Void: ...
|
|
70
|
+
def set_time(self, timestamp: float) -> _Void: ...
|
|
71
|
+
def with_live[A, E, R](self, eff: Effect[A, E, R]) -> Effect[A, E, R]: ...
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@final
|
|
75
|
+
@dataclass(slots=True, eq=False) # identity: release removes this entry, not an equal one
|
|
76
|
+
class _Sleep:
|
|
77
|
+
timestamp: float
|
|
78
|
+
latch: Latch = field(default_factory=Latch.make_unsafe)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@final
|
|
82
|
+
@dataclass(slots=True)
|
|
83
|
+
class _WakeTracker:
|
|
84
|
+
"""Dispatcher tasks a wake scheduled that have not finished yet."""
|
|
85
|
+
|
|
86
|
+
pending: int = 0
|
|
87
|
+
on_idle: Callable[[], None] | None = None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _millis_to_nanos(millis: float) -> int:
|
|
91
|
+
"""millisToNanos (TestClock.ts:234-238): whole millis, plus the fraction's nanos floored."""
|
|
92
|
+
whole = math.floor(millis)
|
|
93
|
+
return whole * 1_000_000 + math.floor((millis - whole) * 1_000_000)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _js_round(x: float) -> int:
|
|
97
|
+
"""Math.round: half up, so 2.5 gives 3 (Python's round gives 2)."""
|
|
98
|
+
floor = math.floor(x)
|
|
99
|
+
return floor + 1 if x - floor >= 0.5 else floor
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@final
|
|
103
|
+
class _State:
|
|
104
|
+
"""One clock's state, shared by the clock and every copy of it."""
|
|
105
|
+
|
|
106
|
+
__slots__ = (
|
|
107
|
+
"current_tracker",
|
|
108
|
+
"live_clock",
|
|
109
|
+
"live_console",
|
|
110
|
+
"mono",
|
|
111
|
+
"now",
|
|
112
|
+
"run_semaphore",
|
|
113
|
+
"sleeps",
|
|
114
|
+
"wall",
|
|
115
|
+
"warning",
|
|
116
|
+
"warning_delay",
|
|
117
|
+
"warning_semaphore",
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def __init__(
|
|
121
|
+
self, warning_delay: Input, live_clock: ClockService, live_console: ConsoleService
|
|
122
|
+
) -> None:
|
|
123
|
+
self.warning_delay = warning_delay
|
|
124
|
+
self.live_clock = live_clock
|
|
125
|
+
self.live_console = live_console
|
|
126
|
+
self.sleeps: list[_Sleep] = [] # descending timestamp: pop() is the earliest
|
|
127
|
+
self.warning_semaphore = Semaphore.make_unsafe(1)
|
|
128
|
+
self.run_semaphore = Semaphore.make_unsafe(1)
|
|
129
|
+
self.now: float = 0
|
|
130
|
+
self.wall = 0
|
|
131
|
+
self.mono = 0
|
|
132
|
+
self.warning: _Warning = "start"
|
|
133
|
+
self.current_tracker: _WakeTracker | None = None
|
|
134
|
+
|
|
135
|
+
def set_warning(self, warning: _Warning) -> None:
|
|
136
|
+
self.warning = warning
|
|
137
|
+
|
|
138
|
+
def run_tracked(self, tracker: _WakeTracker, f: Callable[[], object]) -> None:
|
|
139
|
+
previous = self.current_tracker
|
|
140
|
+
self.current_tracker = tracker
|
|
141
|
+
try:
|
|
142
|
+
f()
|
|
143
|
+
finally:
|
|
144
|
+
self.current_tracker = previous
|
|
145
|
+
|
|
146
|
+
def advance_to(self, timestamp: float) -> None:
|
|
147
|
+
delta = timestamp - self.now
|
|
148
|
+
if delta > 0 and math.isfinite(delta):
|
|
149
|
+
self.mono += _js_round(delta * 1_000_000)
|
|
150
|
+
if math.isfinite(timestamp):
|
|
151
|
+
self.wall = _millis_to_nanos(timestamp)
|
|
152
|
+
self.now = timestamp
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@final
|
|
156
|
+
class _TestClock:
|
|
157
|
+
"""A TestClock. ``copy.copy`` gives another handle on the same clock."""
|
|
158
|
+
|
|
159
|
+
__slots__ = ("_s",)
|
|
160
|
+
|
|
161
|
+
def __init__(self, state: _State) -> None:
|
|
162
|
+
self._s = state
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def live_clock(self) -> ClockService:
|
|
166
|
+
"""The clock this one was made over (upstream's liveClocks WeakMap entry)."""
|
|
167
|
+
return self._s.live_clock
|
|
168
|
+
|
|
169
|
+
def __repr__(self) -> str:
|
|
170
|
+
return f"TestClock(current_time_millis={self._s.now!r})"
|
|
171
|
+
|
|
172
|
+
def current_time_millis_unsafe(self) -> float:
|
|
173
|
+
return self._s.now
|
|
174
|
+
|
|
175
|
+
def current_time_nanos_unsafe(self) -> int:
|
|
176
|
+
return self._s.wall
|
|
177
|
+
|
|
178
|
+
def monotonic_time_nanos_unsafe(self) -> int:
|
|
179
|
+
return self._s.mono
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def current_time_millis(self) -> Effect[float, Never, Never]:
|
|
183
|
+
return sync(self.current_time_millis_unsafe)
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def current_time_nanos(self) -> Effect[int, Never, Never]:
|
|
187
|
+
return sync(self.current_time_nanos_unsafe)
|
|
188
|
+
|
|
189
|
+
@property
|
|
190
|
+
def monotonic_time_nanos(self) -> Effect[int, Never, Never]:
|
|
191
|
+
return sync(self.monotonic_time_nanos_unsafe)
|
|
192
|
+
|
|
193
|
+
def with_live[A, E, R](self, eff: Effect[A, E, R]) -> Effect[A, E, R]:
|
|
194
|
+
"""Run ``eff`` on the clock that was in place when this one was made."""
|
|
195
|
+
live = self._s.live_clock
|
|
196
|
+
return update_context(eff, lambda old: {**old, Clock.key: live})
|
|
197
|
+
|
|
198
|
+
def sleep(self, duration: Duration) -> _Void:
|
|
199
|
+
s = self._s
|
|
200
|
+
|
|
201
|
+
def go() -> _Void:
|
|
202
|
+
end = s.now + to_millis(duration)
|
|
203
|
+
if end <= s.now:
|
|
204
|
+
return succeed(None)
|
|
205
|
+
|
|
206
|
+
def insert() -> _Sleep:
|
|
207
|
+
# before entries with an equal timestamp, so they wake in sleep order
|
|
208
|
+
entry, low, high = _Sleep(end), 0, len(s.sleeps)
|
|
209
|
+
while low < high:
|
|
210
|
+
mid = (low + high) // 2
|
|
211
|
+
if s.sleeps[mid].timestamp > end:
|
|
212
|
+
low = mid + 1
|
|
213
|
+
else:
|
|
214
|
+
high = mid
|
|
215
|
+
s.sleeps.insert(low, entry)
|
|
216
|
+
return entry
|
|
217
|
+
|
|
218
|
+
def remove(entry: _Sleep) -> None:
|
|
219
|
+
if entry in s.sleeps: # gone already if run popped it
|
|
220
|
+
s.sleeps.remove(entry)
|
|
221
|
+
|
|
222
|
+
return acquire_use_release(
|
|
223
|
+
sync(insert),
|
|
224
|
+
lambda entry: self._warning_start().flat_map(lambda _: entry.latch.await_()),
|
|
225
|
+
lambda entry, _exit: sync(lambda: remove(entry)),
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
return suspend(go)
|
|
229
|
+
|
|
230
|
+
def adjust(self, duration: Input) -> _Void:
|
|
231
|
+
decoded = from_input_unsafe(duration)
|
|
232
|
+
millis = to_millis(decoded)
|
|
233
|
+
nanos = to_nanos_unsafe(decoded) if math.isfinite(millis) else None
|
|
234
|
+
return self.warning_done().flat_map(lambda _: self._run(lambda now: now + millis, nanos))
|
|
235
|
+
|
|
236
|
+
def set_time(self, timestamp: float) -> _Void:
|
|
237
|
+
return self.warning_done().flat_map(lambda _: self._run(lambda _now: timestamp, None))
|
|
238
|
+
|
|
239
|
+
def _on_live_console(self, eff: _Void) -> _Void:
|
|
240
|
+
live = self._s.live_console
|
|
241
|
+
return update_context(eff, lambda old: {**old, Console.key: live})
|
|
242
|
+
|
|
243
|
+
def _warning_start(self) -> _Void:
|
|
244
|
+
"""warningStart: the first sleep forks the warning, a child of the sleeping fiber,
|
|
245
|
+
interruptible whatever that fiber's mask. It sleeps and logs on the live services."""
|
|
246
|
+
s = self._s
|
|
247
|
+
|
|
248
|
+
def go() -> _Void:
|
|
249
|
+
if s.warning != "start":
|
|
250
|
+
return succeed(None)
|
|
251
|
+
warn = self._on_live_console(log_warning(WARNING_MESSAGE))
|
|
252
|
+
delayed = self.with_live(sleep(s.warning_delay).flat_map(lambda _: warn))
|
|
253
|
+
return fork(delayed).flat_map(lambda fiber: sync(lambda: s.set_warning(fiber)))
|
|
254
|
+
|
|
255
|
+
return s.warning_semaphore.with_permits(1)(suspend(go))
|
|
256
|
+
|
|
257
|
+
def warning_done(self) -> _Void:
|
|
258
|
+
"""warningDone: stop a pending warning; no warning starts after this."""
|
|
259
|
+
s = self._s
|
|
260
|
+
|
|
261
|
+
def go() -> _Void:
|
|
262
|
+
state = s.warning
|
|
263
|
+
if isinstance(state, Fiber):
|
|
264
|
+
return state.interrupt().flat_map(lambda _: sync(lambda: s.set_warning("done")))
|
|
265
|
+
s.warning = "done"
|
|
266
|
+
return succeed(None)
|
|
267
|
+
|
|
268
|
+
return s.warning_semaphore.with_permits(1)(suspend(go))
|
|
269
|
+
|
|
270
|
+
def _wake(self, latch: Latch) -> _Void:
|
|
271
|
+
s = self._s
|
|
272
|
+
|
|
273
|
+
def go() -> _Void:
|
|
274
|
+
tracker = _WakeTracker()
|
|
275
|
+
s.run_tracked(tracker, latch.open_unsafe)
|
|
276
|
+
if tracker.pending == 0:
|
|
277
|
+
return yield_now
|
|
278
|
+
|
|
279
|
+
def register(resume: Callable[[_Void], None]) -> _Void | None:
|
|
280
|
+
if tracker.pending == 0:
|
|
281
|
+
resume(succeed(None))
|
|
282
|
+
return None
|
|
283
|
+
tracker.on_idle = lambda: resume(succeed(None))
|
|
284
|
+
|
|
285
|
+
def cancel() -> None:
|
|
286
|
+
tracker.on_idle = None
|
|
287
|
+
|
|
288
|
+
return sync(cancel)
|
|
289
|
+
|
|
290
|
+
def busy() -> _Void:
|
|
291
|
+
return self._on_live_console(log_warning(BUSY_WARNING_MESSAGE))
|
|
292
|
+
|
|
293
|
+
settled = timeout_or_else(async_(register), duration=s.warning_delay, or_else=busy)
|
|
294
|
+
return self.with_live(settled).flat_map(lambda _: yield_now)
|
|
295
|
+
|
|
296
|
+
return suspend(go)
|
|
297
|
+
|
|
298
|
+
def _run(self, step: Callable[[float], float], adjustment: int | None) -> _Void:
|
|
299
|
+
return self._s.run_semaphore.with_permits(1)(self._run_body(step, adjustment))
|
|
300
|
+
|
|
301
|
+
@gen
|
|
302
|
+
def _run_body(
|
|
303
|
+
self, step: Callable[[float], float], adjustment: int | None
|
|
304
|
+
) -> Generator[Effect[Any, Never, Never], Any]:
|
|
305
|
+
s = self._s
|
|
306
|
+
barrier = yield from fork(yield_now)
|
|
307
|
+
yield from barrier.await_()
|
|
308
|
+
initial_wall, initial_mono = s.wall, s.mono
|
|
309
|
+
end = step(s.now)
|
|
310
|
+
while s.sleeps:
|
|
311
|
+
if s.sleeps[-1].timestamp > end:
|
|
312
|
+
break
|
|
313
|
+
entry = s.sleeps.pop()
|
|
314
|
+
s.advance_to(entry.timestamp)
|
|
315
|
+
yield from self._wake(entry.latch)
|
|
316
|
+
s.advance_to(end)
|
|
317
|
+
if adjustment is not None and math.isfinite(end):
|
|
318
|
+
s.wall = initial_wall + adjustment
|
|
319
|
+
if adjustment > 0:
|
|
320
|
+
s.mono = initial_mono + adjustment
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
@final
|
|
324
|
+
class _TrackingScheduler:
|
|
325
|
+
"""The parent scheduler, except that a task scheduled during a wake is counted in that
|
|
326
|
+
wake's tracker, and runs with it as the current tracker, so the tasks it schedules count
|
|
327
|
+
too (TestClock.ts TrackingScheduler). Not a MixedScheduler, so fibers ask ``should_yield``
|
|
328
|
+
on every step; it answers as the parent does."""
|
|
329
|
+
|
|
330
|
+
__slots__ = ("_parent", "_state")
|
|
331
|
+
|
|
332
|
+
def __init__(self, state: _State, parent: SchedulerService) -> None:
|
|
333
|
+
self._state = state
|
|
334
|
+
self._parent = parent
|
|
335
|
+
|
|
336
|
+
@property
|
|
337
|
+
def execution_mode(self) -> Literal["sync", "async"]:
|
|
338
|
+
return self._parent.execution_mode
|
|
339
|
+
|
|
340
|
+
def should_yield(self, fiber: Fiber[Any, Any]) -> bool:
|
|
341
|
+
return self._parent.should_yield(fiber)
|
|
342
|
+
|
|
343
|
+
def make_dispatcher(self) -> SchedulerDispatcher:
|
|
344
|
+
return _TrackingDispatcher(self._state, self._parent.make_dispatcher())
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
@final
|
|
348
|
+
class _TrackingDispatcher:
|
|
349
|
+
__slots__ = ("_dispatcher", "_state")
|
|
350
|
+
|
|
351
|
+
def __init__(self, state: _State, dispatcher: SchedulerDispatcher) -> None:
|
|
352
|
+
self._state = state
|
|
353
|
+
self._dispatcher = dispatcher
|
|
354
|
+
|
|
355
|
+
def schedule_task(self, task: Callable[[], None], priority: int) -> None:
|
|
356
|
+
state = self._state
|
|
357
|
+
tracker = state.current_tracker
|
|
358
|
+
if tracker is None:
|
|
359
|
+
self._dispatcher.schedule_task(task, priority)
|
|
360
|
+
return
|
|
361
|
+
|
|
362
|
+
def tracked() -> None:
|
|
363
|
+
try:
|
|
364
|
+
state.run_tracked(tracker, task)
|
|
365
|
+
finally:
|
|
366
|
+
tracker.pending -= 1
|
|
367
|
+
if tracker.pending == 0 and tracker.on_idle is not None:
|
|
368
|
+
tracker.on_idle()
|
|
369
|
+
|
|
370
|
+
tracker.pending += 1
|
|
371
|
+
self._dispatcher.schedule_task(tracked, priority)
|
|
372
|
+
|
|
373
|
+
def flush(self) -> None:
|
|
374
|
+
self._dispatcher.flush()
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def _make_with_scheduler(
|
|
378
|
+
warning_delay: Input,
|
|
379
|
+
) -> Effect[tuple[_TestClock, _TrackingScheduler], Never, Scope]:
|
|
380
|
+
"""makeWithScheduler (TestClock.ts): the clock and its scheduler, built over the services in
|
|
381
|
+
place now; closing the Scope stops a pending warning."""
|
|
382
|
+
|
|
383
|
+
@gen
|
|
384
|
+
def go() -> Generator[Effect[Any, Never, Any], Any, tuple[_TestClock, _TrackingScheduler]]:
|
|
385
|
+
current = yield from Clock()
|
|
386
|
+
live = current.live_clock if isinstance(current, _TestClock) else current
|
|
387
|
+
state = _State(warning_delay, live, (yield from Console()))
|
|
388
|
+
clock = _TestClock(state)
|
|
389
|
+
yield from add_finalizer(lambda _exit: clock.warning_done())
|
|
390
|
+
return clock, _TrackingScheduler(state, (yield from Scheduler()))
|
|
391
|
+
|
|
392
|
+
return go()
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _test_clock_with[A, E, R](f: Callable[[TestClockService], Effect[A, E, R]]) -> Effect[A, E, R]:
|
|
396
|
+
def check(clock: ClockService) -> Effect[A, E, R]:
|
|
397
|
+
if isinstance(clock, _TestClock):
|
|
398
|
+
return f(clock)
|
|
399
|
+
return die(TypeError(f"the fiber's Clock is not a TestClock: {clock!r}"))
|
|
400
|
+
|
|
401
|
+
return Clock().use().flat_map(check)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
@final
|
|
405
|
+
class _TestClockModule:
|
|
406
|
+
"""The TestClock module's exports (TestClock.ts). An instance, not a class, so a test runner
|
|
407
|
+
never takes it for a test class."""
|
|
408
|
+
|
|
409
|
+
__slots__ = ()
|
|
410
|
+
|
|
411
|
+
WARNING_MESSAGE: ClassVar[str] = WARNING_MESSAGE
|
|
412
|
+
BUSY_WARNING_MESSAGE: ClassVar[str] = BUSY_WARNING_MESSAGE
|
|
413
|
+
|
|
414
|
+
@staticmethod
|
|
415
|
+
def make(*, warning_delay: Input = "1 second") -> Effect[TestClockService, Never, Scope]:
|
|
416
|
+
"""A new TestClock over the current Clock and Console; not installed anywhere."""
|
|
417
|
+
return _make_with_scheduler(warning_delay).map(lambda pair: pair[0])
|
|
418
|
+
|
|
419
|
+
@staticmethod
|
|
420
|
+
def layer(*, warning_delay: Input = "1 second") -> Layer[Clock | Scheduler]:
|
|
421
|
+
"""Clock = a new TestClock, Scheduler = its tracking scheduler, per build."""
|
|
422
|
+
return Layer.effect_context(
|
|
423
|
+
_make_with_scheduler(warning_delay).map(
|
|
424
|
+
lambda pair: Clock.context(pair[0]) | Scheduler.context(pair[1])
|
|
425
|
+
)
|
|
426
|
+
)
|
|
427
|
+
|
|
428
|
+
@staticmethod
|
|
429
|
+
def test_clock_with[A, E, R](
|
|
430
|
+
f: Callable[[TestClockService], Effect[A, E, R]],
|
|
431
|
+
) -> Effect[A, E, R]:
|
|
432
|
+
"""Run ``f`` with the fiber's Clock, which must be a TestClock."""
|
|
433
|
+
return _test_clock_with(f)
|
|
434
|
+
|
|
435
|
+
@staticmethod
|
|
436
|
+
def adjust(duration: Input) -> _Void:
|
|
437
|
+
"""Advance the fiber's TestClock by ``duration``."""
|
|
438
|
+
return _test_clock_with(lambda c: c.adjust(duration))
|
|
439
|
+
|
|
440
|
+
@staticmethod
|
|
441
|
+
def set_time(timestamp: float) -> _Void:
|
|
442
|
+
"""Move the fiber's TestClock to ``timestamp`` milliseconds."""
|
|
443
|
+
return _test_clock_with(lambda c: c.set_time(timestamp))
|
|
444
|
+
|
|
445
|
+
@staticmethod
|
|
446
|
+
def with_live[A, E, R](eff: Effect[A, E, R]) -> Effect[A, E, R]:
|
|
447
|
+
"""Run ``eff`` on the live clock behind the fiber's TestClock."""
|
|
448
|
+
return _test_clock_with(lambda c: c.with_live(eff))
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
TestClock = _TestClockModule()
|
|
452
|
+
|
|
453
|
+
__all__ = ["BUSY_WARNING_MESSAGE", "WARNING_MESSAGE", "TestClock", "TestClockService"]
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""TestConsole: a Console that records every call instead of printing.
|
|
2
|
+
|
|
3
|
+
provide_layer(TestConsole.layer)(program)
|
|
4
|
+
lines = yield from TestConsole.log_lines # every Console.log argument, flattened
|
|
5
|
+
|
|
6
|
+
Effect v4: src/testing/TestConsole.ts. ``test_console_with`` checks that the fiber's Console is a
|
|
7
|
+
TestConsole and dies with a TypeError otherwise, where upstream casts.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from typing import ClassVar, Literal, Never, Protocol, final
|
|
14
|
+
|
|
15
|
+
from ..console import Console, ConsoleService
|
|
16
|
+
from ..core import Effect, die, sync
|
|
17
|
+
from ..layer import Layer
|
|
18
|
+
|
|
19
|
+
type Method = Literal["log", "error", "warn", "info", "debug"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TestConsoleService(ConsoleService, Protocol):
|
|
23
|
+
"""A Console whose ``log`` and ``error`` arguments can be read back."""
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def log_lines(self) -> Effect[tuple[object, ...], Never, Never]: ...
|
|
27
|
+
@property
|
|
28
|
+
def error_lines(self) -> Effect[tuple[object, ...], Never, Never]: ...
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@final
|
|
32
|
+
class _TestConsole:
|
|
33
|
+
__slots__ = ("entries",)
|
|
34
|
+
|
|
35
|
+
def __init__(self) -> None:
|
|
36
|
+
self.entries: list[tuple[Method, tuple[object, ...]]] = []
|
|
37
|
+
|
|
38
|
+
def log(self, *args: object) -> None:
|
|
39
|
+
self.entries.append(("log", args))
|
|
40
|
+
|
|
41
|
+
def error(self, *args: object) -> None:
|
|
42
|
+
self.entries.append(("error", args))
|
|
43
|
+
|
|
44
|
+
def warn(self, *args: object) -> None:
|
|
45
|
+
self.entries.append(("warn", args))
|
|
46
|
+
|
|
47
|
+
def info(self, *args: object) -> None:
|
|
48
|
+
self.entries.append(("info", args))
|
|
49
|
+
|
|
50
|
+
def debug(self, *args: object) -> None:
|
|
51
|
+
self.entries.append(("debug", args))
|
|
52
|
+
|
|
53
|
+
def _lines(self, method: Method) -> tuple[object, ...]:
|
|
54
|
+
return tuple(p for m, params in self.entries if m == method for p in params)
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def log_lines(self) -> Effect[tuple[object, ...], Never, Never]:
|
|
58
|
+
return sync(lambda: self._lines("log"))
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def error_lines(self) -> Effect[tuple[object, ...], Never, Never]:
|
|
62
|
+
return sync(lambda: self._lines("error"))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _test_console_with[A, E, R](
|
|
66
|
+
f: Callable[[TestConsoleService], Effect[A, E, R]],
|
|
67
|
+
) -> Effect[A, E, R]:
|
|
68
|
+
def check(console: ConsoleService) -> Effect[A, E, R]:
|
|
69
|
+
if isinstance(console, _TestConsole):
|
|
70
|
+
return f(console)
|
|
71
|
+
return die(TypeError(f"the fiber's Console is not a TestConsole: {console!r}"))
|
|
72
|
+
|
|
73
|
+
return Console().use().flat_map(check)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@final
|
|
77
|
+
class _TestConsoleModule:
|
|
78
|
+
"""The TestConsole module's exports (TestConsole.ts). An instance, not a class, so a test
|
|
79
|
+
runner never takes it for a test class."""
|
|
80
|
+
|
|
81
|
+
__slots__ = ()
|
|
82
|
+
|
|
83
|
+
make: ClassVar[Effect[TestConsoleService, Never, Never]] = sync(_TestConsole)
|
|
84
|
+
"""A fresh recording console each time it runs."""
|
|
85
|
+
layer: ClassVar[Layer[Console]] = Layer.effect(Console, make)
|
|
86
|
+
"""Console = a fresh TestConsole, per build."""
|
|
87
|
+
log_lines: ClassVar[Effect[tuple[object, ...], Never, Never]] = _test_console_with(
|
|
88
|
+
lambda c: c.log_lines
|
|
89
|
+
)
|
|
90
|
+
error_lines: ClassVar[Effect[tuple[object, ...], Never, Never]] = _test_console_with(
|
|
91
|
+
lambda c: c.error_lines
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def test_console_with[A, E, R](
|
|
96
|
+
f: Callable[[TestConsoleService], Effect[A, E, R]],
|
|
97
|
+
) -> Effect[A, E, R]:
|
|
98
|
+
"""Run ``f`` with the fiber's Console, which must be a TestConsole."""
|
|
99
|
+
return _test_console_with(f)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
TestConsole = _TestConsoleModule()
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
__all__ = ["TestConsole", "TestConsoleService"]
|
peffect/timeout.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Timeouts: race an effect against a sleep on the fiber's Clock.
|
|
2
|
+
|
|
3
|
+
yield from timeout_option(fetch(), "2 seconds") # Some(value), or None on timeout
|
|
4
|
+
yield from timeout_or_else(fetch(), duration=10, or_else=lambda: succeed(cached))
|
|
5
|
+
yield from timeout(fetch(), "1 minute") # fails with TimeoutError
|
|
6
|
+
|
|
7
|
+
Built from `race_first` and `sleep`: the source and the sleep race as two racers, so a timed-out
|
|
8
|
+
source is interrupted, and its cleanup finishes, before the timeout continues. Data-first only.
|
|
9
|
+
Effect v4: internal/effect.ts:3929-4007 (timeoutOrElse, timeout, timeoutOption), :6499
|
|
10
|
+
(TimeoutError).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from typing import final
|
|
17
|
+
|
|
18
|
+
from .clock import sleep
|
|
19
|
+
from .core import Effect, fail, succeed
|
|
20
|
+
from .duration import Input, format, from_input_unsafe
|
|
21
|
+
from .fiber import race_first
|
|
22
|
+
from .option import Option, Some
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@final
|
|
26
|
+
class TimeoutError(Exception):
|
|
27
|
+
"""What `timeout` fails with: ``Operation timed out after '<duration>'``. Catch it with
|
|
28
|
+
``catch_tag(TimeoutError, ...)``. Not the builtin `TimeoutError` (an OSError)."""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def timeout_option[A, E, R](self: Effect[A, E, R], duration: Input) -> Effect[Option[A], E, R]:
|
|
32
|
+
"""``Some(value)`` if ``self`` ends first, ``None`` if ``duration`` passes first. A failure
|
|
33
|
+
of ``self`` that comes first is kept. ``duration`` is read when the effect runs, so an invalid
|
|
34
|
+
one is a defect then (timeoutOption, :3988-4007)."""
|
|
35
|
+
some: Effect[Option[A], E, R] = self.map(Some)
|
|
36
|
+
none: Effect[Option[A], E, R] = sleep(duration).as_(None)
|
|
37
|
+
return race_first(some, none)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def timeout_or_else[A, E, R](
|
|
41
|
+
self: Effect[A, E, R], *, duration: Input, or_else: Callable[[], Effect[A, E, R]]
|
|
42
|
+
) -> Effect[A, E, R]:
|
|
43
|
+
"""``self``'s result if it ends within ``duration``; otherwise ``or_else()``, called only
|
|
44
|
+
then, on the calling fiber (timeoutOrElse, :3929-3951).
|
|
45
|
+
|
|
46
|
+
One type variable per channel: pyright joins the source's and the fallback's types."""
|
|
47
|
+
|
|
48
|
+
def choose(option: Option[A]) -> Effect[A, E, R]:
|
|
49
|
+
return or_else() if option is None else succeed(option.value)
|
|
50
|
+
|
|
51
|
+
return timeout_option(self, duration).flat_map(choose)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def timeout[A, E, R](self: Effect[A, E, R], duration: Input) -> Effect[A, E | TimeoutError, R]:
|
|
55
|
+
"""``self``'s result, or a ``TimeoutError`` failure if ``duration`` passes first. Unlike the
|
|
56
|
+
other two, ``duration`` is decoded now: an invalid one raises ValueError here (timeout,
|
|
57
|
+
:3954-3985)."""
|
|
58
|
+
decoded = from_input_unsafe(duration)
|
|
59
|
+
|
|
60
|
+
def or_else() -> Effect[A, E | TimeoutError, R]: # a fresh error per timeout, as upstream
|
|
61
|
+
return fail(TimeoutError(f"Operation timed out after '{format(decoded)}'"))
|
|
62
|
+
|
|
63
|
+
widened: Effect[A, E | TimeoutError, R] = self
|
|
64
|
+
return timeout_or_else(widened, duration=decoded, or_else=or_else)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
__all__ = ["TimeoutError", "timeout", "timeout_option", "timeout_or_else"]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
peffect/__init__.py,sha256=DhRmzNK5wus5OXCDaFaEpoVOr2TrR1w9CLkamOCwVkk,4208
|
|
2
|
+
peffect/cause.py,sha256=Vb2YNRoowTwcWPu3Qw-1n0dsJGNMR1GCAAQnhzPxy2c,5985
|
|
3
|
+
peffect/clock.py,sha256=KvLtDpLIngRZ0KB4TyUfalrGvabgmFTECXtqmLl9YP4,5142
|
|
4
|
+
peffect/console.py,sha256=qDFzYh_HoKMSgmZ1gGib8ggCj7fAEGwG2chkiMxF4LI,2907
|
|
5
|
+
peffect/context.py,sha256=ioJFOvBpiPXohqFpYJ3rlCybQY60y-bG6W6LjH1IIrg,9891
|
|
6
|
+
peffect/core.py,sha256=FxGnBZiOxbAJ2T0HRiZyTsHqBP0kBfYu2iCFN2QLFq8,41477
|
|
7
|
+
peffect/deferred.py,sha256=rmxSynwoLrnNuLoZg5C1XpBx5HC1NvaufsMb40lUdpw,3774
|
|
8
|
+
peffect/duration.py,sha256=kL46hxeA6m3b7oPloOz2ItsDbmSE1SZbF9Kr3-DrwGI,15254
|
|
9
|
+
peffect/fiber.py,sha256=hdbrMmyXzZx3oz0LioA8l05HCtCjDy1EvTdhFFs_Dtc,41288
|
|
10
|
+
peffect/latch.py,sha256=5OsDPYeefQcbq0K7KtFgt4V3GG9dv9n_LXunLsUTJbI,4481
|
|
11
|
+
peffect/layer.py,sha256=2_Xn75TFspa4eHW51zaIXW9dOlHig0VL4LQMPM1y6fo,26059
|
|
12
|
+
peffect/logger.py,sha256=_x8q8RdSp97-3ncaI1Bl0skOxqvG6RJsZDyZcPC7DM0,5676
|
|
13
|
+
peffect/managed_runtime.py,sha256=n7YT801INuKyKd-KJ6RfO85CJtpP96JiNDdKb0_SceQ,13359
|
|
14
|
+
peffect/option.py,sha256=suUsJJqpYZ1J5-Lhp98xAdbGsawTGC2A2ddMswlPH4I,1719
|
|
15
|
+
peffect/pull.py,sha256=bVp7QhA-KjQAexcUURXVK1IM2-eIs6JjSiJa3upGFtQ,4275
|
|
16
|
+
peffect/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
17
|
+
peffect/queue.py,sha256=OdOrhmcqmhFfvaxVC_PhxSovPpB5C37anEeJNgp-12Q,23729
|
|
18
|
+
peffect/ref.py,sha256=6VJrELUno1srXMxO425d1Jjer_v84Ov6goT-yn7bmrU,4333
|
|
19
|
+
peffect/resources.py,sha256=GIVDEFS5JeIBpv-L-Tput7gpyJo7jUjJVpt7RDYnlcM,4624
|
|
20
|
+
peffect/scheduler.py,sha256=jgxMzQct6c6y44d8OANJZlYkvZ0LvYGJOPOw6SZDyYU,1659
|
|
21
|
+
peffect/scope.py,sha256=axm3LYTAGvGz4stD43dFWk7TpN7mMgdvzpznMOJMN4k,14344
|
|
22
|
+
peffect/semaphore.py,sha256=SdpGmAPrIgv6eldzCzSZPNWMKFAbx_rBHh9rjJ4OP5Y,9842
|
|
23
|
+
peffect/synchronized_ref.py,sha256=FCHy05bItv245bG4cpvLIvNqplLqghoxqztSdRuQf2s,7316
|
|
24
|
+
peffect/timeout.py,sha256=TeT9KGnAgynzx6k4d8m5hU3WxOCPFYjG4sR0wbzb0Cs,2934
|
|
25
|
+
peffect/testing/__init__.py,sha256=s9Eg_0NJ-7LNXxPsYco0G4uyjeY3oHSzvhxKGlmt9w8,331
|
|
26
|
+
peffect/testing/_clock.py,sha256=bttR5J7k0kSzbHhx22JLuWS_Id5dYzANtAW40W2Tvos,16400
|
|
27
|
+
peffect/testing/_console.py,sha256=ikXfEQ1Hh65a8lT0DVuzcvtAGUfCs4PmeY9bgz6Bz_Q,3442
|
|
28
|
+
peffect-0.1.2.dist-info/METADATA,sha256=CUEsBRvVkXhtHBfhKQYZ2061C5eYTpX_XLJzFq2tk18,149
|
|
29
|
+
peffect-0.1.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
30
|
+
peffect-0.1.2.dist-info/RECORD,,
|