@mandateops/cli-linux-arm64 0.0.0-stage → 0.7.1

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.
Files changed (68) hide show
  1. package/LICENSE +55 -0
  2. package/README.md +175 -2
  3. package/audit-lab/README.md +194 -0
  4. package/audit-lab/bin/mandateops +0 -0
  5. package/audit-lab/contracts/contact-plain-text.vectors.json +85 -0
  6. package/audit-lab/contracts/history-reading.md +185 -0
  7. package/audit-lab/contracts/history-reading.vectors.json +284 -0
  8. package/audit-lab/contracts/profiles.md +161 -0
  9. package/audit-lab/contracts/properties.md +512 -0
  10. package/audit-lab/contracts/sdk-config.md +155 -0
  11. package/audit-lab/contracts/system-under-test.md +385 -0
  12. package/audit-lab/contracts/test-provider.md +350 -0
  13. package/audit-lab/lab/compose.audit.yml +181 -0
  14. package/audit-lab/lab/config/fault-control.json +14 -0
  15. package/audit-lab/lab/examples/agents/Dockerfile +28 -0
  16. package/audit-lab/lab/examples/agents/codeloc.cjs +199 -0
  17. package/audit-lab/lab/examples/agents/load.cjs +9 -0
  18. package/audit-lab/lab/examples/agents/package-lock.json +2840 -0
  19. package/audit-lab/lab/examples/agents/package.json +9 -0
  20. package/audit-lab/lab/examples/agents/python/mandateops_codeloc.py +271 -0
  21. package/audit-lab/lab/examples/agents/python/sitecustomize.py +51 -0
  22. package/audit-lab/lab/examples/agents/requirements-python.txt +522 -0
  23. package/audit-lab/lab/examples/agents/telemetry-router.cjs +272 -0
  24. package/audit-lab/lab/examples/test-provider/.dockerignore +4 -0
  25. package/audit-lab/lab/examples/test-provider/Dockerfile +28 -0
  26. package/audit-lab/lab/examples/test-provider/bun.lock +405 -0
  27. package/audit-lab/lab/examples/test-provider/package.json +42 -0
  28. package/audit-lab/lab/examples/test-provider/src/amount.ts +32 -0
  29. package/audit-lab/lab/examples/test-provider/src/app.ts +538 -0
  30. package/audit-lab/lab/examples/test-provider/src/auth.ts +30 -0
  31. package/audit-lab/lab/examples/test-provider/src/barrier.ts +262 -0
  32. package/audit-lab/lab/examples/test-provider/src/codeloc.ts +27 -0
  33. package/audit-lab/lab/examples/test-provider/src/config.ts +311 -0
  34. package/audit-lab/lab/examples/test-provider/src/connect.ts +204 -0
  35. package/audit-lab/lab/examples/test-provider/src/declaration.ts +270 -0
  36. package/audit-lab/lab/examples/test-provider/src/declared.ts +198 -0
  37. package/audit-lab/lab/examples/test-provider/src/domain.ts +193 -0
  38. package/audit-lab/lab/examples/test-provider/src/egress.ts +396 -0
  39. package/audit-lab/lab/examples/test-provider/src/flow.ts +263 -0
  40. package/audit-lab/lab/examples/test-provider/src/gate.ts +301 -0
  41. package/audit-lab/lab/examples/test-provider/src/main.ts +31 -0
  42. package/audit-lab/lab/examples/test-provider/src/notify.ts +157 -0
  43. package/audit-lab/lab/examples/test-provider/src/owner.ts +60 -0
  44. package/audit-lab/lab/examples/test-provider/src/payment.ts +103 -0
  45. package/audit-lab/lab/examples/test-provider/src/profile.ts +417 -0
  46. package/audit-lab/lab/examples/test-provider/src/request.ts +201 -0
  47. package/audit-lab/lab/examples/test-provider/src/rows.ts +173 -0
  48. package/audit-lab/lab/examples/test-provider/src/schema.ts +114 -0
  49. package/audit-lab/lab/examples/test-provider/src/signature.ts +86 -0
  50. package/audit-lab/lab/examples/test-provider/src/staged.ts +318 -0
  51. package/audit-lab/lab/examples/test-provider/src/store.ts +432 -0
  52. package/audit-lab/lab/examples/test-provider/src/traffic.ts +50 -0
  53. package/audit-lab/lab/examples/test-provider/src/webauthn.d.ts +11 -0
  54. package/audit-lab/lab/examples/test-provider/src/wire.ts +153 -0
  55. package/audit-lab/lab/examples/test-provider/tsconfig.build.json +9 -0
  56. package/audit-lab/lab/examples/test-provider/tsconfig.json +24 -0
  57. package/audit-lab/lab/images/capture/Dockerfile +15 -0
  58. package/audit-lab/lab/images/capture/LICENSE +201 -0
  59. package/audit-lab/lab/images/fault-control/Dockerfile +13 -0
  60. package/audit-lab/lab/images/fault-control/LICENSE +21 -0
  61. package/audit-lab/lab/images/provider-store/Dockerfile +4 -0
  62. package/audit-lab/lab/images/provider-store/LICENSE +23 -0
  63. package/audit-lab/lab/images/telemetry/Dockerfile +14 -0
  64. package/audit-lab/lab/images/telemetry/LICENSE +201 -0
  65. package/audit-lab/lab/scripts/compose-down.sh +143 -0
  66. package/audit-lab/lab/scripts/compose-lib.sh +632 -0
  67. package/audit-lab/lab/scripts/compose-up.sh +240 -0
  68. package/package.json +16 -4
