hydo-assert 0.0.0-stage → 0.2.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.
package/index.js ADDED
@@ -0,0 +1,585 @@
1
+ 'use strict';
2
+ // hydo-assert: hydo's assertion SDK for Node.js guest programs.
3
+ //
4
+ // A program running under hydo (the deterministic hypervisor) uses it to say what must be
5
+ // true (always, alwaysOrUnreachable, unreachable), what should happen at least once
6
+ // (sometimes, reachable), what must happen within a deadline (eventually), and where a
7
+ // dependency may misbehave (buggify fault points). Records go to the guest console in the
8
+ // wire format of the Rust, Go and Python SDKs, byte for byte, with the same deduplication
9
+ // rules; hydo/ASSERTIONS.md is the contract.
10
+ //
11
+ // Wire format, one record per line, each written with a single write():
12
+ //
13
+ // HYDO-ASSERT-DECL {"t":"always","id":"order.acked","msg":"..."}
14
+ // HYDO-ASSERT {"t":"always","id":"order.acked","ok":false,"msg":"...","details":{...}}
15
+ // HYDO-SETUP-COMPLETE
16
+ //
17
+ // Determinism: the output is a pure function of the evaluation sequence -- no clocks (except
18
+ // the guest's monotonic clock for `eventually`, which hydo makes deterministic), no host
19
+ // state, the catalog in declaration order, details with object keys in bytewise (UTF-8)
20
+ // order, numbers and strings formatted as Go's encoding/json formats them.
21
+ //
22
+ // No runtime dependencies; plain CommonJS (index.mjs re-exports this module for ESM, so a
23
+ // program that uses both share one state).
24
+
25
+ const fs = require('fs');
26
+
27
+ // ---------------------------------------------------------------------------------------------
28
+ // Output sink: the guest console, opened once, as the Go SDK does.
29
+ //
30
+ // HYDO_ASSERT_OUT unset or empty: /dev/ttyS0; "off": nothing (a no-op outside hydo); "stderr":
31
+ // standard error (plain logging outside hydo); anything else: that file, appended. If the
32
+ // file cannot be opened the records go to standard error.
33
+
34
+ const SINK_UNSET = 0;
35
+ const SINK_OFF = 1;
36
+ const SINK_FD = 2;
37
+ let sinkState = SINK_UNSET;
38
+ let sinkFd = -1;
39
+
40
+ function openSink() {
41
+ const p = process.env.HYDO_ASSERT_OUT || '';
42
+ if (p === 'off') {
43
+ sinkState = SINK_OFF;
44
+ return;
45
+ }
46
+ sinkState = SINK_FD;
47
+ if (p === 'stderr') {
48
+ sinkFd = 2;
49
+ return;
50
+ }
51
+ const c = fs.constants;
52
+ // O_NOCTTY: never make the console the controlling terminal of the caller (0 where absent).
53
+ const flags = c.O_WRONLY | c.O_APPEND | (c.O_NOCTTY || 0);
54
+ try {
55
+ sinkFd = fs.openSync(p === '' ? '/dev/ttyS0' : p, flags);
56
+ } catch (e) {
57
+ sinkFd = 2;
58
+ }
59
+ }
60
+
61
+ // writeLine writes one complete line (a Buffer ending in '\n'). One write() call; a short
62
+ // write (which the console never does) is continued, as Go's File.Write does.
63
+ function writeLine(buf) {
64
+ if (sinkState === SINK_UNSET) openSink();
65
+ if (sinkState === SINK_OFF) return;
66
+ try {
67
+ let off = 0;
68
+ while (off < buf.length) {
69
+ const n = fs.writeSync(sinkFd, buf, off, buf.length - off);
70
+ if (n <= 0) break;
71
+ off += n;
72
+ }
73
+ } catch (e) {
74
+ // like the Go SDK: a failed console write is ignored
75
+ }
76
+ }
77
+
78
+ // ---------------------------------------------------------------------------------------------
79
+ // JSON encoder: exactly what Go's encoding/json (json.Marshal) writes for the same data.
80
+ //
81
+ // - object keys sorted by their UTF-8 bytes (Go sorts map keys bytewise; JavaScript's own
82
+ // string order is by UTF-16 units, which differs above U+D7FF);
83
+ // - strings: '"' and '\\' escaped, \b \f \n \r \t, other control characters as \u00xx,
84
+ // '<' '>' '&' as \u003c \u003e \u0026, U+2028 and U+2029 as \u2028 and \u2029, and a
85
+ // lone surrogate (JavaScript's form of invalid UTF-8) as \ufffd;
86
+ // - numbers: shortest round-trip digits, exponent form below 1e-6 and from 1e21 (JavaScript's
87
+ // Number#toString already matches Go's float64 format there), -0 as "-0"; a NaN or an
88
+ // infinity makes the whole record unencodable (Go's Marshal fails, the record is dropped);
89
+ // - bigint: decimal integer (Go's int64/uint64/big.Int);
90
+ // - Uint8Array (and Buffer): a base64 string (Go's []byte);
91
+ // - other typed arrays and Set: arrays; Map: an object with String(key) keys;
92
+ // - a value with a toJSON() method is replaced by its result (as JSON.stringify does);
93
+ // - undefined, functions and symbols: left out of objects, null in arrays (as JSON.stringify);
94
+ // - a cycle makes the record unencodable (Go's Marshal fails on cycles too).
95
+
96
+ class Unencodable extends Error {}
97
+
98
+ const HEX = '0123456789abcdef';
99
+
100
+ function quote(s) {
101
+ s = String(s);
102
+ let out = '"';
103
+ let start = 0;
104
+ for (let i = 0; i < s.length; i++) {
105
+ const c = s.charCodeAt(i);
106
+ let esc = null;
107
+ if (c < 0x80) {
108
+ if (c >= 0x20 && c !== 0x22 && c !== 0x5c && c !== 0x3c && c !== 0x3e && c !== 0x26) continue;
109
+ switch (c) {
110
+ case 0x22: esc = '\\"'; break;
111
+ case 0x5c: esc = '\\\\'; break;
112
+ case 0x08: esc = '\\b'; break;
113
+ case 0x0c: esc = '\\f'; break;
114
+ case 0x0a: esc = '\\n'; break;
115
+ case 0x0d: esc = '\\r'; break;
116
+ case 0x09: esc = '\\t'; break;
117
+ default: esc = '\\u00' + HEX[c >> 4] + HEX[c & 0xf];
118
+ }
119
+ } else if (c === 0x2028) {
120
+ esc = '\\u2028';
121
+ } else if (c === 0x2029) {
122
+ esc = '\\u2029';
123
+ } else if (c >= 0xd800 && c <= 0xdbff) {
124
+ const d = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
125
+ if (d >= 0xdc00 && d <= 0xdfff) {
126
+ i++; // a valid pair: written as is (UTF-8 on the wire)
127
+ continue;
128
+ }
129
+ esc = '\\ufffd';
130
+ } else if (c >= 0xdc00 && c <= 0xdfff) {
131
+ esc = '\\ufffd';
132
+ } else {
133
+ continue;
134
+ }
135
+ out += s.slice(start, i) + esc;
136
+ start = i + 1;
137
+ }
138
+ return out + s.slice(start) + '"';
139
+ }
140
+
141
+ function formatNumber(x) {
142
+ if (!Number.isFinite(x)) throw new Unencodable();
143
+ if (x === 0 && 1 / x < 0) return '-0';
144
+ return String(x);
145
+ }
146
+
147
+ // Bytewise (UTF-8) order of two strings. Equal to UTF-16 order except when one side has a
148
+ // surrogate (astral character) where the other has U+E000..U+FFFF.
149
+ function cmpUtf8(a, b) {
150
+ if (a === b) return 0;
151
+ return Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));
152
+ }
153
+
154
+ function isSkipped(v) {
155
+ return v === undefined || typeof v === 'function' || typeof v === 'symbol';
156
+ }
157
+
158
+ function encodeObject(entries, stack) {
159
+ // entries: [key, value] pairs; skipped values are left out, keys sorted bytewise
160
+ const kept = entries.filter((e) => !isSkipped(e[1]));
161
+ kept.sort((x, y) => cmpUtf8(x[0], y[0]));
162
+ let out = '{';
163
+ for (let i = 0; i < kept.length; i++) {
164
+ if (i > 0) out += ',';
165
+ out += quote(kept[i][0]) + ':' + encodeValue(kept[i][1], stack);
166
+ }
167
+ return out + '}';
168
+ }
169
+
170
+ function encodeArray(items, stack) {
171
+ let out = '[';
172
+ for (let i = 0; i < items.length; i++) {
173
+ if (i > 0) out += ',';
174
+ out += isSkipped(items[i]) ? 'null' : encodeValue(items[i], stack);
175
+ }
176
+ return out + ']';
177
+ }
178
+
179
+ function encodeValue(v, stack) {
180
+ if (v !== null && typeof v === 'object' && typeof v.toJSON === 'function' && !(v instanceof Uint8Array)) {
181
+ v = v.toJSON();
182
+ }
183
+ switch (typeof v) {
184
+ case 'string': return quote(v);
185
+ case 'number': return formatNumber(v);
186
+ case 'bigint': return v.toString(10);
187
+ case 'boolean': return v ? 'true' : 'false';
188
+ case 'undefined': return 'null';
189
+ case 'function':
190
+ case 'symbol': return 'null';
191
+ }
192
+ if (v === null) return 'null';
193
+ if (v instanceof Number || v instanceof String || v instanceof Boolean) return encodeValue(v.valueOf(), stack);
194
+ if (stack.indexOf(v) >= 0) throw new Unencodable(); // a cycle
195
+ stack.push(v);
196
+ let out;
197
+ if (v instanceof Uint8Array) {
198
+ out = '"' + Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString('base64') + '"';
199
+ } else if (Array.isArray(v)) {
200
+ out = encodeArray(v, stack);
201
+ } else if (ArrayBuffer.isView(v) && typeof v.length === 'number') {
202
+ out = encodeArray(Array.from(v), stack);
203
+ } else if (v instanceof Set) {
204
+ out = encodeArray(Array.from(v), stack);
205
+ } else if (v instanceof Map) {
206
+ out = encodeObject(Array.from(v, (e) => [String(e[0]), e[1]]), stack);
207
+ } else {
208
+ out = encodeObject(Object.keys(v).map((k) => [k, v[k]]), stack);
209
+ }
210
+ stack.pop();
211
+ return out;
212
+ }
213
+
214
+ // toJSON returns the Go encoding of a details value, or null if it cannot be encoded (it holds
215
+ // a NaN, an infinity or a cycle). Exported as _toJSON for the SDK's tests only.
216
+ function toJSON(v) {
217
+ try {
218
+ return encodeValue(v, []);
219
+ } catch (e) {
220
+ if (e instanceof Unencodable || e instanceof RangeError) return null;
221
+ throw e;
222
+ }
223
+ }
224
+
225
+ // A details object is omitted from a record when it is absent or has no keys (Go's
226
+ // `json:"details,omitempty"` on a map).
227
+ // A details value that is not an object (or is an array) is written as {"value": d}.
228
+ function detailsJSON(d) {
229
+ if (d === undefined || d === null) return '';
230
+ if (typeof d !== 'object' || Array.isArray(d)) d = { value: d };
231
+ const s = encodeValue(d, []);
232
+ return s === '{}' ? '' : s;
233
+ }
234
+
235
+ function emitRaw(prefix, json) {
236
+ writeLine(Buffer.from(prefix + ' ' + json + '\n', 'utf8'));
237
+ }
238
+
239
+ // ---------------------------------------------------------------------------------------------
240
+ // Assertions.
241
+
242
+ const T_ALWAYS = 'always';
243
+ const T_ALWAYS_OR_UNREACHABLE = 'always_or_unreachable';
244
+ const T_SOMETIMES = 'sometimes';
245
+ const T_REACHABLE = 'reachable';
246
+ const T_UNREACHABLE = 'unreachable';
247
+ const T_EVENTUALLY = 'eventually';
248
+
249
+ const catalogList = [];
250
+
251
+ const OPS = {
252
+ '<': (l, r) => l < r,
253
+ '<=': (l, r) => l <= r,
254
+ '==': (l, r) => l == r, // eslint-disable-line eqeqeq -- 1n == 1 must hold
255
+ '!=': (l, r) => l != r, // eslint-disable-line eqeqeq
256
+ '>=': (l, r) => l >= r,
257
+ '>': (l, r) => l > r,
258
+ };
259
+
260
+ // withFields adds fields to the details of an evaluation: to the caller's own object (as the
261
+ // Go SDK writes into the caller's map) or, when there is none, to a new one.
262
+ function withFields(d, fields) {
263
+ if (d instanceof Map) {
264
+ for (const k of Object.keys(fields)) d.set(k, fields[k]);
265
+ return d;
266
+ }
267
+ if (d === undefined || d === null) d = {};
268
+ else if (typeof d !== 'object' || Array.isArray(d)) d = { value: d };
269
+ return Object.assign(d, fields);
270
+ }
271
+
272
+ class Assertion {
273
+ constructor(t, id, msg) {
274
+ this.t = t;
275
+ this.id = String(id);
276
+ this.msg = String(msg);
277
+ this.seen = [false, false]; // outcome already emitted by this process: [false, true]
278
+ }
279
+
280
+ record(ok, d) {
281
+ const i = ok ? 1 : 0;
282
+ if (this.seen[i]) return;
283
+ this.seen[i] = true;
284
+ let det;
285
+ try {
286
+ det = detailsJSON(d);
287
+ } catch (e) {
288
+ if (e instanceof Unencodable || e instanceof RangeError) return; // Go: Marshal fails, nothing is written
289
+ throw e;
290
+ }
291
+ emitRaw('HYDO-ASSERT', '{"t":' + quote(this.t) + ',"id":' + quote(this.id) + ',"ok":' + (ok ? 'true' : 'false') +
292
+ ',"msg":' + quote(this.msg) + (det ? ',"details":' + det : '') + '}');
293
+ }
294
+
295
+ // check evaluates an always / alwaysOrUnreachable / sometimes assertion. For sometimes only
296
+ // a true outcome is recorded. Returns the condition as a boolean, so it can be used inline.
297
+ check(cond, d) {
298
+ const ok = !!cond;
299
+ if (this.t === T_SOMETIMES && !ok) return ok;
300
+ this.record(ok, d);
301
+ return ok;
302
+ }
303
+
304
+ // hit marks a reachable (recorded ok:true) or unreachable (recorded ok:false: reaching it
305
+ // is a violation) location as reached.
306
+ hit(d) {
307
+ this.record(this.t !== T_UNREACHABLE, d);
308
+ }
309
+
310
+ // cmp evaluates `left op right` (op one of "<", "<=", "==", "!=", ">=", ">"; another op
311
+ // evaluates to false) as a check, with left/op/right added to the details. left and right
312
+ // are numbers or bigints.
313
+ cmp(left, op, right, d) {
314
+ const f = Object.prototype.hasOwnProperty.call(OPS, op) ? OPS[op] : null;
315
+ const ok = f ? f(left, right) : false;
316
+ return this.check(ok, withFields(d, { left, op, right }));
317
+ }
318
+ }
319
+
320
+ function declare(t, id, msg) {
321
+ const a = new Assertion(t, id, msg);
322
+ catalogList.push(a);
323
+ return a;
324
+ }
325
+
326
+ // Declare properties at module top level (load time), so the whole catalog is known before
327
+ // the first evaluation and a property that is never evaluated is still reported.
328
+ function always(id, msg) { return declare(T_ALWAYS, id, msg); }
329
+ function alwaysOrUnreachable(id, msg) { return declare(T_ALWAYS_OR_UNREACHABLE, id, msg); }
330
+ function sometimes(id, msg) { return declare(T_SOMETIMES, id, msg); }
331
+ function reachable(id, msg) { return declare(T_REACHABLE, id, msg); }
332
+ function unreachable(id, msg) { return declare(T_UNREACHABLE, id, msg); }
333
+
334
+ // catalog emits one HYDO-ASSERT-DECL line per declared assertion, in declaration order. Call it
335
+ // once, early, from the process that should carry the catalog into the console.
336
+ function catalog() {
337
+ for (const a of catalogList) {
338
+ emitRaw('HYDO-ASSERT-DECL', '{"t":' + quote(a.t) + ',"id":' + quote(a.id) + ',"msg":' + quote(a.msg) + '}');
339
+ }
340
+ }
341
+
342
+ // setupComplete emits the lifecycle line HYDO-SETUP-COMPLETE: the system is provisioned and
343
+ // ready, faults may begin, and the point is a good snapshot/branch base.
344
+ function setupComplete() {
345
+ writeLine(Buffer.from('HYDO-SETUP-COMPLETE\n', 'utf8'));
346
+ }
347
+
348
+ // ---------------------------------------------------------------------------------------------
349
+ // Eventually: bounded liveness. After an anchor, the condition becomes true within a deadline
350
+ // measured on the monotonic clock (deterministic under hydo). One record per episode, with
351
+ // "elapsed_ms" and "within_ms" in the details; each outcome at most once per process.
352
+
353
+ function nowNs() { return process.hrtime.bigint(); }
354
+
355
+ class Watch {
356
+ constructor(l) {
357
+ this.l = l;
358
+ this.start = nowNs();
359
+ this.finished = false;
360
+ }
361
+
362
+ finish(ok, d) {
363
+ if (this.finished) return ok;
364
+ this.finished = true;
365
+ this.l.a.record(ok, withFields(d, {
366
+ elapsed_ms: Number((nowNs() - this.start) / 1000000n),
367
+ within_ms: Math.trunc(this.l.withinMs),
368
+ }));
369
+ return ok;
370
+ }
371
+
372
+ // done records that the condition became true now: ok if within the deadline, else a
373
+ // violation (true, but too late). Returns whether it was in time.
374
+ done(d) { return this.finish(nowNs() - this.start <= this.l.withinNs, d); }
375
+
376
+ // expire records that the deadline passed with the condition still false (a violation).
377
+ expire(d) { this.finish(false, d); }
378
+ }
379
+
380
+ let sleepCell = null;
381
+ function sleepSync(ms) {
382
+ if (sleepCell === null) sleepCell = new Int32Array(new SharedArrayBuffer(4));
383
+ Atomics.wait(sleepCell, 0, 0, Math.max(0, ms));
384
+ }
385
+
386
+ class Liveness {
387
+ constructor(id, msg, withinMs) {
388
+ this.a = declare(T_EVENTUALLY, id, msg);
389
+ this.withinMs = Number(withinMs);
390
+ this.withinNs = BigInt(Math.round(this.withinMs * 1e6));
391
+ }
392
+
393
+ get id() { return this.a.id; }
394
+
395
+ // begin starts an episode now (the anchor).
396
+ begin() { return new Watch(this); }
397
+
398
+ // awaitCond starts an episode now, evaluates cond (which may return a promise) every
399
+ // pollMs until it is true or the deadline has passed, records the outcome and resolves to
400
+ // it. The last evaluation happens at or after the deadline, so a condition that becomes
401
+ // true exactly at the deadline still counts.
402
+ async awaitCond(cond, pollMs, d) {
403
+ const w = this.begin();
404
+ for (;;) {
405
+ if (await cond()) return w.done(d);
406
+ if (nowNs() - w.start > this.withinNs) {
407
+ w.expire(d);
408
+ return false;
409
+ }
410
+ await new Promise((r) => setTimeout(r, pollMs));
411
+ }
412
+ }
413
+
414
+ // awaitCondSync is awaitCond for synchronous code: it blocks the thread between
415
+ // evaluations (cond must return a boolean, not a promise).
416
+ awaitCondSync(cond, pollMs, d) {
417
+ const w = this.begin();
418
+ for (;;) {
419
+ if (cond()) return w.done(d);
420
+ if (nowNs() - w.start > this.withinNs) {
421
+ w.expire(d);
422
+ return false;
423
+ }
424
+ sleepSync(pollMs);
425
+ }
426
+ }
427
+ }
428
+
429
+ // eventually declares a bounded-liveness property: after an anchor, the condition holds within
430
+ // withinMs milliseconds.
431
+ function eventually(id, msg, withinMs) { return new Liveness(id, msg, withinMs); }
432
+
433
+ // ---------------------------------------------------------------------------------------------
434
+ // BUGGIFY: code-level fault points (FoundationDB style), the Go SDK's decisions exactly.
435
+ //
436
+ // Configured by $HYDO_BUGGIFY, or else the file $HYDO_BUGGIFY_FILE (default /tmp/hydo-buggify),
437
+ // holding "<seed-hex>[,<enable-permille>[,<fire-permille>]]" (defaults 250 and 250). Under hydo
438
+ // the guest init writes the schedule's B= token to that file. Read once, at the first
439
+ // evaluation of any point. A point is enabled for the run when
440
+ // splitmix64(seed ^ fnv1a(id)) % 1000 < enable; its k-th evaluation (k = 1, 2, ...) fires when
441
+ // splitmix64(splitmix64(seed ^ fnv1a(id)) + k * 0x9e3779b97f4a7c15) % 1000 < fire.
442
+
443
+ const M64 = (1n << 64n) - 1n;
444
+ const GOLDEN = 0x9e3779b97f4a7c15n;
445
+
446
+ function bgMix(z) { // splitmix64 finalizer
447
+ z = (z + GOLDEN) & M64;
448
+ z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & M64;
449
+ z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & M64;
450
+ return z ^ (z >> 31n);
451
+ }
452
+
453
+ function bgKey(id) { // FNV-1a over the UTF-8 bytes
454
+ let h = 14695981039346656037n;
455
+ for (const b of Buffer.from(id, 'utf8')) {
456
+ h ^= BigInt(b);
457
+ h = (h * 1099511628211n) & M64;
458
+ }
459
+ return h;
460
+ }
461
+
462
+ // Go's strings.TrimSpace (unicode.IsSpace), which differs from String#trim.
463
+ const GO_SPACE = new Set([0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0x85, 0xa0, 0x1680,
464
+ 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a,
465
+ 0x2028, 0x2029, 0x202f, 0x205f, 0x3000]);
466
+ function goTrimSpace(s) {
467
+ let a = 0;
468
+ let b = s.length;
469
+ while (a < b && GO_SPACE.has(s.charCodeAt(a))) a++;
470
+ while (b > a && GO_SPACE.has(s.charCodeAt(b - 1))) b--;
471
+ return s.slice(a, b);
472
+ }
473
+
474
+ // Go's strconv.ParseUint(s, base, 64) for base 16 or 10; null on any error.
475
+ function parseUint64(s, base) {
476
+ if (!(base === 16 ? /^[0-9a-fA-F]+$/ : /^[0-9]+$/).test(s)) return null;
477
+ const v = BigInt((base === 16 ? '0x' : '') + s);
478
+ return v > M64 ? null : v;
479
+ }
480
+
481
+ const points = [];
482
+ let bgLoaded = false;
483
+ let bgOn = false;
484
+ let bgSeed = 0n;
485
+ let bgEnable = 250n;
486
+ let bgFire = 250n;
487
+
488
+ class Point {
489
+ constructor(id, msg) {
490
+ this.id = String(id);
491
+ this.a = declare(T_SOMETIMES, 'buggify.' + this.id, 'fault point fired: ' + String(msg));
492
+ this.hits = 0n;
493
+ this.key = bgKey(this.id);
494
+ }
495
+
496
+ enabled() { return bgMix(bgSeed ^ this.key) % 1000n < bgEnable; }
497
+
498
+ // fire reports whether the point misbehaves on this evaluation. Always false when BUGGIFY is
499
+ // not configured; then it has no other effect either. When it fires, {"hit": k} is added
500
+ // to the details (the caller's object, as the Go SDK adds it to the caller's map) and the
501
+ // point's sometimes property is recorded.
502
+ fire(d) {
503
+ if (!bgLoaded) bgLoad();
504
+ if (!bgOn || !this.enabled()) return false;
505
+ this.hits = (this.hits + 1n) & M64;
506
+ const k = this.hits;
507
+ const f = bgMix((bgMix(bgSeed ^ this.key) + k * GOLDEN) & M64) % 1000n < bgFire;
508
+ if (f) {
509
+ this.a.record(true, withFields(d, { hit: k }));
510
+ }
511
+ return f;
512
+ }
513
+ }
514
+
515
+ function bgLoad() {
516
+ bgLoaded = true;
517
+ let cfg = process.env.HYDO_BUGGIFY || '';
518
+ if (cfg === '') {
519
+ const f = process.env.HYDO_BUGGIFY_FILE || '/tmp/hydo-buggify';
520
+ try {
521
+ cfg = fs.readFileSync(f, 'utf8');
522
+ } catch (e) {
523
+ cfg = '';
524
+ }
525
+ }
526
+ const parts = goTrimSpace(cfg).split(',');
527
+ const seed = parseUint64(parts[0], 16);
528
+ if (seed === null) return; // no configuration: every point stays off
529
+ bgOn = true;
530
+ bgSeed = seed;
531
+ if (parts.length > 1) {
532
+ const v = parseUint64(parts[1], 10);
533
+ if (v !== null) bgEnable = v;
534
+ }
535
+ if (parts.length > 2) {
536
+ const v = parseUint64(parts[2], 10);
537
+ if (v !== null) bgFire = v;
538
+ }
539
+ const enabled = points.filter((p) => p.enabled()).map((p) => p.id);
540
+ emitRaw('HYDO-BUGGIFY', '{"seed":' + quote(bgSeed.toString(16)) + ',"enable_pm":' + bgEnable.toString() +
541
+ ',"fire_pm":' + bgFire.toString() + ',"enabled":' + encodeArray(enabled, []) + '}');
542
+ }
543
+
544
+ // buggify declares a fault point.
545
+ function buggify(id, msg) {
546
+ const p = new Point(id, msg);
547
+ points.push(p);
548
+ return p;
549
+ }
550
+
551
+ // For tests: forget the sink and the BUGGIFY configuration (declarations are kept).
552
+ function _reset() {
553
+ if (sinkState === SINK_FD && sinkFd > 2) {
554
+ try { fs.closeSync(sinkFd); } catch (e) { /* ignore */ }
555
+ }
556
+ sinkState = SINK_UNSET;
557
+ sinkFd = -1;
558
+ bgLoaded = false;
559
+ bgOn = false;
560
+ bgSeed = 0n;
561
+ bgEnable = 250n;
562
+ bgFire = 250n;
563
+ for (const p of points) p.hits = 0n;
564
+ for (const a of catalogList) a.seen = [false, false];
565
+ }
566
+
567
+ module.exports = {
568
+ always,
569
+ alwaysOrUnreachable,
570
+ sometimes,
571
+ reachable,
572
+ unreachable,
573
+ eventually,
574
+ buggify,
575
+ catalog,
576
+ setupComplete,
577
+ Assertion,
578
+ Liveness,
579
+ Watch,
580
+ Point,
581
+ // For the SDK's own tests only (not part of the API): the Go encoding of a value, and a
582
+ // reset of the process state.
583
+ _toJSON: toJSON,
584
+ _reset,
585
+ };
package/index.mjs ADDED
@@ -0,0 +1,20 @@
1
+ // ESM entry of hydo-assert: re-exports the CommonJS module, so a program that loads the SDK
2
+ // both with require() and with import uses ONE state (one catalog, one dedup table, one sink).
3
+ import m from './index.js';
4
+
5
+ export const {
6
+ always,
7
+ alwaysOrUnreachable,
8
+ sometimes,
9
+ reachable,
10
+ unreachable,
11
+ eventually,
12
+ buggify,
13
+ catalog,
14
+ setupComplete,
15
+ Assertion,
16
+ Liveness,
17
+ Watch,
18
+ Point,
19
+ } = m;
20
+ export default m;
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "hydo-assert",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Assertion SDK for Node.js programs tested under hydo, a deterministic hypervisor: always/sometimes/reachable/unreachable/eventually properties, BUGGIFY fault points and operation histories",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/kakoc/hydo.git",
9
+ "directory": "sdk/js"
10
+ },
11
+ "homepage": "https://github.com/kakoc/hydo/tree/main/sdk/js#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/kakoc/hydo/issues"
14
+ },
15
+ "keywords": [
16
+ "testing",
17
+ "assertions",
18
+ "deterministic",
19
+ "fault-injection",
20
+ "simulation",
21
+ "hydo"
22
+ ],
23
+ "main": "./index.js",
24
+ "types": "./index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "import": {
28
+ "types": "./index.d.mts",
29
+ "default": "./index.mjs"
30
+ },
31
+ "require": {
32
+ "types": "./index.d.ts",
33
+ "default": "./index.js"
34
+ }
35
+ },
36
+ "./history": {
37
+ "import": {
38
+ "types": "./history.d.mts",
39
+ "default": "./history.mjs"
40
+ },
41
+ "require": {
42
+ "types": "./history.d.ts",
43
+ "default": "./history.js"
44
+ }
45
+ },
46
+ "./package.json": "./package.json"
47
+ },
48
+ "files": [
49
+ "index.js",
50
+ "index.mjs",
51
+ "index.d.ts",
52
+ "index.d.mts",
53
+ "history.js",
54
+ "history.mjs",
55
+ "history.d.ts",
56
+ "history.d.mts",
57
+ "README.md"
58
+ ],
59
+ "engines": {
60
+ "node": ">=16"
61
+ },
62
+ "scripts": {
63
+ "test": "node --test test/unit.test.js test/history.test.js"
64
+ }
65
+ }