@catamorphic/work-server 0.1.0-alpha.39 → 0.1.0-alpha.42
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/NOTICE.txt +7 -0
- package/README.md +9 -9
- package/dist/admission/routes.d.ts +1 -1
- package/dist/admission/routes.d.ts.map +1 -1
- package/dist/agent-capabilities.d.ts.map +1 -1
- package/dist/agents.d.ts +5 -6
- package/dist/agents.d.ts.map +1 -1
- package/dist/auth/fastify-auth.d.ts.map +1 -1
- package/dist/auth/work-auth-types.d.ts +2 -0
- package/dist/auth/work-auth-types.d.ts.map +1 -1
- package/dist/auth/work-auth.d.ts.map +1 -1
- package/dist/chunk-kcck20aw.js +676 -0
- package/dist/chunk-kcck20aw.js.map +11 -0
- package/dist/cluster.d.ts +8 -7
- package/dist/cluster.d.ts.map +1 -1
- package/dist/config.d.ts +5 -15
- package/dist/config.d.ts.map +1 -1
- package/dist/execution-config.d.ts +22 -0
- package/dist/execution-config.d.ts.map +1 -1
- package/dist/fake-agent.d.ts +1 -0
- package/dist/fake-agent.d.ts.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2730 -2851
- package/dist/index.js.map +28 -28
- package/dist/machines/contract-kit.d.ts +91 -0
- package/dist/machines/contract-kit.d.ts.map +1 -0
- package/dist/machines/contract.d.ts +383 -0
- package/dist/machines/contract.d.ts.map +1 -0
- package/dist/machines/sequencer.d.ts +267 -0
- package/dist/machines/sequencer.d.ts.map +1 -0
- package/dist/machines/simulation.d.ts +124 -0
- package/dist/machines/simulation.d.ts.map +1 -0
- package/dist/machines/work-machines.d.ts +61 -0
- package/dist/machines/work-machines.d.ts.map +1 -0
- package/dist/server.d.ts +15 -11
- package/dist/server.d.ts.map +1 -1
- package/dist/setup/machines.d.ts +9 -17
- package/dist/setup/machines.d.ts.map +1 -1
- package/dist/shares/share-routes.d.ts +1 -1
- package/dist/shares/share-routes.d.ts.map +1 -1
- package/dist/testing.d.ts +8 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +1013 -0
- package/dist/testing.js.map +11 -0
- package/dist/workers/disk-care.d.ts +41 -0
- package/dist/workers/disk-care.d.ts.map +1 -0
- package/dist/workers/harness-sign-ins.d.ts +146 -0
- package/dist/workers/harness-sign-ins.d.ts.map +1 -0
- package/dist/workers/machine-store.d.ts +196 -0
- package/dist/workers/machine-store.d.ts.map +1 -0
- package/dist/workers/member-machine-routes.d.ts +5 -3
- package/dist/workers/member-machine-routes.d.ts.map +1 -1
- package/dist/workers/member-machines.d.ts +47 -28
- package/dist/workers/member-machines.d.ts.map +1 -1
- package/dist/workers/placement.d.ts +23 -40
- package/dist/workers/placement.d.ts.map +1 -1
- package/dist/workers/sign-ins.d.ts +44 -17
- package/dist/workers/sign-ins.d.ts.map +1 -1
- package/dist/workers/worker-protocol.d.ts +5 -2
- package/dist/workers/worker-protocol.d.ts.map +1 -1
- package/dist/workers/worker-registry.d.ts +174 -223
- package/dist/workers/worker-registry.d.ts.map +1 -1
- package/dist/workers/worker-routes.d.ts.map +1 -1
- package/dist/workers/worker-runtime.d.ts.map +1 -1
- package/package.json +31 -21
- package/src/admission/routes.ts +5 -2
- package/src/agent-capabilities.ts +22 -8
- package/src/agents.ts +52 -23
- package/src/auth/fastify-auth.ts +149 -17
- package/src/auth/work-auth-types.ts +2 -0
- package/src/auth/work-auth.ts +27 -0
- package/src/cluster.ts +115 -42
- package/src/config.ts +15 -41
- package/src/execution-config.ts +40 -0
- package/src/fake-agent.ts +21 -4
- package/src/index.ts +26 -12
- package/src/machines/contract-kit.ts +648 -0
- package/src/machines/contract.ts +522 -0
- package/src/machines/sequencer.ts +1010 -0
- package/src/machines/simulation.ts +833 -0
- package/src/machines/work-machines.ts +231 -0
- package/src/server.ts +235 -150
- package/src/setup/machines.ts +128 -121
- package/src/shares/share-routes.ts +17 -1
- package/src/testing.ts +22 -0
- package/src/workers/disk-care.ts +121 -0
- package/src/workers/fake-claude-cli.ts +95 -0
- package/src/workers/fake-codex-cli.ts +11 -4
- package/src/workers/harness-sign-ins.ts +580 -0
- package/src/workers/machine-store.ts +1065 -0
- package/src/workers/member-machine-routes.ts +92 -20
- package/src/workers/member-machines.ts +163 -99
- package/src/workers/placement.ts +59 -70
- package/src/workers/sign-ins.ts +109 -52
- package/src/workers/worker-protocol.ts +5 -2
- package/src/workers/worker-registry.ts +894 -754
- package/src/workers/worker-routes.ts +4 -1
- package/src/workers/worker-runtime.ts +55 -23
- package/dist/test-support.d.ts +0 -133
- package/dist/test-support.d.ts.map +0 -1
- package/dist/workers/codex-sign-ins.d.ts +0 -107
- package/dist/workers/codex-sign-ins.d.ts.map +0 -1
- package/dist/workers/install-script.d.ts +0 -71
- package/dist/workers/install-script.d.ts.map +0 -1
- package/dist/workers/machine-classes.d.ts +0 -115
- package/dist/workers/machine-classes.d.ts.map +0 -1
- package/dist/workers/machine-rules.d.ts +0 -402
- package/dist/workers/machine-rules.d.ts.map +0 -1
- package/src/test-support.ts +0 -404
- package/src/workers/codex-sign-ins.ts +0 -360
- package/src/workers/install-script.ts +0 -394
- package/src/workers/machine-classes.ts +0 -152
- package/src/workers/machine-rules.ts +0 -1954
|
@@ -0,0 +1,648 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type {
|
|
3
|
+
DesiredMachine,
|
|
4
|
+
MachineCreateRequest,
|
|
5
|
+
MachinePlanFacts,
|
|
6
|
+
MachinesHook,
|
|
7
|
+
MachineTarget,
|
|
8
|
+
PersonFacts,
|
|
9
|
+
WaitingWork,
|
|
10
|
+
} from "./contract.js";
|
|
11
|
+
import { MachinePlanSchema } from "./contract.js";
|
|
12
|
+
import { canonical } from "./sequencer.js";
|
|
13
|
+
import {
|
|
14
|
+
type SimulatedCall,
|
|
15
|
+
SimulatedWork,
|
|
16
|
+
type SimulatedWorkOptions,
|
|
17
|
+
} from "./simulation.js";
|
|
18
|
+
|
|
19
|
+
/*
|
|
20
|
+
* The machines hook contract kit (ADR 0349). It runs a host's hook against
|
|
21
|
+
* a simulated Work with a fake clock and checks what Work relies on: names
|
|
22
|
+
* are stable, the plan converges and does not flap, no machine is made
|
|
23
|
+
* twice under retries or a lost answer, nothing holding live work is
|
|
24
|
+
* stopped or destroyed, verbs are idempotent, and a lost machine is
|
|
25
|
+
* replaced. A failure says what happened and what to change.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/** A check failed. Its message says what happened and what to change. */
|
|
29
|
+
export class MachinesContractError extends Error {
|
|
30
|
+
constructor(
|
|
31
|
+
readonly check: string,
|
|
32
|
+
message: string,
|
|
33
|
+
) {
|
|
34
|
+
super(`machines hook contract: ${check}\n${message}`);
|
|
35
|
+
this.name = "MachinesContractError";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function fail(check: string, lines: readonly string[]): never {
|
|
40
|
+
throw new MachinesContractError(check, lines.join("\n"));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The provisioner half of a hook: the calls that touch the host's cloud. */
|
|
44
|
+
export type MachineProvisioner = Pick<
|
|
45
|
+
MachinesHook,
|
|
46
|
+
"create" | "destroy" | "stop" | "start" | "describe"
|
|
47
|
+
>;
|
|
48
|
+
|
|
49
|
+
/** A hook from a plan and a provisioner, as hosts compose them. */
|
|
50
|
+
export function machinesHook(args: {
|
|
51
|
+
plan: MachinesHook["plan"];
|
|
52
|
+
provisioner: MachineProvisioner;
|
|
53
|
+
onEvent?: MachinesHook["onEvent"];
|
|
54
|
+
}): MachinesHook {
|
|
55
|
+
return {
|
|
56
|
+
plan: args.plan,
|
|
57
|
+
...args.provisioner,
|
|
58
|
+
...(args.onEvent ? { onEvent: args.onEvent } : {}),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** One machine in a {@link MemoryCloud}. */
|
|
63
|
+
export interface MemoryCloudMachine {
|
|
64
|
+
ref: string;
|
|
65
|
+
name: string;
|
|
66
|
+
idempotencyKey: string;
|
|
67
|
+
state: "running" | "stopped" | "gone";
|
|
68
|
+
options: Readonly<Record<string, unknown>>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* An in-memory cloud for tests of a plan: a provisioner that keeps its
|
|
73
|
+
* machines in a list, honors idempotency keys, stops, starts and
|
|
74
|
+
* describes. `kill` ends a machine as a cloud would (a Spot reclaim, a
|
|
75
|
+
* terminated instance).
|
|
76
|
+
*/
|
|
77
|
+
export class MemoryCloud {
|
|
78
|
+
readonly machines: MemoryCloudMachine[] = [];
|
|
79
|
+
/** Answers `create` gives instead of making a machine, in order. */
|
|
80
|
+
readonly refusals: string[] = [];
|
|
81
|
+
private count = 0;
|
|
82
|
+
|
|
83
|
+
/** Machines that still exist. */
|
|
84
|
+
alive(): MemoryCloudMachine[] {
|
|
85
|
+
return this.machines.filter((machine) => machine.state !== "gone");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
kill(ref: string): void {
|
|
89
|
+
const machine = this.machines.find((entry) => entry.ref === ref);
|
|
90
|
+
if (machine) machine.state = "gone";
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
provisioner(options: { stoppable?: boolean } = {}): MachineProvisioner {
|
|
94
|
+
const find = (target: MachineTarget) =>
|
|
95
|
+
this.machines.filter(
|
|
96
|
+
(machine) =>
|
|
97
|
+
machine.state !== "gone" &&
|
|
98
|
+
(machine.ref === target.ref ||
|
|
99
|
+
(target.idempotencyKey !== null &&
|
|
100
|
+
machine.idempotencyKey === target.idempotencyKey)),
|
|
101
|
+
);
|
|
102
|
+
const stoppable = options.stoppable ?? true;
|
|
103
|
+
return {
|
|
104
|
+
create: async (request) => {
|
|
105
|
+
const key = request.enrollment.idempotencyKey;
|
|
106
|
+
const existing = this.machines.find(
|
|
107
|
+
(machine) => machine.idempotencyKey === key,
|
|
108
|
+
);
|
|
109
|
+
if (existing) return { ref: existing.ref };
|
|
110
|
+
const refusal = this.refusals.shift();
|
|
111
|
+
if (refusal) return { refused: refusal };
|
|
112
|
+
this.count += 1;
|
|
113
|
+
const ref = `memory-${this.count}`;
|
|
114
|
+
this.machines.push({
|
|
115
|
+
ref,
|
|
116
|
+
name: request.name,
|
|
117
|
+
idempotencyKey: key,
|
|
118
|
+
state: "running",
|
|
119
|
+
options: request.options,
|
|
120
|
+
});
|
|
121
|
+
return { ref };
|
|
122
|
+
},
|
|
123
|
+
destroy: async (target) => {
|
|
124
|
+
for (const machine of find(target)) machine.state = "gone";
|
|
125
|
+
return { done: true };
|
|
126
|
+
},
|
|
127
|
+
...(stoppable
|
|
128
|
+
? {
|
|
129
|
+
stop: async (target: MachineTarget) => {
|
|
130
|
+
for (const machine of find(target)) machine.state = "stopped";
|
|
131
|
+
return { done: true };
|
|
132
|
+
},
|
|
133
|
+
start: async (target: MachineTarget) => {
|
|
134
|
+
const machines = find(target);
|
|
135
|
+
if (machines.length === 0) return { gone: true as const };
|
|
136
|
+
for (const machine of machines) machine.state = "running";
|
|
137
|
+
return { done: true };
|
|
138
|
+
},
|
|
139
|
+
}
|
|
140
|
+
: {}),
|
|
141
|
+
describe: async (target) => {
|
|
142
|
+
const machine = find(target)[0];
|
|
143
|
+
return { state: machine ? machine.state : ("gone" as const) };
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** What a provisioner check knows about the cloud behind it, when a test can say. */
|
|
150
|
+
export interface PlatformProbe {
|
|
151
|
+
/** How many machines exist on the platform right now (running or stopped). */
|
|
152
|
+
count(): Promise<number> | number;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function requestFor(args: {
|
|
156
|
+
name: string;
|
|
157
|
+
options: Readonly<Record<string, unknown>>;
|
|
158
|
+
labels: Readonly<Record<string, string>>;
|
|
159
|
+
generation: number;
|
|
160
|
+
}): MachineCreateRequest {
|
|
161
|
+
const code = `wke_contract_${args.name}_${args.generation}`;
|
|
162
|
+
return {
|
|
163
|
+
name: args.name,
|
|
164
|
+
options: args.options,
|
|
165
|
+
labels: args.labels,
|
|
166
|
+
enrollment: {
|
|
167
|
+
controlPlaneUrl: "https://work.example.test",
|
|
168
|
+
code,
|
|
169
|
+
idempotencyKey: createHash("sha256").update(code).digest("hex"),
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Repeat a verb as Work does, until it answers what `until` accepts. */
|
|
175
|
+
async function repeat<T>(args: {
|
|
176
|
+
check: string;
|
|
177
|
+
what: string;
|
|
178
|
+
call: () => Promise<T>;
|
|
179
|
+
until: (answer: T) => boolean;
|
|
180
|
+
attempts?: number;
|
|
181
|
+
between?: () => Promise<void> | void;
|
|
182
|
+
hint: string;
|
|
183
|
+
}): Promise<T> {
|
|
184
|
+
let answer = await args.call();
|
|
185
|
+
for (let index = 1; index < (args.attempts ?? 20); index += 1) {
|
|
186
|
+
if (args.until(answer)) return answer;
|
|
187
|
+
await args.between?.();
|
|
188
|
+
answer = await args.call();
|
|
189
|
+
}
|
|
190
|
+
if (args.until(answer)) return answer;
|
|
191
|
+
return fail(args.check, [
|
|
192
|
+
`${args.what} never finished: after ${args.attempts ?? 20} calls it still answered ${JSON.stringify(answer)}.`,
|
|
193
|
+
args.hint,
|
|
194
|
+
]);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Check a provisioner's verbs directly, as Work calls them: `create` twice
|
|
199
|
+
* with one key makes one machine, `stop` and `start` (when it has them)
|
|
200
|
+
* may be repeated, `destroy` may be repeated and removes a machine whose
|
|
201
|
+
* create answer was lost. Pass `platform` when the test can count the
|
|
202
|
+
* machines behind it, and `between` to let a fake cloud's time pass
|
|
203
|
+
* between repeats.
|
|
204
|
+
*/
|
|
205
|
+
export async function checkMachineProvisioner(args: {
|
|
206
|
+
provisioner: MachineProvisioner;
|
|
207
|
+
/** The options a plan would give these machines. */
|
|
208
|
+
options?: Readonly<Record<string, unknown>>;
|
|
209
|
+
labels?: Readonly<Record<string, string>>;
|
|
210
|
+
platform?: PlatformProbe;
|
|
211
|
+
/** Runs between repeats of a verb: move a fake cloud's clock here. */
|
|
212
|
+
between?: () => Promise<void> | void;
|
|
213
|
+
/** The name the check's machine gets. */
|
|
214
|
+
name?: string;
|
|
215
|
+
}): Promise<void> {
|
|
216
|
+
const { provisioner, platform } = args;
|
|
217
|
+
const name = args.name ?? "contract-check-1";
|
|
218
|
+
const options = args.options ?? {};
|
|
219
|
+
const labels = args.labels ?? {};
|
|
220
|
+
const between = args.between ?? (() => {});
|
|
221
|
+
const before = platform ? await platform.count() : 0;
|
|
222
|
+
const request = requestFor({ name, options, labels, generation: 1 });
|
|
223
|
+
|
|
224
|
+
// create: repeated with one key until it answers a ref.
|
|
225
|
+
const created = await repeat({
|
|
226
|
+
check: "create answers a ref",
|
|
227
|
+
what: "create",
|
|
228
|
+
call: () => provisioner.create(request),
|
|
229
|
+
until: (answer) => !("pending" in answer),
|
|
230
|
+
between,
|
|
231
|
+
hint: "Answer { pending: true } only while the machine is on its way, then { ref } with the platform's id. Answer { refused: reason } when the platform made nothing.",
|
|
232
|
+
});
|
|
233
|
+
if ("refused" in created)
|
|
234
|
+
fail("create answers a ref", [
|
|
235
|
+
`create refused: ${created.refused}.`,
|
|
236
|
+
"The check needs one machine made: give it options and a fake cloud that can make one.",
|
|
237
|
+
]);
|
|
238
|
+
if (!("ref" in created)) return;
|
|
239
|
+
const again = await provisioner.create(request);
|
|
240
|
+
if (!("ref" in again) || again.ref !== created.ref)
|
|
241
|
+
fail("create is idempotent", [
|
|
242
|
+
`Called twice with the same idempotencyKey, create answered ${JSON.stringify(created)} and then ${JSON.stringify(again)}.`,
|
|
243
|
+
"Work repeats create with one key until it hears a ref, and after a lost answer. Hand enrollment.idempotencyKey to the platform as its idempotency token (EC2 ClientToken, a unique name or label elsewhere), and when a machine with that key exists, return its ref instead of making another.",
|
|
244
|
+
]);
|
|
245
|
+
if (platform && (await platform.count()) !== before + 1)
|
|
246
|
+
fail("create is idempotent", [
|
|
247
|
+
`After two creates with one idempotencyKey the platform has ${(await platform.count()) - before} machine(s); it must have exactly 1.`,
|
|
248
|
+
"Hand enrollment.idempotencyKey to the platform as its idempotency token so a repeated create makes nothing new.",
|
|
249
|
+
]);
|
|
250
|
+
const target: MachineTarget = {
|
|
251
|
+
name,
|
|
252
|
+
ref: created.ref,
|
|
253
|
+
idempotencyKey: request.enrollment.idempotencyKey,
|
|
254
|
+
options,
|
|
255
|
+
labels,
|
|
256
|
+
};
|
|
257
|
+
|
|
258
|
+
if (provisioner.describe) {
|
|
259
|
+
const described = await provisioner.describe(target);
|
|
260
|
+
if (described.state === "gone" || described.state === "stopped")
|
|
261
|
+
fail("describe sees a machine create made", [
|
|
262
|
+
`Right after create, describe answered ${JSON.stringify(described)} for ref ${created.ref}.`,
|
|
263
|
+
'Answer "running" for a machine that exists and is not stopped (starting counts), "unknown" when the platform cannot say, and "gone" only when it certainly no longer exists: Work treats "gone" as a loss and makes the machine again.',
|
|
264
|
+
]);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const requestedAt = new Date().toISOString();
|
|
268
|
+
const { stop, start } = provisioner;
|
|
269
|
+
if (stop && !start)
|
|
270
|
+
fail("stop comes with start", [
|
|
271
|
+
"The provisioner has stop but no start.",
|
|
272
|
+
"A machine Work stopped could never serve again. Add start, or remove stop so no plan can stop a machine.",
|
|
273
|
+
]);
|
|
274
|
+
if (stop && start) {
|
|
275
|
+
const stopped = await repeat({
|
|
276
|
+
check: "stop finishes",
|
|
277
|
+
what: "stop",
|
|
278
|
+
call: () => stop({ ...target, requestedAt }),
|
|
279
|
+
until: (answer) => answer.done,
|
|
280
|
+
between,
|
|
281
|
+
hint: "Answer { done: false } while the machine is stopping and { done: true } once it is stopped with its disk kept.",
|
|
282
|
+
});
|
|
283
|
+
const stoppedAgain = await stop({ ...target, requestedAt });
|
|
284
|
+
if (!stopped.done || !stoppedAgain.done)
|
|
285
|
+
fail("stop is idempotent", [
|
|
286
|
+
`stop on a machine that is already stopped answered ${JSON.stringify(stoppedAgain)}.`,
|
|
287
|
+
"Work repeats stop until it is done and may repeat it after: stopping a stopped machine answers { done: true } and changes nothing.",
|
|
288
|
+
]);
|
|
289
|
+
if (provisioner.describe) {
|
|
290
|
+
const described = await provisioner.describe(target);
|
|
291
|
+
if (described.state === "gone")
|
|
292
|
+
fail("stop keeps the machine", [
|
|
293
|
+
'After stop, describe answered "gone".',
|
|
294
|
+
"stop must keep the machine and its disk (worker identity, sign-ins, volumes, caches) so start brings the same machine back. Do not terminate on stop, and do not offer stop for machines that cannot be stopped (EC2 Spot without a persistent request).",
|
|
295
|
+
]);
|
|
296
|
+
}
|
|
297
|
+
const started = await repeat({
|
|
298
|
+
check: "start finishes",
|
|
299
|
+
what: "start",
|
|
300
|
+
call: () => start({ ...target, requestedAt }),
|
|
301
|
+
until: (answer) => "gone" in answer || answer.done,
|
|
302
|
+
between,
|
|
303
|
+
hint: "Answer { done: false } while the machine is starting, { done: true } once the platform runs it, and { gone: true } when it no longer exists.",
|
|
304
|
+
});
|
|
305
|
+
if ("gone" in started)
|
|
306
|
+
fail("start brings back a stopped machine", [
|
|
307
|
+
"start answered { gone: true } for a machine stop had just stopped.",
|
|
308
|
+
"stop must keep the machine and its disk. Answer { gone: true } from start only when the machine no longer exists.",
|
|
309
|
+
]);
|
|
310
|
+
const startedAgain = await start({ ...target, requestedAt });
|
|
311
|
+
if ("gone" in startedAgain || !startedAgain.done)
|
|
312
|
+
fail("start is idempotent", [
|
|
313
|
+
`start on a machine that is already running answered ${JSON.stringify(startedAgain)}.`,
|
|
314
|
+
"Starting a running machine answers { done: true } and changes nothing.",
|
|
315
|
+
]);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// destroy: repeated until done, then harmless.
|
|
319
|
+
await repeat({
|
|
320
|
+
check: "destroy finishes",
|
|
321
|
+
what: "destroy",
|
|
322
|
+
call: () => provisioner.destroy({ ...target, requestedAt }),
|
|
323
|
+
until: (answer) => answer.done,
|
|
324
|
+
attempts: 60,
|
|
325
|
+
between,
|
|
326
|
+
hint: "Answer { done: false } while the machine is going and { done: true } once none with this ref, key or name is left. Work forgets the machine only then.",
|
|
327
|
+
});
|
|
328
|
+
const destroyedAgain = await provisioner.destroy({ ...target, requestedAt });
|
|
329
|
+
if (!destroyedAgain.done)
|
|
330
|
+
fail("destroy is idempotent", [
|
|
331
|
+
`destroy on a machine that is already gone answered ${JSON.stringify(destroyedAgain)}.`,
|
|
332
|
+
"Destroying a machine that no longer exists answers { done: true }.",
|
|
333
|
+
]);
|
|
334
|
+
if (platform && (await platform.count()) !== before)
|
|
335
|
+
fail("destroy removes the machine", [
|
|
336
|
+
`After destroy answered done, the platform still has ${(await platform.count()) - before} machine(s) from this check.`,
|
|
337
|
+
"Answer { done: true } only once the machine is gone.",
|
|
338
|
+
]);
|
|
339
|
+
if (start) {
|
|
340
|
+
const gone = await start({ ...target, requestedAt });
|
|
341
|
+
if (!("gone" in gone))
|
|
342
|
+
fail("start says when a machine is gone", [
|
|
343
|
+
`start on a destroyed machine answered ${JSON.stringify(gone)}.`,
|
|
344
|
+
"Answer { gone: true } when the machine no longer exists: Work then treats it as lost and makes it again, instead of waiting for a worker that never connects.",
|
|
345
|
+
]);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// A create whose answer was lost: destroy must find it without a ref.
|
|
349
|
+
const orphan = requestFor({ name, options, labels, generation: 2 });
|
|
350
|
+
const made = await repeat({
|
|
351
|
+
check: "create answers a ref",
|
|
352
|
+
what: "create",
|
|
353
|
+
call: () => provisioner.create(orphan),
|
|
354
|
+
until: (answer) => !("pending" in answer),
|
|
355
|
+
between,
|
|
356
|
+
hint: "Answer { ref } once the machine exists.",
|
|
357
|
+
});
|
|
358
|
+
if (!("ref" in made)) return;
|
|
359
|
+
if (made.ref === created.ref)
|
|
360
|
+
fail("a new enrollment makes a new machine", [
|
|
361
|
+
`A create with a new idempotencyKey answered the destroyed machine's ref ${made.ref}.`,
|
|
362
|
+
"Key machines by enrollment.idempotencyKey, never by name alone: a later machine reuses the name of one that is gone.",
|
|
363
|
+
]);
|
|
364
|
+
await repeat({
|
|
365
|
+
check: "destroy finds a machine whose ref was never recorded",
|
|
366
|
+
what: "destroy with ref: null",
|
|
367
|
+
call: () =>
|
|
368
|
+
provisioner.destroy({
|
|
369
|
+
name,
|
|
370
|
+
ref: null,
|
|
371
|
+
idempotencyKey: orphan.enrollment.idempotencyKey,
|
|
372
|
+
options,
|
|
373
|
+
labels,
|
|
374
|
+
requestedAt,
|
|
375
|
+
}),
|
|
376
|
+
until: (answer) => answer.done,
|
|
377
|
+
attempts: 60,
|
|
378
|
+
between,
|
|
379
|
+
hint: "When ref is null, find the machine by idempotencyKey (and by name), destroy it, and answer { done: true } only once nothing is left.",
|
|
380
|
+
});
|
|
381
|
+
if (platform && (await platform.count()) !== before)
|
|
382
|
+
fail("destroy finds a machine whose ref was never recorded", [
|
|
383
|
+
`After destroy with ref: null answered done, the platform still has ${(await platform.count()) - before} machine(s).`,
|
|
384
|
+
"A create whose answer was lost leaves a machine Work knows only by its idempotencyKey and name. destroy must look it up by those and remove it.",
|
|
385
|
+
]);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Facts a plan is checked with. */
|
|
389
|
+
export interface ContractFacts {
|
|
390
|
+
people?: readonly PersonFacts[];
|
|
391
|
+
/** Work that waits when the check starts. */
|
|
392
|
+
work?: ReadonlyArray<Partial<Omit<WaitingWork, "id">> & { project: string }>;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function names(plan: readonly DesiredMachine[]): string[] {
|
|
396
|
+
return plan.map((machine) => machine.name).sort();
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function creates(calls: readonly SimulatedCall[]): SimulatedCall[] {
|
|
400
|
+
return calls.filter((call) => call.verb === "create");
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Check a whole hook against a simulated Work. Give it facts under which
|
|
405
|
+
* the plan wants at least one machine (people, waiting work). Throws a
|
|
406
|
+
* {@link MachinesContractError} that reads as an instruction.
|
|
407
|
+
*/
|
|
408
|
+
export async function checkMachinesHook(args: {
|
|
409
|
+
hook: MachinesHook;
|
|
410
|
+
facts?: ContractFacts;
|
|
411
|
+
/** Runs whenever the simulated clock moves: move a fake cloud's clock too. */
|
|
412
|
+
onAdvance?: (now: string) => Promise<void> | void;
|
|
413
|
+
/** End a machine on the platform as a cloud would, so its loss is real. */
|
|
414
|
+
kill?: (machine: {
|
|
415
|
+
name: string;
|
|
416
|
+
ref: string | null;
|
|
417
|
+
}) => Promise<void> | void;
|
|
418
|
+
simulation?: Omit<SimulatedWorkOptions, "hook" | "people">;
|
|
419
|
+
}): Promise<void> {
|
|
420
|
+
const { hook } = args;
|
|
421
|
+
const sim = new SimulatedWork({
|
|
422
|
+
...args.simulation,
|
|
423
|
+
hook,
|
|
424
|
+
...(args.facts?.people ? { people: args.facts.people } : {}),
|
|
425
|
+
});
|
|
426
|
+
for (const work of args.facts?.work ?? []) sim.addWork(work);
|
|
427
|
+
const advance = async (time: { seconds?: number; minutes?: number }) => {
|
|
428
|
+
sim.advance(time);
|
|
429
|
+
await args.onAdvance?.(sim.now);
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
// 1. The same facts give the same plan.
|
|
433
|
+
const facts: MachinePlanFacts = {
|
|
434
|
+
now: sim.now,
|
|
435
|
+
work: [...sim.waiting()],
|
|
436
|
+
machines: sim.facts(),
|
|
437
|
+
people: sim.people,
|
|
438
|
+
};
|
|
439
|
+
const first = MachinePlanSchema.safeParse(await hook.plan(facts));
|
|
440
|
+
const second = MachinePlanSchema.safeParse(await hook.plan(facts));
|
|
441
|
+
if (!first.success || !second.success) {
|
|
442
|
+
const issue = (first.success ? second : first).error?.issues[0];
|
|
443
|
+
fail("plan returns valid machines", [
|
|
444
|
+
`plan returned something Work cannot use${issue ? `: ${issue.path.join(".") || "result"}: ${issue.message}` : ""}.`,
|
|
445
|
+
"Return an array of { name, for?, labels?, state?, options?, trusted?, lostAfterMinutes?, reason? }. Names are lowercase letters, digits and dashes, at most 63 characters, each once.",
|
|
446
|
+
]);
|
|
447
|
+
}
|
|
448
|
+
if (canonical(first.data) !== canonical(second.data))
|
|
449
|
+
fail("plan is stable", [
|
|
450
|
+
`Asked twice with the same facts, plan returned [${names(first.data).join(", ")}] and then [${names(second.data).join(", ")}] (or the same names with different settings).`,
|
|
451
|
+
"Work matches machines by name: a name that changes is a machine destroyed and another created. Derive every name from something that lasts (a user id, a project id, a chat key, a slot number), never from the time, a counter or randomness.",
|
|
452
|
+
]);
|
|
453
|
+
if (first.data.length === 0)
|
|
454
|
+
fail("the check has something to check", [
|
|
455
|
+
"With the facts given, plan wants no machine.",
|
|
456
|
+
"Pass facts under which it wants at least one: people with the roles it looks for, or waiting work it serves (checkMachinesHook({ hook, facts: { people, work } })).",
|
|
457
|
+
]);
|
|
458
|
+
|
|
459
|
+
// 2. A lost create answer never makes a second machine.
|
|
460
|
+
sim.loseNextCreateAnswer();
|
|
461
|
+
await sim.pass();
|
|
462
|
+
await advance({ seconds: 10 });
|
|
463
|
+
await sim.pass();
|
|
464
|
+
const byName = new Map<string, SimulatedCall[]>();
|
|
465
|
+
for (const call of creates(sim.calls))
|
|
466
|
+
byName.set(call.name, [...(byName.get(call.name) ?? []), call]);
|
|
467
|
+
for (const [name, calls] of byName) {
|
|
468
|
+
const keys = new Set(calls.map((call) => call.idempotencyKey));
|
|
469
|
+
const refs = new Set(
|
|
470
|
+
calls.flatMap((call) => {
|
|
471
|
+
const answer = call.answer;
|
|
472
|
+
return answer && typeof answer === "object" && "ref" in answer
|
|
473
|
+
? [String(answer.ref)]
|
|
474
|
+
: [];
|
|
475
|
+
}),
|
|
476
|
+
);
|
|
477
|
+
if (keys.size === 1 && refs.size > 1)
|
|
478
|
+
fail("no machine is made twice", [
|
|
479
|
+
`create was repeated for '${name}' with one idempotencyKey (its first answer was lost) and answered different refs: ${[...refs].join(", ")}.`,
|
|
480
|
+
"The platform now has two machines for one name. Hand enrollment.idempotencyKey to the platform as its idempotency token, and return the existing machine's ref when one was already made with that key.",
|
|
481
|
+
]);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// 3. The plan settles and then stays put.
|
|
485
|
+
const settled = await settleWith({ sim, advance, limit: 40 });
|
|
486
|
+
if (!settled)
|
|
487
|
+
fail("plan converges", [
|
|
488
|
+
`After 40 passes over ${Math.round((40 * 30) / 60)} simulated minutes, with no fact changed from outside, the hook was still being asked to change machines. The latest calls: ${recent(sim.calls)}.`,
|
|
489
|
+
"A plan must settle: once the machines it asked for exist, it asks for the same set again. Look for a name that depends on a machine's own state (so reaching that state renames it), or a machine dropped because of a fact the drop itself changes back.",
|
|
490
|
+
]);
|
|
491
|
+
const settledAt = sim.calls.length;
|
|
492
|
+
for (let index = 0; index < 5; index += 1) {
|
|
493
|
+
await advance({ seconds: 10 });
|
|
494
|
+
await sim.pass();
|
|
495
|
+
}
|
|
496
|
+
const after = sim.calls
|
|
497
|
+
.slice(settledAt)
|
|
498
|
+
.filter((call) => call.verb === "create" || call.verb === "destroy");
|
|
499
|
+
if (after.length > 0)
|
|
500
|
+
fail("plan does not flap", [
|
|
501
|
+
`Nothing changed, yet within a simulated minute the plan had machines made or destroyed: ${recent(after)}.`,
|
|
502
|
+
"Keep a machine while the reason for it holds. If the plan drops machines that are idle, give them an idle time of minutes, not seconds, and measure it from the machine's own idleSince.",
|
|
503
|
+
]);
|
|
504
|
+
for (const [name, calls] of groupByName(creates(sim.calls))) {
|
|
505
|
+
const keys = new Set(calls.map((call) => call.idempotencyKey));
|
|
506
|
+
if (keys.size > 1)
|
|
507
|
+
fail("plan does not flap", [
|
|
508
|
+
`'${name}' was created ${keys.size} times (under ${keys.size} enrollments) while nothing changed from outside.`,
|
|
509
|
+
'The plan dropped a machine and asked for it again. Decide from facts that stay the same while a machine starts: a machine in state "starting" is on its way, not missing.',
|
|
510
|
+
]);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// 4. Nothing holding live work is stopped or destroyed out of band.
|
|
514
|
+
const serving = sim
|
|
515
|
+
.facts()
|
|
516
|
+
.filter((machine) => machine.managed && machine.state === "serving");
|
|
517
|
+
if (hook.describe) {
|
|
518
|
+
const describe = hook.describe.bind(hook);
|
|
519
|
+
for (const machine of serving) {
|
|
520
|
+
if (machine.holding.workspaces === 0) continue;
|
|
521
|
+
const described = await describe({
|
|
522
|
+
name: machine.name,
|
|
523
|
+
ref: machine.ref,
|
|
524
|
+
idempotencyKey: null,
|
|
525
|
+
options: machine.options,
|
|
526
|
+
labels: machine.labels,
|
|
527
|
+
});
|
|
528
|
+
if (described.state === "gone" || described.state === "stopped")
|
|
529
|
+
fail("nothing holding live work is stopped or destroyed", [
|
|
530
|
+
`'${machine.name}' holds ${machine.holding.workspaces} live workspace(s) and Work never asked to stop or destroy it, yet describe says it is ${described.state}.`,
|
|
531
|
+
"Something in the hook removed it: a sweep by tag or name prefix, a time limit enforced inside create or plan. Only stop and destroy end machines, and Work calls them once a machine holds no live work (or is lost).",
|
|
532
|
+
]);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// 5. A lost machine is replaced, under a new enrollment.
|
|
537
|
+
const victim = serving[0];
|
|
538
|
+
if (victim) {
|
|
539
|
+
const before = creates(sim.calls).filter(
|
|
540
|
+
(call) => call.name === victim.name,
|
|
541
|
+
);
|
|
542
|
+
const oldKey = before[before.length - 1]?.idempotencyKey ?? null;
|
|
543
|
+
sim.lose(victim.name);
|
|
544
|
+
await args.kill?.({ name: victim.name, ref: victim.ref });
|
|
545
|
+
for (let index = 0; index < 30; index += 1) {
|
|
546
|
+
await advance({ minutes: 1 });
|
|
547
|
+
await sim.pass();
|
|
548
|
+
const now = sim.machine(victim.name);
|
|
549
|
+
if (now?.state === "serving" && now.ref !== victim.ref) break;
|
|
550
|
+
if (!now && !(await wants({ hook, sim, name: victim.name }))) break;
|
|
551
|
+
}
|
|
552
|
+
const destroyed = sim.calls.some(
|
|
553
|
+
(call) =>
|
|
554
|
+
call.verb === "destroy" &&
|
|
555
|
+
call.name === victim.name &&
|
|
556
|
+
answerDone(call.answer),
|
|
557
|
+
);
|
|
558
|
+
if (!destroyed)
|
|
559
|
+
fail("a lost machine is destroyed", [
|
|
560
|
+
`'${victim.name}' stopped calling and was lost, but destroy never answered { done: true } for it in 30 simulated minutes. Its latest answers: ${recent(sim.calls.filter((call) => call.verb === "destroy" && call.name === victim.name))}.`,
|
|
561
|
+
"Work asks destroy for a lost machine until it is done, so nothing is left running on the platform. Answer { done: true } once the machine is gone, including when it is gone already.",
|
|
562
|
+
]);
|
|
563
|
+
if (await wants({ hook, sim, name: victim.name })) {
|
|
564
|
+
const remade = creates(sim.calls).filter(
|
|
565
|
+
(call) => call.name === victim.name && call.idempotencyKey !== oldKey,
|
|
566
|
+
);
|
|
567
|
+
const now = sim.machine(victim.name);
|
|
568
|
+
if (remade.length === 0 || now?.state !== "serving")
|
|
569
|
+
fail("a lost machine is replaced", [
|
|
570
|
+
`The plan still names '${victim.name}' after it was lost, but 30 simulated minutes later it is ${now ? now.state : "not there"}${now?.lastError ? ` (${now.lastError.verb}: ${now.lastError.message})` : ""}.`,
|
|
571
|
+
"Work destroys what is left of a lost machine and creates it again under a new enrollment and idempotencyKey. create must make a new machine for the new key although the name is the same, and destroy must not answer done before the old one is gone.",
|
|
572
|
+
]);
|
|
573
|
+
const refs = new Set(
|
|
574
|
+
remade.flatMap((call) => {
|
|
575
|
+
const answer = call.answer;
|
|
576
|
+
return answer && typeof answer === "object" && "ref" in answer
|
|
577
|
+
? [String(answer.ref)]
|
|
578
|
+
: [];
|
|
579
|
+
}),
|
|
580
|
+
);
|
|
581
|
+
if (victim.ref !== null && refs.has(victim.ref))
|
|
582
|
+
fail("a lost machine is replaced", [
|
|
583
|
+
`The replacement for '${victim.name}' got the lost machine's ref ${victim.ref} back.`,
|
|
584
|
+
"Key a create by enrollment.idempotencyKey, not by name: a new key is a new machine.",
|
|
585
|
+
]);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
async function wants(args: {
|
|
591
|
+
hook: MachinesHook;
|
|
592
|
+
sim: SimulatedWork;
|
|
593
|
+
name: string;
|
|
594
|
+
}): Promise<boolean> {
|
|
595
|
+
const plan = MachinePlanSchema.safeParse(
|
|
596
|
+
await args.hook.plan({
|
|
597
|
+
now: args.sim.now,
|
|
598
|
+
work: [...args.sim.waiting()],
|
|
599
|
+
machines: args.sim.facts(),
|
|
600
|
+
people: args.sim.people,
|
|
601
|
+
}),
|
|
602
|
+
);
|
|
603
|
+
return (
|
|
604
|
+
plan.success && plan.data.some((machine) => machine.name === args.name)
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async function settleWith(args: {
|
|
609
|
+
sim: SimulatedWork;
|
|
610
|
+
advance: (time: { seconds?: number }) => Promise<void>;
|
|
611
|
+
limit: number;
|
|
612
|
+
}): Promise<boolean> {
|
|
613
|
+
for (let index = 0; index < args.limit; index += 1) {
|
|
614
|
+
const { quiet } = await args.sim.settle({ limit: 1 });
|
|
615
|
+
if (quiet) return true;
|
|
616
|
+
await args.advance({ seconds: 30 });
|
|
617
|
+
}
|
|
618
|
+
return false;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function groupByName(
|
|
622
|
+
calls: readonly SimulatedCall[],
|
|
623
|
+
): Map<string, SimulatedCall[]> {
|
|
624
|
+
const grouped = new Map<string, SimulatedCall[]>();
|
|
625
|
+
for (const call of calls)
|
|
626
|
+
grouped.set(call.name, [...(grouped.get(call.name) ?? []), call]);
|
|
627
|
+
return grouped;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function answerDone(answer: unknown): boolean {
|
|
631
|
+
return (
|
|
632
|
+
typeof answer === "object" &&
|
|
633
|
+
answer !== null &&
|
|
634
|
+
"done" in answer &&
|
|
635
|
+
answer.done === true
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
function recent(calls: readonly SimulatedCall[]): string {
|
|
640
|
+
if (calls.length === 0) return "none";
|
|
641
|
+
return calls
|
|
642
|
+
.slice(-6)
|
|
643
|
+
.map(
|
|
644
|
+
(call) =>
|
|
645
|
+
`${call.verb} ${call.name} -> ${call.error ? `threw ${call.error}` : JSON.stringify(call.answer)}`,
|
|
646
|
+
)
|
|
647
|
+
.join("; ");
|
|
648
|
+
}
|