@plimsollmark/client 0.27.2 → 0.28.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/README.md +104 -3
- package/dist/ai-sdk.d.ts +20 -1
- package/dist/ai-sdk.js +28 -1
- package/dist/checkpoint.d.ts +41 -0
- package/dist/checkpoint.js +131 -0
- package/dist/client.d.ts +114 -15
- package/dist/client.js +335 -40
- package/dist/errors.d.ts +27 -4
- package/dist/errors.js +60 -10
- package/dist/granted.gen.d.ts +32 -0
- package/dist/granted.gen.js +33 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/mastra.d.ts +38 -1
- package/dist/mastra.js +23 -1
- package/dist/record.d.ts +36 -2
- package/dist/record.js +130 -41
- package/dist/sandboxes.d.ts +59 -1
- package/dist/sandboxes.js +179 -0
- package/dist/tables.gen.d.ts +76 -0
- package/dist/tables.gen.js +85 -2
- package/dist/tool.d.ts +13 -4
- package/dist/tool.js +57 -9
- package/dist/trigger.js +4 -1
- package/dist/wire.d.ts +48 -0
- package/dist/wire.js +25 -1
- package/package.json +2 -2
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 {
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
|
|
9
|
+
import { checkRecord, checkUnanswered, recordDigest, recordFromWire, requestDigest, sessionFingerprint, softwareRuleAllows, softwareRuleId, statesOnlyProblem, } from "./record.js";
|
|
10
|
+
import { CALL_ALREADY_SENT_TEXT, LANGUAGES, MAX_RESPONSE_BYTES, MAX_SOFTWARE_IDENTITIES, MAX_SOFTWARE_IDENTITY_BYTES, NOT_DISPATCHED_HEADER, OUTCOME_NAMES, PROTOCOL, RECORD_VERSION, REQUEST_ID_HEADER, SOFTWARE_IDENTITY_PATTERN, TIERS, } from "./tables.gen.js";
|
|
11
|
+
import { checkpointProblem, validDaemonName } from "./checkpoint.js";
|
|
12
|
+
import { CallAlreadySentError, errorFromWire, PlimsollError, sessionEndFromWire, StaleOwnerError, unboundSuccess } from "./errors.js";
|
|
13
|
+
import { trailing, 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
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 <=
|
|
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 <=
|
|
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",
|
|
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
|
|
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
|
/**
|
|
@@ -443,11 +456,22 @@ export class PlimsollClient {
|
|
|
443
456
|
warmOnly: opts.warmOnly || undefined,
|
|
444
457
|
}, opts.signal);
|
|
445
458
|
const s = decoded(() => new Session(this, m, rule, opts.minimumIsolation));
|
|
459
|
+
if (m.generation !== "1" && m.generation !== 1) {
|
|
460
|
+
// The session exists on the daemon either way, and nothing else holds its ID.
|
|
461
|
+
await s.close().catch(() => undefined);
|
|
462
|
+
throw new PlimsollError("data_loss", "plimsoll: the daemon's answer to the open states an ownership generation other than 1; the session was closed");
|
|
463
|
+
}
|
|
446
464
|
if (decoded(() => s.fingerprint !== sessionFingerprint(m.sessionId ?? ""))) {
|
|
447
465
|
// The session exists on the daemon either way, and nothing else holds its ID.
|
|
448
466
|
await s.close().catch(() => undefined);
|
|
449
467
|
throw new PlimsollError("data_loss", "plimsoll: the daemon's session fingerprint does not match its session ID; the session was closed");
|
|
450
468
|
}
|
|
469
|
+
if ((m.minimumIsolation ?? "") !== (opts.minimumIsolation ?? "") || decoded(() => wireRuleId(m.softwareRule)) !== softwareRuleId(rule)) {
|
|
470
|
+
// The floor and rule the daemon keeps for the session are what an attach answer
|
|
471
|
+
// repeats and a checkpoint states, so they must be the ones sent.
|
|
472
|
+
await s.close().catch(() => undefined);
|
|
473
|
+
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");
|
|
474
|
+
}
|
|
451
475
|
if (opts.minimumIsolation && !meets(s.isolation, opts.minimumIsolation)) {
|
|
452
476
|
await s.close().catch(() => undefined);
|
|
453
477
|
throw new PlimsollError("data_loss", `plimsoll: the session opened at ${s.isolation}, below the requested ${opts.minimumIsolation}`);
|
|
@@ -458,6 +482,106 @@ export class PlimsollClient {
|
|
|
458
482
|
}
|
|
459
483
|
return s;
|
|
460
484
|
}
|
|
485
|
+
/**
|
|
486
|
+
* Takes over the session `cp` names and carries its chain on from cp's head (Go:
|
|
487
|
+
* Remote.AttachSession): the daemon raises the session's ownership generation by one, and
|
|
488
|
+
* every call or close a worker holding an older one sends is refused before it runs
|
|
489
|
+
* (StaleOwnerError).
|
|
490
|
+
*
|
|
491
|
+
* Refused here, with nothing sent, when cp does not validate, when it names another daemon
|
|
492
|
+
* than this client's daemonName, or when the client has none. The daemon refuses an
|
|
493
|
+
* unknown, ended or another caller's session as not found, a stale generation as
|
|
494
|
+
* StaleOwnerError and a checkpoint that is not its head (a call ran after cp was saved)
|
|
495
|
+
* as CheckpointMismatchError; open development mode refuses every attach.
|
|
496
|
+
*
|
|
497
|
+
* The answer must repeat cp exactly, else data_loss, and the session is not closed: a bad
|
|
498
|
+
* answer gives this client no right to destroy a session another worker may be using. A
|
|
499
|
+
* transport failure or an abort after sending is thrown as it is and never retried: the
|
|
500
|
+
* daemon may have raised the generation, so cp may already be stale.
|
|
501
|
+
*
|
|
502
|
+
* opts.lostRequestSha256 names the call this application believes ran after cp with no
|
|
503
|
+
* answer reaching it (session.lostRequestSha256 gives it for a call of this process).
|
|
504
|
+
* With it, the daemon takes the session over from a checkpoint exactly one call behind
|
|
505
|
+
* its head when its last record is that call, following cp (the explained gap), and
|
|
506
|
+
* returns the record; it must check on its own, be the call named, at cp's next place,
|
|
507
|
+
* stating the evidence the session stated at open, and be the new head
|
|
508
|
+
* (session.lostCall). The attached session then refuses its first call if it repeats
|
|
509
|
+
* that call (CallAlreadySentError). A lost call's record the attach did not name is refused
|
|
510
|
+
* as data_loss.
|
|
511
|
+
*/
|
|
512
|
+
async attachSession(cp, opts = {}) {
|
|
513
|
+
const problem = checkpointProblem(cp);
|
|
514
|
+
if (problem)
|
|
515
|
+
throw new PlimsollError("invalid_argument", `plimsoll: invalid session checkpoint: ${problem}`, { notDispatched: "request" });
|
|
516
|
+
const lost = opts.lostRequestSha256 ?? "";
|
|
517
|
+
if (lost !== "" && !/^[0-9a-f]{64}$/.test(lost)) {
|
|
518
|
+
throw new PlimsollError("invalid_argument", "plimsoll: the lost call's request digest is not 64 lowercase hex digits", { notDispatched: "request" });
|
|
519
|
+
}
|
|
520
|
+
if (this.daemonName === undefined || cp.daemon !== this.daemonName) {
|
|
521
|
+
throw new PlimsollError("invalid_argument", "plimsoll: the checkpoint names another daemon than this client's daemonName", { notDispatched: "request" });
|
|
522
|
+
}
|
|
523
|
+
const body = {
|
|
524
|
+
protocol: PROTOCOL,
|
|
525
|
+
session: cp.session,
|
|
526
|
+
checkpoint: { generation: cp.generation.toString(), calls: cp.calls.toString(), lastRecordSha256: cp.lastRecordSha256 },
|
|
527
|
+
traceId: opts.traceId,
|
|
528
|
+
lostRequestSha256: lost || undefined,
|
|
529
|
+
};
|
|
530
|
+
const m = await this.call("AttachSession", body, opts.signal);
|
|
531
|
+
return decoded(() => this.attached(cp, m, lost));
|
|
532
|
+
}
|
|
533
|
+
// The attached session, once the answer repeats the checkpoint exactly, or carries the
|
|
534
|
+
// record of the call lost names at the checkpoint's next place and a head after it.
|
|
535
|
+
attached(cp, m, lost) {
|
|
536
|
+
const info = m.sessionInfo;
|
|
537
|
+
const head = m.checkpoint;
|
|
538
|
+
let problem;
|
|
539
|
+
let lostCall;
|
|
540
|
+
if (m.lostRecord) {
|
|
541
|
+
const checked = lostRecord(cp, lost, m.lostRecord);
|
|
542
|
+
if ("problem" in checked)
|
|
543
|
+
problem = checked.problem;
|
|
544
|
+
else
|
|
545
|
+
lostCall = checked.record;
|
|
546
|
+
}
|
|
547
|
+
const calls = lostCall ? lostCall.sequence : cp.calls;
|
|
548
|
+
const last = lostCall ? lostCall.sha256 : cp.lastRecordSha256;
|
|
549
|
+
if (problem) {
|
|
550
|
+
// the lost call's record does not check
|
|
551
|
+
}
|
|
552
|
+
else if (!info || !head)
|
|
553
|
+
problem = "lacks the session or its checkpoint";
|
|
554
|
+
else if ((info.session ?? "") !== cp.session || sessionFingerprint(info.sessionId ?? "") !== cp.session) {
|
|
555
|
+
problem = "names another session, or a session ID whose SHA-256 is not the fingerprint";
|
|
556
|
+
}
|
|
557
|
+
else if (BigInt(info.generation ?? 0) !== cp.generation + 1n || BigInt(head.generation ?? 0) !== cp.generation + 1n) {
|
|
558
|
+
problem = "states a generation other than one past the checkpoint's";
|
|
559
|
+
}
|
|
560
|
+
else if (BigInt(head.calls ?? 0) !== calls || (head.lastRecordSha256 ?? "") !== last) {
|
|
561
|
+
problem = "states another chain head than the checkpoint's (or, across an explained gap, than the lost call's)";
|
|
562
|
+
}
|
|
563
|
+
else if ((info.sandbox ?? "") !== cp.provider || (info.isolation ?? "") !== cp.isolation ||
|
|
564
|
+
(info.isolationQualification ?? "") !== cp.isolationQualification || (info.softwareIdentity ?? "") !== cp.softwareIdentity) {
|
|
565
|
+
problem = "states another provider, tier, qualification or software than the session stated at open";
|
|
566
|
+
}
|
|
567
|
+
else if ((info.minimumIsolation ?? "") !== cp.openFloor || wireRuleId(info.softwareRule) !== cp.openRule) {
|
|
568
|
+
problem = "states another floor or software rule than the session was opened with";
|
|
569
|
+
}
|
|
570
|
+
else if (num(info.expiresUnixMs) !== cp.expiresUnixMs || (info.idleTimeoutMs ?? 0) !== cp.idleTimeoutMs) {
|
|
571
|
+
problem = "states another lifetime or idle timeout than the session's";
|
|
572
|
+
}
|
|
573
|
+
if (problem || !info)
|
|
574
|
+
throw new PlimsollError("data_loss", `plimsoll: the daemon's answer to the attach ${problem}; the session was left as it is`);
|
|
575
|
+
const rule = cp.openRule && info.softwareRule ? { mode: info.softwareRule.mode, identities: [...info.softwareRule.identities] } : undefined;
|
|
576
|
+
const floor = cp.openFloor === "" ? undefined : cp.openFloor;
|
|
577
|
+
return new Session(this, info, rule, floor, {
|
|
578
|
+
generation: cp.generation + 1n,
|
|
579
|
+
calls,
|
|
580
|
+
last,
|
|
581
|
+
lostCall: lostCall ? lostCall.requestSha256 : cp.lostCallSha256,
|
|
582
|
+
lostRecord: lostCall,
|
|
583
|
+
});
|
|
584
|
+
}
|
|
461
585
|
/** @internal */
|
|
462
586
|
envelope(opts, rule) {
|
|
463
587
|
return {
|
|
@@ -484,6 +608,54 @@ export class PlimsollClient {
|
|
|
484
608
|
return { run: resp, record: r };
|
|
485
609
|
}
|
|
486
610
|
}
|
|
611
|
+
// The record an attach answer returns for the call the attach named (lost), once it is a
|
|
612
|
+
// live record that checks on its own, of the session cp names, at cp's next place in the
|
|
613
|
+
// chain, carrying the named request digest and the evidence the session stated at open.
|
|
614
|
+
// Exported for the shared test cases (internal/clientcases); not part of the package's API.
|
|
615
|
+
/** @internal */
|
|
616
|
+
export function lostRecord(cp, lost, m) {
|
|
617
|
+
if (lost === "")
|
|
618
|
+
return { problem: "carries a lost call's record, but the attach named no lost call" };
|
|
619
|
+
const r = recordFromWire(m);
|
|
620
|
+
if (r.version !== RECORD_VERSION)
|
|
621
|
+
return { problem: `carries a lost call's record of version ${r.version}, not the live version ${RECORD_VERSION}` };
|
|
622
|
+
const states = statesOnlyProblem(r);
|
|
623
|
+
if (states)
|
|
624
|
+
return { problem: `carries a lost call's record that does not check (${states})` };
|
|
625
|
+
if (recordDigest(r) !== r.sha256)
|
|
626
|
+
return { problem: "carries a lost call's record whose own digest does not match" };
|
|
627
|
+
if (r.session !== cp.session || r.sequence !== cp.calls + 1n || r.previousSha256 !== cp.lastRecordSha256) {
|
|
628
|
+
return { problem: "carries a lost call's record that is not the checkpoint's next call" };
|
|
629
|
+
}
|
|
630
|
+
if (r.requestSha256 !== lost)
|
|
631
|
+
return { problem: "carries the record of another call than the one the attach named" };
|
|
632
|
+
if (r.provider !== cp.provider || r.isolation !== cp.isolation || r.softwareIdentity !== cp.softwareIdentity || r.isolationQualification !== cp.isolationQualification) {
|
|
633
|
+
return { problem: "carries a lost call's record stating other evidence than the session stated at open" };
|
|
634
|
+
}
|
|
635
|
+
return { record: r };
|
|
636
|
+
}
|
|
637
|
+
// The ID of a software rule as the daemon sent it, "" for none; a rule this client would
|
|
638
|
+
// not send (an unknown mode, a malformed identity) has an ID no checkpoint states.
|
|
639
|
+
function wireRuleId(r) {
|
|
640
|
+
if (!r || (!r.mode && !(r.identities ?? []).length))
|
|
641
|
+
return "";
|
|
642
|
+
try {
|
|
643
|
+
return softwareRuleId(validateRule({ mode: r.mode, identities: [...(r.identities ?? [])] }));
|
|
644
|
+
}
|
|
645
|
+
catch {
|
|
646
|
+
return "invalid";
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
// The grant profile a run selects: the call's own when it names one ("" for none), else
|
|
650
|
+
// the client's.
|
|
651
|
+
function grantFor(opts, client) {
|
|
652
|
+
if (opts.grantProfile === undefined)
|
|
653
|
+
return client;
|
|
654
|
+
if (typeof opts.grantProfile !== "string") {
|
|
655
|
+
throw new PlimsollError("invalid_argument", "plimsoll: grantProfile must be a string", { notDispatched: "request" });
|
|
656
|
+
}
|
|
657
|
+
return opts.grantProfile;
|
|
658
|
+
}
|
|
487
659
|
/** @internal */
|
|
488
660
|
export function projectPayload(req, grantProfile) {
|
|
489
661
|
return {
|
|
@@ -521,6 +693,8 @@ export class Session {
|
|
|
521
693
|
fingerprint;
|
|
522
694
|
/** The tier the daemon measured when the session opened. */
|
|
523
695
|
isolation;
|
|
696
|
+
/** The sentence the provider states beside that tier, "" when it states none. Every call's record states it too. */
|
|
697
|
+
isolationQualification;
|
|
524
698
|
sandbox;
|
|
525
699
|
/** The selected software the daemon stated at open. */
|
|
526
700
|
softwareIdentity;
|
|
@@ -528,7 +702,9 @@ export class Session {
|
|
|
528
702
|
idleTimeoutMs;
|
|
529
703
|
// The session ID is a capability: it goes to the daemon and nowhere else.
|
|
530
704
|
#id;
|
|
705
|
+
#generation;
|
|
531
706
|
#client;
|
|
707
|
+
// The rule and floor given at open, which a checkpoint states.
|
|
532
708
|
#rule;
|
|
533
709
|
// The floor given at open: every call carries it unless the call asks for more.
|
|
534
710
|
#floor;
|
|
@@ -539,16 +715,39 @@ export class Session {
|
|
|
539
715
|
// have run it and moved its chain on, so every later call would run and then fail
|
|
540
716
|
// the chain check. They are refused here instead, before anything is sent.
|
|
541
717
|
#unknown;
|
|
718
|
+
// Set once the daemon refused a call or close because another worker attached the
|
|
719
|
+
// session: this worker must not use it again.
|
|
720
|
+
#stale;
|
|
721
|
+
// Set once the daemon answered this client's close.
|
|
722
|
+
#closed = false;
|
|
723
|
+
// The request digest the session's next call is refused for repeating, set by an attach
|
|
724
|
+
// across an explained gap (or inherited with a checkpoint) and spent by the next call;
|
|
725
|
+
// the record of that lost call; and the request digest of the call after which this
|
|
726
|
+
// session stopped with no answer it could check.
|
|
727
|
+
#lostCall = "";
|
|
728
|
+
#lostRecord;
|
|
729
|
+
#lostRequest = "";
|
|
542
730
|
#queue = Promise.resolve();
|
|
543
731
|
#closing;
|
|
544
732
|
/** @internal */
|
|
545
|
-
constructor(client, m, rule, floor) {
|
|
733
|
+
constructor(client, m, rule, floor, attached) {
|
|
546
734
|
this.#client = client;
|
|
547
735
|
this.#id = m.sessionId ?? "";
|
|
736
|
+
// Every daemon opens a session at generation 1; openSession refuses an answer that
|
|
737
|
+
// says otherwise, after closing the session with this one. An attached session
|
|
738
|
+
// carries on from the checkpoint it was attached with.
|
|
739
|
+
this.#generation = attached?.generation ?? 1n;
|
|
740
|
+
if (attached) {
|
|
741
|
+
this.#calls = attached.calls;
|
|
742
|
+
this.#last = attached.last;
|
|
743
|
+
this.#lostCall = attached.lostCall;
|
|
744
|
+
this.#lostRecord = attached.lostRecord;
|
|
745
|
+
}
|
|
548
746
|
this.#rule = rule;
|
|
549
747
|
this.#floor = floor;
|
|
550
748
|
this.fingerprint = m.session ?? "";
|
|
551
749
|
this.isolation = m.isolation ?? "";
|
|
750
|
+
this.isolationQualification = m.isolationQualification ?? "";
|
|
552
751
|
this.sandbox = m.sandbox ?? "";
|
|
553
752
|
this.softwareIdentity = m.softwareIdentity ?? "";
|
|
554
753
|
this.expiresAtMs = num(m.expiresUnixMs);
|
|
@@ -559,7 +758,63 @@ export class Session {
|
|
|
559
758
|
* answer it could check (the call may have run); undefined while it is usable.
|
|
560
759
|
*/
|
|
561
760
|
get stopped() {
|
|
562
|
-
return this.#unknown;
|
|
761
|
+
return this.#stale ?? this.#unknown;
|
|
762
|
+
}
|
|
763
|
+
/**
|
|
764
|
+
* The request digest of the call after which this session stopped with no answer it could
|
|
765
|
+
* check, or "": the call that may have run, for another worker's attachSession to name
|
|
766
|
+
* (lostRequestSha256) together with a checkpoint saved before it.
|
|
767
|
+
*/
|
|
768
|
+
get lostRequestSha256() {
|
|
769
|
+
return this.#lostRequest;
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* The record of the call that was sent once and whose answer was lost, on a session attached
|
|
773
|
+
* across an explained gap; its output is lost. The record says whether the daemon answered
|
|
774
|
+
* it: a result digest when the daemon answered, which does not show that the call ran to its
|
|
775
|
+
* end (a step stopped at its time limit and a setup that failed are answers too), an
|
|
776
|
+
* unanswered code when it ended without an answer, so that it may have done none, part or all
|
|
777
|
+
* of its work.
|
|
778
|
+
*/
|
|
779
|
+
get lostCall() {
|
|
780
|
+
return this.#lostRecord;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* The session's checkpoint (Go: Session.Checkpoint), for the application to save where
|
|
784
|
+
* only it can write, so another process can attachSession. It waits for a call in
|
|
785
|
+
* flight, so the head it states follows that call. Refused when the client has no
|
|
786
|
+
* daemonName and when the session is stopped, closed or ended.
|
|
787
|
+
*/
|
|
788
|
+
checkpoint() {
|
|
789
|
+
return this.#serial(async () => {
|
|
790
|
+
const refuse = (why) => new PlimsollError("failed_precondition", `plimsoll: this session cannot be checkpointed: ${why}`, { notDispatched: "request" });
|
|
791
|
+
const daemon = this.#client.daemonName;
|
|
792
|
+
if (daemon === undefined)
|
|
793
|
+
throw refuse("the client has no daemonName");
|
|
794
|
+
if (this.stopped !== undefined)
|
|
795
|
+
throw refuse(`it is stopped (${this.stopped})`);
|
|
796
|
+
if (this.#closed)
|
|
797
|
+
throw refuse("it is closed");
|
|
798
|
+
if (this.#end !== undefined && this.#end.reason !== "open")
|
|
799
|
+
throw refuse(`it ended (${this.#end.reason})`);
|
|
800
|
+
return {
|
|
801
|
+
version: 1,
|
|
802
|
+
daemon,
|
|
803
|
+
session: this.fingerprint,
|
|
804
|
+
generation: this.#generation,
|
|
805
|
+
calls: this.#calls,
|
|
806
|
+
lastRecordSha256: this.#last,
|
|
807
|
+
provider: this.sandbox,
|
|
808
|
+
isolation: this.isolation,
|
|
809
|
+
isolationQualification: this.isolationQualification,
|
|
810
|
+
softwareIdentity: this.softwareIdentity,
|
|
811
|
+
openFloor: this.#floor ?? "",
|
|
812
|
+
openRule: softwareRuleId(this.#rule),
|
|
813
|
+
expiresUnixMs: this.expiresAtMs,
|
|
814
|
+
idleTimeoutMs: this.idleTimeoutMs,
|
|
815
|
+
lostCallSha256: this.#lostCall,
|
|
816
|
+
};
|
|
817
|
+
});
|
|
563
818
|
}
|
|
564
819
|
/** The session's end once a response reported it, else undefined. */
|
|
565
820
|
get ended() {
|
|
@@ -611,6 +866,9 @@ export class Session {
|
|
|
611
866
|
#call(payload, opts) {
|
|
612
867
|
const rule = mergeRules(this.#rule, validateRule(opts.software));
|
|
613
868
|
return this.#serial(async () => {
|
|
869
|
+
if (this.#stale !== undefined) {
|
|
870
|
+
throw new StaleOwnerError(`plimsoll: ${this.#stale}; this worker sends nothing more on the session`, { notDispatched: "request" });
|
|
871
|
+
}
|
|
614
872
|
if (this.#unknown !== undefined) {
|
|
615
873
|
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
874
|
}
|
|
@@ -618,12 +876,27 @@ export class Session {
|
|
|
618
876
|
// Before the digest, which cannot encode such text either.
|
|
619
877
|
refuseIllFormed({ ...env, ...payload }, "the request");
|
|
620
878
|
const digest = requestDigest({ protocol: env.protocol, minimumIsolation: env.minimumIsolation ?? "", timeoutMs: env.timeoutMs ?? 0, softwareRule: rule, payload: digestPayload(payload) });
|
|
879
|
+
// The first call after an attach across an explained gap: a repeat of the lost call is
|
|
880
|
+
// a retry of a call that was already sent once, refused here with nothing sent, and the
|
|
881
|
+
// refusal spends the note. Only the first call is checked: any other call spends the
|
|
882
|
+
// note once it is sent, unless the daemon refuses it with the not-dispatched mark,
|
|
883
|
+
// since then nothing ran, the head is where it was, and the next call is still the
|
|
884
|
+
// first.
|
|
885
|
+
if (this.#lostCall !== "" && digest === this.#lostCall) {
|
|
886
|
+
this.#lostCall = "";
|
|
887
|
+
throw new CallAlreadySentError(`plimsoll: ${CALL_ALREADY_SENT_TEXT}; nothing was sent`);
|
|
888
|
+
}
|
|
621
889
|
try {
|
|
622
|
-
|
|
890
|
+
const answered = await this.#exchange(payload, opts, rule, env, digest);
|
|
891
|
+
this.#lostCall = "";
|
|
892
|
+
return answered;
|
|
623
893
|
}
|
|
624
894
|
catch (e) {
|
|
895
|
+
if (e instanceof StaleOwnerError)
|
|
896
|
+
this.#stale = "another worker attached the session";
|
|
625
897
|
if (e instanceof PlimsollError && e.notDispatched)
|
|
626
898
|
throw e;
|
|
899
|
+
this.#lostCall = "";
|
|
627
900
|
if (e instanceof PlimsollError && e.unanswered) {
|
|
628
901
|
// The call may have run, and the daemon chained its record: check it and keep
|
|
629
902
|
// it in the chain, so the session goes on and the call is not hidden.
|
|
@@ -632,14 +905,16 @@ export class Session {
|
|
|
632
905
|
// With no response to compare it with, the record's evidence must be what the
|
|
633
906
|
// session stated at open.
|
|
634
907
|
const r = checked.record;
|
|
635
|
-
if (r.provider !== this.sandbox || r.isolation !== this.isolation || r.softwareIdentity !== this.softwareIdentity
|
|
908
|
+
if (r.provider !== this.sandbox || r.isolation !== this.isolation || r.softwareIdentity !== this.softwareIdentity ||
|
|
909
|
+
r.isolationQualification !== this.isolationQualification) {
|
|
636
910
|
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}"`,
|
|
911
|
+
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
912
|
};
|
|
639
913
|
}
|
|
640
914
|
}
|
|
641
915
|
if ("problem" in checked) {
|
|
642
916
|
this.#unknown = checked.problem;
|
|
917
|
+
this.#lostRequest ||= digest;
|
|
643
918
|
throw new PlimsollError("data_loss", `plimsoll: ${checked.problem}`, { cause: e });
|
|
644
919
|
}
|
|
645
920
|
this.#calls = checked.record.sequence;
|
|
@@ -648,6 +923,7 @@ export class Session {
|
|
|
648
923
|
throw e;
|
|
649
924
|
}
|
|
650
925
|
this.#unknown = e instanceof Error ? e.message : String(e);
|
|
926
|
+
this.#lostRequest ||= digest;
|
|
651
927
|
throw e;
|
|
652
928
|
}
|
|
653
929
|
});
|
|
@@ -655,7 +931,8 @@ export class Session {
|
|
|
655
931
|
async #exchange(payload, opts, rule, env, digest) {
|
|
656
932
|
let m;
|
|
657
933
|
try {
|
|
658
|
-
|
|
934
|
+
const body = { ...env, sessionId: this.#id, generation: this.#generation.toString(), ...payload };
|
|
935
|
+
m = await this.#client.call("SessionRun", body, opts.signal);
|
|
659
936
|
}
|
|
660
937
|
catch (e) {
|
|
661
938
|
if (e instanceof PlimsollError && e.sessionEnded)
|
|
@@ -684,34 +961,52 @@ export class Session {
|
|
|
684
961
|
}
|
|
685
962
|
/**
|
|
686
963
|
* 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.
|
|
688
|
-
*
|
|
689
|
-
*
|
|
690
|
-
*
|
|
691
|
-
*
|
|
692
|
-
*
|
|
964
|
+
* daemon's count of executed calls against the chain this client saw. Once the
|
|
965
|
+
* daemon has answered a close with its count, every later call returns that
|
|
966
|
+
* close's promise, so its summary or its error (a count that differs from this
|
|
967
|
+
* client's chain included), without another request: the daemon forgets a session
|
|
968
|
+
* at its first close, and a second CloseSession would be answered NotFound. A close
|
|
969
|
+
* that ended any other way (lost in transit, timed out, its signal aborted, refused
|
|
970
|
+
* by the daemon, as with "the session is still ending; close it again") is sent
|
|
971
|
+
* again by the next call (finding hunt-quality-90). A call made while a close is in
|
|
972
|
+
* flight shares it, and that close's signal is the one that applies.
|
|
693
973
|
*/
|
|
694
974
|
close(signal) {
|
|
695
975
|
return (this.#closing ??= this.#closeOnce(signal));
|
|
696
976
|
}
|
|
697
977
|
#closeOnce(signal) {
|
|
698
978
|
return this.#serial(async () => {
|
|
979
|
+
if (this.#stale !== undefined) {
|
|
980
|
+
this.#closing = undefined;
|
|
981
|
+
throw new StaleOwnerError(`plimsoll: ${this.#stale}; this worker sends nothing more on the session`, { notDispatched: "request" });
|
|
982
|
+
}
|
|
699
983
|
let m;
|
|
700
984
|
try {
|
|
701
|
-
|
|
985
|
+
const body = { protocol: PROTOCOL, sessionId: this.#id, generation: this.#generation.toString() };
|
|
986
|
+
m = await this.#client.call("CloseSession", body, signal);
|
|
702
987
|
}
|
|
703
988
|
catch (e) {
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
989
|
+
if (e instanceof StaleOwnerError)
|
|
990
|
+
this.#stale = "another worker attached the session";
|
|
991
|
+
// No count came back, so the next close is sent: the close may never have
|
|
992
|
+
// reached the daemon, and the daemon may ask for it again.
|
|
993
|
+
this.#closing = undefined;
|
|
994
|
+
throw e;
|
|
995
|
+
}
|
|
996
|
+
this.#closed = true;
|
|
997
|
+
let sum;
|
|
998
|
+
try {
|
|
999
|
+
sum = decoded(() => ({
|
|
1000
|
+
session: m.session ?? "",
|
|
1001
|
+
calls: BigInt(m.calls ?? 0),
|
|
1002
|
+
lastRecordSha256: m.lastRecordSha256 ?? "",
|
|
1003
|
+
end: sessionEndFromWire(m.ended),
|
|
1004
|
+
}));
|
|
1005
|
+
}
|
|
1006
|
+
catch (e) {
|
|
1007
|
+
this.#closing = undefined; // a count this client cannot read is no count
|
|
707
1008
|
throw e;
|
|
708
1009
|
}
|
|
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
1010
|
this.#end ??= { reason: sum.end, detail: "" };
|
|
716
1011
|
if (sum.session !== this.fingerprint || sum.calls !== this.#calls || sum.lastRecordSha256 !== this.#last) {
|
|
717
1012
|
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 });
|
package/dist/errors.d.ts
CHANGED
|
@@ -65,10 +65,33 @@ export declare class PlimsollError extends Error {
|
|
|
65
65
|
cause?: unknown;
|
|
66
66
|
});
|
|
67
67
|
}
|
|
68
|
-
/**
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
68
|
+
/**
|
|
69
|
+
* A session call, close or attach the daemon refused because another worker attached the
|
|
70
|
+
* session (or its ownership generation is spent): nothing ran, and the session goes on for
|
|
71
|
+
* its new owner. After it on a call or a close, the Session sends nothing more (Go:
|
|
72
|
+
* client.ErrStaleOwner).
|
|
73
|
+
*/
|
|
74
|
+
export declare class StaleOwnerError extends PlimsollError {
|
|
75
|
+
constructor(message: string, opts?: ConstructorParameters<typeof PlimsollError>[2]);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* An attach the daemon refused because the checkpoint is not the session's head: a call ran
|
|
79
|
+
* after the checkpoint was saved, its answer perhaps lost. Nothing ran, and ownership did
|
|
80
|
+
* not move (Go: client.ErrCheckpointMismatch).
|
|
81
|
+
*/
|
|
82
|
+
export declare class CheckpointMismatchError extends PlimsollError {
|
|
83
|
+
constructor(message: string, opts?: ConstructorParameters<typeof PlimsollError>[2]);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* The first call of a session taken over across an explained gap repeats the lost call:
|
|
87
|
+
* that call was already sent once and its answer was lost, so this is a retry of it.
|
|
88
|
+
* Refused before anything was sent (notDispatched "request"), and never a retry signal.
|
|
89
|
+
* Only the first call is checked (Go: client.ErrCallAlreadySent, in the same words).
|
|
90
|
+
* The lost call's record says whether the daemon answered it (session.lostCall).
|
|
91
|
+
*/
|
|
92
|
+
export declare class CallAlreadySentError extends PlimsollError {
|
|
93
|
+
constructor(message: string);
|
|
94
|
+
}
|
|
72
95
|
/** The error for a success answer that is not bound to its request: the call may have run. */
|
|
73
96
|
export declare function unboundSuccess(method: string): PlimsollError;
|
|
74
97
|
export declare function sessionEndFromWire(v: string | number | undefined): SessionEnd;
|