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/deferred.py ADDED
@@ -0,0 +1,99 @@
1
+ """One-time coordination with a stored completion Effect, not a memoized result.
2
+
3
+ Pinned Effect v4 Deferred.ts:151-193, :363-409, :647-695, :806-810, :881-894.
4
+ Only the constructors, await and completion operations covered by the Deferred unit are
5
+ ported. complete/completeWith, polling and the remaining convenience APIs are not ported.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Callable
11
+ from typing import Never, final
12
+
13
+ from .cause import Cause
14
+ from .core import Effect, Exit, Failure, Success, async_, fiber_id, sync
15
+
16
+
17
+ @final
18
+ class Deferred[A, E = Never]:
19
+ """An invariant cell completed once; each waiter runs the stored Effect itself.
20
+
21
+ A and E are invariant because the same cell is both completed and awaited. Stored
22
+ effects require no environment: an awaiter need not supply the completing fiber's services.
23
+ Like upstream, effect/resumes are visible for low-level consumers and white-box tests.
24
+ """
25
+
26
+ __slots__ = ("effect", "resumes")
27
+
28
+ def __init__(self) -> None:
29
+ self.effect: Effect[A, E, Never] | None = None
30
+ self.resumes: list[Callable[[Effect[A, E, Never]], None]] | None = None
31
+
32
+ @classmethod
33
+ def make_unsafe(cls) -> Deferred[A, E]:
34
+ """Allocate an empty cell synchronously (Deferred.ts:151)."""
35
+ return cls()
36
+
37
+ @classmethod
38
+ def make(cls) -> Effect[Deferred[A, E], Never, Never]:
39
+ """Allocate a fresh empty cell each time this effect runs (:178)."""
40
+ return sync(cls.make_unsafe)
41
+
42
+ def await_(self) -> Effect[A, E, Never]:
43
+ """Run the stored completion, or register until completed (:180-193)."""
44
+
45
+ def register(
46
+ resume: Callable[[Effect[A, E, Never]], None],
47
+ ) -> Effect[None, Never, Never] | None:
48
+ if self.effect is not None:
49
+ resume(self.effect)
50
+ return None
51
+ if self.resumes is None:
52
+ self.resumes = []
53
+ self.resumes.append(resume)
54
+
55
+ def unregister() -> None:
56
+ resumes = self.resumes
57
+ if resumes is None:
58
+ return # completion already detached the callbacks
59
+ try:
60
+ index = resumes.index(resume)
61
+ except ValueError:
62
+ return
63
+ del resumes[index]
64
+
65
+ return sync(unregister)
66
+
67
+ return async_(register)
68
+
69
+ def done_unsafe(self, effect: Effect[A, E, Never]) -> bool:
70
+ """Store once, detach all callbacks, then notify them synchronously (:881-894)."""
71
+ if self.effect is not None:
72
+ return False
73
+ self.effect = effect
74
+ if self.resumes is not None:
75
+ resumes = self.resumes
76
+ self.resumes = None
77
+ for resume in resumes:
78
+ resume(effect)
79
+ return True
80
+
81
+ def done(self, exit_: Exit[A, E]) -> Effect[bool, Never, Never]:
82
+ """Attempt completion with an Exit (:363-366, completeWith :323-326)."""
83
+ return sync(lambda: self.done_unsafe(exit_))
84
+
85
+ def succeed(self, value: A) -> Effect[bool, Never, Never]:
86
+ """Attempt successful completion (:806-810)."""
87
+ return self.done(Success(value))
88
+
89
+ def fail(self, error: E) -> Effect[bool, Never, Never]:
90
+ """Attempt typed failure completion (:400-404)."""
91
+ return self.done(Failure(Cause.fail(error)))
92
+
93
+ def interrupt_with(self, fiber_id_: int) -> Effect[bool, Never, Never]:
94
+ """Attempt interruption by the specified fiber (:683-695)."""
95
+ return self.done(Failure(Cause.interrupt(fiber_id_)))
96
+
97
+ def interrupt(self) -> Effect[bool, Never, Never]:
98
+ """Attempt interruption by the fiber executing this effect (:647-648)."""
99
+ return fiber_id.flat_map(self.interrupt_with)
peffect/duration.py ADDED
@@ -0,0 +1,497 @@
1
+ """Duration: a span of time, exact to the nanosecond. A port of the subset of Effect v4's
2
+ packages/effect/src/Duration.ts (vendor/effect-v4, commit 289a53f) that Clock and TestClock use.
3
+
4
+ A Duration holds one of four cases (Duration.ts:139 `DurationValue`): `Millis` (a JS number, here
5
+ a `float`), `Nanos` (a JS bigint, here an unbounded `int`), `Infinity` and `NegativeInfinity`.
6
+ Exact nanoseconds are only ever `int`, so they never lose precision through a float.
7
+
8
+ A Python `int` passed where upstream takes a JS number (`millis`, `seconds`, an `Input`) becomes
9
+ one the way JS `Number(bigint)` does: rounded to the nearest double, +-Infinity past its range.
10
+ Mapping, adaptations and the boundary cases: tests/test_duration_upstream.py.
11
+ """
12
+
13
+ import math
14
+ import re
15
+ from collections.abc import Callable
16
+ from dataclasses import dataclass
17
+ from decimal import Decimal
18
+ from typing import Final, Literal, Never, final, overload
19
+
20
+
21
+ @final
22
+ @dataclass(frozen=True, slots=True)
23
+ class Millis:
24
+ millis: float
25
+
26
+
27
+ @final
28
+ @dataclass(frozen=True, slots=True)
29
+ class Nanos:
30
+ nanos: int
31
+
32
+
33
+ @final
34
+ @dataclass(frozen=True, slots=True)
35
+ class Infinity:
36
+ pass
37
+
38
+
39
+ @final
40
+ @dataclass(frozen=True, slots=True)
41
+ class NegativeInfinity:
42
+ pass
43
+
44
+
45
+ type DurationValue = Millis | Nanos | Infinity | NegativeInfinity
46
+
47
+ _TOKEN: Final = object()
48
+
49
+
50
+ @final
51
+ class Duration:
52
+ """Built only by the constructors below, which normalize like upstream's private `make`."""
53
+
54
+ __slots__ = ("_value",)
55
+ _value: DurationValue
56
+
57
+ def __init__(self, value: DurationValue, token: object) -> None:
58
+ if token is not _TOKEN:
59
+ raise TypeError("build a Duration with millis, nanos or from_input_unsafe")
60
+ object.__setattr__(self, "_value", value)
61
+
62
+ @property
63
+ def value(self) -> DurationValue:
64
+ return self._value
65
+
66
+ def __setattr__(self, name: str, value: object) -> Never:
67
+ raise AttributeError("Duration is immutable")
68
+
69
+ def __delattr__(self, name: str) -> Never:
70
+ raise AttributeError("Duration is immutable")
71
+
72
+ def __eq__(self, that: object) -> bool: # Duration.ts:425, Equal.symbol
73
+ return isinstance(that, Duration) and equals(self, that)
74
+
75
+ def __hash__(self) -> int: # Duration.ts:415-424: canonical nanoseconds for finite values
76
+ match self._value:
77
+ case Millis(m):
78
+ return hash(_round_millis_to_nanos(m))
79
+ case Nanos(n):
80
+ return hash(n)
81
+ case v: # Hash.structure of the tag: the two infinities hash apart
82
+ return hash(type(v).__name__)
83
+
84
+ def __repr__(self) -> str:
85
+ return f"Duration({self._value!r})"
86
+
87
+
88
+ type Input = Duration | int | float | str
89
+ """Duration.ts:203. A number is millis; tuple and DurationObject inputs are not ported yet."""
90
+
91
+
92
+ # --- JS number arithmetic -------------------------------------------------------------------
93
+
94
+
95
+ def _number(x: float) -> float:
96
+ """JS `Number(x)`: an int too large for a double is +-Infinity, not an OverflowError."""
97
+ if isinstance(x, float):
98
+ return x
99
+ try:
100
+ return float(x)
101
+ except OverflowError:
102
+ return math.inf if x > 0 else -math.inf
103
+
104
+
105
+ def _round_ties_away_from_zero(x: float) -> int: # Duration.ts:43
106
+ a = abs(x)
107
+ whole = math.floor(a)
108
+ rounded = whole + 1 if a - whole >= 0.5 else whole
109
+ return -rounded if x < 0 else rounded
110
+
111
+
112
+ def _round_millis_to_nanos(millis: float) -> int: # Duration.ts:45
113
+ if millis.is_integer():
114
+ return int(millis) * 1_000_000
115
+ return _round_ties_away_from_zero(millis * 1_000_000)
116
+
117
+
118
+ def _trunc_divmod(n: int, d: int) -> tuple[int, int]:
119
+ """JS bigint `/` and `%`: the quotient truncates toward zero, the remainder takes n's sign."""
120
+ q = abs(n) // d
121
+ q = -q if n < 0 else q
122
+ return q, n - q * d
123
+
124
+
125
+ def _nanos_to_unit(nanos: int, divisor: int) -> float: # Duration.ts:50
126
+ value = _number(nanos)
127
+ if math.isfinite(value):
128
+ return value / divisor
129
+ q, r = _trunc_divmod(nanos, divisor)
130
+ return _number(q) + _number(r) / divisor
131
+
132
+
133
+ # --- make (Duration.ts:462) -----------------------------------------------------------------
134
+
135
+
136
+ def _make(value: DurationValue) -> Duration:
137
+ return Duration(value, _TOKEN)
138
+
139
+
140
+ def _from_number(x: float) -> Duration:
141
+ if math.isnan(x) or x == 0:
142
+ return zero
143
+ if math.isinf(x):
144
+ return infinity if x > 0 else negative_infinity
145
+ if not x.is_integer():
146
+ return _make(Nanos(_round_millis_to_nanos(x)))
147
+ return _make(Millis(x))
148
+
149
+
150
+ def _from_bigint(n: int) -> Duration:
151
+ return zero if n == 0 else _make(Nanos(n))
152
+
153
+
154
+ zero: Final[Duration] = _make(Millis(0.0))
155
+ infinity: Final[Duration] = _make(Infinity())
156
+ negative_infinity: Final[Duration] = _make(NegativeInfinity())
157
+
158
+
159
+ def nanos(nanos: int) -> Duration:
160
+ return _from_bigint(nanos)
161
+
162
+
163
+ def millis(millis: float) -> Duration:
164
+ return _from_number(_number(millis))
165
+
166
+
167
+ def seconds(seconds: float) -> Duration:
168
+ return _from_number(_number(seconds) * 1000)
169
+
170
+
171
+ def minutes(minutes: float) -> Duration:
172
+ return _from_number(_number(minutes) * 60_000)
173
+
174
+
175
+ def hours(hours: float) -> Duration:
176
+ return _from_number(_number(hours) * 3_600_000)
177
+
178
+
179
+ # --- from_input_unsafe (Duration.ts:246-330) ------------------------------------------------
180
+
181
+ # JS `\s` (WhiteSpace and LineTerminator) and ASCII-only `\d`; used with fullmatch, as JS `^...$`.
182
+ _JS_SPACE = "\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"
183
+ _DURATION_REGEXP: Final = re.compile(
184
+ rf"(-?[0-9]+(?:\.[0-9]+)?)[{_JS_SPACE}]+"
185
+ r"(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)"
186
+ )
187
+ _MILLIS_PER_UNIT: Final = {
188
+ "milli": 1,
189
+ "second": 1_000,
190
+ "minute": 60_000,
191
+ "hour": 3_600_000,
192
+ "day": 86_400_000,
193
+ "week": 604_800_000,
194
+ }
195
+
196
+
197
+ def _divide_ties_away_from_zero(numerator: int, denominator: int) -> int: # Duration.ts:71
198
+ a = abs(numerator)
199
+ rounded = a // denominator + (1 if a % denominator * 2 >= denominator else 0)
200
+ return -rounded if numerator < 0 else rounded
201
+
202
+
203
+ def _decimal_integer(text: str) -> int:
204
+ """Parse validated ASCII digits without Python's process-wide decimal limit."""
205
+ negative = text.startswith("-")
206
+ digits = text[1:] if negative else text
207
+ value = 0
208
+ for start in range(0, len(digits), 600):
209
+ chunk = digits[start : start + 600]
210
+ value = value * 10 ** len(chunk) + int(chunk)
211
+ return -value if negative else value
212
+
213
+
214
+ def _parse_nanos(text: str, scale: int) -> int: # Duration.ts:58
215
+ if "." not in text:
216
+ return _decimal_integer(text) * scale
217
+ negative = text[0] == "-"
218
+ whole, fractional = text[1 if negative else 0 :].split(".")
219
+ fractional_scale = 10 ** len(fractional)
220
+ scaled = (_decimal_integer(whole) * fractional_scale + _decimal_integer(fractional)) * scale
221
+ return _divide_ties_away_from_zero(-scaled if negative else scaled, fractional_scale)
222
+
223
+
224
+ def _from_millis_string(text: str, scale: int) -> Duration: # Duration.ts:77
225
+ millis = float(text) * scale
226
+ if not math.isfinite(millis):
227
+ return _from_number(millis)
228
+ nanos = _parse_nanos(text, scale * 1_000_000)
229
+ # Keep the millisecond representation only when it preserves the exact value.
230
+ if millis.is_integer() and int(millis) * 1_000_000 == nanos:
231
+ return _from_number(millis)
232
+ return _from_bigint(nanos)
233
+
234
+
235
+ def _js_string(value: object) -> str:
236
+ match value:
237
+ case None:
238
+ return "null"
239
+ case bool():
240
+ return "true" if value else "false"
241
+ case _:
242
+ return str(value)
243
+
244
+
245
+ def _invalid(value: object) -> Never: # Duration.ts:384
246
+ raise ValueError(f"Invalid Input: {_js_string(value)}")
247
+
248
+
249
+ def from_input_unsafe(input: Input) -> Duration:
250
+ match input:
251
+ case Duration():
252
+ return input
253
+ case bool(): # JS rejects booleans (typeof "boolean"); Python bool is an int
254
+ return _invalid(input)
255
+ case int() | float():
256
+ return millis(input)
257
+ case "Infinity":
258
+ return infinity
259
+ case "-Infinity":
260
+ return negative_infinity
261
+ case str():
262
+ found = _DURATION_REGEXP.fullmatch(input)
263
+ if found is None:
264
+ return _invalid(input)
265
+ text, unit = found.group(1), found.group(2).removesuffix("s")
266
+ if unit == "nano":
267
+ return nanos(_parse_nanos(text, 1))
268
+ if unit == "micro":
269
+ return nanos(_parse_nanos(text, 1_000))
270
+ return _from_millis_string(text, _MILLIS_PER_UNIT[unit])
271
+ case _: # the Input union is closed, but an untyped caller can pass anything
272
+ return _invalid(input)
273
+
274
+
275
+ # --- getters (Duration.ts:891, 1051) --------------------------------------------------------
276
+
277
+
278
+ def to_millis(input: Input) -> float:
279
+ match from_input_unsafe(input).value:
280
+ case Millis(m):
281
+ return m
282
+ case Nanos(n):
283
+ return _nanos_to_unit(n, 1_000_000)
284
+ case Infinity():
285
+ return math.inf
286
+ case NegativeInfinity():
287
+ return -math.inf
288
+
289
+
290
+ def to_nanos_unsafe(input: Input) -> int:
291
+ match from_input_unsafe(input).value:
292
+ case Millis(m):
293
+ return _round_millis_to_nanos(m)
294
+ case Nanos(n):
295
+ return n
296
+ case Infinity() | NegativeInfinity():
297
+ raise ValueError("Cannot convert infinite duration to nanos")
298
+
299
+
300
+ # --- pattern matching (Duration.ts:1140, 1198) ----------------------------------------------
301
+
302
+
303
+ @overload
304
+ def match[A, B, C](
305
+ self: Duration,
306
+ *,
307
+ on_millis: Callable[[float], A],
308
+ on_nanos: Callable[[int], B],
309
+ on_infinity: Callable[[], C],
310
+ ) -> A | B | C: ...
311
+ @overload
312
+ def match[A, B, C, D](
313
+ self: Duration,
314
+ *,
315
+ on_millis: Callable[[float], A],
316
+ on_nanos: Callable[[int], B],
317
+ on_infinity: Callable[[], C],
318
+ on_negative_infinity: Callable[[], D],
319
+ ) -> A | B | C | D: ...
320
+ def match[A, B, C, D](
321
+ self: Duration,
322
+ *,
323
+ on_millis: Callable[[float], A],
324
+ on_nanos: Callable[[int], B],
325
+ on_infinity: Callable[[], C],
326
+ on_negative_infinity: Callable[[], D] | None = None,
327
+ ) -> A | B | C | D:
328
+ match self.value:
329
+ case Millis(m):
330
+ return on_millis(m)
331
+ case Nanos(n):
332
+ return on_nanos(n)
333
+ case Infinity():
334
+ return on_infinity()
335
+ case NegativeInfinity():
336
+ return on_infinity() if on_negative_infinity is None else on_negative_infinity()
337
+
338
+
339
+ def _match_pair[A](
340
+ self: Duration,
341
+ that: Duration,
342
+ on_millis: Callable[[float, float], A],
343
+ on_nanos: Callable[[int, int], A],
344
+ on_infinity: Callable[[DurationValue, DurationValue], A],
345
+ ) -> A:
346
+ s, t = self.value, that.value
347
+ if isinstance(s, Infinity | NegativeInfinity) or isinstance(t, Infinity | NegativeInfinity):
348
+ return on_infinity(s, t)
349
+ if isinstance(s, Millis) and isinstance(t, Millis):
350
+ return on_millis(s.millis, t.millis)
351
+ return on_nanos(to_nanos_unsafe(self), to_nanos_unsafe(that))
352
+
353
+
354
+ # --- predicates (Duration.ts:516-594) -------------------------------------------------------
355
+
356
+
357
+ def is_finite(self: Duration) -> bool:
358
+ return isinstance(self.value, Millis | Nanos)
359
+
360
+
361
+ def is_zero(self: Duration) -> bool:
362
+ match self.value:
363
+ case Millis(m):
364
+ return m == 0
365
+ case Nanos(n):
366
+ return n == 0
367
+ case _:
368
+ return False
369
+
370
+
371
+ def is_negative(self: Duration) -> bool:
372
+ match self.value:
373
+ case Millis(m):
374
+ return m < 0
375
+ case Nanos(n):
376
+ return n < 0
377
+ case Infinity():
378
+ return False
379
+ case NegativeInfinity():
380
+ return True
381
+
382
+
383
+ # --- comparison and arithmetic (Duration.ts:1262-1645) --------------------------------------
384
+
385
+
386
+ def _compare(a: float, b: float) -> Literal[-1, 0, 1]:
387
+ return -1 if a < b else 1 if a > b else 0
388
+
389
+
390
+ def _compare_infinities(s: DurationValue, t: DurationValue) -> Literal[-1, 0, 1]:
391
+ if type(s) is type(t):
392
+ return 0
393
+ if isinstance(s, Infinity):
394
+ return 1
395
+ if isinstance(s, NegativeInfinity):
396
+ return -1
397
+ return -1 if isinstance(t, Infinity) else 1
398
+
399
+
400
+ def order(self: Duration, that: Duration) -> Literal[-1, 0, 1]:
401
+ return _match_pair(self, that, _compare, _compare, _compare_infinities)
402
+
403
+
404
+ def equals(self: Duration, that: Duration) -> bool:
405
+ return _match_pair(
406
+ self,
407
+ that,
408
+ lambda s, t: s == t,
409
+ lambda s, t: s == t,
410
+ lambda s, t: type(s) is type(t),
411
+ )
412
+
413
+
414
+ def _sum_infinities(s: DurationValue, t: DurationValue) -> Duration:
415
+ if isinstance(s, Infinity) and isinstance(t, NegativeInfinity):
416
+ return zero
417
+ if isinstance(s, NegativeInfinity) and isinstance(t, Infinity):
418
+ return zero
419
+ if isinstance(s, Infinity) or isinstance(t, Infinity):
420
+ return infinity
421
+ return negative_infinity
422
+
423
+
424
+ def sum(self: Duration, that: Duration) -> Duration:
425
+ return _match_pair(
426
+ self,
427
+ that,
428
+ lambda s, t: _from_number(s + t),
429
+ lambda s, t: _from_bigint(s + t),
430
+ _sum_infinities,
431
+ )
432
+
433
+
434
+ def _subtract_infinities(s: DurationValue, t: DurationValue) -> Duration:
435
+ if isinstance(s, Infinity):
436
+ return zero if isinstance(t, Infinity) else infinity
437
+ if isinstance(s, NegativeInfinity):
438
+ return zero if isinstance(t, NegativeInfinity) else negative_infinity
439
+ return negative_infinity if isinstance(t, Infinity) else infinity
440
+
441
+
442
+ def subtract(self: Duration, that: Duration) -> Duration:
443
+ return _match_pair(
444
+ self,
445
+ that,
446
+ lambda s, t: _from_number(s - t),
447
+ lambda s, t: _from_bigint(s - t),
448
+ _subtract_infinities,
449
+ )
450
+
451
+
452
+ # --- format (Duration.ts:1789-1895) ---------------------------------------------------------
453
+
454
+
455
+ def _js_integer_string(n: int) -> str:
456
+ """JS `${Number(n)}` for a whole count: digits below 1e21, then exponent notation (repr's
457
+ shortest round-trip form, e.g. `1e+21`), and `Infinity` past the double range."""
458
+ x = _number(n)
459
+ if math.isinf(x):
460
+ return "Infinity" if x > 0 else "-Infinity"
461
+ # Expand the shortest round-trip decimal, not the exact binary integer.
462
+ return f"{Decimal(repr(x)):f}".removesuffix(".0") if abs(x) < 1e21 else repr(x)
463
+
464
+
465
+ def format(self: Duration) -> str:
466
+ """``2d 6h``, ``1s 500ms``, ``1ms 500000ns``; ``0``, ``Infinity``, ``-Infinity``. The
467
+ nanosecond piece is what is left below a millisecond (upstream `parts`)."""
468
+ match self.value:
469
+ case Infinity():
470
+ return "Infinity"
471
+ case NegativeInfinity():
472
+ return "-Infinity"
473
+ case _:
474
+ pass
475
+ if is_zero(self):
476
+ return "0"
477
+ n = to_nanos_unsafe(self)
478
+ if n < 0:
479
+ return "-" + format(_from_bigint(-n))
480
+ ms, nanos_part = divmod(n, 1_000_000)
481
+ sec, ms_part = divmod(ms, 1_000)
482
+ mins, sec_part = divmod(sec, 60)
483
+ hrs, min_part = divmod(mins, 60)
484
+ days, hr_part = divmod(hrs, 24)
485
+ pieces = [
486
+ f"{_js_integer_string(value)}{unit}"
487
+ for value, unit in (
488
+ (days, "d"),
489
+ (hr_part, "h"),
490
+ (min_part, "m"),
491
+ (sec_part, "s"),
492
+ (ms_part, "ms"),
493
+ (nanos_part, "ns"),
494
+ )
495
+ if value != 0
496
+ ]
497
+ return " ".join(pieces)