@plimsollmark/client 0.27.2 → 0.29.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/dist/client.js CHANGED
@@ -6,22 +6,27 @@
6
6
  // records so a call it did not make is caught.
7
7
  import { createHash, createHmac, randomBytes } from "node:crypto";
8
8
  import { isIP } from "node:net";
9
- import { checkRecord, checkUnanswered, requestDigest, sessionFingerprint, softwareRuleAllows, } from "./record.js";
10
- import { LANGUAGES, OUTCOME_NAMES, TIERS } from "./tables.gen.js";
11
- import { errorFromWire, NOT_DISPATCHED_HEADER, PlimsollError, REQUEST_ID_HEADER, sessionEndFromWire, unboundSuccess } from "./errors.js";
12
- import { wireBytes } from "./wire.js";
13
- /** The wire protocol number this client speaks (protocol.Number in Go). */
14
- export const PROTOCOL = 5;
9
+ import { checkLostAnswer, checkRecord, checkUnanswered, recordDigest, recordFromWire, requestDigest, sessionFingerprint, softwareRuleAllows, softwareRuleId, statesOnlyProblem, } from "./record.js";
10
+ import { LANGUAGES, MAX_RESPONSE_BYTES, MAX_SOFTWARE_IDENTITIES, MAX_SOFTWARE_IDENTITY_BYTES, NOT_DISPATCHED_HEADER, OUTCOME_NAMES, CHECKPOINT_VERSION, PROTOCOL, RECORD_VERSION, RECOVERING_TEXT, REQUEST_ID_HEADER, SOFTWARE_IDENTITY_PATTERN, TIERS, } from "./tables.gen.js";
11
+ import { checkpointProblem, validDaemonName } from "./checkpoint.js";
12
+ import { errorFromWire, HeadMismatchError, PlimsollError, RecoveringError, sessionEndFromWire, StaleOwnerError, unboundSuccess, } from "./errors.js";
13
+ import { INT64, trailing, UINT32, UINT64, wholeInt, wireBytes } from "./wire.js";
14
+ // PROTOCOL, the wire protocol number this client speaks, and MAX_RESPONSE_BYTES, above the
15
+ // largest legitimate project response so a misbehaving daemon cannot make the client buffer
16
+ // without bound, are generated from the Go protocol and client packages (tables.gen.ts).
17
+ export { PROTOCOL };
15
18
  const SERVICE = "plimsoll.v1.SandboxService";
16
- // Above the largest legitimate project response, so a misbehaving daemon cannot
17
- // make the client buffer without bound (the Go client's maxResponseBytes).
18
- const MAX_RESPONSE_BYTES = 32 << 20;
19
- /** Whether a tier the daemon reported meets a floor. An unknown tier meets nothing. */
19
+ const SOFTWARE_IDENTITY_FORM = new RegExp(SOFTWARE_IDENTITY_PATTERN);
20
+ /**
21
+ * Whether a tier the daemon reported is at least `floor`, as the Go client's
22
+ * IsolationClass.Meets and the Python client's meets. A tier or floor this client does
23
+ * not know (including an empty one) meets nothing; every known tier meets "none". A
24
+ * request cannot state "none" as its floor (minimumIsolation), which is a separate rule.
25
+ */
20
26
  export function meets(actual, floor) {
21
27
  const a = TIERS.indexOf(actual);
22
28
  const f = TIERS.indexOf(floor);
23
- // A floor is process, container, kernel or vm; anything else is met by nothing.
24
- return a >= 0 && f >= 1 && a >= f;
29
+ return a >= 0 && f >= 0 && a >= f;
25
30
  }
26
31
  const DEFAULT_REQUEST_TIMEOUT_MS = 6 * 60_000;