@@ -0,0 +1,262 @@
1
+ import { ProviderError } from "./domain.js";
2
+
3
+ export type BarrierState = "idle" | "armed" | "committed" | "released";
4
+ export type BarrierView = Readonly<{
5
+ state: BarrierState;
6
+ effectId: string | null;
7
+ }>;
8
+ /** A response the provider has computed but not yet written. */
9
+ export type HeldResponse = Readonly<{
10
+ /** Drops the response unwritten and closes its connection if still open. */
11
+ discard: () => void;
12
+ }>;
13
+
14
+ /** Terms a request must carry for an armed barrier to take its response. */
15
+ export type HoldMatch = Readonly<Record<string, string | undefined>>;
16
+
17
+ type Phase =
18
+ | Readonly<{ state: "idle" }>
19
+ | Readonly<{ state: "armed"; match: HoldMatch }>
20
+ | Readonly<{ state: "committed"; effectId: string; held: HeldResponse }>
21
+ | Readonly<{ state: "released"; effectId: string }>;
22
+
23
+ const carries = (
24
+ match: HoldMatch,
25
+ terms: Readonly<Record<string, string | undefined>>,
26
+ ): boolean =>
27
+ Object.entries(match).every(([name, value]) => terms[name] === value);
28
+
29
+ /** One armed refusal in one attempt's hands; its identity is the attempt's. */
30
+ type RefusalClaim = Readonly<{ match: HoldMatch }>;
31
+
32
+ /** One request's use of a refusal; only the attempt that took it may end it. */
33
+ export type RefusalAttempt = Readonly<{
34
+ takes: (terms: Readonly<Record<string, string | undefined>>) => boolean;
35
+ /** The refusal is on record, so the claim is spent. */
36
+ settled: () => void;
37
+ /** Re-arms a claim whose record failed. */
38
+ abandon: () => void;
39
+ }>;
40
+
41
+ /** Most faults of one kind armed or in use at once. */
42
+ export const MAX_ARMED_REFUSALS = 64;
43
+
44
+ const sameMatch = (left: HoldMatch, right: HoldMatch): boolean => {
45
+ const entries = (match: HoldMatch) =>
46
+ JSON.stringify(
47
+ Object.entries(match).sort(([one], [other]) => one.localeCompare(other)),
48
+ );
49
+ return entries(left) === entries(right);
50
+ };
51
+ const matchesAll = (match: HoldMatch): boolean =>
52
+ Object.keys(match).length === 0;
53
+
54
+ /**
55
+ * Faults armed for the next request carrying their terms. Several may wait
56
+ * at once when each names other terms, so a scaled run can fault many
57
+ * payments concurrently; one naming no terms matches every request and must
58
+ * wait alone. A request is taken by the first armed match it carries.
59
+ */
60
+ class ArmedMatches {
61
+ private armed: HoldMatch[] = [];
62
+
63
+ /** `busy` are matches taken but not yet spent, which still block a twin. */
64
+ arm(match: HoldMatch, busy: readonly HoldMatch[]): void {
65
+ const held = [...this.armed, ...busy];
66
+ if (
67
+ held.length >= MAX_ARMED_REFUSALS ||
68
+ (held.length > 0 && matchesAll(match)) ||
69
+ held.some((other) => matchesAll(other) || sameMatch(other, match))
70
+ )
71
+ throw new ProviderError(409, "refusal_busy");
72
+ this.armed.push(match);
73
+ }
74
+
75
+ take(
76
+ terms: Readonly<Record<string, string | undefined>>,
77
+ ): HoldMatch | undefined {
78
+ const index = this.armed.findIndex((match) => carries(match, terms));
79
+ const match = this.armed[index];
80
+ if (match !== undefined) this.armed.splice(index, 1);
81
+ return match;
82
+ }
83
+
84
+ /** Whether a request carrying `terms` would take an armed match. */
85
+ has(terms: Readonly<Record<string, string | undefined>>): boolean {
86
+ return this.armed.some((match) => carries(match, terms));
87
+ }
88
+
89
+ /** Removes an armed match no request took; whether one was armed. */
90
+ withdraw(match: HoldMatch): boolean {
91
+ const index = this.armed.findIndex((other) => sameMatch(other, match));
92
+ if (index < 0) return false;
93
+ this.armed.splice(index, 1);
94
+ return true;
95
+ }
96
+
97
+ restore(match: HoldMatch): void {
98
+ this.armed.push(match);
99
+ }
100
+
101
+ reset(): void {
102
+ this.armed = [];
103
+ }
104
+ }
105
+
106
+ /** Declines the next request carrying its terms, once. Creates no effect. */
107
+ export class Refusal {
108
+ private readonly armed = new ArmedMatches();
109
+ private readonly claimed = new Set<RefusalClaim>();
110
+
111
+ arm(match: HoldMatch = {}): void {
112
+ this.armed.arm(
113
+ match,
114
+ [...this.claimed].map((one) => one.match),
115
+ );
116
+ }
117
+
118
+ /** Withdraws a refusal no request took; whether one waited. */
119
+ withdraw(match: HoldMatch): boolean {
120
+ return this.armed.withdraw(match);
121
+ }
122
+
123
+ attempt(): RefusalAttempt {
124
+ let taken: RefusalClaim | undefined;
125
+ const holdsClaim = () => taken !== undefined && this.claimed.has(taken);
126
+ return {
127
+ takes: (terms) => {
128
+ const match = this.armed.take(terms);
129
+ if (match === undefined) return false;
130
+ taken = { match };
131
+ this.claimed.add(taken);
132
+ return true;
133
+ },
134
+ settled: () => {
135
+ if (taken && holdsClaim()) this.claimed.delete(taken);
136
+ },
137
+ abandon: () => {
138
+ if (!taken || !holdsClaim()) return;
139
+ this.claimed.delete(taken);
140
+ this.armed.restore(taken.match);
141
+ },
142
+ };
143
+ }
144
+
145
+ reset(): void {
146
+ this.armed.reset();
147
+ this.claimed.clear();
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Loses the reply of the next payment carrying its terms, after its effect
153
+ * commits: the connection closes unanswered, as when a reply is lost on the
154
+ * way back. Unlike the barrier, many may wait at once for different terms.
155
+ */
156
+ export class Drops {
157
+ private readonly armed = new ArmedMatches();
158
+
159
+ arm(match: HoldMatch = {}): void {
160
+ this.armed.arm(match, []);
161
+ }
162
+
163
+ /** Withdraws a lost reply no payment took; whether one waited. */
164
+ withdraw(match: HoldMatch): boolean {
165
+ return this.armed.withdraw(match);
166
+ }
167
+
168
+ /** Whether a lost reply waits for a payment carrying `terms`. */
169
+ armedFor(terms: Readonly<Record<string, string | undefined>>): boolean {
170
+ return this.armed.has(terms);
171
+ }
172
+
173
+ /** Whether this committed payment's reply is to be lost. */
174
+ takes(terms: Readonly<Record<string, string | undefined>>): boolean {
175
+ return this.armed.take(terms) !== undefined;
176
+ }
177
+
178
+ reset(): void {
179
+ this.armed.reset();
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Test barrier over one delayed response: idle -> armed -> committed -> released.
185
+ * An armed barrier that never captured a response may be disarmed back to idle.
186
+ *
187
+ * The held response is delayed information about an effect that is already
188
+ * durable. Nothing here can remove an effect, and no timer or connection close
189
+ * moves the state: only an explicit runner release, disarm or reset does. A closed
190
+ * client connection leaves the barrier committed until the runner releases it.
191
+ */
192
+ export class Barrier {
193
+ private phase: Phase = { state: "idle" };
194
+
195
+ view(): BarrierView {
196
+ return {
197
+ state: this.phase.state,
198
+ effectId:
199
+ this.phase.state === "committed" || this.phase.state === "released"
200
+ ? this.phase.effectId
201
+ : null,
202
+ };
203
+ }
204
+
205
+ /** Arms the barrier for the next successful payout response carrying `match`. */
206
+ arm(match: HoldMatch = {}): void {
207
+ if (this.phase.state === "armed" || this.phase.state === "committed") {
208
+ throw new ProviderError(409, "barrier_busy");
209
+ }
210
+ this.phase = { state: "armed", match };
211
+ }
212
+
213
+ /** Whether the barrier waits for a payment carrying `terms`. */
214
+ armedFor(terms: Readonly<Record<string, string | undefined>>): boolean {
215
+ return this.phase.state === "armed" && carries(this.phase.match, terms);
216
+ }
217
+
218
+ /**
219
+ * Takes ownership of a response for an effect that has durably committed.
220
+ * Returns false when the barrier is not armed or `terms` do not carry its
221
+ * match; the caller then responds.
222
+ */
223
+ capture(
224
+ effectId: string,
225
+ held: HeldResponse,
226
+ terms: Readonly<Record<string, string | undefined>> = {},
227
+ ): boolean {
228
+ if (this.phase.state !== "armed") return false;
229
+ if (!carries(this.phase.match, terms)) return false;
230
+ this.phase = { state: "committed", effectId, held };
231
+ return true;
232
+ }
233
+
234
+ /** Discards the held response. The effect it describes remains. */
235
+ release(): void {
236
+ if (this.phase.state !== "committed") {
237
+ throw new ProviderError(409, "barrier_not_committed");
238
+ }
239
+ const { effectId, held } = this.phase;
240
+ this.phase = { state: "released", effectId };
241
+ held.discard();
242
+ }
243
+
244
+ /**
245
+ * Returns an armed barrier to idle so a later request is answered normally.
246
+ * Rejected in any other state: a committed barrier holds a response that
247
+ * only release may discard.
248
+ */
249
+ disarm(): void {
250
+ if (this.phase.state !== "armed") {
251
+ throw new ProviderError(409, "barrier_not_armed");
252
+ }
253
+ this.phase = { state: "idle" };
254
+ }
255
+
256
+ /** Returns to idle for a fresh run, discarding any held response. */
257
+ reset(): void {
258
+ const previous = this.phase;
259
+ this.phase = { state: "idle" };
260
+ if (previous.state === "committed") previous.held.discard();
261
+ }
262
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The provider's side of code locations. A backend's preload adds
3
+ * `x-mandateops-call` with a random id to each request for the provider; this
4
+ * module takes that header off the request before any other code reads it,
5
+ * so nothing past this point (authentication, key reading, records) ever
6
+ * sees it, and logs one line naming the id beside the effect the request
7
+ * made. The lab's provider is the end of the line: the header is never sent
8
+ * on to another host.
9
+ */
10
+ export const CALL_HEADER = "x-mandateops-call";
11
+ const LINE_PREFIX = "mandateops-provider-call ";
12
+ const CALL_ID =
13
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
14
+
15
+ type Headers = Record<string, string | string[] | undefined>;
16
+
17
+ /** Removes the header and returns its id, or null when absent or malformed. */
18
+ export function takeCallId(headers: Headers): string | null {
19
+ const value = headers[CALL_HEADER];
20
+ Reflect.deleteProperty(headers, CALL_HEADER);
21
+ return typeof value === "string" && CALL_ID.test(value) ? value : null;
22
+ }
23
+
24
+ /** The line one payment request leaves in the provider's log. */
25
+ export function callLine(call: string | null, effect: string | null): string {
26
+ return `${LINE_PREFIX}${JSON.stringify({ call, effect })}`;
27
+ }
@@ -0,0 +1,311 @@
1
+ import { z } from "zod";
2
+ import { wiseOptionsOf, wiseWire } from "./staged.js";
3
+ import { declaredWire } from "./declared.js";
4
+ import { nativeWire } from "./wire.js";
5
+ import type { PaymentWire } from "./wire.js";
6
+ import {
7
+ DEFAULT_IDEMPOTENCY_SCOPE,
8
+ DEFAULT_PROVIDER_NAME,
9
+ MAX_PROVIDERS,
10
+ DEFAULT_PROVIDER_ACCOUNT,
11
+ DEFAULT_PROVIDER_OPERATION,
12
+ idSchema,
13
+ MAX_RECORDS_PER_RUN,
14
+ RECORD_LIMIT_CEILING,
15
+ routeSchema,
16
+ } from "./domain.js";
17
+ import type { NotifyTarget } from "./notify.js";
18
+ import { loadProfile, replicaWire } from "./profile.js";
19
+ import type { CalibratedProfile } from "./profile.js";
20
+
21
+ /** A credential long enough for the hex key of a signed format. */
22
+ const paymentTokenSchema = z.string().min(32).max(4096);
23
+
24
+ const configSchema = z.object({
25
+ databaseUrl: z.url(),
26
+ paymentToken: paymentTokenSchema,
27
+ controlToken: z.string().min(32).max(128),
28
+ listenHost: z.enum(["127.0.0.1", "0.0.0.0"]),
29
+ port: z.coerce.number().int().min(1).max(65535),
30
+ providerAccount: idSchema,
31
+ providerOperation: idSchema,
32
+ idempotencyScope: idSchema,
33
+ rateLimitPerSecond: z.coerce.number().int().min(1).max(100_000),
34
+ requestTimeoutMs: z.coerce.number().int().min(1000).max(600_000),
35
+ bodyLimitBytes: z.coerce.number().int().min(1024).max(1_048_576),
36
+ rateWindowMs: z.coerce.number().int().min(100).max(60_000),
37
+ /** Bounds held sockets, as a held response may never time out. */
38
+ maxConnections: z.coerce.number().int().min(1).max(65_536),
39
+ poolConnections: z.coerce.number().int().min(1).max(100),
40
+ connectionTimeoutMs: z.coerce.number().int().min(100).max(60_000),
41
+ statementTimeoutMs: z.coerce.number().int().min(100).max(60_000),
42
+ idleTransactionTimeoutMs: z.coerce.number().int().min(100).max(60_000),
43
+ /** Records one run keeps; a scaled run raises it, nothing is dropped. */
44
+ recordLimit: z.coerce.number().int().min(1).max(RECORD_LIMIT_CEILING),
45
+ /** The host every payment must arrive through, when one is declared. */
46
+ proxyHost: z.string().min(1).max(253).optional(),
47
+ });
48
+ /**
49
+ * One provider of the run: its name in the list, the format it speaks, and
50
+ * how long it waits before committing the first request under each key.
51
+ */
52
+ export type ServedProvider = Readonly<{
53
+ name: string;
54
+ wire: PaymentWire;
55
+ commitDelayMs: number;
56
+ }>;
57
+
58
+ export type Config = Readonly<
59
+ z.infer<typeof configSchema> & {
60
+ /** Every provider of the run, in the order the run lists them. */
61
+ providers: readonly [ServedProvider, ...ServedProvider[]];
62
+ notifyTarget: NotifyTarget | undefined;
63
+ /** The calibrated profile the replica answers by, when one is loaded. */
64
+ profile?: CalibratedProfile | undefined;
65
+ /** Seeds the replica's choice among recorded race outcomes. */
66
+ raceSeed?: number | undefined;
67
+ }
68
+ >;
69
+
70
+ /** Hosts a notification may go to: the lab's own ingress, or this machine. */
71
+ const NOTIFY_HOSTS = ["gate-lab", "127.0.0.1", "localhost"];
72
+ const NOTIFY_TIMEOUT_MS = 5000;
73
+
74
+ /** Where notifications go and what signs them, as the deployment declares. */
75
+ type NotifySettings = Readonly<{
76
+ origin: string | undefined;
77
+ path: string | undefined;
78
+ secret: string | undefined;
79
+ tokens: readonly string[];
80
+ }>;
81
+
82
+ /**
83
+ * Where the backend takes notifications, when the deployment declares a
84
+ * path; otherwise none are sent. Only a plain HTTP origin of the lab is
85
+ * accepted, and a secret of its own, never a token, signs each delivery.
86
+ */
87
+ function notifyTargetFrom(settings: NotifySettings): NotifyTarget | undefined {
88
+ const { origin, path, tokens } = settings;
89
+ if (!path) return undefined;
90
+ const secret = z.string().min(32).max(256).parse(settings.secret);
91
+ if (tokens.includes(secret))
92
+ throw new Error("the notification secret must differ from every token");
93
+ const route = routeSchema.parse(path);
94
+ const base = new URL(z.url().parse(origin));
95
+ if (
96
+ base.protocol !== "http:" ||
97
+ base.username ||
98
+ base.password ||
99
+ base.search ||
100
+ base.hash ||
101
+ base.pathname !== "/" ||
102
+ !NOTIFY_HOSTS.includes(base.hostname)
103
+ )
104
+ throw new Error("notifications go only to the lab's own HTTP origin");
105
+ return { url: new URL(route, base), secret, timeoutMs: NOTIFY_TIMEOUT_MS };
106
+ }
107
+
108
+ const fromHex = (encoded: string): string =>
109
+ Buffer.from(encoded, "hex").toString("utf8");
110
+
111
+ const providerNamesSchema = z
112
+ .array(idSchema)
113
+ .min(1)
114
+ .max(MAX_PROVIDERS)
115
+ .refine((names) => new Set(names).size === names.length, "repeated name");
116
+
117
+ /** The run's provider names, comma-separated; one default provider if unset. */
118
+ const providerNamesFrom = (listed: string | undefined): readonly string[] =>
119
+ providerNamesSchema.parse(
120
+ listed ? listed.split(",") : [DEFAULT_PROVIDER_NAME],
121
+ );
122
+
123
+ /** The largest declared format, as compact JSON. */
124
+ const MAX_PROVIDER_WIRE_BYTES = 8192;
125
+ /** The largest list of every provider's format: one largest format each. */
126
+ export const MAX_PROVIDER_WIRES_BYTES = MAX_PROVIDER_WIRE_BYTES * MAX_PROVIDERS;
127
+ /** Lowercase hex, two digits per byte, as the host encodes its values. */
128
+ const hexSchema = z.string().regex(/^([0-9a-f]{2})*$/);
129
+ const wireHexSchema = hexSchema.max(MAX_PROVIDER_WIRES_BYTES * 2);
130
+ const listedSchema = z.array(
131
+ z.object({ name: idSchema, format: z.unknown() }).strict(),
132
+ );
133
+
134
+ /**
135
+ * The run's declared formats arrive hex-encoded as one JSON array of
136
+ * `{ name, format }` in list order, a `null` format for the lab's own, so no
137
+ * shell or env file reads them. Unset means every provider speaks the lab's
138
+ * own format. The names must be the run's, in its order.
139
+ */
140
+ function declarationsFrom(
141
+ encoded: string | undefined,
142
+ names: readonly string[],
143
+ ): readonly unknown[] {
144
+ if (!encoded) return names.map(() => null);
145
+ const listed = listedSchema.parse(
146
+ JSON.parse(fromHex(wireHexSchema.parse(encoded))),
147
+ );
148
+ if (
149
+ listed.length !== names.length ||
150
+ listed.some((provider, index) => provider.name !== names[index])
151
+ )
152
+ throw new Error("the declared formats must name the run's providers");
153
+ return listed.map((provider) => provider.format ?? null);
154
+ }
155
+
156
+ /**
157
+ * The credential of the provider at `index`: the first provider's is
158
+ * `PROVIDER_TOKEN`, each later one's `PROVIDER_TOKEN_<position>`, so no
159
+ * provider accepts another's.
160
+ */
161
+ function providerTokenFrom(
162
+ env: NodeJS.ProcessEnv,
163
+ index: number,
164
+ first: string,
165
+ ): string {
166
+ if (index === 0) return first;
167
+ return paymentTokenSchema.parse(env[`PROVIDER_TOKEN_${String(index + 1)}`]);
168
+ }
169
+
170
+ /** The longest a provider may wait before committing a key's first request. */
171
+ const MAX_COMMIT_DELAY_MS = 120_000;
172
+ const commitDelaySchema = z
173
+ .tuple([idSchema, z.coerce.number().int().min(1).max(MAX_COMMIT_DELAY_MS)])
174
+ .readonly();
175
+
176
+ /**
177
+ * Each listed provider's wait before committing a key's first request that a
178
+ * reply fault is armed for, from `name=milliseconds` pairs separated by
179
+ * commas; none for a provider unnamed.
180
+ * A delayed commit lets a run show what a backend does while a provider has
181
+ * neither paid nor refused.
182
+ */
183
+ function commitDelaysFrom(
184
+ listed: string | undefined,
185
+ names: readonly string[],
186
+ ): ReadonlyMap<string, number> {
187
+ if (!listed) return new Map();
188
+ const delays = new Map(
189
+ listed.split(",").map((pair) => commitDelaySchema.parse(pair.split("="))),
190
+ );
191
+ for (const name of delays.keys())
192
+ if (!names.includes(name))
193
+ throw new Error("a commit delay must name a provider of the run");
194
+ return delays;
195
+ }
196
+
197
+ /** One provider's wire from its declaration, untrusted until validated. */
198
+ function wireFrom(
199
+ declaration: unknown,
200
+ token: string,
201
+ profile: CalibratedProfile | undefined,
202
+ recordLimit: number,
203
+ ): PaymentWire {
204
+ if (declaration === null) return nativeWire(token);
205
+ const staged = z.object({ flow: z.string() }).safeParse(declaration).success;
206
+ if (!staged) return declaredWire(declaration, token);
207
+ return wiseWire(declaration, token, wiseOptionsOf(profile, recordLimit));
208
+ }
209
+
210
+ /**
211
+ * A calibrated profile, hex-encoded like the formats. It applies only to a
212
+ * run of one provider whose declared format names the same provider, so a
213
+ * Stripe profile can never shape a Wise replica or the lab's own format.
214
+ */
215
+ function profileFrom(
216
+ encoded: string | undefined,
217
+ declarations: readonly unknown[],
218
+ ): CalibratedProfile | undefined {
219
+ if (!encoded) return undefined;
220
+ const profile = loadProfile(fromHex(hexSchema.parse(encoded)));
221
+ if (declarations.length !== 1)
222
+ throw new Error("a profile applies to a run of one provider");
223
+ const declared = z
224
+ .object({ provider: z.string().optional() })
225
+ .loose()
226
+ .nullable()
227
+ .parse(declarations[0])?.provider;
228
+ if (declared !== profile.provider)
229
+ throw new Error("the profile's provider must match the declared format's");
230
+ return profile;
231
+ }
232
+
233
+ /**
234
+ * Only the local test lab is supported; configuration is never request
235
+ * input. These are the only defaults: an unset or empty setting takes one.
236
+ */
237
+ export function parseConfig(env: NodeJS.ProcessEnv): Config {
238
+ if (env["MANDATEOPS_LAB"] !== "1")
239
+ throw new Error("MANDATEOPS_LAB=1 is required");
240
+ const config = configSchema.parse({
241
+ databaseUrl: env["DATABASE_URL"],
242
+ paymentToken: env["PROVIDER_TOKEN"],
243
+ controlToken: env["PROVIDER_CONTROL_TOKEN"],
244
+ listenHost: env["LISTEN_HOST"] ?? "127.0.0.1",
245
+ port: env["PORT"] ?? "8080",
246
+ providerAccount: env["PROVIDER_ACCOUNT"] ?? DEFAULT_PROVIDER_ACCOUNT,
247
+ providerOperation: env["PROVIDER_OPERATION"] ?? DEFAULT_PROVIDER_OPERATION,
248
+ idempotencyScope:
249
+ env["PROVIDER_IDEMPOTENCY_SCOPE"] ?? DEFAULT_IDEMPOTENCY_SCOPE,
250
+ rateLimitPerSecond: env["PROVIDER_RATE_LIMIT"] || "1000",
251
+ requestTimeoutMs: env["PROVIDER_REQUEST_TIMEOUT_MS"] || "15000",
252
+ bodyLimitBytes: env["PROVIDER_BODY_LIMIT_BYTES"] || "8192",
253
+ rateWindowMs: env["PROVIDER_RATE_WINDOW_MS"] || "1000",
254
+ maxConnections: env["PROVIDER_MAX_CONNECTIONS"] || "256",
255
+ poolConnections: env["PROVIDER_POOL_CONNECTIONS"] || "5",
256
+ connectionTimeoutMs: env["PROVIDER_POOL_CONNECTION_TIMEOUT_MS"] || "2000",
257
+ statementTimeoutMs: env["PROVIDER_STATEMENT_TIMEOUT_MS"] || "3000",
258
+ idleTransactionTimeoutMs:
259
+ env["PROVIDER_IDLE_TRANSACTION_TIMEOUT_MS"] || "5000",
260
+ proxyHost: env["PROVIDER_PROXY_HOST"],
261
+ recordLimit: env["PROVIDER_RECORD_LIMIT"] || String(MAX_RECORDS_PER_RUN),
262
+ });
263
+ if (config.paymentToken === config.controlToken)
264
+ throw new Error("provider tokens must differ");
265
+ const names = providerNamesFrom(env["PROVIDER_NAMES"]);
266
+ const declarations = declarationsFrom(env["PROVIDER_WIRE"], names);
267
+ const profile = profileFrom(env["PROVIDER_PROFILE"], declarations);
268
+ const tokens = names.map((_name, index) =>
269
+ providerTokenFrom(env, index, config.paymentToken),
270
+ );
271
+ // No provider accepts another's credential, nor the runner's.
272
+ if (
273
+ tokens.includes(config.controlToken) ||
274
+ new Set(tokens).size !== tokens.length
275
+ )
276
+ throw new Error("provider tokens must differ");
277
+ const delays = commitDelaysFrom(env["PROVIDER_COMMIT_DELAYS"], names);
278
+ const served = names.map((name, index): ServedProvider => {
279
+ const declared = wireFrom(
280
+ declarations[index] ?? null,
281
+ tokens[index] ?? config.paymentToken,
282
+ profile,
283
+ config.recordLimit,
284
+ );
285
+ return {
286
+ name,
287
+ wire: profile ? replicaWire(declared, profile) : declared,
288
+ commitDelayMs: delays.get(name) ?? 0,
289
+ };
290
+ });
291
+ const [first, ...rest] = served;
292
+ if (!first) throw new Error("a run serves at least one provider");
293
+ const providers: Config["providers"] = [first, ...rest];
294
+ return Object.freeze({
295
+ ...config,
296
+ profile,
297
+ raceSeed: z.coerce
298
+ .number()
299
+ .int()
300
+ .min(0)
301
+ .max(2 ** 31)
302
+ .parse(env["PROVIDER_RACE_SEED"] || "1"),
303
+ providers,
304
+ notifyTarget: notifyTargetFrom({
305
+ origin: env["PROVIDER_NOTIFY_ORIGIN"],
306
+ path: env["PROVIDER_NOTIFY_PATH"],
307
+ secret: env["PROVIDER_NOTIFY_SECRET"],
308
+ tokens: [config.paymentToken, config.controlToken],
309
+ }),
310
+ });
311
+ }