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/__init__.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""peffect: Effect-style programs for Python. See docs/DESIGN.md."""
|
|
2
|
+
|
|
3
|
+
from peffect.cause import (
|
|
4
|
+
Cause,
|
|
5
|
+
DefectError,
|
|
6
|
+
Die,
|
|
7
|
+
Done,
|
|
8
|
+
Fail,
|
|
9
|
+
FailureError,
|
|
10
|
+
Interrupt,
|
|
11
|
+
Interrupted,
|
|
12
|
+
is_done,
|
|
13
|
+
)
|
|
14
|
+
from peffect.clock import (
|
|
15
|
+
Clock,
|
|
16
|
+
ClockService,
|
|
17
|
+
clock_with,
|
|
18
|
+
current_time_millis,
|
|
19
|
+
current_time_nanos,
|
|
20
|
+
monotonic_time_nanos,
|
|
21
|
+
sleep,
|
|
22
|
+
)
|
|
23
|
+
from peffect.context import Context, MissingService, Reference, Tag, provide, run_fork_with
|
|
24
|
+
from peffect.core import (
|
|
25
|
+
ContextMap,
|
|
26
|
+
Do,
|
|
27
|
+
Effect,
|
|
28
|
+
Exit,
|
|
29
|
+
Failure,
|
|
30
|
+
Success,
|
|
31
|
+
async_,
|
|
32
|
+
attempt,
|
|
33
|
+
catch_all,
|
|
34
|
+
catch_cause,
|
|
35
|
+
catch_tag,
|
|
36
|
+
die,
|
|
37
|
+
ensuring,
|
|
38
|
+
exit_,
|
|
39
|
+
fail,
|
|
40
|
+
fail_cause,
|
|
41
|
+
fiber_id,
|
|
42
|
+
from_async,
|
|
43
|
+
gen,
|
|
44
|
+
interruptible,
|
|
45
|
+
never,
|
|
46
|
+
on_error,
|
|
47
|
+
on_exit,
|
|
48
|
+
on_exit_with_dispatcher,
|
|
49
|
+
on_interrupt,
|
|
50
|
+
succeed,
|
|
51
|
+
suspend,
|
|
52
|
+
suspend_exit,
|
|
53
|
+
sync,
|
|
54
|
+
tap,
|
|
55
|
+
uninterruptible,
|
|
56
|
+
uninterruptible_mask,
|
|
57
|
+
update_context,
|
|
58
|
+
yield_now,
|
|
59
|
+
)
|
|
60
|
+
from peffect.deferred import Deferred
|
|
61
|
+
from peffect.fiber import (
|
|
62
|
+
DEFAULT_SCHEDULER,
|
|
63
|
+
Fiber,
|
|
64
|
+
FiberOwner,
|
|
65
|
+
MixedScheduler,
|
|
66
|
+
RootRunner,
|
|
67
|
+
SchedulerDispatcher,
|
|
68
|
+
SchedulerService,
|
|
69
|
+
await_all,
|
|
70
|
+
await_exit,
|
|
71
|
+
for_each,
|
|
72
|
+
fork,
|
|
73
|
+
fork_daemon,
|
|
74
|
+
fork_in_owner,
|
|
75
|
+
interrupt_all,
|
|
76
|
+
race,
|
|
77
|
+
race_all,
|
|
78
|
+
race_all_first,
|
|
79
|
+
race_first,
|
|
80
|
+
run,
|
|
81
|
+
run_exit,
|
|
82
|
+
run_fork,
|
|
83
|
+
run_in_owner,
|
|
84
|
+
with_dispatcher,
|
|
85
|
+
)
|
|
86
|
+
from peffect.latch import Latch
|
|
87
|
+
from peffect.layer import CurrentMemoMap, Layer, MemoMap, provide_layer
|
|
88
|
+
from peffect.managed_runtime import ManagedRuntime
|
|
89
|
+
from peffect.option import Option, Some
|
|
90
|
+
from peffect.pull import done
|
|
91
|
+
from peffect.queue import Dequeue, Enqueue, Queue
|
|
92
|
+
from peffect.ref import Ref
|
|
93
|
+
from peffect.resources import acquire_release, acquire_use_release, add_finalizer
|
|
94
|
+
from peffect.scheduler import MaxOpsBeforeYield, PreventSchedulerYield, Scheduler
|
|
95
|
+
from peffect.scope import (
|
|
96
|
+
Closeable,
|
|
97
|
+
Scope,
|
|
98
|
+
ScopeService,
|
|
99
|
+
fork_in,
|
|
100
|
+
fork_scoped,
|
|
101
|
+
run_in,
|
|
102
|
+
scope,
|
|
103
|
+
scoped,
|
|
104
|
+
)
|
|
105
|
+
from peffect.semaphore import Semaphore
|
|
106
|
+
from peffect.synchronized_ref import SynchronizedRef
|
|
107
|
+
from peffect.timeout import TimeoutError, timeout, timeout_option, timeout_or_else
|
|
108
|
+
|
|
109
|
+
__all__ = [
|
|
110
|
+
"DEFAULT_SCHEDULER",
|
|
111
|
+
"Cause",
|
|
112
|
+
"Clock",
|
|
113
|
+
"ClockService",
|
|
114
|
+
"Closeable",
|
|
115
|
+
"Context",
|
|
116
|
+
"ContextMap",
|
|
117
|
+
"CurrentMemoMap",
|
|
118
|
+
"DefectError",
|
|
119
|
+
"Deferred",
|
|
120
|
+
"Dequeue",
|
|
121
|
+
"Die",
|
|
122
|
+
"Do",
|
|
123
|
+
"Done",
|
|
124
|
+
"Effect",
|
|
125
|
+
"Enqueue",
|
|
126
|
+
"Exit",
|
|
127
|
+
"Fail",
|
|
128
|
+
"Failure",
|
|
129
|
+
"FailureError",
|
|
130
|
+
"Fiber",
|
|
131
|
+
"FiberOwner",
|
|
132
|
+
"Interrupt",
|
|
133
|
+
"Interrupted",
|
|
134
|
+
"Latch",
|
|
135
|
+
"Layer",
|
|
136
|
+
"ManagedRuntime",
|
|
137
|
+
"MaxOpsBeforeYield",
|
|
138
|
+
"MemoMap",
|
|
139
|
+
"MissingService",
|
|
140
|
+
"MixedScheduler",
|
|
141
|
+
"Option",
|
|
142
|
+
"PreventSchedulerYield",
|
|
143
|
+
"Queue",
|
|
144
|
+
"Ref",
|
|
145
|
+
"Reference",
|
|
146
|
+
"RootRunner",
|
|
147
|
+
"Scheduler",
|
|
148
|
+
"SchedulerDispatcher",
|
|
149
|
+
"SchedulerService",
|
|
150
|
+
"Scope",
|
|
151
|
+
"ScopeService",
|
|
152
|
+
"Semaphore",
|
|
153
|
+
"Some",
|
|
154
|
+
"Success",
|
|
155
|
+
"SynchronizedRef",
|
|
156
|
+
"Tag",
|
|
157
|
+
"TimeoutError",
|
|
158
|
+
"acquire_release",
|
|
159
|
+
"acquire_use_release",
|
|
160
|
+
"add_finalizer",
|
|
161
|
+
"async_",
|
|
162
|
+
"attempt",
|
|
163
|
+
"await_all",
|
|
164
|
+
"await_exit",
|
|
165
|
+
"catch_all",
|
|
166
|
+
"catch_cause",
|
|
167
|
+
"catch_tag",
|
|
168
|
+
"clock_with",
|
|
169
|
+
"current_time_millis",
|
|
170
|
+
"current_time_nanos",
|
|
171
|
+
"die",
|
|
172
|
+
"done",
|
|
173
|
+
"ensuring",
|
|
174
|
+
"exit_",
|
|
175
|
+
"fail",
|
|
176
|
+
"fail_cause",
|
|
177
|
+
"fiber_id",
|
|
178
|
+
"for_each",
|
|
179
|
+
"fork",
|
|
180
|
+
"fork_daemon",
|
|
181
|
+
"fork_in",
|
|
182
|
+
"fork_in_owner",
|
|
183
|
+
"fork_scoped",
|
|
184
|
+
"from_async",
|
|
185
|
+
"gen",
|
|
186
|
+
"interrupt_all",
|
|
187
|
+
"interruptible",
|
|
188
|
+
"is_done",
|
|
189
|
+
"monotonic_time_nanos",
|
|
190
|
+
"never",
|
|
191
|
+
"on_error",
|
|
192
|
+
"on_exit",
|
|
193
|
+
"on_exit_with_dispatcher",
|
|
194
|
+
"on_interrupt",
|
|
195
|
+
"provide",
|
|
196
|
+
"provide_layer",
|
|
197
|
+
"race",
|
|
198
|
+
"race_all",
|
|
199
|
+
"race_all_first",
|
|
200
|
+
"race_first",
|
|
201
|
+
"run",
|
|
202
|
+
"run_exit",
|
|
203
|
+
"run_fork",
|
|
204
|
+
"run_fork_with",
|
|
205
|
+
"run_in",
|
|
206
|
+
"run_in_owner",
|
|
207
|
+
"scope",
|
|
208
|
+
"scoped",
|
|
209
|
+
"sleep",
|
|
210
|
+
"succeed",
|
|
211
|
+
"suspend",
|
|
212
|
+
"suspend_exit",
|
|
213
|
+
"sync",
|
|
214
|
+
"tap",
|
|
215
|
+
"timeout",
|
|
216
|
+
"timeout_option",
|
|
217
|
+
"timeout_or_else",
|
|
218
|
+
"uninterruptible",
|
|
219
|
+
"uninterruptible_mask",
|
|
220
|
+
"update_context",
|
|
221
|
+
"with_dispatcher",
|
|
222
|
+
"yield_now",
|
|
223
|
+
]
|
peffect/cause.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Cause: everything that went wrong, as data.
|
|
2
|
+
|
|
3
|
+
A failed effect doesn't carry one exception; it carries a Cause: an ordered tuple of reasons.
|
|
4
|
+
|
|
5
|
+
Fail(error) an expected, typed failure. Its type is the E in Effect[A, E, R].
|
|
6
|
+
Die(defect) a bug: an exception nobody declared. Not in E.
|
|
7
|
+
Interrupt(by) the fiber was asked to stop (by fiber id `by`).
|
|
8
|
+
|
|
9
|
+
One Cause can hold several: a request failed AND its cleanup crashed AND a sibling was interrupted.
|
|
10
|
+
Flat like Effect v4 (src/Cause.ts:79-82); `+` keeps order and drops exact duplicates
|
|
11
|
+
(src/internal/core.ts:283-323).
|
|
12
|
+
|
|
13
|
+
A Die's defect is any value, as in v4 (`Die.defect: unknown`): when a defect is present, a
|
|
14
|
+
finalizer's combine elects every Fail to a Die (`elect_defects`), and a Fail's error need not be
|
|
15
|
+
an exception. `die()` still takes an exception; only election makes a non-exception defect.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from typing import ClassVar, Generic, Never, Self, TypeIs, TypeVar, final, overload
|
|
22
|
+
|
|
23
|
+
E_co = TypeVar("E_co", covariant=True)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@final
|
|
27
|
+
class Done[A = None]:
|
|
28
|
+
"""Normal input completion, carried as Fail(Done(value)), not as a new Reason.
|
|
29
|
+
|
|
30
|
+
Effect v4 internal/core.ts:739-767. Python None represents the void leftover.
|
|
31
|
+
The read-only payload follows Some's immutable, covariant representation.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
__slots__ = ("_value",)
|
|
35
|
+
__match_args__ = ("value",)
|
|
36
|
+
_value: A
|
|
37
|
+
_void: ClassVar[Self | None] = None
|
|
38
|
+
|
|
39
|
+
def __new__(cls, value: A | None = None) -> Self:
|
|
40
|
+
if value is None:
|
|
41
|
+
if cls._void is None:
|
|
42
|
+
cls._void = super().__new__(cls)
|
|
43
|
+
return cls._void
|
|
44
|
+
return super().__new__(cls)
|
|
45
|
+
|
|
46
|
+
@overload
|
|
47
|
+
def __init__(self: Done[None]) -> None: ...
|
|
48
|
+
@overload
|
|
49
|
+
def __init__(self, value: A) -> None: ...
|
|
50
|
+
def __init__(self, value: object = None) -> None:
|
|
51
|
+
object.__setattr__(self, "_value", value)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def value(self) -> A:
|
|
55
|
+
return self._value
|
|
56
|
+
|
|
57
|
+
def __setattr__(self, name: str, value: object) -> None:
|
|
58
|
+
raise AttributeError(f"Done is immutable: cannot set {name!r}")
|
|
59
|
+
|
|
60
|
+
def __delattr__(self, name: str) -> None:
|
|
61
|
+
raise AttributeError(f"Done is immutable: cannot delete {name!r}")
|
|
62
|
+
|
|
63
|
+
def __repr__(self) -> str:
|
|
64
|
+
return f"Done({self._value!r})"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def is_done(value: object) -> TypeIs[Done[object]]:
|
|
68
|
+
"""Recognize the nominal Python completion value (Cause.ts:1286)."""
|
|
69
|
+
return isinstance(value, Done)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@final
|
|
73
|
+
@dataclass(frozen=True, slots=True)
|
|
74
|
+
class Fail(Generic[E_co]):
|
|
75
|
+
error: E_co
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@final
|
|
79
|
+
@dataclass(frozen=True, slots=True)
|
|
80
|
+
class Die:
|
|
81
|
+
defect: object
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@final
|
|
85
|
+
@dataclass(frozen=True, slots=True)
|
|
86
|
+
class Interrupt:
|
|
87
|
+
by: int | None = None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
type Reason[E] = Fail[E] | Die | Interrupt
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@final
|
|
94
|
+
@dataclass(frozen=True, slots=True)
|
|
95
|
+
class Cause(Generic[E_co]):
|
|
96
|
+
reasons: tuple[Fail[E_co] | Die | Interrupt, ...] = ()
|
|
97
|
+
|
|
98
|
+
# -- constructors -----------------------------------------------------------------------------
|
|
99
|
+
@staticmethod
|
|
100
|
+
def fail[E](error: E) -> Cause[E]:
|
|
101
|
+
return Cause((Fail(error),))
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def die(defect: BaseException) -> Cause[Never]:
|
|
105
|
+
return Cause((Die(defect),))
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def interrupt(by: int | None = None) -> Cause[Never]:
|
|
109
|
+
return Cause((Interrupt(by),))
|
|
110
|
+
|
|
111
|
+
# -- combine ----------------------------------------------------------------------------------
|
|
112
|
+
def __add__[E2](self, other: Cause[E2]) -> Cause[E_co | E2]:
|
|
113
|
+
out: list[Fail[E_co | E2] | Die | Interrupt] = list(self.reasons)
|
|
114
|
+
out.extend(r for r in other.reasons if r not in out)
|
|
115
|
+
return Cause(tuple(out))
|
|
116
|
+
|
|
117
|
+
def elect_defects(self) -> Cause[E_co]:
|
|
118
|
+
"""If a Die is present, every Fail becomes a Die holding its error, in place.
|
|
119
|
+
Effect v4: causeElectDefects, internal/effect.ts:184-191."""
|
|
120
|
+
if not (self.defects and self.failures):
|
|
121
|
+
return self
|
|
122
|
+
return Cause(tuple(Die(r.error) if isinstance(r, Fail) else r for r in self.reasons))
|
|
123
|
+
|
|
124
|
+
def without_fails(self) -> Cause[Never]:
|
|
125
|
+
return Cause(tuple(r for r in self.reasons if not isinstance(r, Fail)))
|
|
126
|
+
|
|
127
|
+
# -- queries ----------------------------------------------------------------------------------
|
|
128
|
+
@property
|
|
129
|
+
def failures(self) -> list[E_co]:
|
|
130
|
+
return [r.error for r in self.reasons if isinstance(r, Fail)]
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def defects(self) -> list[object]:
|
|
134
|
+
return [r.defect for r in self.reasons if isinstance(r, Die)]
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def is_interrupted(self) -> bool:
|
|
138
|
+
return any(isinstance(r, Interrupt) for r in self.reasons)
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def is_interrupted_only(self) -> bool:
|
|
142
|
+
return bool(self.reasons) and all(isinstance(r, Interrupt) for r in self.reasons)
|
|
143
|
+
|
|
144
|
+
def squash(self) -> BaseException:
|
|
145
|
+
"""One exception for a Python boundary. Lossy, like v4's squash
|
|
146
|
+
(internal/effect.ts:289-299): first typed failure, else first defect, else interruption."""
|
|
147
|
+
for r in self.reasons:
|
|
148
|
+
if isinstance(r, Fail):
|
|
149
|
+
err = r.error
|
|
150
|
+
return err if isinstance(err, BaseException) else FailureError(err)
|
|
151
|
+
for r in self.reasons:
|
|
152
|
+
if isinstance(r, Die):
|
|
153
|
+
d = r.defect
|
|
154
|
+
return d if isinstance(d, BaseException) else DefectError(d)
|
|
155
|
+
return Interrupted(self)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class FailureError(Exception):
|
|
159
|
+
"""A typed failure that isn't an exception, raised at the run() boundary."""
|
|
160
|
+
|
|
161
|
+
def __init__(self, error: object) -> None:
|
|
162
|
+
super().__init__(error)
|
|
163
|
+
self.error = error
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class DefectError(Exception):
|
|
167
|
+
"""A defect that isn't an exception (an elected Fail), raised at the run() boundary."""
|
|
168
|
+
|
|
169
|
+
def __init__(self, defect: object) -> None:
|
|
170
|
+
super().__init__(defect)
|
|
171
|
+
self.defect = defect
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class Interrupted(Exception):
|
|
175
|
+
def __init__(self, cause: Cause[object]) -> None:
|
|
176
|
+
super().__init__("fiber interrupted")
|
|
177
|
+
self.cause = cause
|
peffect/clock.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""Clock: time and sleeping as a service, so a test can swap in its own.
|
|
2
|
+
|
|
3
|
+
now = yield from current_time_millis # read through the fiber's Clock
|
|
4
|
+
yield from sleep("1.5 seconds") # the fiber's Clock does the sleeping
|
|
5
|
+
provide(Clock.context(my_clock))(program) # replace it
|
|
6
|
+
|
|
7
|
+
`Clock` is a Reference, so using it never adds to R; its default is the live clock.
|
|
8
|
+
Effect v4: Clock.ts, internal/effect.ts:6395-6486 (ClockRef, ClockImpl, clockWith, sleep).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
import math
|
|
15
|
+
import time
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from typing import Never, Protocol, final
|
|
18
|
+
|
|
19
|
+
from .context import Reference
|
|
20
|
+
from .core import Effect, async_, never, succeed, sync, yield_now
|
|
21
|
+
from .duration import Duration, Input, from_input_unsafe, to_millis
|
|
22
|
+
|
|
23
|
+
NANOS_PER_MILLI = 1_000_000
|
|
24
|
+
REANCHOR_THRESHOLD_NANOS = 1_000_000_000 # wall time re-anchors when it drifts more than 1s
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ClockService(Protocol):
|
|
28
|
+
"""What a Clock provides (Clock.ts:53-150). Milliseconds are a float, as upstream's
|
|
29
|
+
`number` (a TestClock can stand at 0.0015 or at infinity); nanoseconds an int (`bigint`)."""
|
|
30
|
+
|
|
31
|
+
def current_time_millis_unsafe(self) -> float: ...
|
|
32
|
+
def current_time_nanos_unsafe(self) -> int: ...
|
|
33
|
+
def monotonic_time_nanos_unsafe(self) -> int: ...
|
|
34
|
+
@property
|
|
35
|
+
def current_time_millis(self) -> Effect[float, Never, Never]: ...
|
|
36
|
+
@property
|
|
37
|
+
def current_time_nanos(self) -> Effect[int, Never, Never]: ...
|
|
38
|
+
@property
|
|
39
|
+
def monotonic_time_nanos(self) -> Effect[int, Never, Never]: ...
|
|
40
|
+
def sleep(self, duration: Duration) -> Effect[None, Never, Never]: ...
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# -- the live clock (ClockImpl, internal/effect.ts:6401-6470) -------------------------------------
|
|
44
|
+
|
|
45
|
+
_origin: int | None = None # wall minus monotonic, one per process, as upstream's module closure
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _wall_millis() -> int:
|
|
49
|
+
return time.time_ns() // NANOS_PER_MILLI # Date.now(): whole milliseconds
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _wall_nanos() -> int:
|
|
53
|
+
"""Monotonic time shifted onto the wall clock, re-anchored when the two drift apart by more
|
|
54
|
+
than 1s (a suspended machine, a clock set back). All int: no float step."""
|
|
55
|
+
global _origin
|
|
56
|
+
monotonic = time.monotonic_ns()
|
|
57
|
+
wall = _wall_millis() * NANOS_PER_MILLI
|
|
58
|
+
if _origin is None or abs(wall - (_origin + monotonic)) > REANCHOR_THRESHOLD_NANOS:
|
|
59
|
+
_origin = wall - monotonic
|
|
60
|
+
return _origin + monotonic
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@final
|
|
64
|
+
class _LiveClock:
|
|
65
|
+
__slots__ = ()
|
|
66
|
+
|
|
67
|
+
def current_time_millis_unsafe(self) -> float:
|
|
68
|
+
return _wall_millis()
|
|
69
|
+
|
|
70
|
+
def current_time_nanos_unsafe(self) -> int:
|
|
71
|
+
return _wall_nanos()
|
|
72
|
+
|
|
73
|
+
def monotonic_time_nanos_unsafe(self) -> int:
|
|
74
|
+
return time.monotonic_ns()
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def current_time_millis(self) -> Effect[float, Never, Never]:
|
|
78
|
+
return sync(self.current_time_millis_unsafe)
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def current_time_nanos(self) -> Effect[int, Never, Never]:
|
|
82
|
+
return sync(self.current_time_nanos_unsafe)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def monotonic_time_nanos(self) -> Effect[int, Never, Never]:
|
|
86
|
+
return sync(self.monotonic_time_nanos_unsafe)
|
|
87
|
+
|
|
88
|
+
def sleep(self, duration: Duration) -> Effect[None, Never, Never]:
|
|
89
|
+
# sleepMillis(toMillis(duration)) (internal/effect.ts:6415-6421): <= 0 (-Infinity too) is
|
|
90
|
+
# a yield, Infinity never wakes; Duration has already turned NaN into zero
|
|
91
|
+
millis = to_millis(duration)
|
|
92
|
+
if millis <= 0:
|
|
93
|
+
return yield_now
|
|
94
|
+
if not math.isfinite(millis):
|
|
95
|
+
return never
|
|
96
|
+
seconds = millis / 1000 # asyncio's call_later takes seconds: the only unit conversion
|
|
97
|
+
|
|
98
|
+
def register(
|
|
99
|
+
resume: Callable[[Effect[None, Never, Never]], None],
|
|
100
|
+
) -> Effect[None, Never, Never]:
|
|
101
|
+
handle = asyncio.get_running_loop().call_later(seconds, resume, succeed(None))
|
|
102
|
+
return sync(handle.cancel) # run on interrupt: clearTimeout
|
|
103
|
+
|
|
104
|
+
return async_(register)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Clock(Reference[ClockService], key="effect/Clock"): # internal/effect.ts:6395
|
|
108
|
+
"""The fiber's Clock. ``yield from Clock()`` gives the service; the default is the live one."""
|
|
109
|
+
|
|
110
|
+
@classmethod
|
|
111
|
+
def default(cls) -> ClockService:
|
|
112
|
+
return _LiveClock()
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def clock_with[A, E, R](f: Callable[[ClockService], Effect[A, E, R]]) -> Effect[A, E, R]:
|
|
116
|
+
"""Run ``f`` with the fiber's Clock (internal/effect.ts:6472-6473)."""
|
|
117
|
+
return Clock().use().flat_map(f)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
current_time_millis: Effect[float, Never, Never] = clock_with(lambda c: c.current_time_millis)
|
|
121
|
+
current_time_nanos: Effect[int, Never, Never] = clock_with(lambda c: c.current_time_nanos)
|
|
122
|
+
monotonic_time_nanos: Effect[int, Never, Never] = clock_with(lambda c: c.monotonic_time_nanos)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def sleep(duration: Input) -> Effect[None, Never, Never]:
|
|
126
|
+
"""Suspend for ``duration`` on the fiber's Clock: a Duration, a string such as ``"5 seconds"``,
|
|
127
|
+
or a number of milliseconds. ``<= 0`` is a yield; infinity never wakes. Interrupting it cancels
|
|
128
|
+
the timer. The input is converted when the effect runs, so invalid input is a defect then
|
|
129
|
+
(internal/effect.ts:6476-6477)."""
|
|
130
|
+
return clock_with(lambda c: c.sleep(from_input_unsafe(duration)))
|
peffect/console.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Console: printing as a service, so a test can capture it.
|
|
2
|
+
|
|
3
|
+
yield from Console.log("hello", 1) # through the fiber's Console
|
|
4
|
+
provide(Console.Console.context(recorder))(p) # replace it
|
|
5
|
+
|
|
6
|
+
`Console` is a Reference: using it never adds to R. The default prints with `print`, log/info/debug
|
|
7
|
+
to `sys.stdout` and warn/error to `sys.stderr`, each stream read on every call (a platform
|
|
8
|
+
adaptation of Node's console, not a parity claim about its formatting). Five methods only, the
|
|
9
|
+
ones TestClock and the default logger need. Effect v4: internal/effect.ts:6584-6587 (ConsoleRef),
|
|
10
|
+
Console.ts.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import sys
|
|
16
|
+
from collections.abc import Callable
|
|
17
|
+
from typing import Never, Protocol, final
|
|
18
|
+
|
|
19
|
+
from .context import Reference
|
|
20
|
+
from .core import Effect, sync
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ConsoleService(Protocol):
|
|
24
|
+
"""What a Console provides: the five methods TestClock and the default logger use."""
|
|
25
|
+
|
|
26
|
+
def log(self, *args: object) -> None: ...
|
|
27
|
+
def error(self, *args: object) -> None: ...
|
|
28
|
+
def warn(self, *args: object) -> None: ...
|
|
29
|
+
def info(self, *args: object) -> None: ...
|
|
30
|
+
def debug(self, *args: object) -> None: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@final
|
|
34
|
+
class _LiveConsole:
|
|
35
|
+
__slots__ = ()
|
|
36
|
+
|
|
37
|
+
def log(self, *args: object) -> None:
|
|
38
|
+
print(*args, file=sys.stdout)
|
|
39
|
+
|
|
40
|
+
def error(self, *args: object) -> None:
|
|
41
|
+
print(*args, file=sys.stderr)
|
|
42
|
+
|
|
43
|
+
def warn(self, *args: object) -> None:
|
|
44
|
+
print(*args, file=sys.stderr)
|
|
45
|
+
|
|
46
|
+
def info(self, *args: object) -> None:
|
|
47
|
+
print(*args, file=sys.stdout)
|
|
48
|
+
|
|
49
|
+
def debug(self, *args: object) -> None:
|
|
50
|
+
print(*args, file=sys.stdout)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
LIVE_CONSOLE: ConsoleService = _LiveConsole()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class Console(Reference[ConsoleService], key="effect/Console"): # internal/effect.ts:6585
|
|
57
|
+
"""The fiber's Console. ``yield from Console()`` gives the service; the default is live."""
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def default(cls) -> ConsoleService:
|
|
61
|
+
return LIVE_CONSOLE
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def console_with[A, E, R](f: Callable[[ConsoleService], Effect[A, E, R]]) -> Effect[A, E, R]:
|
|
65
|
+
"""Run ``f`` with the fiber's Console (Console.ts consoleWith)."""
|
|
66
|
+
return Console().use().flat_map(f)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def log(*args: object) -> Effect[None, Never, Never]:
|
|
70
|
+
return console_with(lambda c: sync(lambda: c.log(*args)))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def error(*args: object) -> Effect[None, Never, Never]:
|
|
74
|
+
return console_with(lambda c: sync(lambda: c.error(*args)))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def warn(*args: object) -> Effect[None, Never, Never]:
|
|
78
|
+
return console_with(lambda c: sync(lambda: c.warn(*args)))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def info(*args: object) -> Effect[None, Never, Never]:
|
|
82
|
+
return console_with(lambda c: sync(lambda: c.info(*args)))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def debug(*args: object) -> Effect[None, Never, Never]:
|
|
86
|
+
return console_with(lambda c: sync(lambda: c.debug(*args)))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
__all__ = [
|
|
90
|
+
"LIVE_CONSOLE",
|
|
91
|
+
"Console",
|
|
92
|
+
"ConsoleService",
|
|
93
|
+
"console_with",
|
|
94
|
+
"debug",
|
|
95
|
+
"error",
|
|
96
|
+
"info",
|
|
97
|
+
"log",
|
|
98
|
+
"warn",
|
|
99
|
+
]
|