27
32
  /**
@@ -60,7 +65,8 @@ function validateBaseUrl(raw, insecureHttp) {
60
65
  if (u.protocol === "http:" && !loopback && !insecureHttp) {
61
66
  throw new PlimsollError("invalid_argument", "plimsoll: cleartext HTTP to a non-loopback daemon requires insecureHttp");
62
67
  }
63
- return u.toString().replace(/\/+$/, "");
68
+ const s = u.toString();
69
+ return s.slice(0, s.length - trailing(s, "/")); // not /\/+$/, which is quadratic in a run of "/" (hunt-security-35)
64
70
  }
65
71
  function timeoutMs(ms) {
66
72
  if (ms === undefined || !(ms > 0))
@@ -76,11 +82,11 @@ function validateRule(rule) {
76
82
  if (!rule)
77
83
  return undefined;
78
84
  const ids = rule.identities;
79
- const ok = (rule.mode === "exact" ? ids.length === 1 : rule.mode === "approved" && ids.length >= 1 && ids.length <= 32) &&
85
+ const ok = (rule.mode === "exact" ? ids.length === 1 : rule.mode === "approved" && ids.length >= 1 && ids.length <= MAX_SOFTWARE_IDENTITIES) &&
80
86
  new Set(ids).size === ids.length &&
81
- ids.every((id) => id.length > 0 && id.length <= 256 && /^[A-Za-z0-9._:/@+-]+$/.test(id));
87
+ ids.every((id) => id.length > 0 && id.length <= MAX_SOFTWARE_IDENTITY_BYTES && SOFTWARE_IDENTITY_FORM.test(id));
82
88
  if (!ok) {
83
- throw new PlimsollError("invalid_argument", "plimsoll: software rule needs exact with one identity or approved with 1 to 32 identities", {
89
+ throw new PlimsollError("invalid_argument", `plimsoll: software rule needs exact with one identity or approved with 1 to ${MAX_SOFTWARE_IDENTITIES} identities`, {
84
90
  notDispatched: "request",
85
91
  });
86
92
  }
@@ -120,6 +126,7 @@ function evidence(resp, record) {
120
126
  return {
121
127
  sandbox: resp.sandbox ?? "",
122
128
  isolation: resp.isolation ?? "",
129
+ isolationQualification: resp.isolationQualification ?? "",
123
130
  softwareIdentity: resp.softwareIdentity ?? "",
124
131
  environment: resp.environment ?? "",
125
132
  instance: resp.instance ?? "",
@@ -250,6 +257,7 @@ export class PlimsollClient {
250
257
  requestTimeoutMs;
251
258
  /** @internal */ jsGrant;
252
259
  /** @internal */ projectGrant;
