gdp-wired 0.41.1 → 0.43.0

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.
@@ -0,0 +1,817 @@
1
+ // Effect's Schedule (3.x and 4.x) as a rule (`gdp-wired/effect`): a retry or repeat policy read from its source into
2
+ // one state machine, each step one of the schedule's decisions (continue after a delay, or stop). Every combinator is a
3
+ // fragment of that machine, its own state beside the others', and composes with any other: spaced, recurs, forever,
4
+ // exponential (its delay a `recur` function of the attempt, its lemmas proven by induction), fibonacci (its two
5
+ // numbers), linear, during, upTo, union/intersect (4.x: min/max), andThen (4.x: concat), whileInput/whileOutput and
6
+ // untilInput/untilOutput (4.x: while), addDelay, modifyDelay and jittered (each jittered delay an input bounded by
7
+ // its range). The rule's own state is what a law reads: `attempt` (decisions made), `retries` (those that continued),
8
+ // `delay` (the last delay decided), `elapsed` (when the last decision was made, from the first) and `done`; each step's
9
+ // inputs are `took` (how long the attempt before it ran) and, where the schedule reads it, its input (the error a
10
+ // retry feeds it). The check steps Effect's own schedule (4.x's Schedule.toStep, 3.x's step) beside the rule.
11
+ //
12
+ // const x = extractEffect('./policy.ts', {entry: 'policy'}) // a schedule in a file, or fromSchedule(source, {effect})
13
+ // proveRule(x.rule!, [x.rule!.law('the delay never exceeds the cap', ({delay}) => delay.atMost(5000))])
14
+ import ts from 'typescript';
15
+ import { all, any, bool, lit, max, min, nat, no, oneOf, recur, rule, when, yes } from "./dsl.js";
16
+ import { evalC, interpret, seeded } from "./machine.js";
17
+ import { Refusal, bare as strip, memberName, refuse, text } from "./extract-read.js";
18
+ // What the reading builds beside the fragments: the rule's params, inputs, functions, assumptions, state and notes.
19
+ class Parts {
20
+ params = new Map();
21
+ inputs = new Map();
22
+ fns = {};
23
+ assume = [];
24
+ state = new Map();
25
+ notes = new Set();
26
+ jitters = [];
27
+ inputType;
28
+ inputAt;
29
+ fields = new Map();
30
+ n = new Map();
31
+ fresh(stem) { const i = (this.n.get(stem) ?? 0) + 1; this.n.set(stem, i); return `${stem}${i}`; }
32
+ initOf(name, env) { const s = this.state.get(name); return typeof s.init === 'function' ? s.init(env) : typeof s.init === 'boolean' ? (s.init ? yes : no) : lit(s.init); }
33
+ }
34
+ const term = (n, env) => (n.k === 'lit' ? lit(n.v) : n.scale === 1 ? env[n.name] : env[n.name].times(n.scale));
35
+ const UNITS = { nano: 1e-6, nanos: 1e-6, micro: 1e-3, micros: 1e-3, milli: 1, millis: 1, second: 1000, seconds: 1000, minute: 60_000, minutes: 60_000, hour: 3_600_000, hours: 3_600_000, day: 86_400_000, days: 86_400_000, week: 604_800_000, weeks: 604_800_000 };
36
+ const whole = (at, v, what) => (Number.isSafeInteger(v) && v >= 0 ? v : refuse(at, `${what} is ${v}: a whole number of milliseconds, at least 0, is read (the rule counts milliseconds as naturals)`));
37
+ // --- the reader ------------------------------------------------------------------------------------------------------
38
+ export function readSchedule(e, rc, parts = new Parts()) {
39
+ return { frag: sched(e, rc, parts), parts };
40
+ }
41
+ function sched(e0, rc, P) {
42
+ const e = strip(e0);
43
+ // A name: a schedule the file makes elsewhere (its value read where it is written).
44
+ if (ts.isIdentifier(e)) {
45
+ const d = rc.checker.getSymbolAtLocation(e)?.valueDeclaration, b = d && rc.bound?.get(d);
46
+ if (b) {
47
+ rc.bound.delete(d);
48
+ return b;
49
+ }
50
+ if (d && rc.bound && ts.isParameter(d) && rc.bound.has(d) === false && d.parent && ts.isArrowFunction(d.parent))
51
+ return refuse(e, `${e.text}: the schedule a function in a pipe is given, read twice (its state would step twice)`);
52
+ if (d && ts.isVariableDeclaration(d) && d.initializer && d.getSourceFile() === rc.sf)
53
+ return sched(d.initializer, rc, P);
54
+ return refuse(e, `${e.text}: a schedule other than one written in this file`);
55
+ }
56
+ const api = ts.isPropertyAccessExpression(e) ? rc.api(e) : ts.isCallExpression(e) ? rc.api(e.expression) : undefined;
57
+ // x.pipe(f, g, ...): each a combinator given its other arguments (data-last).
58
+ if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && memberName(e.expression.name) === 'pipe' && !api) {
59
+ let f = sched(e.expression.expression, rc, P);
60
+ for (const a of e.arguments)
61
+ f = combinator(strip(a), f, rc, P);
62
+ return f;
63
+ }
64
+ const [m, op = ''] = api?.split('.') ?? [];
65
+ if (m !== 'Schedule')
66
+ return refuse(e, `${text(e)}: not a schedule the reader reads (Schedule's constructors and combinators)`);
67
+ if (ts.isPropertyAccessExpression(e)) {
68
+ if (op === 'forever')
69
+ return spacedFrag(P, { k: 'lit', v: 0 });
70
+ if (op === 'once')
71
+ return recursFrag(P, { k: 'lit', v: 1 });
72
+ if (op === 'stop' && !rc.v4)
73
+ return recursFrag(P, { k: 'lit', v: 0 });
74
+ return refuse(e, `Schedule.${op} (${READ})`);
75
+ }
76
+ const c = e, a0 = c.arguments[0];
77
+ switch (op) {
78
+ case 'spaced': return spacedFrag(P, dur(a0, c, rc));
79
+ case 'recurs': return recursFrag(P, count(a0, c, rc));
80
+ case 'exponential': return expFrag(P, dur(a0, c, rc), c.arguments[1] ? factor(c.arguments[1], rc) : 2, c);
81
+ case 'fibonacci': return fibFrag(P, dur(a0, c, rc));
82
+ case 'linear':
83
+ if (!rc.v4)
84
+ return linearFrag(P, dur(a0, c, rc));
85
+ break;
86
+ case 'during':
87
+ if (rc.v4)
88
+ return duringFrag(P, dur(a0, c, rc));
89
+ break;
90
+ case 'fromDelay':
91
+ case 'duration': return onceFrag(P, dur(a0, c, rc));
92
+ case 'recurUpTo':
93
+ if (!rc.v4)
94
+ return upToFrag(leaf((_, __, cx) => ({ cont: yes, delay: lit(0), out: cx.elapsed, outDur: true, next: {} })), P, dur(a0, c, rc), undefined, true);
95
+ break;
96
+ case 'min':
97
+ case 'max':
98
+ if (rc.v4) {
99
+ const xs = a0 && ts.isArrayLiteralExpression(strip(a0)) ? strip(a0).elements : refuse(c, `Schedule.${op} of other than an array written here`);
100
+ if (!xs.length)
101
+ return refuse(c, `Schedule.${op}([])`);
102
+ // (min steps every schedule again after it stopped: a combinator inside counts its own metadata, see own())
103
+ const rc2 = op === 'min' ? { ...rc, underMin: true } : rc;
104
+ return xs.slice(1).reduce((f, x) => both(op === 'min' ? 'union' : 'intersect', f, sched(x, rc2, P), P), sched(xs[0], rc2, P));
105
+ }
106
+ break;
107
+ }
108
+ // A combinator given its schedule first (data-first): Schedule.union(a, b), Schedule.upTo(s, d).
109
+ if (c.arguments.length >= 1 && COMBINATORS.has(op))
110
+ return combinator(c, sched(a0, rc, P), rc, P, 1);
111
+ return refuse(c, `Schedule.${op}${rc.v4 ? ' in Effect 4' : ' in Effect 3'} (${READ})`);
112
+ }
113
+ const READ = 'read: spaced, recurs, forever, once, exponential, fibonacci, linear (3.x), during (4.x), union, intersect, either, andThen (3.x), min, max, concat (4.x), upTo, whileInput, whileOutput, untilInput, untilOutput, check (3.x), while (4.x), addDelay, modifyDelay, jittered, jitteredWith (3.x), passthrough';
114
+ const COMBINATORS = new Set(['union', 'either', 'intersect', 'zipLeft', 'zipRight', 'andThen', 'concat', 'upTo', 'whileInput', 'whileOutput', 'untilInput', 'untilOutput', 'check', 'while', 'addDelay', 'modifyDelay', 'jittered', 'jitteredWith', 'passthrough']);
115
+ // A combinator applied to `self`: its call (data-last, `skip` 0) or its data-first call (`skip` 1: the schedule is its
116
+ // first argument).
117
+ function combinator(a, self, rc, P, skip = 0) {
118
+ // (a function of the schedule so far, written in the pipe: its body read with its parameter that schedule)
119
+ if ((ts.isArrowFunction(a) || ts.isFunctionExpression(a)) && a.parameters.length === 1 && skip === 0) {
120
+ const body = ts.isBlock(a.body) ? (a.body.statements.length === 1 && ts.isReturnStatement(a.body.statements[0]) ? a.body.statements[0].expression : undefined) : a.body;
121
+ if (!body)
122
+ return refuse(a, 'a function in a pipe other than one returning a schedule');
123
+ (rc.bound ??= new Map()).set(a.parameters[0], self);
124
+ return sched(body, rc, P);
125
+ }
126
+ const api = rc.api(ts.isCallExpression(a) ? a.expression : a) ?? '';
127
+ const [m, op = ''] = api.split('.');
128
+ if (m !== 'Schedule')
129
+ return refuse(a, `${text(a)} in a schedule's pipe (${READ})`);
130
+ // (a value given to pipe: Schedule.jittered, Schedule.passthrough)
131
+ if (!ts.isCallExpression(a) || (skip === 1 && a.arguments.length === 1)) {
132
+ if (op === 'jittered')
133
+ return jitterFrag(self, P, [4, 5], [6, 5]);
134
+ if (op === 'passthrough')
135
+ return { ...self, step: (env, get, c) => ({ ...self.step(env, get, c), out: undefined }) };
136
+ return refuse(a, `Schedule.${op} given as a value (${READ})`);
137
+ }
138
+ const args = a.arguments.slice(skip), x = args[0];
139
+ const other = () => sched(x ?? refuse(a, `Schedule.${op}() with no schedule`), rc, P);
140
+ switch (op) {
141
+ case 'union':
142
+ case 'either':
143
+ if (!rc.v4)
144
+ return both('union', self, other(), P);
145
+ break;
146
+ case 'intersect':
147
+ case 'zipLeft':
148
+ case 'zipRight':
149
+ if (!rc.v4)
150
+ return both('intersect', self, other(), P);
151
+ break;
152
+ case 'andThen':
153
+ case 'concat':
154
+ if ((op === 'concat') === rc.v4)
155
+ return andThenFrag(self, other(), P);
156
+ break;
157
+ case 'upTo':
158
+ if (!rc.v4)
159
+ return upToFrag(self, P, dur(x, a, rc), undefined, true);
160
+ if (x && ts.isObjectLiteralExpression(strip(x))) {
161
+ const o = strip(x), get = (k) => o.properties.find(p => ts.isPropertyAssignment(p) && memberName(p.name) === k)?.initializer;
162
+ for (const p of o.properties)
163
+ if (!ts.isPropertyAssignment(p) || !['duration', 'times'].includes(memberName(p.name)))
164
+ refuse(p, `Schedule.upTo's ${text(p)} (duration and times are read)`);
165
+ return upToFrag(self, P, get('duration') && dur(get('duration'), a, rc), get('times') && count(get('times'), a, rc), false, rc);
166
+ }
167
+ return refuse(a, 'Schedule.upTo of other than {duration, times} written here');
168
+ case 'whileInput':
169
+ case 'untilInput':
170
+ case 'whileOutput':
171
+ case 'untilOutput':
172
+ if (!rc.v4)
173
+ return whileFrag(self, P, x, rc, op);
174
+ break;
175
+ case 'check':
176
+ if (!rc.v4)
177
+ return whileFrag(self, P, x, rc, op);
178
+ break;
179
+ case 'while':
180
+ if (rc.v4)
181
+ return whileFrag(self, P, x, rc, op);
182
+ break;
183
+ case 'addDelay':
184
+ case 'modifyDelay': return delayFrag(self, P, x, rc, op);
185
+ case 'jitteredWith':
186
+ if (!rc.v4) {
187
+ const o = x && ts.isObjectLiteralExpression(strip(x)) ? strip(x) : refuse(a, 'Schedule.jitteredWith of other than {min, max} written here');
188
+ const get = (k, d) => { const p = o.properties.find(q => ts.isPropertyAssignment(q) && memberName(q.name) === k); return p ? ratio(p.initializer) : d; };
189
+ return jitterFrag(self, P, get('min', [4, 5]), get('max', [6, 5]));
190
+ }
191
+ break;
192
+ }
193
+ return refuse(a, `Schedule.${op}${rc.v4 ? ' in Effect 4' : ' in Effect 3'} (${READ})`);
194
+ }
195
+ // A duration: 'N unit', a number of milliseconds, Duration.<unit>(n) of a literal or a param, a const of the file.
196
+ function dur(x, at, rc) {
197
+ if (!x)
198
+ return refuse(at, `${text(at)} with no duration`);
199
+ const e = strip(x);
200
+ if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e)) {
201
+ const m = /^\s*(\d+(?:\.\d+)?)\s*([a-z]+)\s*$/.exec(e.text);
202
+ if (!m || !(m[2] in UNITS))
203
+ return refuse(e, `the duration ${e.getText()} (a number and a unit, as Duration reads it)`);
204
+ return { k: 'lit', v: whole(e, Number(m[1]) * UNITS[m[2]], e.getText()) };
205
+ }
206
+ if (ts.isCallExpression(e)) {
207
+ const api = rc.api(e.expression) ?? '', unit = /^Duration\.(millis|seconds|minutes|hours|days|weeks)$/.exec(api)?.[1];
208
+ if (unit) {
209
+ const n = count(e.arguments[0], e, rc);
210
+ return n.k === 'lit' ? { k: 'lit', v: whole(e, n.v * UNITS[unit], e.getText()) } : { ...n, scale: n.scale * UNITS[unit] };
211
+ }
212
+ if (api === 'Duration.decode' || api === 'Duration.fromInputUnsafe')
213
+ return dur(e.arguments[0], e, rc);
214
+ return refuse(e, `the duration ${text(e)} (Duration.millis, seconds, minutes, hours, days or weeks, a number of milliseconds, or 'N unit')`);
215
+ }
216
+ if (ts.isPropertyAccessExpression(e) && rc.api(e) === 'Duration.zero')
217
+ return { k: 'lit', v: 0 };
218
+ const n = count(e, at, rc);
219
+ return n;
220
+ }
221
+ // A whole number: a literal, a param of the function that makes the schedule, or a const of the file.
222
+ function count(x, at, rc) {
223
+ if (!x)
224
+ return refuse(at, `${text(at)} with no number`);
225
+ const e = strip(x);
226
+ if (ts.isNumericLiteral(e))
227
+ return { k: 'lit', v: whole(e, Number(e.text), e.text) };
228
+ if (ts.isIdentifier(e)) {
229
+ const d = rc.checker.getSymbolAtLocation(e)?.valueDeclaration;
230
+ const p = d && rc.params.get(d);
231
+ if (p)
232
+ return { k: 'param', name: p, scale: 1 };
233
+ // (a parameter of a function around it that isn't the schedule's: a policy written inside a service)
234
+ if (d && ts.isParameter(d) && rc.outer)
235
+ return rc.outer(e);
236
+ if (d && ts.isVariableDeclaration(d) && d.initializer && ts.isVariableDeclarationList(d.parent) && d.parent.flags & ts.NodeFlags.Const)
237
+ return count(d.initializer, at, rc);
238
+ }
239
+ return refuse(e, `${text(e)}: a number other than a literal, a const or a param of the function making the schedule`);
240
+ }
241
+ const factor = (x, rc) => {
242
+ const lit0 = strip(x);
243
+ if (ts.isNumericLiteral(lit0) && !(Number.isInteger(Number(lit0.text)) && Number(lit0.text) >= 1))
244
+ return refuse(x, `an exponential's factor ${lit0.text}: a whole number at least 1, written here, is read (another makes fractional delays)`);
245
+ const n = count(x, x, rc);
246
+ return n.k === 'lit' && n.v >= 1 ? n.v : refuse(x, `an exponential's factor ${text(x)}: a whole number at least 1, written here, is read (another makes fractional delays)`);
247
+ };
248
+ // A fraction written as a decimal literal (jitter's bounds): [p, q] for p / q.
249
+ const ratio = (x) => {
250
+ const e = strip(x);
251
+ if (!ts.isNumericLiteral(e))
252
+ return refuse(e, `${text(e)}: a jitter's bound other than a number written here`);
253
+ const [i = '', f = ''] = e.text.split('.'), q = 10 ** f.length;
254
+ return [Number(i + f), q];
255
+ };
256
+ function own(P, rc) {
257
+ if (!rc.v4 || !rc.underMin)
258
+ return undefined;
259
+ const n = nat0(P, 'meta_n'), start = nat0(P, 'meta_start'), on = flag(P, 'meta_on');
260
+ return {
261
+ names: [n, start, on],
262
+ ctx: (env, get) => { const now = env.$now; return { attempt: get(n), elapsed: when(get(on), now.minus(get(start)), 0), first: get(n).eq(0) }; },
263
+ next: (env, get, x) => { const now = env.$now, on0 = get(on); return { [n]: when(x.cont, get(n).plus(1), get(n)), [start]: when(on0.not().and(x.cont), now, get(start)), [on]: on0.or(x.cont) }; },
264
+ };
265
+ }
266
+ const nat0 = (P, stem) => { const n = P.fresh(stem); P.state.set(n, { kind: 'nat', init: 0 }); return n; };
267
+ const flag = (P, stem, init = false) => { const n = P.fresh(stem); P.state.set(n, { kind: 'bool', init }); return n; };
268
+ const leaf = (step) => ({ step, names: [] });
269
+ function spacedFrag(P, d) { void P; return leaf((env, _, c) => ({ cont: yes, delay: term(d, env), out: c.attempt, next: {} })); }
270
+ function recursFrag(P, n) { void P; return leaf((env, _, c) => ({ cont: c.attempt.lt(term(n, env)), delay: lit(0), out: c.attempt, next: {} })); }
271
+ function onceFrag(P, d) { void P; return leaf((env, _, c) => ({ cont: c.attempt.eq(0), delay: when(c.attempt.eq(0), term(d, env), 0), next: {} })); }
272
+ function duringFrag(P, d) { void P; return leaf((env, _, c) => ({ cont: c.elapsed.atMost(term(d, env)), delay: lit(0), out: c.elapsed, outDur: true, next: {} })); }
273
+ function linearFrag(P, d) {
274
+ return leaf((env, _, c) => { const base = term(d, env), at = c.attempt.plus(1), delay = d.k === 'lit' ? at.times(d.v) : base.mul(at); void P; return { cont: yes, delay, out: delay, outDur: true, next: {} }; });
275
+ }
276
+ // The exponential's delay: base·factor^attempt, a function defined by its recurrence on the attempt, its lemmas (at
277
+ // least the base; never shrinks) proven by induction when it is made.
278
+ const exps = new Map();
279
+ function expFrag(P, d, f, at) {
280
+ void at;
281
+ const name = d.k === 'lit' ? `exponential_x${f}_b${d.v}` : `exponential_x${f}`;
282
+ let fd = exps.get(name);
283
+ if (!fd) {
284
+ fd = d.k === 'lit'
285
+ ? recur(name, { zero: d.v, next: (_, p) => p.times(f) }, { 'at least the base': (_, p) => p.atLeast(d.v) }, { 'never shrinks': (_, p, __, q) => p.atMost(q) })
286
+ : recur(name, { args: ['base'], zero: ({ base }) => base, next: (_, p) => p.times(f) }, { 'at least the base': (_, p, { base }) => p.atLeast(base) }, { 'never shrinks': (_, p, __, q) => p.atMost(q) });
287
+ exps.set(name, fd);
288
+ }
289
+ P.fns[name] = fd;
290
+ P.notes.add(`an exponential's delay is ${name}(attempt), defined by its recurrence (base, then ×${f} a step); its lemmas (at least the base; never shrinks) are proven by induction and are its facts`);
291
+ return leaf((env, _, c) => { const delay = d.k === 'lit' ? env[name](c.attempt) : env[name](c.attempt, term(d, env)); return { cont: yes, delay, out: delay, outDur: true, next: {} }; });
292
+ }
293
+ // Fibonacci: its two numbers in the state (one, one, two, three, ...), as Effect keeps them.
294
+ function fibFrag(P, d) {
295
+ const a = P.fresh('fib_a'), b = P.fresh('fib_b');
296
+ P.state.set(a, { kind: 'nat', init: 0 });
297
+ P.state.set(b, { kind: 'nat', init: d.k === 'lit' ? d.v : (p) => term(d, p) });
298
+ return { names: [a, b], step: (_, get) => ({ cont: yes, delay: get(b), out: get(b), outDur: true, next: { [a]: get(b), [b]: get(a).plus(get(b)) } }) };
299
+ }
300
+ // union: either goes on, the smaller delay of those that do; intersect: both go on, the larger delay.
301
+ function both(how, l, r, P) {
302
+ void P;
303
+ return { names: [...l.names, ...r.names], jitters: [...l.jitters ?? [], ...r.jitters ?? []], step: (env, get, c) => {
304
+ const x = l.step(env, get, c), y = r.step(env, get, c);
305
+ const cont = how === 'union' ? any(x.cont, y.cont) : all(x.cont, y.cont);
306
+ const delay = how === 'union' ? when(x.cont.and(y.cont), min(x.delay, y.delay), when(x.cont, x.delay, y.delay)) : max(x.delay, y.delay);
307
+ return { cont, delay, next: { ...x.next, ...y.next }, jittered: x.jittered || y.jittered };
308
+ } };
309
+ }
310
+ // andThen: the first until it stops, then the second from its start (stepped at once, as Effect steps it), its own
311
+ // attempts and elapsed time counted from there.
312
+ function andThenFrag(l, r, P) {
313
+ const phase = flag(P, 'then'), n = nat0(P, 'then_n'), start = nat0(P, 'then_start');
314
+ return { names: [...l.names, ...r.names, phase, n, start], jitters: [...l.jitters ?? [], ...r.jitters ?? []], step: (env, get, c) => {
315
+ const inR = get(phase), now = env.$now;
316
+ const x = l.step(env, get, c), fromStart = (k) => (r.names.includes(k) ? P.initOf(k, env) : get(k));
317
+ const dl = (l.jitters ?? []).map(j => env[`${j}$on`]);
318
+ const y0 = r.step(env, fromStart, { attempt: lit(0), elapsed: lit(0), first: yes }), d0 = (r.jitters ?? []).map(j => ({ d: env[`${j}$d`], on: env[`${j}$on`] }));
319
+ const y1 = r.step(env, get, { attempt: get(n), elapsed: now.minus(get(start)), first: get(n).eq(0) });
320
+ (r.jitters ?? []).forEach((j, i) => { env[`${j}$d`] = when(inR, env[`${j}$d`], d0[i].d); env[`${j}$on`] = when(inR, env[`${j}$on`], d0[i].on.and(inR.not(), x.cont.not())); });
321
+ (l.jitters ?? []).forEach((j, i) => { env[`${j}$on`] = inR.not().and(dl[i]); });
322
+ const toR = inR.not().and(x.cont.not());
323
+ const pick = (a, b, cc) => when(inR, a, when(x.cont, b, cc));
324
+ const next = {};
325
+ for (const k of l.names)
326
+ next[k] = when(inR, get(k), x.next[k] ?? get(k));
327
+ for (const k of r.names)
328
+ next[k] = pick(y1.next[k] ?? get(k), get(k), y0.next[k] ?? P.initOf(k, env));
329
+ for (const j of r.jitters ?? []) {
330
+ const on = P.jitters.find(q => q.name === j).on;
331
+ next[on] = env[`${j}$on`];
332
+ }
333
+ for (const j of l.jitters ?? []) {
334
+ const on = P.jitters.find(q => q.name === j).on;
335
+ next[on] = env[`${j}$on`];
336
+ }
337
+ next[phase] = inR.or(toR);
338
+ next[n] = when(inR.or(toR), get(n).plus(1), get(n));
339
+ next[start] = when(toR, now, get(start));
340
+ return { cont: pick(y1.cont, yes, y0.cont), delay: pick(y1.delay, x.delay, y0.delay), next, jittered: x.jittered || y0.jittered || y1.jittered };
341
+ } };
342
+ }
343
+ // upTo: goes on while the elapsed time is within the duration (3.x: below it; 4.x: at most it) and, in 4.x, while it has
344
+ // been stepped fewer than `times` times.
345
+ function upToFrag(self, P, d, times, strict, rc) {
346
+ const o = rc && own(P, rc);
347
+ return { ...self, names: [...self.names, ...o?.names ?? []], step: (env, get, c0) => {
348
+ const x = self.step(env, get, c0), c = o ? o.ctx(env, get, c0) : c0;
349
+ const within = d ? (strict ? c.elapsed.lt(term(d, env)) : c.elapsed.atMost(term(d, env))) : yes, few = times ? c.attempt.lt(term(times, env)) : yes;
350
+ return { ...x, cont: all(x.cont, within, few), next: { ...x.next, ...o?.next(env, get, x) } };
351
+ } };
352
+ }
353
+ // jittered: the delay drawn between lo and hi times the delay (Effect's Random); in the rule an input of each step,
354
+ // assumed within the range rounded outward to whole milliseconds, the delay it jitters kept beside it.
355
+ function jitterFrag(self, P, lo, hi) {
356
+ const j = P.fresh('jitter'), base = nat0(P, `${j}_base`), on = flag(P, `${j}_on`);
357
+ P.inputs.set(j, nat);
358
+ P.jitters.push({ name: j, base, on, lo, hi });
359
+ P.notes.add(`each jittered delay is an input (${j}), assumed between ${lo[0] / lo[1]} and ${hi[0] / hi[1]} times the delay it jitters, rounded outward to whole milliseconds: Effect draws a real number there. Every run of Effect's is one of the rule's with each jittered delay rounded down or up (the attempts' times taking up the rest), so a decision on the time (below or at most a whole number of milliseconds, as upTo and during make it: the times rounded down, or up) comes out the same, and so does a law comparing the delay with a whole number of milliseconds or with another delay; a law comparing it with the elapsed time is decided on whole milliseconds. A function reading the delay after the jitter is refused`);
360
+ // (the range assumed where the jitter is drawn: the delay it jitters goes on, in a schedule the step takes)
361
+ P.assume.push(env => { const d = env[`${j}$d`] ?? lit(0), used = env[`${j}$on`] ?? no; return used.implies(all(d.times(lo[0]).atMost(env[j].times(lo[1]).plus(lo[1] - 1)), env[j].times(hi[1]).atMost(d.times(hi[0]).plus(hi[1] - 1)))); });
362
+ return { names: [...self.names, base, on], jitters: [...self.jitters ?? [], j], step: (env, get, c) => {
363
+ const x = self.step(env, get, c);
364
+ env[`${j}$d`] = x.delay;
365
+ env[`${j}$on`] = x.cont;
366
+ return { ...x, delay: when(x.cont, env[j], x.delay), next: { ...x.next, [base]: x.delay, [on]: x.cont }, jittered: true };
367
+ } };
368
+ }
369
+ // while / whileInput / whileOutput / untilInput / untilOutput / check: goes on where the inner one does and the predicate
370
+ // holds of the input, the output or (4.x) the metadata.
371
+ function whileFrag(self, P, f, rc, op) {
372
+ const fn = f && strip(f);
373
+ if (!fn || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)))
374
+ return refuse(f ?? fn, `Schedule.${op} of other than a function written here`);
375
+ const o = own(P, rc);
376
+ return { ...self, names: [...self.names, ...o?.names ?? []], step: (env, get, c0) => {
377
+ const x = self.step(env, get, c0), c = o ? o.ctx(env, get, c0) : c0;
378
+ const ctx = callbackCtx(fn, rc, P, env, c, x, op);
379
+ const v = body(fn, ctx), ok = asCond(v, fn);
380
+ return { ...x, cont: x.cont.and(/^until/.test(op) ? ok.not() : ok), next: { ...x.next, ...o?.next(env, get, x) } };
381
+ } };
382
+ }
383
+ // addDelay / modifyDelay: the delay the function gives (3.x: of the output and the delay; 4.x: of the metadata, as an
384
+ // effect), added to the delay or put in its place.
385
+ function delayFrag(self, P, f, rc, op) {
386
+ const fn = f && strip(f);
387
+ if (!fn || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)))
388
+ return refuse(f ?? fn, `Schedule.${op} of other than a function written here`);
389
+ const o = own(P, rc);
390
+ return { ...self, names: [...self.names, ...o?.names ?? []], step: (env, get, c0) => {
391
+ const x = self.step(env, get, c0), c = o ? o.ctx(env, get, c0) : c0;
392
+ const v = asDur(body(fn, callbackCtx(fn, rc, P, env, c, x, op)), fn);
393
+ return { ...x, delay: when(x.cont, op === 'addDelay' ? x.delay.plus(v) : v, x.delay), next: { ...x.next, ...o?.next(env, get, x) } };
394
+ } };
395
+ }
396
+ function callbackCtx(fn, rc, P, env, c, x, op) {
397
+ // (each parameter's value made where the function reads it)
398
+ const vars = new Map();
399
+ const out = (at) => (x.out ? { t: x.outDur ? 'dur' : 'num', e: x.out } : refuse(at, `the output of this schedule (a combination, or one whose output isn't a number or a duration): ${op} reads it`));
400
+ const input = (p) => inputVal(p, rc, P, env);
401
+ // (the elapsed time, where a jitter moves it, is Effect's real number: a comparison of it in a function may come out
402
+ // otherwise on whole milliseconds; upTo and during compare it as the rule's rounding keeps)
403
+ const elapsedRead = (at) => (P.jitters.length ? refuse(at, 'the elapsed time read in a function of a jittered schedule (Effect\'s is a real number of milliseconds there, the rule\'s a whole one): bound it with upTo or during') : { t: 'num', e: c.elapsed });
404
+ const ps = fn.parameters;
405
+ const bind = (p, v) => {
406
+ if (!p)
407
+ return;
408
+ if (ts.isIdentifier(p.name)) {
409
+ vars.set(p, v);
410
+ return;
411
+ }
412
+ if (ts.isObjectBindingPattern(p.name)) {
413
+ const o = v();
414
+ for (const el of p.name.elements) {
415
+ const k = memberName((el.propertyName ?? el.name));
416
+ vars.set(el, () => (o.t === 'obj' ? o.field(k, el) : refuse(el, `${k} of a value with no fields`)));
417
+ }
418
+ return;
419
+ }
420
+ refuse(p, `the parameter ${text(p)} (a name, or {fields} of the metadata)`);
421
+ };
422
+ if (rc.v4) {
423
+ // 4.x's metadata: input, output, attempt (from 1), elapsed, duration (the delay).
424
+ const p = ps[0];
425
+ const meta = { t: 'obj', field: (k, at) => k === 'input' ? (p ? inputVal(p, rc, P, env, 'input') : refuse(at, 'input')) : k === 'output' ? out(at) : k === 'attempt' ? { t: 'num', e: c.attempt.plus(1) } : k === 'elapsed' ? elapsedRead(at) : k === 'duration' ? jitteredDelay(x, at)
426
+ : refuse(at, `the metadata's ${k} (input, output, attempt, elapsed and duration are read)`) };
427
+ bind(p, () => meta);
428
+ }
429
+ else if (op === 'whileInput' || op === 'untilInput')
430
+ bind(ps[0], () => input(ps[0]));
431
+ else if (op === 'whileOutput' || op === 'untilOutput' || op === 'addDelay')
432
+ bind(ps[0], () => out(ps[0]));
433
+ else if (op === 'check') {
434
+ bind(ps[0], () => input(ps[0]));
435
+ bind(ps[1], () => out(ps[1]));
436
+ }
437
+ else if (op === 'modifyDelay') {
438
+ bind(ps[0], () => out(ps[0]));
439
+ bind(ps[1], () => jitteredDelay(x, ps[1]));
440
+ }
441
+ return { rc, P, env, vars };
442
+ }
443
+ // The schedule's input (a retry's error): a number, a boolean, a choice of strings, or an object whose fields read are
444
+ // those (a tagged error's _tag a choice of its cases' tags). Each is an input of the step.
445
+ function inputVal(p, rc, P, env, sub) {
446
+ let t = rc.checker.getTypeAtLocation(p);
447
+ if (sub)
448
+ t = propType(rc.checker, t, sub, p) ?? refuse(p, `no type for the input of ${text(p)}`);
449
+ P.inputType ??= t;
450
+ P.inputAt ??= p;
451
+ // (an input first read while the rule is made: a stand-in, the rule made again with it)
452
+ const scalar = (ty, name, at) => {
453
+ const k = kindOfType(ty, rc.checker, at);
454
+ if (!P.inputs.has(name)) {
455
+ P.inputs.set(name, k);
456
+ P.fields.set(name, k);
457
+ if (k === nat)
458
+ P.notes.add(`the input's ${name === 'input' ? 'value' : name.replace(/^input_/, '')} is read as a natural (a whole number at least 0): an input below 0 or with a fraction is one the rule's runs don't feed it`);
459
+ }
460
+ const v = env[name] ?? (k === nat ? lit(0) : k === bool ? no : { is: () => no });
461
+ return k === nat ? { t: 'num', e: v } : k === bool ? { t: 'bool', c: v } : { t: 'choice', e: v };
462
+ };
463
+ if (t.flags & (ts.TypeFlags.NumberLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.StringLike) || (t.isUnion() && t.types.every(u => u.flags & (ts.TypeFlags.StringLiteral | ts.TypeFlags.BooleanLike))))
464
+ return scalar(t, 'input', p);
465
+ return { t: 'obj', field: (k, at) => {
466
+ const types = t.isUnion() ? t.types : [t];
467
+ if (k === '_tag') {
468
+ const tags = types.map(u => { const pt = propType(rc.checker, u, '_tag', at); return pt?.isStringLiteral() ? pt.value : undefined; });
469
+ if (tags.some(x => x === undefined))
470
+ return refuse(at, `_tag of an input whose cases aren't each tagged`);
471
+ const name = 'input__tag';
472
+ if (!P.inputs.has(name)) {
473
+ const kd = oneOf(...new Set(tags));
474
+ P.inputs.set(name, kd);
475
+ P.fields.set('_tag', kd);
476
+ }
477
+ return { t: 'choice', e: env[name] ?? { is: () => no } };
478
+ }
479
+ const pts = types.map(u => propType(rc.checker, u, k, at));
480
+ if (pts.some(x => !x))
481
+ return refuse(at, `the input's ${k}, which not every case of it has`);
482
+ const name = `input_${k}`, v = scalar(pts, name, at);
483
+ P.fields.set(k, P.inputs.get(name));
484
+ return v;
485
+ } };
486
+ }
487
+ // A property's type, through its symbol (the checker's public API).
488
+ const propType = (checker, t, k, at) => { const p = t.getProperty(k); return p && checker.getTypeOfSymbolAtLocation(p, at); };
489
+ // The kind of an input's type (or of the union of several: a field each case of a union has).
490
+ const kindOfType = (t0, checker, at) => {
491
+ const ts0 = Array.isArray(t0) ? t0 : [t0], all = ts0.flatMap(t => (t.isUnion() ? t.types : [t]));
492
+ if (all.every(t => t.flags & ts.TypeFlags.NumberLike))
493
+ return nat;
494
+ if (all.every(t => t.flags & ts.TypeFlags.BooleanLike))
495
+ return bool;
496
+ const lits = all.map(u => (u.isStringLiteral() ? u.value : undefined));
497
+ if (lits.every(x => x !== undefined))
498
+ return oneOf(...new Set(lits));
499
+ return refuse(at, `the input's ${ts0.map(t => checker.typeToString(t)).join(' | ')} (a number, a boolean, a string literal or a tagged error is read)`);
500
+ };
501
+ // The delay a function reads, where a jitter decided it: Effect's is a real number of milliseconds there, the rule's a
502
+ // whole one, and a comparison with it may come out otherwise.
503
+ const jitteredDelay = (x, at) => (x.jittered ? refuse(at, 'the delay read after a jitter (Effect\'s is a real number of milliseconds there, the rule\'s a whole one: a comparison with it may come out otherwise): jitter after this function') : { t: 'dur', e: x.delay });
504
+ const asCond = (v, at) => (v.t === 'bool' ? v.c : v.t === 'eff' ? asCond(v.v, at) : refuse(at, `${text(at)} gives other than a boolean`));
505
+ const asNum = (v, at) => (v.t === 'num' ? v.e : refuse(at, `${text(at)} is ${v.t === 'dur' ? 'a Duration (an object in JavaScript: Duration.toMillis reads its milliseconds)' : 'other than a number'}`));
506
+ const asDur = (v, at) => (v.t === 'dur' || v.t === 'num' ? v.e : v.t === 'eff' ? asDur(v.v, at) : v.t === 'str' ? lit(strDur(v.s, at)) : refuse(at, `${text(at)} gives other than a duration`));
507
+ const strDur = (s, at) => { const m = /^\s*(\d+(?:\.\d+)?)\s*([a-z]+)\s*$/.exec(s); return m && m[2] in UNITS ? whole(at, Number(m[1]) * UNITS[m[2]], s) : refuse(at, `the duration '${s}'`); };
508
+ function body(fn, c) {
509
+ const b = fn.body;
510
+ if (!ts.isBlock(b))
511
+ return val(b, c);
512
+ const st = b.statements;
513
+ if (st.length !== 1 || !ts.isReturnStatement(st[0]) || !st[0].expression)
514
+ return refuse(b, 'a function body other than one return (write it as an expression)');
515
+ return val(st[0].expression, c);
516
+ }
517
+ function val(e0, c) {
518
+ const e = strip(e0);
519
+ if (ts.isNumericLiteral(e))
520
+ return { t: 'num', e: lit(whole(e, Number(e.text), e.text)) };
521
+ if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e))
522
+ return { t: 'str', s: e.text };
523
+ if (e.kind === ts.SyntaxKind.TrueKeyword)
524
+ return { t: 'bool', c: yes };
525
+ if (e.kind === ts.SyntaxKind.FalseKeyword)
526
+ return { t: 'bool', c: no };
527
+ if (ts.isIdentifier(e)) {
528
+ const d = c.rc.checker.getSymbolAtLocation(e)?.valueDeclaration;
529
+ const v = d && c.vars.get(d);
530
+ if (v)
531
+ return v();
532
+ const n = count(e, e, c.rc);
533
+ return { t: 'num', e: term(n, c.env) };
534
+ }
535
+ if (ts.isPropertyAccessExpression(e)) {
536
+ const api = c.rc.api(e);
537
+ if (api === 'Duration.zero')
538
+ return { t: 'dur', e: lit(0) };
539
+ const o = val(e.expression, c);
540
+ return o.t === 'obj' ? o.field(memberName(e.name), e) : refuse(e, `${text(e)}: a field of a value with no fields`);
541
+ }
542
+ if (ts.isPrefixUnaryExpression(e) && e.operator === ts.SyntaxKind.ExclamationToken)
543
+ return { t: 'bool', c: asCond(val(e.operand, c), e.operand).not() };
544
+ if (ts.isConditionalExpression(e)) {
545
+ const k = asCond(val(e.condition, c), e.condition), a = val(e.whenTrue, c), b = val(e.whenFalse, c);
546
+ if (a.t === 'bool' || b.t === 'bool')
547
+ return { t: 'bool', c: when(k, asCond(a, e.whenTrue), asCond(b, e.whenFalse)) };
548
+ if ((a.t === 'dur') !== (b.t === 'dur') && a.t !== 'str' && b.t !== 'str')
549
+ return refuse(e, `${text(e)}: a Duration on one side and a number on the other`);
550
+ return { t: a.t === 'dur' || b.t === 'dur' || a.t === 'str' ? 'dur' : 'num', e: when(k, a.t === 'str' ? asDur(a, e) : a.t === 'dur' ? a.e : asNum(a, e.whenTrue), b.t === 'str' ? asDur(b, e) : b.t === 'dur' ? b.e : asNum(b, e.whenFalse)) };
551
+ }
552
+ if (ts.isBinaryExpression(e)) {
553
+ const o = e.operatorToken.kind, K = ts.SyntaxKind;
554
+ if (o === K.AmpersandAmpersandToken || o === K.BarBarToken) {
555
+ const a = asCond(val(e.left, c), e.left), b = asCond(val(e.right, c), e.right);
556
+ return { t: 'bool', c: o === K.AmpersandAmpersandToken ? a.and(b) : a.or(b) };
557
+ }
558
+ const a = val(e.left, c), b = val(e.right, c);
559
+ if (o === K.EqualsEqualsEqualsToken || o === K.ExclamationEqualsEqualsToken || o === K.EqualsEqualsToken || o === K.ExclamationEqualsToken) {
560
+ if (a.t === 'dur' || b.t === 'dur')
561
+ return refuse(e, `${text(e)}: a Duration compared with ${e.operatorToken.getText()} (an object there): Duration.equals or a comparison of Duration's is read`);
562
+ const neg = o === K.ExclamationEqualsEqualsToken || o === K.ExclamationEqualsToken;
563
+ const eq = a.t === 'choice' && b.t === 'str' ? a.e.is(b.s) : b.t === 'choice' && a.t === 'str' ? b.e.is(a.s) : a.t === 'bool' && b.t === 'bool' ? a.c.iff(b.c) : asNum(a, e.left).eq(asNum(b, e.right));
564
+ return { t: 'bool', c: neg ? eq.not() : eq };
565
+ }
566
+ if (a.t === 'dur' || b.t === 'dur')
567
+ return refuse(e, `${text(e)}: a Duration with JavaScript's ${e.operatorToken.getText()} (an object there): Duration's own comparisons and arithmetic are read`);
568
+ const x = asNum(a, e.left), y = asNum(b, e.right), t = 'num';
569
+ if (o === K.MinusToken)
570
+ return refuse(e, `${text(e)}: a subtraction (a natural's is truncated at 0, JavaScript's isn't)`);
571
+ if (o === K.AsteriskToken) {
572
+ const r = strip(e.right), l = strip(e.left);
573
+ return { t, e: ts.isNumericLiteral(r) ? x.times(Number(r.text)) : ts.isNumericLiteral(l) ? y.times(Number(l.text)) : x.mul(y) };
574
+ }
575
+ if (o === K.PlusToken)
576
+ return { t, e: x.plus(y) };
577
+ const cmp = new Map([[K.LessThanToken, () => x.lt(y)], [K.LessThanEqualsToken, () => x.atMost(y)], [K.GreaterThanToken, () => x.gt(y)], [K.GreaterThanEqualsToken, () => x.atLeast(y)]]).get(o);
578
+ if (cmp)
579
+ return { t: 'bool', c: cmp() };
580
+ return refuse(e, `${text(e)} (comparisons, + and * are read)`);
581
+ }
582
+ if (ts.isCallExpression(e)) {
583
+ const api = c.rc.api(e.expression) ?? '', [m, op = ''] = api.split('.'), args = e.arguments.map(a => () => val(a, c));
584
+ if (m === 'Effect' && op === 'succeed')
585
+ return { t: 'eff', v: args[0]() };
586
+ if (m === 'Duration') {
587
+ const d = (i) => asDur(args[i](), e.arguments[i]);
588
+ if (UNITS[op] !== undefined && op !== 'nanos' && op !== 'micros') {
589
+ const n = asNum(args[0](), e.arguments[0]);
590
+ return { t: 'dur', e: UNITS[op] === 1 ? n : n.times(UNITS[op]) };
591
+ }
592
+ if (op === 'toMillis')
593
+ return { t: 'num', e: d(0) };
594
+ if (op === 'decode' || op === 'fromInputUnsafe')
595
+ return { t: 'dur', e: d(0) };
596
+ if (op === 'equals')
597
+ return { t: 'bool', c: d(0).eq(d(1)) };
598
+ if (op === 'sum')
599
+ return { t: 'dur', e: d(0).plus(d(1)) };
600
+ if (op === 'min' || op === 'max')
601
+ return { t: 'dur', e: (op === 'min' ? min : max)(d(0), d(1)) };
602
+ if (op === 'times') {
603
+ const k = strip(e.arguments[1]);
604
+ return ts.isNumericLiteral(k) ? { t: 'dur', e: d(0).times(whole(k, Number(k.text), k.text)) } : refuse(k, 'Duration.times by other than a whole number written here');
605
+ }
606
+ const cmp = { lessThan: (a, b) => a.lt(b), isLessThan: (a, b) => a.lt(b), lessThanOrEqualTo: (a, b) => a.atMost(b), isLessThanOrEqualTo: (a, b) => a.atMost(b), greaterThan: (a, b) => a.gt(b), isGreaterThan: (a, b) => a.gt(b), greaterThanOrEqualTo: (a, b) => a.atLeast(b), isGreaterThanOrEqualTo: (a, b) => a.atLeast(b) };
607
+ if (cmp[op])
608
+ return { t: 'bool', c: cmp[op](d(0), d(1)) };
609
+ }
610
+ if (api === '' && ts.isPropertyAccessExpression(e.expression) && ts.isIdentifier(e.expression.expression) && e.expression.expression.text === 'Math' && ['min', 'max'].includes(memberName(e.expression.name)) && args.length === 2) {
611
+ const a = val(e.arguments[0], c), b = val(e.arguments[1], c);
612
+ if (a.t === 'dur' || b.t === 'dur')
613
+ return refuse(e, `${text(e)}: Math.${memberName(e.expression.name)} of a Duration (an object there): Duration.min and Duration.max are read`);
614
+ return { t: 'num', e: (memberName(e.expression.name) === 'min' ? min : max)(asNum(a, e), asNum(b, e)) };
615
+ }
616
+ return refuse(e, `${text(e)} in a schedule's function (Duration's arithmetic and comparisons, Math.min and max, Effect.succeed are read)`);
617
+ }
618
+ return refuse(e, `${text(e)} in a schedule's function`);
619
+ }
620
+ // The schedule's machine: the fragment's state beside the schedule's own, one decision a step, nothing after it stops.
621
+ export function scheduleRule(frag, P, name, v4) {
622
+ // (made again while reading it finds inputs: a function given to a combinator reads the schedule's input)
623
+ for (let i = 0;; i++) {
624
+ const n = P.inputs.size, s = makeRule(frag, P, name, v4);
625
+ void s.rule.machine;
626
+ if (P.inputs.size === n || i > 4)
627
+ return s;
628
+ }
629
+ }
630
+ function makeRule(frag, P, name, v4) {
631
+ const st = { attempt: 0, retries: 0, delay: 0, elapsed: 0, done: bool.from(false) };
632
+ for (const [n, s] of P.state)
633
+ st[n] = s.kind === 'bool' ? bool.from(s.init) : typeof s.init === 'function' ? s.init : s.init;
634
+ let r = rule(name).params(Object.fromEntries(P.params)).inputs({ took: nat, ...Object.fromEntries(P.inputs) });
635
+ if (Object.keys(P.fns).length)
636
+ r = r.fns(P.fns);
637
+ r = r.state(st);
638
+ // (the step's terms, made once per env: the assumption reads the jittered delays the step decides)
639
+ const decide = (env) => {
640
+ const first = env.attempt.eq(0), now = when(first, 0, env.elapsed.plus(env.delay).plus(env.took));
641
+ const e2 = Object.assign(Object.create(null), env, { $now: now });
642
+ return { e2, now, x: frag.step(e2, k => e2[k], { attempt: env.attempt, elapsed: now, first }) };
643
+ };
644
+ if (P.assume.length)
645
+ r = r.assume((env) => { const { e2 } = decide(env); return all(...P.assume.map(a => a(e2))); });
646
+ r = r.step((env) => {
647
+ const { x, now } = decide(env), live = env.done.not();
648
+ const out = {
649
+ attempt: when(live, env.attempt.plus(1), env.attempt), retries: when(live.and(x.cont), env.retries.plus(1), env.retries),
650
+ delay: when(live.and(x.cont), x.delay, env.delay), elapsed: when(live, now, env.elapsed), done: env.done.or(x.cont.not()),
651
+ };
652
+ for (const [n] of P.state)
653
+ out[n] = n in x.next ? when(live, x.next[n], env[n]) : env[n];
654
+ return out;
655
+ });
656
+ const names = [
657
+ ...['attempt', 'retries', 'delay', 'elapsed', 'done'].map(n => ({ code: n, rule: n, role: 'state' })),
658
+ ...[...P.state.keys()].map(n => ({ code: n, rule: n, role: 'state' })),
659
+ ...[...P.params.keys()].map(n => ({ code: n, rule: n, role: 'param' })),
660
+ { code: 'took', rule: 'took', role: 'input' }, ...[...P.inputs.keys()].map(n => ({ code: n.replace(/^input_/, 'input.'), rule: n, role: 'input' })),
661
+ ];
662
+ return { rule: r, notes: [...P.notes], names, jitters: P.jitters, fields: P.fields, params: [...P.params.keys()], v4 };
663
+ }
664
+ export function stepper(E, schedule) {
665
+ const { Effect } = E, v4 = 'TxRef' in E;
666
+ const rnd = (rs) => () => { const r = rs.shift(); if (r === undefined)
667
+ throw new Error('the schedule drew more randoms than the rule has jitters'); return r; };
668
+ if (v4) {
669
+ const step = Effect.runSync(E.Schedule.toStep(schedule));
670
+ return (now, input, rs) => {
671
+ const next = rnd(rs), eff = E.Pull.matchEffect(step(now, input), { onSuccess: ([, d]) => Effect.succeed({ cont: true, delay: E.Duration.toMillis(d) }), onDone: () => Effect.succeed({ cont: false, delay: 0 }), onFailure: Effect.failCause });
672
+ return Effect.runSync(Effect.provideService(eff, E.Random.Random, { nextDoubleUnsafe: next, nextIntUnsafe: () => Math.floor(next() * 2 ** 31) }));
673
+ };
674
+ }
675
+ const s = schedule;
676
+ let state = s.initial;
677
+ const base = Effect.runSync(Effect.random);
678
+ return (now, input, rs) => {
679
+ const next = rnd(rs), random = Object.create(base, { next: { get: () => Effect.sync(next) } });
680
+ const [st, , dec] = Effect.runSync(Effect.withRandom(s.step(now, input, state), random));
681
+ state = st;
682
+ return dec._tag === 'Done' ? { cont: false, delay: 0 } : { cont: true, delay: E.ScheduleIntervals.start(dec.intervals) - now };
683
+ };
684
+ }
685
+ // The rule beside Effect's schedule: `runs` runs of `depth` decisions, each attempt taking a drawn time, each input
686
+ // drawn, each jitter drawn within its range and Effect's Random answering what gives it. They must decide alike: go on
687
+ // together, with the same delay (within a millionth of a millisecond, a jittered delay being Effect's real number).
688
+ export function scheduleConforms(s, make, E, opts = {}) {
689
+ const rand = seeded(opts.seed ?? 1), r = s.rule, g = r.compiled(), free = interpret({ ...r.machine, assume: undefined });
690
+ let checked = 0;
691
+ for (let run = 0; run < (opts.runs ?? 100); run++) {
692
+ const params = opts.params?.(rand) ?? Object.fromEntries(s.params.map(p => [p, rand(6)]));
693
+ const ps = r.encodeParams(params), decide = stepper(E, make(params)), start = 1_000_000 + rand(1000);
694
+ let st = g.init(ps);
695
+ const sent = [];
696
+ for (let d = 0; d < (opts.depth ?? 12); d++) {
697
+ const before = r.decode(st);
698
+ if (before.done)
699
+ break;
700
+ const took = rand(4) === 0 ? rand(2000) : rand(20), raw = opts.input ? { rule: {}, effect: opts.input(rand) } : drawInput(s, rand);
701
+ // (Effect decides at the rule's time: the run's attempts taking what the rule's times leave, a jittered delay's
702
+ // fraction of a millisecond among them)
703
+ const now = d === 0 ? 0 : Number(before.elapsed) + Number(before.delay) + took;
704
+ const input = { took, ...raw.rule };
705
+ // Each jitter: the delay it jitters (the rule run once with it at 0), then one it may take, and Effect's random.
706
+ const randoms = [];
707
+ for (const j of s.jitters) {
708
+ const probe = free.step(ps, st, r.encodeInput({ ...Object.fromEntries(s.jitters.map(k => [k.name, 0])), ...input }));
709
+ const seen = r.decode(probe);
710
+ if (!seen[j.on]) {
711
+ input[j.name] = 0;
712
+ continue;
713
+ }
714
+ const base = Number(seen[j.base]), lo = Math.ceil(base * j.lo[0] / j.lo[1]), hi = Math.ceil(base * j.hi[0] / j.hi[1]) - 1;
715
+ const pick = base === 0 ? 0 : hi < lo ? lo : lo + rand(hi - lo + 1);
716
+ input[j.name] = pick;
717
+ randoms.push(base === 0 ? 0 : (pick - base * j.lo[0] / j.lo[1]) / (base * (j.hi[0] / j.hi[1] - j.lo[0] / j.lo[1])));
718
+ }
719
+ sent.push(JSON.stringify(input));
720
+ const at = `${Object.keys(params).length ? `with ${JSON.stringify(params)}, ` : ''}after ${sent.join(', ')}`;
721
+ let x;
722
+ try {
723
+ x = decide(start + now, raw.effect, randoms);
724
+ }
725
+ catch (e) {
726
+ return { checked, failure: `${at}: Effect's schedule fails (${e.message})` };
727
+ }
728
+ st = g.step(ps, st, r.encodeInput(input));
729
+ const after = r.decode(st);
730
+ if (Boolean(after.done) === x.cont)
731
+ return { checked, failure: `${at}: Effect's schedule ${x.cont ? `goes on after ${x.delay} ms` : 'stops'}, the rule ${after.done ? 'stops' : `goes on after ${after.delay} ms`}` };
732
+ if (x.cont && Math.abs(Number(after.delay) - x.delay) > 1e-6)
733
+ return { checked, failure: `${at}: Effect's schedule waits ${x.delay} ms, the rule ${after.delay} ms` };
734
+ checked++;
735
+ }
736
+ }
737
+ return { checked };
738
+ }
739
+ // A run of the rule (a refutation's) replayed on Effect's own schedule: each decision at the rule's time, each jitter
740
+ // answered so Effect draws the run's delay. ok where Effect decides as the rule did at every step.
741
+ export function replaySchedule(s, schedule, E, run) {
742
+ const r = s.rule, g = r.compiled(), free = interpret({ ...r.machine, assume: undefined }), ps = r.encodeParams(run.params), decide = stepper(E, schedule);
743
+ let st = g.init(ps);
744
+ const said = [];
745
+ for (const req of run.trace) {
746
+ const before = r.decode(st);
747
+ const now = Number(before.attempt) === 0 ? 0 : Number(before.elapsed) + Number(before.delay) + Number(req.took ?? 0);
748
+ const randoms = [];
749
+ for (const j of s.jitters) {
750
+ const seen = r.decode(free.step(ps, st, req));
751
+ if (!seen[j.on])
752
+ continue;
753
+ const base = Number(seen[j.base]), pick = Number(req[j.name] ?? 0);
754
+ randoms.push(base === 0 ? 0 : Math.min(1 - 1e-12, Math.max(0, (pick - base * j.lo[0] / j.lo[1]) / (base * (j.hi[0] / j.hi[1] - j.lo[0] / j.lo[1])))));
755
+ }
756
+ const x = decide(1_000_000 + now, effectInput(s, req), randoms);
757
+ st = g.step(ps, st, req);
758
+ const after = r.decode(st);
759
+ said.push(x.cont ? `goes on after ${+x.delay.toFixed(6)} ms` : 'stops');
760
+ if (Boolean(after.done) === x.cont || (x.cont && Math.abs(Number(after.delay) - x.delay) > 1e-6))
761
+ return { ok: false, what: `Effect's schedule ${said.join(', ')}; the rule ${after.done ? 'stops' : `goes on after ${after.delay} ms`}` };
762
+ }
763
+ return { ok: true, what: `Effect's schedule, decision by decision: ${said.join(', ')}` };
764
+ }
765
+ // What Effect is fed for a request's input fields (decoded): the value, or an object of the fields read.
766
+ function effectInput(s, req) {
767
+ const vals = {};
768
+ for (const [f, k] of s.fields) {
769
+ const name = f === '_tag' ? 'input__tag' : f === 'input' ? 'input' : `input_${f}`;
770
+ if (name in req)
771
+ vals[f] = k.decode(name, req);
772
+ }
773
+ return 'input' in vals ? vals.input : vals;
774
+ }
775
+ // A run of the rule where each jitter takes the edge of its range (its top, or its bottom), the attempts taking no time:
776
+ // the run a law about the jittered delay is broken by, where a random draw rarely lands (a jitter's range moves with the
777
+ // delay it jitters). The first state that breaks `law` ends it; undefined where none within `depth` decisions does.
778
+ export function jitterRun(s, law, depth = 40, params = {}) {
779
+ const r = s.rule, m = r.machine, run = interpret(m), free = interpret({ ...m, assume: undefined }), ps = r.encodeParams(params);
780
+ for (const edge of ['top', 'bottom']) {
781
+ let st = run.init(ps);
782
+ const trace = [];
783
+ for (let d = 0; d < depth; d++) {
784
+ const req = { took: 0, ...Object.fromEntries([...m.inputs].filter((i) => i !== 'took').map((i) => [i, 0])) };
785
+ for (const j of s.jitters) {
786
+ const seen = r.decode(free.step(ps, st, req)), base = Number(seen[j.base]);
787
+ req[j.name] = !seen[j.on] || base === 0 ? 0 : edge === 'top' ? Math.ceil(base * j.hi[0] / j.hi[1]) - 1 : Math.ceil(base * j.lo[0] / j.lo[1]);
788
+ }
789
+ try {
790
+ st = run.step(ps, st, req);
791
+ }
792
+ catch {
793
+ break;
794
+ }
795
+ trace.push(req);
796
+ if (!evalC(law.holds, { ...ps }, st, m))
797
+ return { params, trace };
798
+ if (r.decode(st).done)
799
+ break;
800
+ }
801
+ }
802
+ return undefined;
803
+ }
804
+ // An input of the schedule drawn from its kinds: the rule's values and what Effect is given (an object of its fields, a
805
+ // tagged error's _tag among them, or the value itself).
806
+ function drawInput(s, rand) {
807
+ const vals = {}, rule = {};
808
+ for (const [f, k] of s.fields) {
809
+ const v = k.sample(rand, 3);
810
+ vals[f] = v;
811
+ rule[f === '_tag' ? 'input__tag' : f === 'input' ? 'input' : `input_${f}`] = v;
812
+ }
813
+ return { rule, effect: 'input' in vals ? vals.input : vals };
814
+ }
815
+ // What a refusal says when the source has no schedule where the reader looks.
816
+ export const notSchedule = (at) => new Refusal(at.getSourceFile().fileName, 'not a schedule');
817
+ export { Parts };