@mark1russell7/algebra 0.8.5 → 0.8.6
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.
- package/README.md +66 -2
- package/build/clock-BPLEBlb6.d.ts +48 -0
- package/build/clock.d.ts +2 -47
- package/build/index.d.ts +2 -273
- package/build/index.js +4 -1009
- package/build/index.js.map +1 -1
- package/build/replay.js +24 -1
- package/build/replay.js.map +1 -0
- package/build/run-DTmtHPlK.js +1142 -0
- package/build/run-DTmtHPlK.js.map +1 -0
- package/build/run-Dol_e0Xa.d.ts +330 -0
- package/build/run.d.ts +2 -0
- package/build/run.js +1 -0
- package/build/states-DXQbSbfM.js +13 -0
- package/build/states-DXQbSbfM.js.map +1 -0
- package/package.json +5 -1
- package/build/replay-CGyXKaW3.js +0 -33
- package/build/replay-CGyXKaW3.js.map +0 -1
|
@@ -0,0 +1,1142 @@
|
|
|
1
|
+
import { n as fromStates, t as arr } from "./states-DXQbSbfM.js";
|
|
2
|
+
import { convertExact, isUnbounded, quantity, rationals, unbounded } from "@mark1russell7/quantity";
|
|
3
|
+
// src/machine.ts
|
|
4
|
+
/**
|
|
5
|
+
* This name is what the waits of a backoff timer read for the number of times that it fired after
|
|
6
|
+
* a reset, from 0. It is not a knob, because nothing sets it. It is the count of the timer itself.
|
|
7
|
+
*/
|
|
8
|
+
const FIRED = "fired";
|
|
9
|
+
/** This function gives the names that a duration reads: its knobs, by the names of the machine, and `fired`. */
|
|
10
|
+
const exprNames = (e) => {
|
|
11
|
+
if ("knob" in e) return [e.knob];
|
|
12
|
+
if ("model" in e) return [...e.knobs];
|
|
13
|
+
if ("expr" in e) return (e.expr.match(/[A-Za-z_][A-Za-z0-9_.]*/g) ?? []).filter((word) => ![
|
|
14
|
+
"min",
|
|
15
|
+
"max",
|
|
16
|
+
"floor",
|
|
17
|
+
"ceil",
|
|
18
|
+
"pow"
|
|
19
|
+
].includes(word));
|
|
20
|
+
return [];
|
|
21
|
+
};
|
|
22
|
+
/** This function gives the knobs that a duration reads, by the names of the machine for them. */
|
|
23
|
+
const exprKnobs = (e) => exprNames(e).filter((name) => name !== FIRED);
|
|
24
|
+
/** This function tells if a duration reads the number of times that its timer fired, as the waits of a backoff do. */
|
|
25
|
+
const readsFired = (e) => exprNames(e).includes(FIRED);
|
|
26
|
+
/**
|
|
27
|
+
* This function gives the problems in the consistency of a document. Each state, event, timer and
|
|
28
|
+
* knob that it refers to must exist, and it must have an initial state. A reader refuses a
|
|
29
|
+
* machine with problems, and does not draw half of it.
|
|
30
|
+
*/
|
|
31
|
+
const machineProblems = (m) => {
|
|
32
|
+
const problems = [];
|
|
33
|
+
const states = new Set(Object.keys(m.states));
|
|
34
|
+
if (!Object.values(m.states).some((state) => state.initial === true)) problems.push("no initial state");
|
|
35
|
+
for (const t of m.transitions) {
|
|
36
|
+
for (const from of arr(t.from)) if (from !== "*" && !states.has(from)) problems.push(`${t.id}: from ${from}`);
|
|
37
|
+
if (!states.has(t.to)) problems.push(`${t.id}: to ${t.to}`);
|
|
38
|
+
for (const event of arr(t.on)) if (m.events[event] === void 0) problems.push(`${t.id}: event ${event}`);
|
|
39
|
+
if (t.timer !== void 0 && m.timers[t.timer] === void 0) problems.push(`${t.id}: timer ${t.timer}`);
|
|
40
|
+
}
|
|
41
|
+
if (m.knobs["fired"] !== void 0) problems.push(`knob ${FIRED}: the name is a backoff timer's count of its firings`);
|
|
42
|
+
for (const [id, tm] of Object.entries(m.timers)) {
|
|
43
|
+
if (m.events[tm.fires] === void 0) problems.push(`timer ${id}: fires ${tm.fires}`);
|
|
44
|
+
for (const knob of exprKnobs(tm.duration)) {
|
|
45
|
+
const def = m.knobs[knob];
|
|
46
|
+
if (def === void 0) problems.push(`timer ${id}: knob ${knob}`);
|
|
47
|
+
else if (def.unit === null) problems.push(`timer ${id}: knob ${knob} is not an amount`);
|
|
48
|
+
}
|
|
49
|
+
if ([
|
|
50
|
+
tm.duration,
|
|
51
|
+
tm.lateness,
|
|
52
|
+
tm.early
|
|
53
|
+
].some((e) => e !== void 0 && readsFired(e)) && tm.backoff === void 0) problems.push(`timer ${id}: reads ${FIRED}, but has no backoff`);
|
|
54
|
+
for (const event of tm.backoff?.resets ?? []) if (!event.startsWith("enter:") && m.events[event] === void 0) problems.push(`timer ${id}: backoff resets on ${event}`);
|
|
55
|
+
}
|
|
56
|
+
for (const [mechanism, how] of Object.entries(m.realizes ?? {})) {
|
|
57
|
+
if ("timer" in how) {
|
|
58
|
+
if (m.timers[how.timer] === void 0 && m.over === void 0) problems.push(`realizes ${mechanism}: timer ${how.timer}`);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
if ([
|
|
62
|
+
how.duration,
|
|
63
|
+
how.lateness,
|
|
64
|
+
how.early
|
|
65
|
+
].some((e) => e !== void 0 && readsFired(e))) problems.push(`realizes ${mechanism}: reads ${FIRED}, which only a backoff timer counts`);
|
|
66
|
+
for (const knob of exprKnobs(how.duration)) {
|
|
67
|
+
const def = m.knobs[knob];
|
|
68
|
+
if (def === void 0) problems.push(`realizes ${mechanism}: knob ${knob}`);
|
|
69
|
+
else if (def.unit === null) problems.push(`realizes ${mechanism}: knob ${knob} is not an amount`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (m.over !== void 0) {
|
|
73
|
+
for (const state of Object.keys(m.over.states)) if (!states.has(state)) problems.push(`over: state ${state}`);
|
|
74
|
+
if (m.events[m.over.ends] === void 0) problems.push(`over: ends ${m.over.ends}`);
|
|
75
|
+
for (const [lower, set] of Object.entries(m.over.sets)) {
|
|
76
|
+
if (readsFired(set)) problems.push(`over: sets ${lower} from ${FIRED}, which is no knob`);
|
|
77
|
+
for (const knob of exprKnobs(set)) {
|
|
78
|
+
const def = m.knobs[knob];
|
|
79
|
+
if (def === void 0) problems.push(`over: sets ${lower} from knob ${knob}`);
|
|
80
|
+
else if (def.unit === null) problems.push(`over: sets ${lower} from ${knob}, no amount`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
for (const [source, view] of Object.entries(m.observe ?? {})) for (const state of Object.values(view.states)) if (!states.has(state)) problems.push(`observe ${source}: ${state}`);
|
|
85
|
+
const ids = m.transitions.map((t) => t.id);
|
|
86
|
+
for (const id of new Set(ids)) if (ids.filter((other) => other === id).length > 1) problems.push(`transition ${id} twice`);
|
|
87
|
+
return problems;
|
|
88
|
+
};
|
|
89
|
+
// src/algebra.ts
|
|
90
|
+
const exact = (n) => ({
|
|
91
|
+
kind: "exact",
|
|
92
|
+
n
|
|
93
|
+
});
|
|
94
|
+
const INFINITE = { kind: "infinite" };
|
|
95
|
+
const NEGATIVE_INFINITE = {
|
|
96
|
+
kind: "infinite",
|
|
97
|
+
negative: true
|
|
98
|
+
};
|
|
99
|
+
/** This function gives the sign of a value that is not unknown: −1, 0 or 1. */
|
|
100
|
+
const signOf = (value) => value.kind === "infinite" ? value.negative === true ? -1 : 1 : value.kind === "exact" ? rationals.cmp(value.n, rationals.ZERO) : 0;
|
|
101
|
+
/** This function gives no bound with a sign. */
|
|
102
|
+
const unboundedOf = (sign) => sign < 0 ? NEGATIVE_INFINITE : INFINITE;
|
|
103
|
+
const unknown = (why) => ({
|
|
104
|
+
kind: "unknown",
|
|
105
|
+
why
|
|
106
|
+
});
|
|
107
|
+
const whole = (n) => rationals.rational(n);
|
|
108
|
+
/** This function gives the first unknown among some values. An operation over them gets it. */
|
|
109
|
+
const unknownOf = (values) => values.find((value) => value.kind === "unknown");
|
|
110
|
+
const FUNCTIONS = {
|
|
111
|
+
min: 2,
|
|
112
|
+
max: 2,
|
|
113
|
+
floor: 1,
|
|
114
|
+
ceil: 1,
|
|
115
|
+
pow: 2
|
|
116
|
+
};
|
|
117
|
+
/** This count is the largest exponent that `pow` takes. A larger one is a mistake in a document, not a timer. */
|
|
118
|
+
const POW_LIMIT = 4096n;
|
|
119
|
+
/**
|
|
120
|
+
* This function gives a value to a whole power: `pow(a, n)`. The exponent must be an exact whole
|
|
121
|
+
* number, for example the `fired` of a backoff. A negative exponent gives the reciprocal. No bound
|
|
122
|
+
* to the power 0 is 1, and to a positive power it keeps its sign when the power is odd.
|
|
123
|
+
*/
|
|
124
|
+
const power = (a, b) => {
|
|
125
|
+
if (b.kind !== "exact" || !rationals.isInteger(b.n)) return unknown("pow takes a whole exponent");
|
|
126
|
+
const k = b.n.n;
|
|
127
|
+
if (k > POW_LIMIT || k < -4096n) return unknown(`pow takes an exponent of ${POW_LIMIT} or less`);
|
|
128
|
+
if (a.kind === "infinite") {
|
|
129
|
+
if (k === 0n) return exact(rationals.ONE);
|
|
130
|
+
if (k < 0n) return exact(rationals.ZERO);
|
|
131
|
+
return k % 2n === 0n ? INFINITE : a;
|
|
132
|
+
}
|
|
133
|
+
if (a.kind !== "exact") return unknown("not an amount");
|
|
134
|
+
if (k < 0n && a.n.n === 0n) return unknown("a division by zero");
|
|
135
|
+
return exact(rationals.pow(a.n, Number(k)));
|
|
136
|
+
};
|
|
137
|
+
/** This function parses the arithmetic of a document, or it throws an error that tells where the text stops making sense. */
|
|
138
|
+
const parseExpr = (text) => {
|
|
139
|
+
const tokens = text.match(/\d+(?:\.\d+)?|[A-Za-z_][A-Za-z0-9_.]*|[-+*/(),]|\S/g) ?? [];
|
|
140
|
+
let at = 0;
|
|
141
|
+
const peek = () => tokens[at];
|
|
142
|
+
const take = (expected) => {
|
|
143
|
+
const token = tokens[at];
|
|
144
|
+
if (token === void 0 || expected !== void 0 && token !== expected) throw new Error(`"${text}": expected ${expected ?? "more"} at ${token ?? "the end"}`);
|
|
145
|
+
at += 1;
|
|
146
|
+
return token;
|
|
147
|
+
};
|
|
148
|
+
const expr = () => {
|
|
149
|
+
let node = term();
|
|
150
|
+
while (peek() === "+" || peek() === "-") node = {
|
|
151
|
+
op: take(),
|
|
152
|
+
a: node,
|
|
153
|
+
b: term()
|
|
154
|
+
};
|
|
155
|
+
return node;
|
|
156
|
+
};
|
|
157
|
+
const term = () => {
|
|
158
|
+
let node = factor();
|
|
159
|
+
while (peek() === "*" || peek() === "/") node = {
|
|
160
|
+
op: take(),
|
|
161
|
+
a: node,
|
|
162
|
+
b: factor()
|
|
163
|
+
};
|
|
164
|
+
return node;
|
|
165
|
+
};
|
|
166
|
+
const factor = () => {
|
|
167
|
+
const token = take();
|
|
168
|
+
if (token === "(") {
|
|
169
|
+
const inner = expr();
|
|
170
|
+
take(")");
|
|
171
|
+
return inner;
|
|
172
|
+
}
|
|
173
|
+
if (token === "-") return {
|
|
174
|
+
op: "neg",
|
|
175
|
+
a: factor()
|
|
176
|
+
};
|
|
177
|
+
if (/^\d/.test(token)) return {
|
|
178
|
+
op: "num",
|
|
179
|
+
n: rationals.fromDecimal(token)
|
|
180
|
+
};
|
|
181
|
+
if (!/^[A-Za-z_]/.test(token)) throw new Error(`"${text}": ${token} is not a term`);
|
|
182
|
+
if (Object.hasOwn(FUNCTIONS, token)) {
|
|
183
|
+
const name = token;
|
|
184
|
+
take("(");
|
|
185
|
+
const args = [expr()];
|
|
186
|
+
while (peek() === ",") {
|
|
187
|
+
take(",");
|
|
188
|
+
args.push(expr());
|
|
189
|
+
}
|
|
190
|
+
take(")");
|
|
191
|
+
if (args.length !== FUNCTIONS[name]) throw new Error(`"${text}": ${name} takes ${FUNCTIONS[name]}, not ${args.length}`);
|
|
192
|
+
return {
|
|
193
|
+
op: name,
|
|
194
|
+
args
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
return {
|
|
198
|
+
op: "knob",
|
|
199
|
+
name: token
|
|
200
|
+
};
|
|
201
|
+
};
|
|
202
|
+
const node = expr();
|
|
203
|
+
if (at < tokens.length) throw new Error(`"${text}": ${tokens[at]} after the end`);
|
|
204
|
+
return node;
|
|
205
|
+
};
|
|
206
|
+
const run = (node, valueOf) => {
|
|
207
|
+
if (node.op === "num") return exact(node.n);
|
|
208
|
+
if (node.op === "knob") return valueOf(node.name);
|
|
209
|
+
if (node.op === "neg") {
|
|
210
|
+
const a = run(node.a, valueOf);
|
|
211
|
+
return a.kind === "exact" ? exact(rationals.neg(a.n)) : a.kind === "infinite" ? unboundedOf(-signOf(a)) : a;
|
|
212
|
+
}
|
|
213
|
+
if ("args" in node) {
|
|
214
|
+
const args = node.args.map((arg) => run(arg, valueOf));
|
|
215
|
+
const lost = unknownOf(args);
|
|
216
|
+
if (lost !== void 0) return lost;
|
|
217
|
+
if (node.op === "floor" || node.op === "ceil") {
|
|
218
|
+
const [a] = args;
|
|
219
|
+
return a.kind === "exact" ? exact(node.op === "floor" ? rationals.floor(a.n) : rationals.ceil(a.n)) : a;
|
|
220
|
+
}
|
|
221
|
+
const [a, b] = args;
|
|
222
|
+
if (node.op === "pow") return power(a, b);
|
|
223
|
+
if (a.kind === "infinite" || b.kind === "infinite") {
|
|
224
|
+
const above = (x, y) => x.kind === "infinite" ? signOf(x) > 0 || y.kind === "infinite" && signOf(y) < 0 : signOf(y) < 0;
|
|
225
|
+
const larger = above(a, b) ? a : b;
|
|
226
|
+
const smaller = larger === a ? b : a;
|
|
227
|
+
return node.op === "max" ? larger : smaller;
|
|
228
|
+
}
|
|
229
|
+
if (a.kind !== "exact" || b.kind !== "exact") return unknown("not an amount");
|
|
230
|
+
const aFirst = rationals.cmp(a.n, b.n) <= 0;
|
|
231
|
+
if (node.op === "min") return aFirst ? a : b;
|
|
232
|
+
return aFirst ? b : a;
|
|
233
|
+
}
|
|
234
|
+
const a = run(node.a, valueOf);
|
|
235
|
+
const b = run(node.b, valueOf);
|
|
236
|
+
const lost = unknownOf([a, b]);
|
|
237
|
+
if (lost !== void 0) return lost;
|
|
238
|
+
if (a.kind === "exact" && b.kind === "exact") {
|
|
239
|
+
if (node.op === "/" && b.n.n === 0n) return unknown("a division by zero");
|
|
240
|
+
const op = {
|
|
241
|
+
"+": rationals.add,
|
|
242
|
+
"-": rationals.sub,
|
|
243
|
+
"*": rationals.mul,
|
|
244
|
+
"/": rationals.div
|
|
245
|
+
}[node.op];
|
|
246
|
+
return exact(op(a.n, b.n));
|
|
247
|
+
}
|
|
248
|
+
if (node.op === "+" || node.op === "-") {
|
|
249
|
+
const sa = signOf(a);
|
|
250
|
+
const sb = node.op === "-" ? -signOf(b) : signOf(b);
|
|
251
|
+
if (a.kind === "infinite" && b.kind === "infinite" && sa !== sb) return unknown("no bound less no bound");
|
|
252
|
+
return unboundedOf(a.kind === "infinite" ? sa : sb);
|
|
253
|
+
}
|
|
254
|
+
if (node.op === "*") {
|
|
255
|
+
const sign = signOf(a) * signOf(b);
|
|
256
|
+
return sign === 0 ? unknown("zero times no bound") : unboundedOf(sign);
|
|
257
|
+
}
|
|
258
|
+
if (a.kind === "infinite" && b.kind === "infinite") return unknown("no bound over no bound");
|
|
259
|
+
if (b.kind === "infinite") return exact(rationals.ZERO);
|
|
260
|
+
const sign = signOf(a) * signOf(b);
|
|
261
|
+
return sign === 0 ? unknown("no bound over zero") : unboundedOf(sign);
|
|
262
|
+
};
|
|
263
|
+
const integer = (value, what) => {
|
|
264
|
+
if (!rationals.isInteger(value) || value.n < 0n) throw new Error(`${what} is not a whole count: ${rationals.toNumber(value)}`);
|
|
265
|
+
return value.n;
|
|
266
|
+
};
|
|
267
|
+
/** This function gives min(base × 2^k, cap), exactly. */
|
|
268
|
+
const capped = (base, k, cap) => {
|
|
269
|
+
const doubled = rationals.mul(base, whole(2n ** k));
|
|
270
|
+
return rationals.cmp(doubled, cap) <= 0 ? doubled : cap;
|
|
271
|
+
};
|
|
272
|
+
/**
|
|
273
|
+
* This function gives the hypothetical retransmission timeout of the kernel, `tcp_model_timeout`
|
|
274
|
+
* in `net/ipv4/tcp_timer.c`. The waits double from the minimum RTO until a step is more than the
|
|
275
|
+
* maximum, and then the waits are capped. For `tcp_retries2` = 15, it is 0.2 s × (2^10 − 1) +
|
|
276
|
+
* 6 × 120 s = 924.6 s.
|
|
277
|
+
*/
|
|
278
|
+
const retransBudget = (retries, min, max) => {
|
|
279
|
+
let thresh = 0n;
|
|
280
|
+
while (rationals.cmp(rationals.mul(min, whole(2n ** (thresh + 1n))), max) <= 0) thresh += 1n;
|
|
281
|
+
if (retries <= thresh) return rationals.mul(min, whole(2n ** (retries + 1n) - 1n));
|
|
282
|
+
return rationals.add(rationals.mul(min, whole(2n ** (thresh + 1n) - 1n)), rationals.mul(whole(retries - thresh), max));
|
|
283
|
+
};
|
|
284
|
+
/** These are `TCP_TIMEOUT_INIT` and `TCP_RTO_MAX` in `include/net/tcp.h` at v6.6: the first SYN RTO and the cap. */
|
|
285
|
+
const TCP_TIMEOUT_INIT = whole(1n);
|
|
286
|
+
const TCP_RTO_MAX = whole(120n);
|
|
287
|
+
/**
|
|
288
|
+
* This function gives the wait of the SYN of a connect after `fired` firings, from 6.5
|
|
289
|
+
* (`tcp_retransmit_timer` in `net/ipv4/tcp_timer.c`). Each firing sends the SYN again. The first
|
|
290
|
+
* `tcp_syn_linear_timeouts` firings keep the initial RTO, thus the waits 0 to
|
|
291
|
+
* `tcp_syn_linear_timeouts` are 1 s each. Then each firing doubles the wait, up to `TCP_RTO_MAX`.
|
|
292
|
+
*/
|
|
293
|
+
const synWait = (fired, linear) => fired <= linear ? TCP_TIMEOUT_INIT : capped(TCP_TIMEOUT_INIT, fired - linear, TCP_RTO_MAX);
|
|
294
|
+
/**
|
|
295
|
+
* This function gives each wait of the SYN of a connect, from 6.5: the waits 0 to
|
|
296
|
+
* `tcp_syn_retries` + `tcp_syn_linear_timeouts` (`synWait`). The connect gives up at the end of the last wait.
|
|
297
|
+
*/
|
|
298
|
+
const synWaits = (retries, linear) => Array.from({ length: Number(linear + 1n + retries) }, (_, fired) => synWait(BigInt(fired), linear));
|
|
299
|
+
/**
|
|
300
|
+
* This function gives the waits of the SYN of a connect up to the firing that gives up, from 6.5
|
|
301
|
+
* (`tcp_write_timeout` in `net/ipv4/tcp_timer.c` at v7.0, lines 242-284). A firing applies two tests.
|
|
302
|
+
*
|
|
303
|
+
* - The count test: the retransmissions before it are `tcp_syn_retries` + `tcp_syn_linear_timeouts`.
|
|
304
|
+
* - The time test: `retransmits_timed_out` with the boundary `tcp_syn_retries` and no linear term. Its
|
|
305
|
+
* budget is `tcp_model_timeout` from an RTO of 1 s, (2^(retries + 1) - 1) s, from the first SYN
|
|
306
|
+
* (`tcp_connect` sets `retrans_stamp`, `tcp_output.c` line 4370). It needs one retransmission.
|
|
307
|
+
*
|
|
308
|
+
* The first firing that passes one test gives up. At the defaults both tests give 131 s. At
|
|
309
|
+
* `tcp_syn_retries` 2 and 4 linear waits, the time test gives 7 s and the count test gives 11 s.
|
|
310
|
+
*/
|
|
311
|
+
const synGiveUpWaits = (retries, linear) => {
|
|
312
|
+
const budget = retransBudget(retries, TCP_TIMEOUT_INIT, TCP_RTO_MAX);
|
|
313
|
+
const waits = synWaits(retries, linear);
|
|
314
|
+
let at = whole(0n);
|
|
315
|
+
for (let fired = 0; fired < waits.length; fired += 1) {
|
|
316
|
+
at = rationals.add(at, waits[fired]);
|
|
317
|
+
if (fired >= 1 && rationals.cmp(at, budget) >= 0) return waits.slice(0, fired + 1);
|
|
318
|
+
}
|
|
319
|
+
return waits;
|
|
320
|
+
};
|
|
321
|
+
/**
|
|
322
|
+
* This function gives how early the connect can give up, in seconds. The time test reads the real
|
|
323
|
+
* time of a firing, and the wheel makes that time late. A firing before the nominal one can pass it when its
|
|
324
|
+
* lateness takes it past the budget. With `tcp_usec_ts`, the test adds one jiffy (line 233).
|
|
325
|
+
*/
|
|
326
|
+
const synGiveUpEarly = (retries, linear, hz) => {
|
|
327
|
+
const budget = retransBudget(retries, TCP_TIMEOUT_INIT, TCP_RTO_MAX);
|
|
328
|
+
const waits = synGiveUpWaits(retries, linear);
|
|
329
|
+
const end = waits.reduce((total, wait) => rationals.add(total, wait), whole(0n));
|
|
330
|
+
const jiffy = rationals.div(whole(1n), hz);
|
|
331
|
+
let at = whole(0n);
|
|
332
|
+
let late = whole(0n);
|
|
333
|
+
for (let fired = 0; fired < waits.length - 1; fired += 1) {
|
|
334
|
+
at = rationals.add(at, waits[fired]);
|
|
335
|
+
late = rationals.add(late, rationals.div(whole(granularity(jiffiesOf(waits[fired], hz))), hz));
|
|
336
|
+
if (fired >= 1 && rationals.cmp(rationals.add(rationals.add(at, late), jiffy), budget) >= 0) {
|
|
337
|
+
const low = rationals.sub(budget, jiffy);
|
|
338
|
+
return rationals.sub(end, rationals.cmp(low, at) >= 0 ? low : at);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return whole(0n);
|
|
342
|
+
};
|
|
343
|
+
/**
|
|
344
|
+
* This function gives the SYNs that a connect sends before it gives up: the first SYN and each
|
|
345
|
+
* retransmission (`synGiveUpWaits`). A connect whose SYN does not leave adds each of them to the field
|
|
346
|
+
* `drop` of conntrack, and each retransmission to `TCPRetransFail`.
|
|
347
|
+
*/
|
|
348
|
+
const synGiveUpSends = (retries, linear) => synGiveUpWaits(BigInt(retries), BigInt(linear)).length;
|
|
349
|
+
/** This function gives the whole jiffies of a time at HZ, rounded up, as `msecs_to_jiffies` and `usecs_to_jiffies` round. */
|
|
350
|
+
const jiffiesOf = (seconds, hz) => rationals.ceil(rationals.mul(seconds, hz)).n;
|
|
351
|
+
/**
|
|
352
|
+
* This function gives the longest wait of the delayed ACK, in jiffies (`tcp_send_delayed_ack` in
|
|
353
|
+
* `net/ipv4/tcp_output.c:4004-4054` at v6.6). The wait is the ACK timeout, `ato`. It is at least
|
|
354
|
+
* `TCP_DELACK_MIN`, HZ/25. Above that, the smoothed round trip in whole jiffies bounds it, but not
|
|
355
|
+
* below `TCP_DELACK_MIN`. The cap is `icsk_delack_max`, `TCP_DELACK_MAX` by default, HZ/5
|
|
356
|
+
* (`include/net/tcp.h:133-136`, `net/ipv4/tcp.c:425`). Thus it is 40 ms on a fast path at each HZ, and
|
|
357
|
+
* 200 ms at most.
|
|
358
|
+
*/
|
|
359
|
+
const delackWait = (rtt, hz) => {
|
|
360
|
+
const ticks = integer(hz, "hz");
|
|
361
|
+
const least = ticks / 25n;
|
|
362
|
+
const most = ticks / 5n;
|
|
363
|
+
const srtt = jiffiesOf(rtt, hz);
|
|
364
|
+
const bound = srtt > least ? srtt : least;
|
|
365
|
+
return bound < most ? bound : most;
|
|
366
|
+
};
|
|
367
|
+
/**
|
|
368
|
+
* This function gives how late the timer wheel can fire a timer that is due in `jiffies`
|
|
369
|
+
* (`calc_wheel_index` in `kernel/time/timer.c` at v6.6). Level 0 holds the timers due in 63 jiffies
|
|
370
|
+
* or less. Each level above holds eight times as long, at eight times the granularity. The wheel
|
|
371
|
+
* rounds a timer up to the next boundary of its level, thus it fires up to one granularity late.
|
|
372
|
+
* At HZ 250, a 2 h timer can be up to 131 s late.
|
|
373
|
+
*/
|
|
374
|
+
const granularity = (jiffies) => {
|
|
375
|
+
let level = 0n;
|
|
376
|
+
while (level < 8n && jiffies >= 63n << 3n * level) level += 1n;
|
|
377
|
+
return 8n ** level;
|
|
378
|
+
};
|
|
379
|
+
/**
|
|
380
|
+
* This function gives the lateness of the retransmission give-up after its budget. The first
|
|
381
|
+
* retransmission sets the RTO to the round trip plus the minimum, rounded up to a jiffy
|
|
382
|
+
* (`tcp_set_rto`). On a Docker network at HZ 250, that is 204 ms, not 200.
|
|
383
|
+
*
|
|
384
|
+
* Each firing doubles the RTO, up to the cap. The budget ends in the firing after the last one
|
|
385
|
+
* that is short of it. Thus the give-up comes one step late at most, plus the rounding of each
|
|
386
|
+
* firing on the wheel. The model assumes a steady path, whose variance stays below the minimum RTO.
|
|
387
|
+
*/
|
|
388
|
+
const retransLateness = (retries, min, max, rtt, hz) => {
|
|
389
|
+
const base = jiffiesOf(rationals.add(min, rtt), hz);
|
|
390
|
+
const cap = jiffiesOf(max, hz);
|
|
391
|
+
let step = base;
|
|
392
|
+
let wheel = 0n;
|
|
393
|
+
for (let k = 1n; k <= retries + 1n; k += 1n) {
|
|
394
|
+
step = base * 2n ** k < cap ? base * 2n ** k : cap;
|
|
395
|
+
wheel += granularity(step);
|
|
396
|
+
}
|
|
397
|
+
return rationals.div(whole(step + wheel), hz);
|
|
398
|
+
};
|
|
399
|
+
/**
|
|
400
|
+
* This function gives one wait of the retransmission timer with one segment in flight, in jiffies
|
|
401
|
+
* (`net/ipv4/tcp_timer.c`, and `tcp_schedule_loss_probe` in `tcp_output.c`, at v6.6). Its first
|
|
402
|
+
* firing is the tail loss probe. For one segment, the probe waits two round trips plus
|
|
403
|
+
* `TCP_RTO_MIN`, but not longer than the RTO. Thus it waits the RTO itself: the round trip plus
|
|
404
|
+
* the minimum, in whole jiffies.
|
|
405
|
+
*
|
|
406
|
+
* The probe arms the RTO again, and each RTO firing doubles it, up to the cap. Thus the
|
|
407
|
+
* firing k comes 2^k RTOs after the send: 0.204, 0.408, 0.816 s on a Docker network at HZ 250.
|
|
408
|
+
* With more than one segment in flight, the probe waits two round trips plus 2 jiffies.
|
|
409
|
+
*/
|
|
410
|
+
const rtoWait = (fired, min, max, rtt, hz) => {
|
|
411
|
+
const base = jiffiesOf(rationals.add(min, rtt), hz);
|
|
412
|
+
const cap = jiffiesOf(max, hz);
|
|
413
|
+
if (fired === 0n) return base;
|
|
414
|
+
const doubled = base * 2n ** (fired - 1n);
|
|
415
|
+
return doubled < cap ? doubled : cap;
|
|
416
|
+
};
|
|
417
|
+
/**
|
|
418
|
+
* This function gives the lateness of keepalive. It adds the idle timer and the interval of each
|
|
419
|
+
* probe, each rounded up on the wheel at its own level. Linux arms the idle timer, then one probe
|
|
420
|
+
* interval for each probe without an answer.
|
|
421
|
+
*/
|
|
422
|
+
/**
|
|
423
|
+
* This function gives the lateness of the retransmission give-up after its budget, under an ICMP
|
|
424
|
+
* host or net unreachable for each RTO retransmission. Each ICMP reverts one doubling of the backoff
|
|
425
|
+
* (`tcp_ld_RTO_revert` in `net/ipv4/tcp_ipv4.c` at v6.6, RFC 6069). Then each wait after the first RTO
|
|
426
|
+
* firing is one RTO again, thus the give-up comes at most one RTO after the budget. Each firing up
|
|
427
|
+
* to it can fire up to the granularity of its level of the wheel late.
|
|
428
|
+
*/
|
|
429
|
+
const retransLatenessReverted = (retries, min, max, rtt, hz) => {
|
|
430
|
+
const base = jiffiesOf(rationals.add(min, rtt), hz);
|
|
431
|
+
const firings = (jiffiesOf(retransBudget(retries, min, max), hz) + base - 1n) / base + 1n;
|
|
432
|
+
return rationals.div(whole(base + firings * granularity(base)), hz);
|
|
433
|
+
};
|
|
434
|
+
const keepaliveLateness = (idle, interval, probes, hz) => {
|
|
435
|
+
const late = (time) => whole(granularity(jiffiesOf(time, hz)));
|
|
436
|
+
return rationals.div(rationals.add(late(idle), rationals.mul(whole(probes), late(interval))), hz);
|
|
437
|
+
};
|
|
438
|
+
const MODELS = {
|
|
439
|
+
"linux.retrans-budget": {
|
|
440
|
+
knobs: [
|
|
441
|
+
null,
|
|
442
|
+
"s",
|
|
443
|
+
"s"
|
|
444
|
+
],
|
|
445
|
+
seconds: ([retries, min, max]) => retransBudget(integer(retries, "tcp_retries2"), min, max),
|
|
446
|
+
source: "net/ipv4/tcp_timer.c tcp_model_timeout at v6.6"
|
|
447
|
+
},
|
|
448
|
+
"linux.retrans-step": {
|
|
449
|
+
knobs: [
|
|
450
|
+
null,
|
|
451
|
+
"s",
|
|
452
|
+
"s",
|
|
453
|
+
"s",
|
|
454
|
+
"Hz"
|
|
455
|
+
],
|
|
456
|
+
seconds: ([retries, min, max, rtt, hz]) => retransLateness(integer(retries, "tcp_retries2"), min, max, rtt, hz),
|
|
457
|
+
source: "net/ipv4/tcp_timer.c, tcp_input.c tcp_set_rto and kernel/time/timer.c at v6.6 (measured by @mark1russell7/harness, 2026-10-08)"
|
|
458
|
+
},
|
|
459
|
+
"linux.rto-wait": {
|
|
460
|
+
knobs: [
|
|
461
|
+
null,
|
|
462
|
+
"s",
|
|
463
|
+
"s",
|
|
464
|
+
"s",
|
|
465
|
+
"Hz"
|
|
466
|
+
],
|
|
467
|
+
seconds: ([fired, min, max, rtt, hz]) => rationals.div(whole(rtoWait(integer(fired, FIRED), min, max, rtt, hz)), hz),
|
|
468
|
+
source: "net/ipv4/tcp_timer.c tcp_retransmit_timer and tcp_output.c tcp_schedule_loss_probe at v6.6 (measured by @mark1russell7/harness, 2026-10-12)"
|
|
469
|
+
},
|
|
470
|
+
"linux.rto-wait-reverted": {
|
|
471
|
+
knobs: [
|
|
472
|
+
null,
|
|
473
|
+
"s",
|
|
474
|
+
"s",
|
|
475
|
+
"s",
|
|
476
|
+
"Hz"
|
|
477
|
+
],
|
|
478
|
+
seconds: ([, min, , rtt, hz]) => rationals.div(whole(jiffiesOf(rationals.add(min, rtt), hz)), hz),
|
|
479
|
+
source: "net/ipv4/tcp_ipv4.c tcp_v4_err and tcp_ld_RTO_revert at v6.6 (RFC 6069)"
|
|
480
|
+
},
|
|
481
|
+
"linux.retrans-step-reverted": {
|
|
482
|
+
knobs: [
|
|
483
|
+
null,
|
|
484
|
+
"s",
|
|
485
|
+
"s",
|
|
486
|
+
"s",
|
|
487
|
+
"Hz"
|
|
488
|
+
],
|
|
489
|
+
seconds: ([retries, min, max, rtt, hz]) => retransLatenessReverted(integer(retries, "tcp_retries2"), min, max, rtt, hz),
|
|
490
|
+
source: "net/ipv4/tcp_ipv4.c tcp_ld_RTO_revert and net/ipv4/tcp_timer.c retransmits_timed_out at v6.6 (RFC 6069)"
|
|
491
|
+
},
|
|
492
|
+
"linux.rto-wait-lateness": {
|
|
493
|
+
knobs: [
|
|
494
|
+
null,
|
|
495
|
+
"s",
|
|
496
|
+
"s",
|
|
497
|
+
"s",
|
|
498
|
+
"Hz"
|
|
499
|
+
],
|
|
500
|
+
seconds: ([fired, min, max, rtt, hz]) => rationals.div(whole(granularity(rtoWait(integer(fired, FIRED), min, max, rtt, hz))), hz),
|
|
501
|
+
source: "kernel/time/timer.c calc_wheel_index at v6.6"
|
|
502
|
+
},
|
|
503
|
+
"linux.keepalive-lateness": {
|
|
504
|
+
knobs: [
|
|
505
|
+
"s",
|
|
506
|
+
"s",
|
|
507
|
+
null,
|
|
508
|
+
"Hz"
|
|
509
|
+
],
|
|
510
|
+
seconds: ([idle, interval, probes, hz]) => keepaliveLateness(idle, interval, integer(probes, "keepcnt"), hz),
|
|
511
|
+
source: "net/ipv4/tcp_timer.c tcp_keepalive_timer and kernel/time/timer.c at v6.6"
|
|
512
|
+
},
|
|
513
|
+
"linux.wheel": {
|
|
514
|
+
knobs: ["s", "Hz"],
|
|
515
|
+
seconds: ([time, hz]) => rationals.div(whole(granularity(jiffiesOf(time, hz))), hz),
|
|
516
|
+
source: "kernel/time/timer.c calc_wheel_index at v6.6"
|
|
517
|
+
},
|
|
518
|
+
"linux.delack": {
|
|
519
|
+
knobs: ["s", "Hz"],
|
|
520
|
+
seconds: ([rtt, hz]) => rationals.div(whole(delackWait(rtt, hz)), hz),
|
|
521
|
+
source: "net/ipv4/tcp_output.c tcp_send_delayed_ack, include/net/tcp.h TCP_DELACK_MIN and TCP_DELACK_MAX at v6.6"
|
|
522
|
+
},
|
|
523
|
+
"linux.delack-lateness": {
|
|
524
|
+
knobs: ["s", "Hz"],
|
|
525
|
+
seconds: ([rtt, hz]) => rationals.div(whole(granularity(delackWait(rtt, hz))), hz),
|
|
526
|
+
source: "net/ipv4/tcp_output.c tcp_send_delayed_ack and kernel/time/timer.c calc_wheel_index at v6.6"
|
|
527
|
+
},
|
|
528
|
+
"linux.jiffy": {
|
|
529
|
+
knobs: ["Hz"],
|
|
530
|
+
seconds: ([hz]) => rationals.div(whole(1n), hz),
|
|
531
|
+
source: "include/linux/jiffies.h"
|
|
532
|
+
},
|
|
533
|
+
"linux.syn-giveup": {
|
|
534
|
+
knobs: [null, null],
|
|
535
|
+
seconds: ([retries, linear]) => synGiveUpWaits(integer(retries, "tcp_syn_retries"), integer(linear, "tcp_syn_linear_timeouts")).reduce((total, wait) => rationals.add(total, wait), whole(0n)),
|
|
536
|
+
source: "net/ipv4/tcp_timer.c tcp_write_timeout, retransmits_timed_out and tcp_model_timeout at v7.0 (lines 187-284)"
|
|
537
|
+
},
|
|
538
|
+
"linux.syn-giveup-lateness": {
|
|
539
|
+
knobs: [
|
|
540
|
+
null,
|
|
541
|
+
null,
|
|
542
|
+
"Hz"
|
|
543
|
+
],
|
|
544
|
+
seconds: ([retries, linear, hz]) => rationals.div(whole(synGiveUpWaits(integer(retries, "tcp_syn_retries"), integer(linear, "tcp_syn_linear_timeouts")).reduce((total, wait) => total + granularity(jiffiesOf(wait, hz)), 0n)), hz),
|
|
545
|
+
source: "net/ipv4/tcp_timer.c tcp_retransmit_timer and kernel/time/timer.c calc_wheel_index at v6.6"
|
|
546
|
+
},
|
|
547
|
+
"linux.syn-giveup-early": {
|
|
548
|
+
knobs: [
|
|
549
|
+
null,
|
|
550
|
+
null,
|
|
551
|
+
"Hz"
|
|
552
|
+
],
|
|
553
|
+
seconds: ([retries, linear, hz]) => synGiveUpEarly(integer(retries, "tcp_syn_retries"), integer(linear, "tcp_syn_linear_timeouts"), hz),
|
|
554
|
+
source: "net/ipv4/tcp_timer.c retransmits_timed_out at v7.0 (lines 214-239) and kernel/time/timer.c calc_wheel_index"
|
|
555
|
+
},
|
|
556
|
+
"linux.syn-wait": {
|
|
557
|
+
knobs: [null, null],
|
|
558
|
+
seconds: ([fired, linear]) => synWait(integer(fired, FIRED), integer(linear, "tcp_syn_linear_timeouts")),
|
|
559
|
+
source: "net/ipv4/tcp_timer.c tcp_retransmit_timer at v6.6 (lines 604 and 624-631) and at v6.17 (lines 448 and 671-678)"
|
|
560
|
+
},
|
|
561
|
+
"linux.syn-wait-lateness": {
|
|
562
|
+
knobs: [
|
|
563
|
+
null,
|
|
564
|
+
null,
|
|
565
|
+
"Hz"
|
|
566
|
+
],
|
|
567
|
+
seconds: ([fired, linear, hz]) => rationals.div(whole(granularity(jiffiesOf(synWait(integer(fired, FIRED), integer(linear, "tcp_syn_linear_timeouts")), hz))), hz),
|
|
568
|
+
source: "net/ipv4/tcp_timer.c tcp_retransmit_timer and kernel/time/timer.c calc_wheel_index at v6.6"
|
|
569
|
+
},
|
|
570
|
+
"ioredis.retry-base": {
|
|
571
|
+
knobs: [null],
|
|
572
|
+
seconds: ([fired]) => capped(rationals.fromDecimal("0.05"), integer(fired, FIRED), whole(5n)),
|
|
573
|
+
source: "ioredis 6.0.0 built/redis/RedisOptions.js retryStrategy and built/redis/event_handler.js"
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
/** This function gives the model of a name, or undefined. Only an own key is a model: `toString` is not one. */
|
|
577
|
+
const modelOf = (name) => Object.hasOwn(MODELS, name) ? MODELS[name] : void 0;
|
|
578
|
+
/**
|
|
579
|
+
* This function gives the value of a knob in the unit that the document gives it (or as a count
|
|
580
|
+
* when it is a count). For `fired`, it gives which wait of a backoff timer it is.
|
|
581
|
+
*/
|
|
582
|
+
const knobIn = (doc, name, unit, values, fired) => {
|
|
583
|
+
if (name === "fired") return fired === void 0 ? unknown("one wait of a timer with a backoff: say which, by how many times it has fired") : exact(rationals.fromNumber(fired));
|
|
584
|
+
if (!Object.hasOwn(doc.knobs, name)) return unknown(`the machine names no knob ${name}`);
|
|
585
|
+
const given = values(name);
|
|
586
|
+
if (given === void 0) return unknown(`nothing gives ${name}'s value`);
|
|
587
|
+
if ("unknown" in given) return unknown(`${name}: ${given.unknown}`);
|
|
588
|
+
if (given.value === "infinite") return INFINITE;
|
|
589
|
+
const value = rationals.fromNumber(given.value);
|
|
590
|
+
const { off, unit: own } = doc.knobs[name];
|
|
591
|
+
if (off !== void 0 && own !== null && rationals.toNumber(convertExact(value, given.unit, own)) === off) return INFINITE;
|
|
592
|
+
return exact(unit === null ? convertExact(value, given.unit, given.unit) : convertExact(value, given.unit, unit));
|
|
593
|
+
};
|
|
594
|
+
const out = (value, unit) => value.kind === "exact" ? quantity(rationals.toNumber(value.n), unit) : value.kind === "infinite" ? value.negative === true ? {
|
|
595
|
+
unknown: "a negative unbounded time",
|
|
596
|
+
unit
|
|
597
|
+
} : unbounded(unit) : {
|
|
598
|
+
unknown: value.why,
|
|
599
|
+
unit
|
|
600
|
+
};
|
|
601
|
+
/**
|
|
602
|
+
* This function evaluates one duration of a timer of a machine, in the unit that its document
|
|
603
|
+
* gives it. The waits of a backoff timer read `fired`, which tells which wait.
|
|
604
|
+
*/
|
|
605
|
+
const evaluate = (doc, expr, values, fired) => {
|
|
606
|
+
if ("const" in expr) return quantity(expr.const, expr.unit);
|
|
607
|
+
if ("knob" in expr) return out(knobIn(doc, expr.knob, expr.unit, values, fired), expr.unit);
|
|
608
|
+
if ("expr" in expr) {
|
|
609
|
+
const tree = parseExpr(expr.expr);
|
|
610
|
+
const value = run(tree, (name) => knobIn(doc, name, doc.knobs[name]?.unit ?? null, values, fired));
|
|
611
|
+
return out(value, expr.unit);
|
|
612
|
+
}
|
|
613
|
+
const model = modelOf(expr.model);
|
|
614
|
+
if (model === void 0) return {
|
|
615
|
+
unknown: `no model ${expr.model}`,
|
|
616
|
+
unit: expr.unit
|
|
617
|
+
};
|
|
618
|
+
if (model.knobs.length !== expr.knobs.length) return {
|
|
619
|
+
unknown: `${expr.model} reads ${model.knobs.length} knobs, not ${expr.knobs.length}`,
|
|
620
|
+
unit: expr.unit
|
|
621
|
+
};
|
|
622
|
+
const args = expr.knobs.map((name, index) => knobIn(doc, name, model.knobs[index] ?? null, values, fired));
|
|
623
|
+
const lost = unknownOf(args);
|
|
624
|
+
if (lost !== void 0) return out(lost, expr.unit);
|
|
625
|
+
if (args.some((arg) => arg.kind === "infinite")) return unbounded(expr.unit);
|
|
626
|
+
const seconds = model.seconds(args.map((arg) => arg.n));
|
|
627
|
+
return quantity(rationals.toNumber(convertExact(seconds, "s", expr.unit)), expr.unit);
|
|
628
|
+
};
|
|
629
|
+
/**
|
|
630
|
+
* This function gives the bounds of a timer of a machine: how long it operates, how late it can
|
|
631
|
+
* fire, how early. For a backoff timer, it gives one of its waits: the wait after `fired` firings.
|
|
632
|
+
*/
|
|
633
|
+
const timerOf = (doc, timer, values, fired) => {
|
|
634
|
+
const def = doc.timers[timer];
|
|
635
|
+
if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
|
|
636
|
+
return {
|
|
637
|
+
duration: evaluate(doc, def.duration, values, fired),
|
|
638
|
+
...def.lateness !== void 0 ? { lateness: evaluate(doc, def.lateness, values, fired) } : {},
|
|
639
|
+
...def.early !== void 0 ? { early: evaluate(doc, def.early, values, fired) } : {}
|
|
640
|
+
};
|
|
641
|
+
};
|
|
642
|
+
/** This count is the most firings that `recovery` examines before it tells that the stall is longer than them. */
|
|
643
|
+
const FIRINGS = 4096;
|
|
644
|
+
/**
|
|
645
|
+
* This function gives the recovery from a stall. A backoff timer continues to fire through a
|
|
646
|
+
* stall, and what each firing sends gets through only after the stall ends. Thus the connection
|
|
647
|
+
* moves again at the first firing at the end or after it. That firing can be most of a wait after
|
|
648
|
+
* the end. A stall that stops immediately after one firing costs almost all of the next, longer
|
|
649
|
+
* wait.
|
|
650
|
+
*
|
|
651
|
+
* The stall counts from the arming of the timer, which is the send that the stall first lost. The
|
|
652
|
+
* waits add, and so do how early and how late each can fire.
|
|
653
|
+
*/
|
|
654
|
+
const recovery = (doc, timer, values, stall) => {
|
|
655
|
+
const def = doc.timers[timer];
|
|
656
|
+
if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
|
|
657
|
+
if (def.backoff === void 0) throw new Error(`${doc.title}'s ${timer} has no backoff`);
|
|
658
|
+
if (isUnbounded(stall)) return {
|
|
659
|
+
unknown: "a stall that never ends: nothing recovers from it",
|
|
660
|
+
unit: "s"
|
|
661
|
+
};
|
|
662
|
+
const end = convertExact(rationals.fromNumber(stall.value), stall.unit, "s");
|
|
663
|
+
const inSeconds = (extent, what) => {
|
|
664
|
+
if (extent === void 0) return rationals.ZERO;
|
|
665
|
+
if ("unknown" in extent) return `${what}: ${extent.unknown}`;
|
|
666
|
+
if (isUnbounded(extent)) return `${what} has no bound, so the timer never fires again`;
|
|
667
|
+
return convertExact(rationals.fromNumber(extent.value), extent.unit, "s");
|
|
668
|
+
};
|
|
669
|
+
const s = (value) => quantity(rationals.toNumber(value), "s");
|
|
670
|
+
const sums = [];
|
|
671
|
+
let low = rationals.ZERO;
|
|
672
|
+
let high = rationals.ZERO;
|
|
673
|
+
for (let fired = 0; fired < FIRINGS; fired += 1) {
|
|
674
|
+
const bounds = timerOf(doc, timer, values, fired);
|
|
675
|
+
const wait = inSeconds(bounds.duration, `wait ${fired}`);
|
|
676
|
+
const early = inSeconds(bounds.early, `wait ${fired}'s early bound`);
|
|
677
|
+
const late = inSeconds(bounds.lateness, `wait ${fired}'s lateness`);
|
|
678
|
+
if (typeof wait === "string") return {
|
|
679
|
+
unknown: wait,
|
|
680
|
+
unit: "s"
|
|
681
|
+
};
|
|
682
|
+
if (typeof early === "string") return {
|
|
683
|
+
unknown: early,
|
|
684
|
+
unit: "s"
|
|
685
|
+
};
|
|
686
|
+
if (typeof late === "string") return {
|
|
687
|
+
unknown: late,
|
|
688
|
+
unit: "s"
|
|
689
|
+
};
|
|
690
|
+
low = rationals.add(low, rationals.sub(wait, early));
|
|
691
|
+
high = rationals.add(high, rationals.add(wait, late));
|
|
692
|
+
sums.push({
|
|
693
|
+
fired,
|
|
694
|
+
low,
|
|
695
|
+
high
|
|
696
|
+
});
|
|
697
|
+
if (rationals.cmp(low, end) < 0) continue;
|
|
698
|
+
const first = sums.filter((f) => rationals.cmp(f.high, end) >= 0);
|
|
699
|
+
const earliest = first[0].low;
|
|
700
|
+
return {
|
|
701
|
+
firings: sums.map((f) => ({
|
|
702
|
+
fired: f.fired,
|
|
703
|
+
low: s(f.low),
|
|
704
|
+
high: s(f.high)
|
|
705
|
+
})),
|
|
706
|
+
first: first.map((f) => f.fired),
|
|
707
|
+
low: s(rationals.cmp(earliest, end) >= 0 ? earliest : end),
|
|
708
|
+
high: s(first.at(-1).high)
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
return {
|
|
712
|
+
unknown: `${FIRINGS} firings do not outlast the stall`,
|
|
713
|
+
unit: "s"
|
|
714
|
+
};
|
|
715
|
+
};
|
|
716
|
+
/** This function gives an amount as an exact value in seconds. Without an amount, it gives zero. */
|
|
717
|
+
const secondsOf = (extent) => {
|
|
718
|
+
if (extent === void 0) return exact(rationals.ZERO);
|
|
719
|
+
if ("unknown" in extent) return unknown(extent.unknown);
|
|
720
|
+
if (isUnbounded(extent)) return INFINITE;
|
|
721
|
+
return exact(convertExact(rationals.fromNumber(extent.value), extent.unit, "s"));
|
|
722
|
+
};
|
|
723
|
+
/**
|
|
724
|
+
* This function gives the band of a timer from its bounds, exactly, in `unit`. The band goes from
|
|
725
|
+
* its duration less its early bound to its duration plus its lateness. A bound that the document
|
|
726
|
+
* does not give is zero. A duration without an end gives a band without an end. A keepalive of 11 s, 4 ms early and 352 ms
|
|
727
|
+
* late, gives 10.996 s to 11.352 s.
|
|
728
|
+
*/
|
|
729
|
+
const timerBand = (bounds, unit = "s") => {
|
|
730
|
+
const duration = secondsOf(bounds.duration);
|
|
731
|
+
const early = secondsOf(bounds.early);
|
|
732
|
+
const late = secondsOf(bounds.lateness);
|
|
733
|
+
const lost = unknownOf([
|
|
734
|
+
duration,
|
|
735
|
+
early,
|
|
736
|
+
late
|
|
737
|
+
]);
|
|
738
|
+
if (lost !== void 0) return out(lost, unit);
|
|
739
|
+
if (duration.kind !== "exact") return {
|
|
740
|
+
low: unbounded(unit),
|
|
741
|
+
high: unbounded(unit)
|
|
742
|
+
};
|
|
743
|
+
if (early.kind !== "exact") return {
|
|
744
|
+
unknown: "an early bound without an end",
|
|
745
|
+
unit
|
|
746
|
+
};
|
|
747
|
+
const low = rationals.sub(duration.n, early.n);
|
|
748
|
+
const at = (n) => quantity(rationals.toNumber(convertExact(n, "s", unit)), unit);
|
|
749
|
+
return {
|
|
750
|
+
low: at(low),
|
|
751
|
+
high: late.kind === "exact" ? at(rationals.add(duration.n, late.n)) : unbounded(unit)
|
|
752
|
+
};
|
|
753
|
+
};
|
|
754
|
+
/**
|
|
755
|
+
* This function gives the firings of a backoff timer on a timeline: the sum of its waits, exactly,
|
|
756
|
+
* from the wait `from`. It stops at the first wait that is not a known amount, or at a stop of the
|
|
757
|
+
* options, or after 4096 firings. Each time is the duration of the waits, without how early or
|
|
758
|
+
* late each can fire.
|
|
759
|
+
*
|
|
760
|
+
* Two examples: the retransmission timer of Linux gives the send of each retransmission. The
|
|
761
|
+
* retry of a call with a deadline gives the start of each try.
|
|
762
|
+
*/
|
|
763
|
+
const firings = (doc, timer, values, options) => {
|
|
764
|
+
const def = doc.timers[timer];
|
|
765
|
+
if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
|
|
766
|
+
if (def.backoff === void 0) throw new Error(`${doc.title}'s ${timer} has no backoff`);
|
|
767
|
+
if (options.count === void 0 && options.until === void 0 && options.reach === void 0) throw new Error(`the firings of ${timer} need a stop: a count, until or reach`);
|
|
768
|
+
const limit = (extent) => extent === void 0 ? void 0 : secondsOf(extent);
|
|
769
|
+
const until = limit(options.until);
|
|
770
|
+
const reach = limit(options.reach);
|
|
771
|
+
const from = options.from ?? 0;
|
|
772
|
+
const count = Math.min(options.count ?? FIRINGS, FIRINGS);
|
|
773
|
+
const result = [];
|
|
774
|
+
let at = rationals.ZERO;
|
|
775
|
+
for (let fired = from; result.length < count; fired += 1) {
|
|
776
|
+
const wait = secondsOf(timerOf(doc, timer, values, fired).duration);
|
|
777
|
+
if (wait.kind !== "exact") break;
|
|
778
|
+
at = rationals.add(at, wait.n);
|
|
779
|
+
if (until?.kind === "exact" && rationals.cmp(at, until.n) > 0) break;
|
|
780
|
+
result.push({
|
|
781
|
+
fired,
|
|
782
|
+
at: quantity(rationals.toNumber(at), "s")
|
|
783
|
+
});
|
|
784
|
+
if (reach?.kind === "exact" && rationals.cmp(at, reach.n) >= 0) break;
|
|
785
|
+
}
|
|
786
|
+
return result;
|
|
787
|
+
};
|
|
788
|
+
/**
|
|
789
|
+
* This function gives the times of a train of probes, exactly, in seconds. The first probe is at
|
|
790
|
+
* `first`, and each next probe is one `interval` later, `count` probes in all. A first time without
|
|
791
|
+
* an end gives no probe. An interval without an end gives only the first probe. Keepalive at its
|
|
792
|
+
* defaults sends its probes at 7200 s, 7275 s, and so on to 7800 s.
|
|
793
|
+
*/
|
|
794
|
+
const probeTrain = (first, interval, count) => {
|
|
795
|
+
const start = secondsOf(first);
|
|
796
|
+
const step = secondsOf(interval);
|
|
797
|
+
if (start.kind !== "exact" || count < 1) return [];
|
|
798
|
+
const times = [quantity(rationals.toNumber(start.n), "s")];
|
|
799
|
+
if (step.kind !== "exact") return times;
|
|
800
|
+
for (let k = 1; k < count; k += 1) times.push(quantity(rationals.toNumber(rationals.add(start.n, rationals.mul(step.n, whole(BigInt(k))))), "s"));
|
|
801
|
+
return times;
|
|
802
|
+
};
|
|
803
|
+
/**
|
|
804
|
+
* This function gives how long a mechanism takes where a machine operates, from the realization
|
|
805
|
+
* of its document. The realization is one of its timers, whole, or its own duration, lateness and
|
|
806
|
+
* early bound over the knobs of the machine. It gives undefined when the document does not realize the mechanism.
|
|
807
|
+
*/
|
|
808
|
+
const realizationOf = (doc, mechanism, values) => {
|
|
809
|
+
const how = doc.realizes?.[mechanism];
|
|
810
|
+
if (how === void 0) return void 0;
|
|
811
|
+
if ("timer" in how) return timerOf(doc, how.timer, values);
|
|
812
|
+
return {
|
|
813
|
+
duration: evaluate(doc, how.duration, values),
|
|
814
|
+
...how.lateness !== void 0 ? { lateness: evaluate(doc, how.lateness, values) } : {},
|
|
815
|
+
...how.early !== void 0 ? { early: evaluate(doc, how.early, values) } : {}
|
|
816
|
+
};
|
|
817
|
+
};
|
|
818
|
+
/** This function gives the knobs that a realization reads, by the names of the machine for them. */
|
|
819
|
+
const realizationKnobs = (doc, mechanism) => {
|
|
820
|
+
const how = doc.realizes?.[mechanism];
|
|
821
|
+
if (how === void 0) return [];
|
|
822
|
+
const def = "timer" in how ? doc.timers[how.timer] : how;
|
|
823
|
+
if (def === void 0) return [];
|
|
824
|
+
return [...new Set([
|
|
825
|
+
def.duration,
|
|
826
|
+
def.lateness,
|
|
827
|
+
def.early
|
|
828
|
+
].flatMap((e) => e === void 0 ? [] : exprKnobs(e)))];
|
|
829
|
+
};
|
|
830
|
+
/** This function gives what in a document the algebra cannot read: arithmetic that does not parse, or a model that it does not have. */
|
|
831
|
+
const algebraProblems = (doc) => {
|
|
832
|
+
const problems = [];
|
|
833
|
+
const read = (where, exprs) => {
|
|
834
|
+
for (const expr of exprs) {
|
|
835
|
+
if (expr === void 0) continue;
|
|
836
|
+
if ("expr" in expr) try {
|
|
837
|
+
parseExpr(expr.expr);
|
|
838
|
+
} catch (error) {
|
|
839
|
+
problems.push(`${where}: ${error.message}`);
|
|
840
|
+
}
|
|
841
|
+
if ("model" in expr && modelOf(expr.model) === void 0) problems.push(`${where}: no model ${expr.model}`);
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
for (const [id, def] of Object.entries(doc.timers)) read(`timer ${id}`, [
|
|
845
|
+
def.duration,
|
|
846
|
+
def.lateness,
|
|
847
|
+
def.early
|
|
848
|
+
]);
|
|
849
|
+
for (const [mechanism, how] of Object.entries(doc.realizes ?? {})) if (!("timer" in how)) read(`realizes ${mechanism}`, [
|
|
850
|
+
how.duration,
|
|
851
|
+
how.lateness,
|
|
852
|
+
how.early
|
|
853
|
+
]);
|
|
854
|
+
for (const [lower, set] of Object.entries(doc.over?.sets ?? {})) read(`over sets ${lower}`, [set]);
|
|
855
|
+
return problems;
|
|
856
|
+
};
|
|
857
|
+
/** This function gives the source of the formula of a named model, for a reader of a result. */
|
|
858
|
+
const modelSource = (name) => modelOf(name)?.source;
|
|
859
|
+
const soonest = (a, b) => {
|
|
860
|
+
const rank = (d) => "unknown" in d.duration ? 2 : d.duration.value === "infinite" ? 1 : 0;
|
|
861
|
+
if (rank(a) !== rank(b)) return rank(a) - rank(b);
|
|
862
|
+
if (rank(a) !== 0) return a.timer.localeCompare(b.timer);
|
|
863
|
+
const seconds = (d) => {
|
|
864
|
+
const value = d.duration;
|
|
865
|
+
return rationals.toNumber(convertExact(rationals.fromNumber(value.value), value.unit, "s"));
|
|
866
|
+
};
|
|
867
|
+
return seconds(a) - seconds(b) || a.timer.localeCompare(b.timer);
|
|
868
|
+
};
|
|
869
|
+
/**
|
|
870
|
+
* This function gives the detection: the minimum over the detectors that are live in the
|
|
871
|
+
* situation. The entry to the state arms a timer, and so does what the failure causes: data in
|
|
872
|
+
* flight without an acknowledgment gets a retransmission. An event that occurs cancels a timer.
|
|
873
|
+
*
|
|
874
|
+
* An event that arms the timer again, and that the failure continues to let through, stops it
|
|
875
|
+
* before it fires. For example, the kernel of a frozen process answers each keepalive probe.
|
|
876
|
+
* Without a live detector, the failure is silent at the level of this machine. Only something
|
|
877
|
+
* above it, the timeout of an application or a heartbeat, can find it. The result is only as good
|
|
878
|
+
* as the events that the document names.
|
|
879
|
+
*/
|
|
880
|
+
const detection = (doc, situation, manifestation, values) => {
|
|
881
|
+
const passes = new Set(manifestation.passes);
|
|
882
|
+
const happened = /* @__PURE__ */ new Set([`enter:${situation.state}`]);
|
|
883
|
+
if (situation.inFlight && !passes.has("rx.ack")) happened.add("tx.retransmit.first");
|
|
884
|
+
const occurs = (event) => happened.has(event) || passes.has(event);
|
|
885
|
+
const detectors = [];
|
|
886
|
+
const held = [];
|
|
887
|
+
for (const [timer, def] of Object.entries(doc.timers)) {
|
|
888
|
+
if (def.backoff !== void 0) continue;
|
|
889
|
+
if (!def.arms.some(occurs)) continue;
|
|
890
|
+
const cancelled = (def.cancels ?? []).find(occurs);
|
|
891
|
+
if (cancelled !== void 0) {
|
|
892
|
+
held.push({
|
|
893
|
+
timer,
|
|
894
|
+
why: `${cancelled} cancels it`
|
|
895
|
+
});
|
|
896
|
+
continue;
|
|
897
|
+
}
|
|
898
|
+
const rearmed = def.arms.find((event) => passes.has(event));
|
|
899
|
+
if (rearmed !== void 0) {
|
|
900
|
+
held.push({
|
|
901
|
+
timer,
|
|
902
|
+
why: `${rearmed} keeps arriving and re-arms it`
|
|
903
|
+
});
|
|
904
|
+
continue;
|
|
905
|
+
}
|
|
906
|
+
const duration = manifestation.replaces?.[timer]?.duration ?? def.duration;
|
|
907
|
+
detectors.push({
|
|
908
|
+
timer,
|
|
909
|
+
fires: def.fires,
|
|
910
|
+
duration: evaluate(doc, duration, values)
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
detectors.sort(soonest);
|
|
914
|
+
const [earliest] = detectors;
|
|
915
|
+
const finite = earliest !== void 0 && !("unknown" in earliest.duration) && earliest.duration.value !== "infinite";
|
|
916
|
+
const delivered = (manifestation.delivers ?? []).flatMap((event) => {
|
|
917
|
+
const taken = transitionOn(doc, situation.state, event);
|
|
918
|
+
return taken === void 0 ? [] : [{
|
|
919
|
+
event,
|
|
920
|
+
to: taken.to,
|
|
921
|
+
errno: taken.errno ?? null
|
|
922
|
+
}];
|
|
923
|
+
});
|
|
924
|
+
return {
|
|
925
|
+
detectors,
|
|
926
|
+
first: finite ? earliest : null,
|
|
927
|
+
unsettled: detectors.filter((d) => "unknown" in d.duration).map((d) => d.timer),
|
|
928
|
+
held,
|
|
929
|
+
delivered
|
|
930
|
+
};
|
|
931
|
+
};
|
|
932
|
+
/**
|
|
933
|
+
* This function gives the bounds of a timer of a machine under a failure: its own bounds, with each
|
|
934
|
+
* duration that the manifestation replaces.
|
|
935
|
+
*/
|
|
936
|
+
const timerUnder = (doc, timer, values, manifestation, fired) => {
|
|
937
|
+
const def = doc.timers[timer];
|
|
938
|
+
if (def === void 0) throw new Error(`${doc.title} has no timer ${timer}`);
|
|
939
|
+
const replaced = manifestation.replaces?.[timer];
|
|
940
|
+
const duration = replaced?.duration ?? def.duration;
|
|
941
|
+
const lateness = replaced?.lateness ?? def.lateness;
|
|
942
|
+
const early = replaced?.early ?? def.early;
|
|
943
|
+
return {
|
|
944
|
+
duration: evaluate(doc, duration, values, fired),
|
|
945
|
+
...lateness !== void 0 ? { lateness: evaluate(doc, lateness, values, fired) } : {},
|
|
946
|
+
...early !== void 0 ? { early: evaluate(doc, early, values, fired) } : {}
|
|
947
|
+
};
|
|
948
|
+
};
|
|
949
|
+
/**
|
|
950
|
+
* This function gives the errno of a detection by a timer: the errno of the transition that its
|
|
951
|
+
* event takes from the state. A soft error of the manifestation replaces ETIMEDOUT, but only for
|
|
952
|
+
* the timers whose segments its ICMP quotes in the window.
|
|
953
|
+
*/
|
|
954
|
+
const errnoOf = (doc, state, detector, manifestation) => {
|
|
955
|
+
const errno = transitionOn(doc, state, detector.fires)?.errno ?? null;
|
|
956
|
+
const soft = manifestation.errno;
|
|
957
|
+
return errno === "ETIMEDOUT" && soft !== void 0 && soft.timers.includes(detector.timer) ? soft.errno : errno;
|
|
958
|
+
};
|
|
959
|
+
/** This function gives the transition that a machine takes from a state on an event, by its document. */
|
|
960
|
+
const transitionOn = (doc, state, event) => doc.transitions.find((t) => fromStates(doc, t.from).includes(state) && arr(t.on).includes(event));
|
|
961
|
+
/**
|
|
962
|
+
* This function gives the values of a machine for the machine that it operates on. These are the
|
|
963
|
+
* knobs that it sets, evaluated over its own knobs, and the other knobs of the lower machine. The
|
|
964
|
+
* keepAlive of ioredis at 5000 ms is the keepidle of the kernel at 5 s.
|
|
965
|
+
*/
|
|
966
|
+
const overValues = (upper, upperValues, lowerValues) => (name) => {
|
|
967
|
+
const set = upper.over?.sets[name];
|
|
968
|
+
return set === void 0 ? lowerValues(name) : evaluate(upper, set, upperValues);
|
|
969
|
+
};
|
|
970
|
+
/**
|
|
971
|
+
* This function gives the detection through the machine that a machine operates on. The detectors
|
|
972
|
+
* of the lower machine are live in the state below the state of this machine. They use the knobs
|
|
973
|
+
* that this machine sets.
|
|
974
|
+
*
|
|
975
|
+
* Each one reaches this machine as the event that the end of the lower
|
|
976
|
+
* machine gives. They are beside the timers of this machine, and the first of all of them is the
|
|
977
|
+
* first detection. A failure lets nothing new through to a machine above the socket, only the end
|
|
978
|
+
* of the socket. Thus the timers of this machine see only what its state arms.
|
|
979
|
+
*/
|
|
980
|
+
const stackedDetection = (upper, lower, situation, manifestation, upperValues, lowerValues) => {
|
|
981
|
+
const over = upper.over;
|
|
982
|
+
if (over === void 0) throw new Error(`${upper.title} runs on no other machine`);
|
|
983
|
+
const sitsOn = over.states[situation.state];
|
|
984
|
+
if (sitsOn === void 0) throw new Error(`${upper.title}'s ${situation.state} sits on no state of ${lower.title}`);
|
|
985
|
+
const own = detection(upper, situation, {
|
|
986
|
+
name: manifestation.name,
|
|
987
|
+
passes: []
|
|
988
|
+
}, upperValues);
|
|
989
|
+
const below = detection(lower, {
|
|
990
|
+
...situation,
|
|
991
|
+
state: sitsOn
|
|
992
|
+
}, manifestation, overValues(upper, upperValues, lowerValues));
|
|
993
|
+
const detectors = [...own.detectors, ...below.detectors.map((d) => ({
|
|
994
|
+
...d,
|
|
995
|
+
beneath: over.machine
|
|
996
|
+
}))].sort(soonest);
|
|
997
|
+
const [earliest] = detectors;
|
|
998
|
+
return {
|
|
999
|
+
detectors,
|
|
1000
|
+
first: earliest !== void 0 && !("unknown" in earliest.duration) && earliest.duration.value !== "infinite" ? earliest : null,
|
|
1001
|
+
unsettled: detectors.filter((d) => "unknown" in d.duration).map((d) => d.timer),
|
|
1002
|
+
held: [...own.held, ...below.held.map((h) => ({
|
|
1003
|
+
...h,
|
|
1004
|
+
why: `${h.why}, beneath`
|
|
1005
|
+
}))],
|
|
1006
|
+
delivered: below.delivered
|
|
1007
|
+
};
|
|
1008
|
+
};
|
|
1009
|
+
// src/run.ts
|
|
1010
|
+
/** This function gives the values of the knobs at their defaults. A knob without a default or without a unit has no value. */
|
|
1011
|
+
const knobDefaults = (doc) => (name) => {
|
|
1012
|
+
const knob = Object.hasOwn(doc.knobs, name) ? doc.knobs[name] : void 0;
|
|
1013
|
+
if (knob === void 0 || knob.unit === null || knob.default === null) return void 0;
|
|
1014
|
+
return quantity(knob.default, knob.unit);
|
|
1015
|
+
};
|
|
1016
|
+
/** This function gives the start state of a run: the state of the options, or the one initial state of the document. */
|
|
1017
|
+
const startState = (doc, state) => {
|
|
1018
|
+
if (state !== void 0) {
|
|
1019
|
+
if (!Object.hasOwn(doc.states, state)) throw new Error(`${doc.title} has no state ${state}`);
|
|
1020
|
+
return state;
|
|
1021
|
+
}
|
|
1022
|
+
const initial = Object.keys(doc.states).filter((name) => doc.states[name].initial === true);
|
|
1023
|
+
if (initial.length !== 1) throw new Error(`${doc.title} has ${initial.length} initial states: give the start state in the options`);
|
|
1024
|
+
return initial[0];
|
|
1025
|
+
};
|
|
1026
|
+
/**
|
|
1027
|
+
* This function starts a live instance of a machine document on a clock. It gives the run: its
|
|
1028
|
+
* state, `send` and `stop`. The run applies these rules:
|
|
1029
|
+
*
|
|
1030
|
+
* - The run refuses a document with problems (`machineProblems`), as each reader does. With a start
|
|
1031
|
+
* state in the options, a document with no initial state is correct.
|
|
1032
|
+
* - At the start, the instance enters its start state. The pseudo event `enter:<state>` operates
|
|
1033
|
+
* the timers, as after a transition.
|
|
1034
|
+
* - An event that the document does not name is an error. The run throws an `Error` that names it.
|
|
1035
|
+
* - `send` takes the transition of `transitionOn` from the state on the event. Then, in sequence,
|
|
1036
|
+
* these events operate the timers: the event itself, each event that the transition emits, and
|
|
1037
|
+
* `enter:<to>`. A transition to the state that it leaves also enters that state again.
|
|
1038
|
+
* - An event without a transition also operates the timers.
|
|
1039
|
+
* - For each timer, an event of `backoff.resets` first sets its count of firings to 0. Then an
|
|
1040
|
+
* event of `cancels` stops it, or else an event of `arms` starts it again from the full
|
|
1041
|
+
* duration. An event in `arms` and in `cancels` stops the timer, as in `detection`.
|
|
1042
|
+
* - The run reads the duration of each start from `timerOf`, with the values and the count of
|
|
1043
|
+
* firings of a backoff timer. It converts the duration to milliseconds exactly. It does not read
|
|
1044
|
+
* the lateness or the early bound. A duration with no bound does not start the timer.
|
|
1045
|
+
* - The run reads the first duration of each timer when it starts. Thus a knob without a value is an
|
|
1046
|
+
* error at the start, not in a callback of the clock.
|
|
1047
|
+
* - When a timer fires, its `fires` event goes through `send`. A backoff timer first adds 1 to its
|
|
1048
|
+
* count and starts again with its next wait. Thus its own `cancels` can stop it.
|
|
1049
|
+
* - The entry to a final state stops each timer. In a final state, `send` does nothing and gives undefined.
|
|
1050
|
+
* - The run gives each transition that it takes to `onTransition`, after the timers. The record has
|
|
1051
|
+
* the machine (the `id` of the document), the instance, the states, the event and the time of the clock.
|
|
1052
|
+
* - The `timer` of a transition is a note for the reader. The run does not read it.
|
|
1053
|
+
*/
|
|
1054
|
+
const runMachine = (doc, options) => {
|
|
1055
|
+
const problems = machineProblems(doc).filter((problem) => options.state === void 0 || problem !== "no initial state");
|
|
1056
|
+
if (problems.length > 0) throw new Error(`${doc.title} has problems: ${problems.join(", ")}`);
|
|
1057
|
+
const clock = options.clock;
|
|
1058
|
+
const values = options.values ?? knobDefaults(doc);
|
|
1059
|
+
const instance = options.instance ?? doc.id;
|
|
1060
|
+
let state = startState(doc, options.state);
|
|
1061
|
+
let stopped = false;
|
|
1062
|
+
const timers = Object.entries(doc.timers).map(([name, def]) => ({
|
|
1063
|
+
name,
|
|
1064
|
+
def,
|
|
1065
|
+
fired: 0,
|
|
1066
|
+
cancel: void 0
|
|
1067
|
+
}));
|
|
1068
|
+
/** This function gives the wait of a timer in milliseconds, or undefined for a duration with no bound. */
|
|
1069
|
+
const waitOf = (timer) => {
|
|
1070
|
+
const duration = timerOf(doc, timer.name, values, timer.def.backoff === void 0 ? void 0 : timer.fired).duration;
|
|
1071
|
+
if ("unknown" in duration) throw new Error(`${doc.title}'s ${timer.name} has no known duration: ${duration.unknown}`);
|
|
1072
|
+
if (isUnbounded(duration)) return void 0;
|
|
1073
|
+
return rationals.toNumber(convertExact(rationals.fromNumber(duration.value), duration.unit, "ms"));
|
|
1074
|
+
};
|
|
1075
|
+
const halt = (timer) => {
|
|
1076
|
+
timer.cancel?.();
|
|
1077
|
+
timer.cancel = void 0;
|
|
1078
|
+
};
|
|
1079
|
+
const begin = (timer) => {
|
|
1080
|
+
halt(timer);
|
|
1081
|
+
const ms = waitOf(timer);
|
|
1082
|
+
if (ms !== void 0) timer.cancel = clock.after(ms, () => fire(timer));
|
|
1083
|
+
};
|
|
1084
|
+
const fire = (timer) => {
|
|
1085
|
+
timer.cancel = void 0;
|
|
1086
|
+
if (stopped) return;
|
|
1087
|
+
if (timer.def.backoff !== void 0) {
|
|
1088
|
+
timer.fired += 1;
|
|
1089
|
+
begin(timer);
|
|
1090
|
+
}
|
|
1091
|
+
run.send(timer.def.fires);
|
|
1092
|
+
};
|
|
1093
|
+
/** This function operates each timer for one event. */
|
|
1094
|
+
const occur = (event) => {
|
|
1095
|
+
for (const timer of timers) {
|
|
1096
|
+
if (timer.def.backoff?.resets.includes(event) === true) timer.fired = 0;
|
|
1097
|
+
if (timer.def.cancels?.includes(event) === true) halt(timer);
|
|
1098
|
+
else if (timer.def.arms.includes(event)) begin(timer);
|
|
1099
|
+
}
|
|
1100
|
+
};
|
|
1101
|
+
const isFinal = (name) => doc.states[name]?.final === true;
|
|
1102
|
+
/** This function enters a state: `enter:<state>` operates the timers, and a final state stops each timer. */
|
|
1103
|
+
const enter = (to) => {
|
|
1104
|
+
occur(`enter:${to}`);
|
|
1105
|
+
if (isFinal(to)) for (const timer of timers) halt(timer);
|
|
1106
|
+
};
|
|
1107
|
+
const run = {
|
|
1108
|
+
get state() {
|
|
1109
|
+
return state;
|
|
1110
|
+
},
|
|
1111
|
+
send(event) {
|
|
1112
|
+
if (!Object.hasOwn(doc.events, event)) throw new Error(`${doc.title} has no event ${event}`);
|
|
1113
|
+
if (stopped || isFinal(state)) return void 0;
|
|
1114
|
+
const from = state;
|
|
1115
|
+
const taken = transitionOn(doc, from, event);
|
|
1116
|
+
if (taken !== void 0) state = taken.to;
|
|
1117
|
+
occur(event);
|
|
1118
|
+
if (taken === void 0) return void 0;
|
|
1119
|
+
for (const sent of taken.emits ?? []) occur(sent);
|
|
1120
|
+
enter(taken.to);
|
|
1121
|
+
options.onTransition?.({
|
|
1122
|
+
machine: doc.id,
|
|
1123
|
+
instance,
|
|
1124
|
+
from,
|
|
1125
|
+
on: event,
|
|
1126
|
+
to: taken.to,
|
|
1127
|
+
at: clock.now()
|
|
1128
|
+
});
|
|
1129
|
+
return taken;
|
|
1130
|
+
},
|
|
1131
|
+
stop() {
|
|
1132
|
+
stopped = true;
|
|
1133
|
+
for (const timer of timers) halt(timer);
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
for (const timer of timers) waitOf(timer);
|
|
1137
|
+
enter(state);
|
|
1138
|
+
return run;
|
|
1139
|
+
};
|
|
1140
|
+
export { readsFired as C, machineProblems as S, timerOf as _, evaluate as a, FIRED as b, overValues as c, realizationKnobs as d, realizationOf as f, timerBand as g, synGiveUpSends as h, errnoOf as i, parseExpr as l, stackedDetection as m, algebraProblems as n, firings as o, recovery as p, detection as r, modelSource as s, runMachine as t, probeTrain as u, timerUnder as v, exprKnobs as x, transitionOn as y };
|
|
1141
|
+
|
|
1142
|
+
//# sourceMappingURL=run-DTmtHPlK.js.map
|