260
+ /** @internal */ daemonName;
253
261
  constructor(opts) {
254
262
  this.base = validateBaseUrl(opts.baseUrl, opts.insecureHttp ?? false);
255
263
  this.token = opts.token;
@@ -262,6 +270,10 @@ export class PlimsollClient {
262
270
  this.requestTimeoutMs = rt;
263
271
  this.jsGrant = opts.javascriptGrantProfile ?? "";
264
272
  this.projectGrant = opts.projectGrantProfile ?? "";
273
+ if (opts.daemonName !== undefined && !validDaemonName(opts.daemonName)) {
274
+ throw new PlimsollError("invalid_argument", "plimsoll: daemonName is 1 to 64 of [A-Za-z0-9._-], never a URL");
275
+ }
276
+ this.daemonName = opts.daemonName;
265
277
  }
266
278
  /** @internal One unary Connect call with the JSON codec. */
267
279
  async call(method, body, signal) {
@@ -374,12 +386,13 @@ export class PlimsollClient {
374
386
  }
375
387
  /** Runs a JavaScript snippet in a fresh sandbox. */
376
388
  async runJavaScript(code, opts = {}) {
377
- const resp = await this.exchange("Run", this.envelope(opts, validateRule(opts.software)), { javascript: { code, grantProfile: this.jsGrant || undefined } }, opts);
389
+ const profile = grantFor(opts, this.jsGrant);
390
+ const resp = await this.exchange("Run", this.envelope(opts, validateRule(opts.software)), { javascript: { code, grantProfile: profile || undefined } }, opts);
378
391
  return decoded(() => finish(resp.run, resp.record, javascriptResult, "javascript", opts.minimumIsolation));
379
392
  }
380
393
  /** Writes a multi-file project into a fresh sandbox and runs its steps in order. */
381
394
  async runProject(req, opts = {}) {
382
- const resp = await this.exchange("Run", this.envelope(opts, validateRule(opts.software)), projectPayload(req, this.projectGrant), opts);
395
+ const resp = await this.exchange("Run", this.envelope(opts, validateRule(opts.software)), projectPayload(req, grantFor(opts, this.projectGrant)), opts);
383
396
  return decoded(() => finish(resp.run, resp.record, projectResult, "project", opts.minimumIsolation));
384
397
  }
385
398
  /**
@@ -431,6 +444,9 @@ export class PlimsollClient {
431
444
  if (opts.warmOnly !== undefined && typeof opts.warmOnly !== "boolean") {
432
445
  throw new PlimsollError("invalid_argument", "plimsoll: warmOnly must be a boolean", { notDispatched: "request" });
433
446
  }
447
+ if (opts.keepNoAnswer !== undefined && typeof opts.keepNoAnswer !== "boolean") {
448
+ throw new PlimsollError("invalid_argument", "plimsoll: keepNoAnswer must be a boolean", { notDispatched: "request" });
449
+ }
434
450
  const m = await this.call("OpenSession", {
435
451
  protocol: PROTOCOL,
436
452
  minimumIsolation: opts.minimumIsolation,
@@ -441,13 +457,30 @@ export class PlimsollClient {
441
457
  languages: opts.languages?.length ? [...new Set(opts.languages)] : undefined,
442
458
  owner: opts.owner === undefined ? undefined : ownerDigest(this.token, opts.owner),
443
459
  warmOnly: opts.warmOnly || undefined,
460
+ keepNoAnswer: opts.keepNoAnswer || undefined,
444
461
  }, opts.signal);
445
462
  const s = decoded(() => new Session(this, m, rule, opts.minimumIsolation));
463
+ if (m.generation !== "1" && m.generation !== 1) {
464
+ // The session exists on the daemon either way, and nothing else holds its ID.
465
+ await s.close().catch(() => undefined);
466
+ throw new PlimsollError("data_loss", "plimsoll: the daemon's answer to the open states an ownership generation other than 1; the session was closed");
467
+ }
468
+ if (wholeInt(m.expiresUnixMs, INT64) === undefined || wholeInt(m.idleTimeoutMs, UINT32) === undefined) {
469
+ // A checkpoint states both, and an attach answer must repeat them exactly.
470
+ await s.close().catch(() => undefined);
471
+ throw new PlimsollError("data_loss", "plimsoll: the daemon's answer to the open states an expiry or idle timeout that is not one whole decimal; the session was closed");
472
+ }
446
473
  if (decoded(() => s.fingerprint !== sessionFingerprint(m.sessionId ?? ""))) {
447
474
  // The session exists on the daemon either way, and nothing else holds its ID.
448
475
  await s.close().catch(() => undefined);
449
476
  throw new PlimsollError("data_loss", "plimsoll: the daemon's session fingerprint does not match its session ID; the session was closed");
450
477
  }
478
+ if ((m.minimumIsolation ?? "") !== (opts.minimumIsolation ?? "") || decoded(() => wireRuleId(m.softwareRule)) !== softwareRuleId(rule)) {
479
+ // The floor and rule the daemon keeps for the session are what an attach answer
480
+ // repeats and a checkpoint states, so they must be the ones sent.
481
+ await s.close().catch(() => undefined);
482
+ throw new PlimsollError("data_loss", "plimsoll: the daemon's answer to the open states another floor or software rule than the open sent; the session was closed");
483
+ }
451
484
  if (opts.minimumIsolation && !meets(s.isolation, opts.minimumIsolation)) {
452
485
  await s.close().catch(() => undefined);
453
486
  throw new PlimsollError("data_loss", `plimsoll: the session opened at ${s.isolation}, below the requested ${opts.minimumIsolation}`);
@@ -458,6 +491,118 @@ export class PlimsollClient {
458
491
  }
459
492
  return s;
460
493
  }
494
+ /**
495
+ * Takes over the session `cp` names and carries its chain on from cp's head (Go:
496
+ * Remote.AttachSession): the daemon raises the session's ownership generation by one, and
497
+ * every call or close a worker holding an older one sends is refused before it runs
498
+ * (StaleOwnerError).
499
+ *
500
+ * Refused here, with nothing sent, when cp does not validate, when it names another daemon
501
+ * than this client's daemonName, or when the client has none. The daemon refuses an
502
+ * unknown, ended or another caller's session as not found, a stale generation as
503
+ * StaleOwnerError and a checkpoint that is not its head (a call ran after cp was saved)
504
+ * as CheckpointMismatchError; open development mode refuses every attach.
505
+ *
506
+ * The answer must repeat cp exactly, else data_loss, and the session is not closed: a bad
507
+ * answer gives this client no right to destroy a session another worker may be using. A
508
+ * transport failure or an abort after sending is thrown as it is and never retried: the
509
+ * daemon may have raised the generation, so cp may already be stale.
510
+ *
511
+ * opts.lostRequestSha256 names the call this application believes ran after cp with no
512
+ * answer reaching it (session.lostRequestSha256 gives it for a call of this process).
513
+ * With it, the daemon takes the session over from a checkpoint exactly one call behind
514
+ * its head when its last record is that call, following cp (the explained gap), and
515
+ * returns the record, and the call's answer when the daemon still keeps it. The record
516
+ * must check on its own, be the call named, at cp's next place, stating the evidence the
517
+ * session stated at open, and be the new head; the answer must carry that same record
518
+ * and a result whose digest is the record's. A lost call's record the attach did not
519
+ * name, and a lost answer with no lost record, are refused as data_loss.
520
+ *
521
+ * A session attached across a lost call, or from a checkpoint saved while recovering, is
522
+ * recovering: session.lostCall says what it knows of the lost call, and every call is
523
+ * refused before it is sent (RecoveringError) until session.resolveLostCall().
524
+ */
525
+ async attachSession(cp, opts = {}) {
526
+ const problem = checkpointProblem(cp);
527
+ if (problem)
528
+ throw new PlimsollError("invalid_argument", `plimsoll: invalid session checkpoint: ${problem}`, { notDispatched: "request" });
529
+ const lost = opts.lostRequestSha256 ?? "";
530
+ if (lost !== "" && !/^[0-9a-f]{64}$/.test(lost)) {
531
+ throw new PlimsollError("invalid_argument", "plimsoll: the lost call's request digest is not 64 lowercase hex digits", { notDispatched: "request" });
532
+ }
533
+ if (this.daemonName === undefined || cp.daemon !== this.daemonName) {
534
+ throw new PlimsollError("invalid_argument", "plimsoll: the checkpoint names another daemon than this client's daemonName", { notDispatched: "request" });
535
+ }
536
+ const body = {
537
+ protocol: PROTOCOL,
538
+ session: cp.session,
539
+ checkpoint: { generation: cp.generation.toString(), calls: cp.calls.toString(), lastRecordSha256: cp.lastRecordSha256 },
540
+ traceId: opts.traceId,
541
+ lostRequestSha256: lost || undefined,
542
+ };
543
+ const m = await this.call("AttachSession", body, opts.signal);
544
+ return decoded(() => this.attached(cp, m, lost));
545
+ }
546
+ // The attached session, once the answer repeats the checkpoint exactly, or carries the
547
+ // record of the call lost names at the checkpoint's next place and a head after it (and,
548
+ // beside that record, the call's answer, when the daemon kept it).
549
+ attached(cp, m, lost) {
550
+ const info = m.sessionInfo;
551
+ const head = m.checkpoint;
552
+ let problem;
553
+ let recovering = cp.recoveringRequestSha256 ? { requestSha256: cp.recoveringRequestSha256 } : undefined;
554
+ let lostCall;
555
+ if (m.lostAnswer !== undefined && m.lostAnswer !== null && !m.lostRecord) {
556
+ problem = "carries a lost call's answer without the lost call's record";
557
+ }
558
+ else if (m.lostRecord) {
559
+ const checked = lostRecord(cp, lost, m.lostRecord);
560
+ if ("problem" in checked)
561
+ problem = checked.problem;
562
+ else {
563
+ lostCall = checked.record;
564
+ recovering = { requestSha256: lostCall.requestSha256, record: lostCall };
565
+ if (m.lostAnswer !== undefined && m.lostAnswer !== null) {
566
+ const answer = checkLostAnswer(m.lostAnswer, lostCall);
567
+ if ("problem" in answer)
568
+ problem = `carries a lost call's answer that does not check against its record (${answer.problem})`;
569
+ else
570
+ recovering.answer = lostAnswerResult(m.lostAnswer, lostCall, answer.kind);
571
+ }
572
+ }
573
+ }
574
+ const calls = lostCall ? lostCall.sequence : cp.calls;
575
+ const last = lostCall ? lostCall.sha256 : cp.lastRecordSha256;
576
+ if (problem) {
577
+ // the lost call's record or answer does not check
578
+ }
579
+ else if (!info || !head)
580
+ problem = "lacks the session or its checkpoint";
581
+ else if ((info.session ?? "") !== cp.session || sessionFingerprint(info.sessionId ?? "") !== cp.session) {
582
+ problem = "names another session, or a session ID whose SHA-256 is not the fingerprint";
583
+ }
584
+ else if (wholeInt(info.generation, UINT64) !== cp.generation + 1n || wholeInt(head.generation, UINT64) !== cp.generation + 1n) {
585
+ problem = "states a generation other than one past the checkpoint's";
586
+ }
587
+ else if (wholeInt(head.calls, UINT64) !== calls || (head.lastRecordSha256 ?? "") !== last) {
588
+ problem = "states another chain head than the checkpoint's (or, across an explained gap, than the lost call's)";
589
+ }
590
+ else if ((info.sandbox ?? "") !== cp.provider || (info.isolation ?? "") !== cp.isolation ||
591
+ (info.isolationQualification ?? "") !== cp.isolationQualification || (info.softwareIdentity ?? "") !== cp.softwareIdentity) {
592
+ problem = "states another provider, tier, qualification or software than the session stated at open";
593
+ }
594
+ else if ((info.minimumIsolation ?? "") !== cp.openFloor || wireRuleId(info.softwareRule) !== cp.openRule) {
595
+ problem = "states another floor or software rule than the session was opened with";
596
+ }
597
+ else if (wholeInt(info.expiresUnixMs, INT64) !== BigInt(cp.expiresUnixMs) || wholeInt(info.idleTimeoutMs, UINT32) !== BigInt(cp.idleTimeoutMs)) {
598
+ problem = "states another lifetime or idle timeout than the session's";
599
+ }
600
+ if (problem || !info)
601
+ throw new PlimsollError("data_loss", `plimsoll: the daemon's answer to the attach ${problem}; the session was left as it is`);
602
+ const rule = cp.openRule && info.softwareRule ? { mode: info.softwareRule.mode, identities: [...info.softwareRule.identities] } : undefined;
603
+ const floor = cp.openFloor === "" ? undefined : cp.openFloor;
604
+ return new Session(this, info, rule, floor, { generation: cp.generation + 1n, calls, last, recovering });
605
+ }
461
606
  /** @internal */
462
607
  envelope(opts, rule) {
463
608
  return {
@@ -484,6 +629,63 @@ export class PlimsollClient {
484
629
  return { run: resp, record: r };
485
630
  }
486
631
  }
632
+ // The record an attach answer returns for the call the attach named (lost), once it is a
633
+ // live record that checks on its own, of the session cp names, at cp's next place in the
634
+ // chain, carrying the named request digest and the evidence the session stated at open.
635
+ // Exported for the shared test cases (internal/clientcases); not part of the package's API.
636
+ /** @internal */
637
+ export function lostRecord(cp, lost, m) {
638
+ if (lost === "")
639
+ return { problem: "carries a lost call's record, but the attach named no lost call" };
640
+ const r = recordFromWire(m);
641
+ if (r.version !== RECORD_VERSION)
642
+ return { problem: `carries a lost call's record of version ${r.version}, not the live version ${RECORD_VERSION}` };
643
+ const states = statesOnlyProblem(r);
644
+ if (states)
645
+ return { problem: `carries a lost call's record that does not check (${states})` };
646
+ if (recordDigest(r) !== r.sha256)
647
+ return { problem: "carries a lost call's record whose own digest does not match" };
648
+ if (r.session !== cp.session || r.sequence !== cp.calls + 1n || r.previousSha256 !== cp.lastRecordSha256) {
649
+ return { problem: "carries a lost call's record that is not the checkpoint's next call" };
650
+ }
651
+ if (r.requestSha256 !== lost)
652
+ return { problem: "carries the record of another call than the one the attach named" };
653
+ if (r.provider !== cp.provider || r.isolation !== cp.isolation || r.softwareIdentity !== cp.softwareIdentity || r.isolationQualification !== cp.isolationQualification) {
654
+ return { problem: "carries a lost call's record stating other evidence than the session stated at open" };
655
+ }
656
+ return { record: r };
657
+ }
658
+ // A lost call's checked answer as the result its kind maps to, as the call would have
659
+ // returned it.
660
+ function lostAnswerResult(resp, record, kind) {
661
+ if (kind === "javascript")
662
+ return { kind, result: javascriptResult(resp, record) };
663
+ if (kind === "project")
664
+ return { kind, result: projectResult(resp, record) };
665
+ return { kind, result: cellResult(resp, record) };
666
+ }
667
+ // The ID of a software rule as the daemon sent it, "" for none; a rule this client would
668
+ // not send (an unknown mode, a malformed identity) has an ID no checkpoint states.
669
+ function wireRuleId(r) {
670
+ if (!r || (!r.mode && !(r.identities ?? []).length))
671
+ return "";
672
+ try {
673
+ return softwareRuleId(validateRule({ mode: r.mode, identities: [...(r.identities ?? [])] }));
674
+ }
675
+ catch {
676
+ return "invalid";
677
+ }
678
+ }
679
+ // The grant profile a run selects: the call's own when it names one ("" for none), else
680
+ // the client's.
681
+ function grantFor(opts, client) {
682
+ if (opts.grantProfile === undefined)
683
+ return client;
684
+ if (typeof opts.grantProfile !== "string") {
685
+ throw new PlimsollError("invalid_argument", "plimsoll: grantProfile must be a string", { notDispatched: "request" });
686
+ }
687
+ return opts.grantProfile;
688
+ }
487
689
  /** @internal */
488
690
  export function projectPayload(req, grantProfile) {
489
691
  return {
@@ -521,6 +723,8 @@ export class Session {
521
723
  fingerprint;
522
724
  /** The tier the daemon measured when the session opened. */
523
725
  isolation;
726
+ /** The sentence the provider states beside that tier, "" when it states none. Every call's record states it too. */
727
+ isolationQualification;
524
728
  sandbox;
525
729
  /** The selected software the daemon stated at open. */
526
730
  softwareIdentity;
@@ -528,7 +732,9 @@ export class Session {
528
732
  idleTimeoutMs;
529
733
  // The session ID is a capability: it goes to the daemon and nowhere else.
530
734
  #id;
735
+ #generation;
531
736
  #client;
737
+ // The rule and floor given at open, which a checkpoint states.
532
738
  #rule;
533
739
  // The floor given at open: every call carries it unless the call asks for more.
534
740
  #floor;
@@ -539,27 +745,120 @@ export class Session {
539
745
  // have run it and moved its chain on, so every later call would run and then fail
540
746
  // the chain check. They are refused here instead, before anything is sent.
541
747
  #unknown;
748
+ // Set once the daemon refused a call or close because another worker attached the
749
+ // session: this worker must not use it again.
750
+ #stale;
751
+ // Set once the daemon refused a call because the head it carried is not the session's
752
+ // (HeadMismatchError): the chain this client tracks no longer follows the daemon's.
753
+ #diverged;
754
+ // Set once the daemon answered this client's close.
755
+ #closed = false;
756
+ // The lost call this session is recovering from, set by an attach across an explained
757
+ // gap or from a checkpoint saved while recovering: while it is set every call is refused
758
+ // before anything is sent, until resolveLostCall(). And the request digest of the call
759
+ // after which this session stopped with no answer it could check.
760
+ #recovering;
761
+ #lostRequest = "";
542
762
  #queue = Promise.resolve();
543
763
  #closing;
544
764
  /** @internal */
545
- constructor(client, m, rule, floor) {
765
+ constructor(client, m, rule, floor, attached) {
546
766
  this.#client = client;
547
767
  this.#id = m.sessionId ?? "";
768
+ // Every daemon opens a session at generation 1; openSession refuses an answer that
769
+ // says otherwise, after closing the session with this one. An attached session
770
+ // carries on from the checkpoint it was attached with.
771
+ this.#generation = attached?.generation ?? 1n;
772
+ if (attached) {
773
+ this.#calls = attached.calls;
774
+ this.#last = attached.last;
775
+ this.#recovering = attached.recovering;
776
+ }
548
777
  this.#rule = rule;
549
778
  this.#floor = floor;
550
779
  this.fingerprint = m.session ?? "";
551
780
  this.isolation = m.isolation ?? "";
781
+ this.isolationQualification = m.isolationQualification ?? "";
552
782
  this.sandbox = m.sandbox ?? "";
553
783
  this.softwareIdentity = m.softwareIdentity ?? "";
554
- this.expiresAtMs = num(m.expiresUnixMs);
555
- this.idleTimeoutMs = m.idleTimeoutMs ?? 0;
784
+ // openSession refuses an answer whose expiry or idle timeout is not one whole decimal,
785
+ // after closing the session with this one; attached() compares both with the checkpoint.
786
+ this.expiresAtMs = Number(wholeInt(m.expiresUnixMs, INT64) ?? 0n);
787
+ this.idleTimeoutMs = Number(wholeInt(m.idleTimeoutMs, UINT32) ?? 0n);
556
788
  }
557
789
  /**
558
790
  * Why this client sends nothing more on the session, once a call ended without an
559
791
  * answer it could check (the call may have run); undefined while it is usable.
560
792
  */
561
793
  get stopped() {
562
- return this.#unknown;
794
+ return this.#stale ?? this.#unknown ?? this.#diverged;
795
+ }
796
+ /**
797
+ * The request digest of the call after which this session stopped with no answer it could
798
+ * check, or "": the call that may have run, for another worker's attachSession to name
799
+ * (lostRequestSha256) together with a checkpoint saved before it.
800
+ */
801
+ get lostRequestSha256() {
802
+ return this.#lostRequest;
803
+ }
804
+ /**
805
+ * The call this session is recovering from, or undefined when it is not recovering: after
806
+ * an attach across an explained gap (attachSession with lostRequestSha256), or from a
807
+ * checkpoint saved while recovering, until resolveLostCall(). While it is defined every
808
+ * call is refused before it is sent (RecoveringError). Its record says whether the daemon
809
+ * answered the call, and its answer, when the daemon kept it, is that call's result.
810
+ */
811
+ get lostCall() {
812
+ const lc = this.#recovering;
813
+ return lc === undefined ? undefined : { ...lc };
814
+ }
815
+ /**
816
+ * Ends the recovering state: the application has read the lost call (lostCall) and
817
+ * handled its outcome, or accepts it as unknown, and the session's calls are sent again.
818
+ * Taking the session over, or copying its head, does not resolve it. On a session that is
819
+ * not recovering it does nothing (Go: Session.ResolveLostCall).
820
+ */
821
+ resolveLostCall() {
822
+ this.#recovering = undefined;
823
+ }
824
+ /**
825
+ * The session's checkpoint (Go: Session.Checkpoint), for the application to save where
826
+ * only it can write, so another process can attachSession. It waits for a call in
827
+ * flight, so the head it states follows that call. Refused when the client has no
828
+ * daemonName and when the session is stopped, closed or ended. A session recovering from
829
+ * a lost call saves that state (recoveringRequestSha256), so the worker that attaches
830
+ * from it is recovering too.
831
+ */
832
+ checkpoint() {
833
+ return this.#serial(async () => {
834
+ const refuse = (why) => new PlimsollError("failed_precondition", `plimsoll: this session cannot be checkpointed: ${why}`, { notDispatched: "request" });
835
+ const daemon = this.#client.daemonName;
836
+ if (daemon === undefined)
837
+ throw refuse("the client has no daemonName");
838
+ if (this.stopped !== undefined)
839
+ throw refuse(`it is stopped (${this.stopped})`);
840
+ if (this.#closed)
841
+ throw refuse("it is closed");
842
+ if (this.#end !== undefined && this.#end.reason !== "open")
843
+ throw refuse(`it ended (${this.#end.reason})`);
844
+ return {
845
+ version: CHECKPOINT_VERSION,
846
+ daemon,
847
+ session: this.fingerprint,
848
+ generation: this.#generation,
849
+ calls: this.#calls,
850
+ lastRecordSha256: this.#last,
851
+ provider: this.sandbox,
852
+ isolation: this.isolation,
853
+ isolationQualification: this.isolationQualification,
854
+ softwareIdentity: this.softwareIdentity,
855
+ openFloor: this.#floor ?? "",
856
+ openRule: softwareRuleId(this.#rule),
857
+ expiresUnixMs: this.expiresAtMs,
858
+ idleTimeoutMs: this.idleTimeoutMs,
859
+ recoveringRequestSha256: this.#recovering?.requestSha256 ?? "",
860
+ };
861
+ });
563
862
  }
564
863
  /** The session's end once a response reported it, else undefined. */
565
864
  get ended() {
@@ -611,9 +910,21 @@ export class Session {
611
910
  #call(payload, opts) {
612
911
  const rule = mergeRules(this.#rule, validateRule(opts.software));
613
912
  return this.#serial(async () => {
913
+ if (this.#stale !== undefined) {
914
+ throw new StaleOwnerError(`plimsoll: ${this.#stale}; this worker sends nothing more on the session`, { notDispatched: "request" });
915
+ }
614
916
  if (this.#unknown !== undefined) {
615
917
  throw new PlimsollError("failed_precondition", `plimsoll: an earlier call of this session ended without an answer this client could check (${this.#unknown}); it may have run, so this client sends nothing more on the session: open a new one`, { notDispatched: "request" });
616
918
  }
919
+ if (this.#diverged !== undefined) {
920
+ throw new PlimsollError("failed_precondition", `plimsoll: ${this.#diverged}; this client sends nothing more on the session: open a new one`, {
921
+ notDispatched: "request",
922
+ });
923
+ }
924
+ // A session recovering from a lost call sends nothing until the application has
925
+ // resolved it: every call is refused here, whatever it is.
926
+ if (this.#recovering !== undefined)
927
+ throw new RecoveringError(`plimsoll: ${RECOVERING_TEXT}; nothing was sent`);
617
928
  const env = this.#client.envelope(opts, rule);
618
929
  // Before the digest, which cannot encode such text either.
619
930
  refuseIllFormed({ ...env, ...payload }, "the request");
@@ -622,6 +933,16 @@ export class Session {
622
933
  return await this.#exchange(payload, opts, rule, env, digest);
623
934
  }
624
935
  catch (e) {
936
+ if (e instanceof StaleOwnerError)
937
+ this.#stale = "another worker attached the session";
938
+ if (e instanceof HeadMismatchError) {
939
+ // The daemon's own word that its chain holds a call this client did not send (or
940
+ // counts one it did not see): this client's chain no longer follows the daemon's,
941
+ // so it sends nothing more. Nothing ran, so no call is lost (lostRequestSha256).
942
+ this.#diverged =
943
+ `the session's head on the daemon is not this client's: the daemon's is call ${e.head.calls} ending "${e.head.lastRecordSha256}", ` +
944
+ `this client sent call ${this.#calls} ending "${this.#last}"`;
945
+ }
625
946
  if (e instanceof PlimsollError && e.notDispatched)
626
947
  throw e;
627
948
  if (e instanceof PlimsollError && e.unanswered) {
@@ -632,14 +953,16 @@ export class Session {
632
953
  // With no response to compare it with, the record's evidence must be what the
633
954
  // session stated at open.
634
955
  const r = checked.record;
635
- if (r.provider !== this.sandbox || r.isolation !== this.isolation || r.softwareIdentity !== this.softwareIdentity) {
956
+ if (r.provider !== this.sandbox || r.isolation !== this.isolation || r.softwareIdentity !== this.softwareIdentity ||
957
+ r.isolationQualification !== this.isolationQualification) {
636
958
  checked = {
637
- problem: `the unanswered call's record names ${r.provider} at "${r.isolation}" running "${r.softwareIdentity}", the session opened as ${this.sandbox} at "${this.isolation}" running "${this.softwareIdentity}"`,
959
+ problem: `the unanswered call's record names ${r.provider} at "${r.isolation}" running "${r.softwareIdentity}", the session opened as ${this.sandbox} at "${this.isolation}" running "${this.softwareIdentity}" (or the tier's qualification differs from the one stated at open)`,
638
960
  };
639
961
  }
640
962
  }
641
963
  if ("problem" in checked) {
642
964
  this.#unknown = checked.problem;
965
+ this.#lostRequest ||= digest;
643
966
  throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { cause: e });
644
967
  }
645
968
  this.#calls = checked.record.sequence;
@@ -648,6 +971,7 @@ export class Session {
648
971
  throw e;
649
972
  }
650
973
  this.#unknown = e instanceof Error ? e.message : String(e);
974
+ this.#lostRequest ||= digest;
651
975
  throw e;
652
976
  }
653
977
  });
@@ -655,7 +979,11 @@ export class Session {
655
979
  async #exchange(payload, opts, rule, env, digest) {
656
980
  let m;
657
981
  try {
658
- m = await this.#client.call("SessionRun", { ...env, sessionId: this.#id, ...payload }, opts.signal);
982
+ // The head this call expects to run on, filled in here, inside the queue that
983
+ // serializes the session's calls, so it is the one the call before it left.
984
+ const head = { generation: this.#generation.toString(), calls: this.#calls.toString(), lastRecordSha256: this.#last };
985
+ const body = { ...env, sessionId: this.#id, head, ...payload };
986
+ m = await this.#client.call("SessionRun", body, opts.signal);
659
987
  }
660
988
  catch (e) {
661
989
  if (e instanceof PlimsollError && e.sessionEnded)
@@ -684,34 +1012,52 @@ export class Session {
684
1012
  }
685
1013
  /**
686
1014
  * Ends the session (or collects one that ended by itself) and checks the
687
- * daemon's count of executed calls against the chain this client saw. Every
688
- * later call returns the first one's promise, so its summary or its error, without
689
- * another request: the daemon forgets a session at its first close, and a second
690
- * CloseSession would be answered NotFound. The one exception is a close refused
691
- * not dispatched (its signal aborted before it was sent, say): it closed nothing,
692
- * so the next call tries again. The first call's signal is the one that applies.
1015
+ * daemon's count of executed calls against the chain this client saw. Once the
1016
+ * daemon has answered a close with its count, every later call returns that
1017
+ * close's promise, so its summary or its error (a count that differs from this
1018
+ * client's chain included), without another request: the daemon forgets a session
1019
+ * at its first close, and a second CloseSession would be answered NotFound. A close
1020
+ * that ended any other way (lost in transit, timed out, its signal aborted, refused
1021
+ * by the daemon, as with "the session is still ending; close it again") is sent
1022
+ * again by the next call (finding hunt-quality-90). A call made while a close is in
1023
+ * flight shares it, and that close's signal is the one that applies.
693
1024
  */
694
1025
  close(signal) {
695
1026
  return (this.#closing ??= this.#closeOnce(signal));
696
1027
  }
697
1028
  #closeOnce(signal) {
698
1029
  return this.#serial(async () => {
1030
+ if (this.#stale !== undefined) {
1031
+ this.#closing = undefined;
1032
+ throw new StaleOwnerError(`plimsoll: ${this.#stale}; this worker sends nothing more on the session`, { notDispatched: "request" });
1033
+ }
699
1034
  let m;
700
1035
  try {
701
- m = await this.#client.call("CloseSession", { protocol: PROTOCOL, sessionId: this.#id }, signal);
1036
+ const body = { protocol: PROTOCOL, sessionId: this.#id, generation: this.#generation.toString() };
1037
+ m = await this.#client.call("CloseSession", body, signal);
702
1038
  }
703
1039
  catch (e) {
704
- // Refused not dispatched: the session is still open on the daemon.
705
- if (e instanceof PlimsollError && e.notDispatched)
706
- this.#closing = undefined;
1040
+ if (e instanceof StaleOwnerError)
1041
+ this.#stale = "another worker attached the session";
1042
+ // No count came back, so the next close is sent: the close may never have
1043
+ // reached the daemon, and the daemon may ask for it again.
1044
+ this.#closing = undefined;
1045
+ throw e;
1046
+ }
1047
+ this.#closed = true;
1048
+ let sum;
1049
+ try {
1050
+ sum = decoded(() => ({
1051
+ session: m.session ?? "",
1052
+ calls: closeCount(m.calls),
1053
+ lastRecordSha256: m.lastRecordSha256 ?? "",
1054
+ end: sessionEndFromWire(m.ended),
1055
+ }));
1056
+ }
1057
+ catch (e) {
1058
+ this.#closing = undefined; // a count this client cannot read is no count
707
1059
  throw e;
708
1060
  }
709
- const sum = decoded(() => ({
710
- session: m.session ?? "",
711
- calls: BigInt(m.calls ?? 0),
712
- lastRecordSha256: m.lastRecordSha256 ?? "",
713
- end: sessionEndFromWire(m.ended),
714
- }));
715
1061
  this.#end ??= { reason: sum.end, detail: "" };
716
1062
  if (sum.session !== this.fingerprint || sum.calls !== this.#calls || sum.lastRecordSha256 !== this.#last) {
717
1063
  throw new PlimsollError("data_loss", `plimsoll: the daemon counts ${sum.calls} calls ending "${sum.lastRecordSha256}", this client saw ${this.#calls} ending "${this.#last}"`, { result: sum });
@@ -720,6 +1066,14 @@ export class Session {
720
1066
  });
721
1067
  }
722
1068
  }
1069
+ // The count a close answer states, read as one whole decimal; anything else is an answer
1070
+ // this client cannot read.
1071
+ function closeCount(v) {
1072
+ const n = wholeInt(v, UINT64);
1073
+ if (n === undefined)
1074
+ throw new PlimsollError("data_loss", "plimsoll: the daemon's count of calls is not one whole decimal");
1075
+ return n;
1076
+ }
723
1077
  // Reads the answer under the call's signal itself, since a fetch implementation
724
1078
  // need not tie its body to the signal it was given.
725
1079
  async function readCapped(res, signal) {