@catamorphic/work-server 0.1.0-alpha.38 → 0.1.0-alpha.41
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 +44 -34
- 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
package/dist/testing.js
ADDED
|
@@ -0,0 +1,1013 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_LOST_AFTER_MINUTES2,
|
|
3
|
+
MachinePlanSchema,
|
|
4
|
+
normalizePrincipals,
|
|
5
|
+
machineStateOf,
|
|
6
|
+
lostAfterMsOf,
|
|
7
|
+
runMachinePass,
|
|
8
|
+
machineTakes,
|
|
9
|
+
canonical
|
|
10
|
+
} from "./chunk-kcck20aw.js";
|
|
11
|
+
|
|
12
|
+
// src/machines/contract-kit.ts
|
|
13
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
14
|
+
|
|
15
|
+
// src/machines/simulation.ts
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
17
|
+
class SimulatedWork {
|
|
18
|
+
options;
|
|
19
|
+
calls = [];
|
|
20
|
+
events = [];
|
|
21
|
+
planError = null;
|
|
22
|
+
people;
|
|
23
|
+
clock;
|
|
24
|
+
machines = new Map;
|
|
25
|
+
waitingWork = [];
|
|
26
|
+
waitingFor = new Map;
|
|
27
|
+
workCount = 0;
|
|
28
|
+
generations = 0;
|
|
29
|
+
neverConnect = new Set;
|
|
30
|
+
answerLost = false;
|
|
31
|
+
constructor(options) {
|
|
32
|
+
this.options = options;
|
|
33
|
+
this.clock = Date.parse(options.start ?? "2026-01-01T00:00:00.000Z");
|
|
34
|
+
this.people = [...options.people ?? []];
|
|
35
|
+
}
|
|
36
|
+
get now() {
|
|
37
|
+
return new Date(this.clock).toISOString();
|
|
38
|
+
}
|
|
39
|
+
facts() {
|
|
40
|
+
return this.records().map((record) => record.facts);
|
|
41
|
+
}
|
|
42
|
+
machine(name) {
|
|
43
|
+
return this.facts().find((machine) => machine.name === name);
|
|
44
|
+
}
|
|
45
|
+
waiting() {
|
|
46
|
+
return this.waitingWork;
|
|
47
|
+
}
|
|
48
|
+
startingFor(workId) {
|
|
49
|
+
return this.waitingFor.get(workId);
|
|
50
|
+
}
|
|
51
|
+
placedOn(workId) {
|
|
52
|
+
for (const machine of this.machines.values())
|
|
53
|
+
if (machine.holding.some((work) => work.id === workId))
|
|
54
|
+
return machine.name;
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
addWork(work) {
|
|
58
|
+
this.workCount += 1;
|
|
59
|
+
const added = {
|
|
60
|
+
id: `work-${this.workCount}`,
|
|
61
|
+
kind: "chat",
|
|
62
|
+
user: null,
|
|
63
|
+
key: null,
|
|
64
|
+
environment: "default",
|
|
65
|
+
pool: {},
|
|
66
|
+
requirements: { resources: {}, capabilities: [] },
|
|
67
|
+
reason: "unavailable",
|
|
68
|
+
waitingSince: this.now,
|
|
69
|
+
...work
|
|
70
|
+
};
|
|
71
|
+
this.waitingWork.push(added);
|
|
72
|
+
this.place();
|
|
73
|
+
return added;
|
|
74
|
+
}
|
|
75
|
+
finishWork(workId) {
|
|
76
|
+
this.waitingWork = this.waitingWork.filter((work) => work.id !== workId);
|
|
77
|
+
for (const machine of this.machines.values()) {
|
|
78
|
+
const before = machine.holding.length;
|
|
79
|
+
machine.holding = machine.holding.filter((work) => work.id !== workId);
|
|
80
|
+
if (machine.holding.length < before)
|
|
81
|
+
machine.lastReleasedAt = this.clock;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
enrollByHand(args) {
|
|
85
|
+
const machine = this.blank({
|
|
86
|
+
name: args.name,
|
|
87
|
+
managed: false,
|
|
88
|
+
for: args.for === undefined ? null : normalizePrincipals(args.for),
|
|
89
|
+
labels: args.labels ?? {},
|
|
90
|
+
trusted: args.trusted ?? false,
|
|
91
|
+
options: {},
|
|
92
|
+
lostAfterMinutes: null,
|
|
93
|
+
reason: null
|
|
94
|
+
});
|
|
95
|
+
machine.connectsAt = this.clock + this.bootMs;
|
|
96
|
+
this.machines.set(args.name, machine);
|
|
97
|
+
}
|
|
98
|
+
lose(name) {
|
|
99
|
+
const machine = this.require(name);
|
|
100
|
+
machine.alive = false;
|
|
101
|
+
machine.connectsAt = null;
|
|
102
|
+
}
|
|
103
|
+
revive(name) {
|
|
104
|
+
const machine = this.require(name);
|
|
105
|
+
if (machine.phase !== "running" || machine.revoked)
|
|
106
|
+
return;
|
|
107
|
+
machine.alive = true;
|
|
108
|
+
machine.lastSeenAt = this.clock;
|
|
109
|
+
}
|
|
110
|
+
neverConnects(name) {
|
|
111
|
+
this.neverConnect.add(name);
|
|
112
|
+
}
|
|
113
|
+
setDisabled(name, disabled) {
|
|
114
|
+
this.require(name).disabledAt = disabled ? this.clock : null;
|
|
115
|
+
}
|
|
116
|
+
loseNextCreateAnswer() {
|
|
117
|
+
this.answerLost = true;
|
|
118
|
+
}
|
|
119
|
+
advance(args) {
|
|
120
|
+
const until = this.clock + (args.seconds ?? 0) * 1000 + (args.minutes ?? 0) * 60000;
|
|
121
|
+
while (this.clock < until) {
|
|
122
|
+
this.clock = Math.min(until, this.clock + 5000);
|
|
123
|
+
this.tick();
|
|
124
|
+
}
|
|
125
|
+
this.tick();
|
|
126
|
+
}
|
|
127
|
+
async pass() {
|
|
128
|
+
this.tick();
|
|
129
|
+
const summary = await runMachinePass({
|
|
130
|
+
hook: this.recordingHook(),
|
|
131
|
+
world: this.world(),
|
|
132
|
+
verbTimeoutMs: 5000,
|
|
133
|
+
planTimeoutMs: 5000
|
|
134
|
+
});
|
|
135
|
+
this.tick();
|
|
136
|
+
return summary;
|
|
137
|
+
}
|
|
138
|
+
async settle(args = {}) {
|
|
139
|
+
const passes = [];
|
|
140
|
+
for (let index = 0;index < (args.limit ?? 40); index += 1) {
|
|
141
|
+
const before = this.calls.length;
|
|
142
|
+
const summary = await this.pass();
|
|
143
|
+
passes.push(summary);
|
|
144
|
+
const verbs = this.calls.slice(before).filter((call) => call.verb !== "describe");
|
|
145
|
+
if (verbs.length === 0 && quietSummary(summary) && !this.transient())
|
|
146
|
+
return { quiet: true, passes };
|
|
147
|
+
this.advance({ seconds: args.seconds ?? 30 });
|
|
148
|
+
}
|
|
149
|
+
return { quiet: false, passes };
|
|
150
|
+
}
|
|
151
|
+
transient() {
|
|
152
|
+
return [...this.machines.values()].some((machine) => machine.phase === "stopping" || machine.phase === "destroying" || machine.phase === "resuming" && machine.alive === false || machine.phase === "starting" && machine.connectsAt !== null && !this.neverConnect.has(machine.name));
|
|
153
|
+
}
|
|
154
|
+
get bootMs() {
|
|
155
|
+
return (this.options.bootSeconds ?? 60) * 1000;
|
|
156
|
+
}
|
|
157
|
+
require(name) {
|
|
158
|
+
const machine = this.machines.get(name);
|
|
159
|
+
if (!machine)
|
|
160
|
+
throw new Error(`The simulation has no machine '${name}'`);
|
|
161
|
+
return machine;
|
|
162
|
+
}
|
|
163
|
+
blank(args) {
|
|
164
|
+
return {
|
|
165
|
+
...args,
|
|
166
|
+
ref: null,
|
|
167
|
+
enrollment: null,
|
|
168
|
+
generation: 0,
|
|
169
|
+
phase: "starting",
|
|
170
|
+
phaseSince: this.clock,
|
|
171
|
+
startAskedAt: null,
|
|
172
|
+
refused: null,
|
|
173
|
+
droppedAt: null,
|
|
174
|
+
disabledAt: null,
|
|
175
|
+
reset: null,
|
|
176
|
+
notice: null,
|
|
177
|
+
lastError: null,
|
|
178
|
+
destroyRequestedAt: null,
|
|
179
|
+
revoked: false,
|
|
180
|
+
alive: false,
|
|
181
|
+
connectsAt: null,
|
|
182
|
+
lastSeenAt: null,
|
|
183
|
+
holding: [],
|
|
184
|
+
lastReleasedAt: null,
|
|
185
|
+
resets: 0
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
newEnrollment(machine) {
|
|
189
|
+
this.generations += 1;
|
|
190
|
+
machine.generation = this.generations;
|
|
191
|
+
const code = `wke_simulated_${machine.name}_${this.generations}`;
|
|
192
|
+
machine.enrollment = {
|
|
193
|
+
code,
|
|
194
|
+
idempotencyKey: createHash("sha256").update(code).digest("hex")
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
live(machine) {
|
|
198
|
+
return machine.alive && !machine.revoked && machine.disabledAt === null && (machine.phase === "running" || machine.phase === "resuming");
|
|
199
|
+
}
|
|
200
|
+
tick() {
|
|
201
|
+
for (const machine of this.machines.values()) {
|
|
202
|
+
if (machine.connectsAt !== null && machine.connectsAt <= this.clock && !this.neverConnect.has(machine.name) && machine.disabledAt === null && (machine.phase === "starting" || machine.phase === "resuming")) {
|
|
203
|
+
const kind = machine.phase === "starting" ? "machine.connected" : "machine.started";
|
|
204
|
+
machine.phase = "running";
|
|
205
|
+
machine.phaseSince = this.clock;
|
|
206
|
+
machine.startAskedAt = null;
|
|
207
|
+
machine.alive = true;
|
|
208
|
+
machine.connectsAt = null;
|
|
209
|
+
this.emit(kind, machine);
|
|
210
|
+
}
|
|
211
|
+
if (this.live(machine))
|
|
212
|
+
machine.lastSeenAt = this.clock;
|
|
213
|
+
}
|
|
214
|
+
this.place();
|
|
215
|
+
}
|
|
216
|
+
place() {
|
|
217
|
+
const capacity = this.options.workspacesPerMachine ?? 4;
|
|
218
|
+
const isolation = this.options.isolation ?? "sandbox";
|
|
219
|
+
this.waitingWork = this.waitingWork.filter((work) => {
|
|
220
|
+
const takers = [...this.machines.values()].filter((machine) => machine.phase === "running" && this.live(machine) && machine.droppedAt === null && machine.reset === null && machine.holding.length < capacity && (machine.trusted || isolation === "sandbox" || machine.for !== null && machine.for.length === 1) && machineTakes(machine, work)).sort((left, right) => (left.for?.length ?? Number.POSITIVE_INFINITY) - (right.for?.length ?? Number.POSITIVE_INFINITY));
|
|
221
|
+
const taker = takers[0];
|
|
222
|
+
if (!taker)
|
|
223
|
+
return true;
|
|
224
|
+
taker.holding.push(work);
|
|
225
|
+
this.waitingFor.delete(work.id);
|
|
226
|
+
return false;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
emit(kind, machine) {
|
|
230
|
+
const event = {
|
|
231
|
+
kind,
|
|
232
|
+
at: this.now,
|
|
233
|
+
machine: {
|
|
234
|
+
name: machine.name,
|
|
235
|
+
ref: machine.ref,
|
|
236
|
+
managed: machine.managed,
|
|
237
|
+
labels: machine.labels,
|
|
238
|
+
for: machine.for,
|
|
239
|
+
options: machine.options,
|
|
240
|
+
reason: machine.reason
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
this.events.push(event);
|
|
244
|
+
Promise.resolve(this.options.hook.onEvent?.(event)).catch(() => {});
|
|
245
|
+
}
|
|
246
|
+
records() {
|
|
247
|
+
const capacity = this.options.workspacesPerMachine ?? 4;
|
|
248
|
+
return [...this.machines.values()].sort((left, right) => left.name.localeCompare(right.name)).map((machine) => {
|
|
249
|
+
const seen = machine.lastSeenAt ?? machine.phaseSince;
|
|
250
|
+
const state = machineStateOf({
|
|
251
|
+
phase: machine.phase,
|
|
252
|
+
dropped: machine.droppedAt !== null,
|
|
253
|
+
disabled: machine.disabledAt !== null,
|
|
254
|
+
live: this.live(machine),
|
|
255
|
+
unseenForMs: this.clock - seen,
|
|
256
|
+
lostAfterMs: lostAfterMsOf({
|
|
257
|
+
lostAfterMinutes: machine.lostAfterMinutes,
|
|
258
|
+
defaultMinutes: DEFAULT_LOST_AFTER_MINUTES2
|
|
259
|
+
}),
|
|
260
|
+
startAskedForMs: machine.startAskedAt === null ? null : this.clock - machine.startAskedAt
|
|
261
|
+
});
|
|
262
|
+
const since = state === "unreachable" || state === "lost" ? machine.phase === "resuming" ? machine.startAskedAt ?? seen : seen : state === "disabled" ? machine.disabledAt ?? machine.phaseSince : state === "draining" ? machine.droppedAt ?? machine.phaseSince : machine.phaseSince;
|
|
263
|
+
const connected = machine.phase !== "starting";
|
|
264
|
+
const facts = {
|
|
265
|
+
name: machine.name,
|
|
266
|
+
ref: machine.ref,
|
|
267
|
+
managed: machine.managed,
|
|
268
|
+
state,
|
|
269
|
+
since: iso(since),
|
|
270
|
+
labels: machine.labels,
|
|
271
|
+
for: machine.for,
|
|
272
|
+
trusted: machine.trusted,
|
|
273
|
+
options: machine.options,
|
|
274
|
+
reason: machine.reason,
|
|
275
|
+
holding: {
|
|
276
|
+
workspaces: machine.holding.length,
|
|
277
|
+
for: normalizePrincipals(machine.holding.map((work) => work.user !== null ? { user: work.user } : work.key !== null ? { project: work.project, key: work.key } : { project: work.project }))
|
|
278
|
+
},
|
|
279
|
+
idleSince: (state === "serving" || state === "draining") && machine.holding.length === 0 ? iso(Math.max(machine.phaseSince, machine.lastReleasedAt ?? 0)) : null,
|
|
280
|
+
lastSeenAt: machine.lastSeenAt === null ? null : iso(machine.lastSeenAt),
|
|
281
|
+
capacity: connected ? { workspaces: capacity } : null,
|
|
282
|
+
usage: connected ? {
|
|
283
|
+
workspaces: machine.holding.length,
|
|
284
|
+
cpuMillis: 0,
|
|
285
|
+
memoryMb: 0,
|
|
286
|
+
storageMb: 0
|
|
287
|
+
} : null,
|
|
288
|
+
disk: null,
|
|
289
|
+
isolation: connected ? this.options.isolation ?? "sandbox" : null,
|
|
290
|
+
signedIn: [],
|
|
291
|
+
notice: machine.notice,
|
|
292
|
+
lastError: machine.lastError ? {
|
|
293
|
+
verb: machine.lastError.verb,
|
|
294
|
+
message: machine.lastError.message,
|
|
295
|
+
at: iso(machine.lastError.at)
|
|
296
|
+
} : null
|
|
297
|
+
};
|
|
298
|
+
return {
|
|
299
|
+
facts,
|
|
300
|
+
phase: machine.phase,
|
|
301
|
+
phaseSince: iso(machine.phaseSince),
|
|
302
|
+
idempotencyKey: machine.enrollment?.idempotencyKey ?? null,
|
|
303
|
+
dropped: machine.droppedAt !== null,
|
|
304
|
+
refused: machine.refused ? { count: machine.refused.count, at: iso(machine.refused.at) } : null,
|
|
305
|
+
reset: machine.reset,
|
|
306
|
+
startAsked: machine.startAskedAt !== null,
|
|
307
|
+
destroyRequestedAt: machine.destroyRequestedAt === null ? null : iso(machine.destroyRequestedAt),
|
|
308
|
+
lostAfterMinutes: machine.lostAfterMinutes,
|
|
309
|
+
revoked: machine.revoked
|
|
310
|
+
};
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
recordingHook() {
|
|
314
|
+
const { hook } = this.options;
|
|
315
|
+
const record = async (call, run) => {
|
|
316
|
+
const entry = { ...call, at: this.now };
|
|
317
|
+
this.calls.push(entry);
|
|
318
|
+
try {
|
|
319
|
+
const answer = await run();
|
|
320
|
+
entry.answer = answer;
|
|
321
|
+
return answer;
|
|
322
|
+
} catch (error) {
|
|
323
|
+
entry.error = error instanceof Error ? error.message : String(error);
|
|
324
|
+
throw error;
|
|
325
|
+
}
|
|
326
|
+
};
|
|
327
|
+
const target = (args) => ({
|
|
328
|
+
name: args.name,
|
|
329
|
+
ref: args.ref,
|
|
330
|
+
idempotencyKey: args.idempotencyKey
|
|
331
|
+
});
|
|
332
|
+
const stop = hook.stop?.bind(hook);
|
|
333
|
+
const start = hook.start?.bind(hook);
|
|
334
|
+
const describe = hook.describe?.bind(hook);
|
|
335
|
+
return {
|
|
336
|
+
plan: (facts) => hook.plan(facts),
|
|
337
|
+
create: async (request) => {
|
|
338
|
+
const entry = {
|
|
339
|
+
verb: "create",
|
|
340
|
+
name: request.name,
|
|
341
|
+
ref: null,
|
|
342
|
+
idempotencyKey: request.enrollment.idempotencyKey,
|
|
343
|
+
at: this.now
|
|
344
|
+
};
|
|
345
|
+
this.calls.push(entry);
|
|
346
|
+
const answer = await hook.create(request).catch((error) => {
|
|
347
|
+
entry.error = error instanceof Error ? error.message : String(error);
|
|
348
|
+
throw error;
|
|
349
|
+
});
|
|
350
|
+
entry.answer = answer;
|
|
351
|
+
if (this.answerLost) {
|
|
352
|
+
this.answerLost = false;
|
|
353
|
+
entry.error = "simulated: the answer was lost on its way back";
|
|
354
|
+
throw new Error("simulated: the answer to create was lost on its way back");
|
|
355
|
+
}
|
|
356
|
+
return answer;
|
|
357
|
+
},
|
|
358
|
+
destroy: (args) => record({ verb: "destroy", ...target(args) }, () => hook.destroy(args)),
|
|
359
|
+
...stop ? {
|
|
360
|
+
stop: (args) => record({ verb: "stop", ...target(args) }, () => stop(args))
|
|
361
|
+
} : {},
|
|
362
|
+
...start ? {
|
|
363
|
+
start: (args) => record({ verb: "start", ...target(args) }, () => start(args))
|
|
364
|
+
} : {},
|
|
365
|
+
...describe ? {
|
|
366
|
+
describe: (args) => record({ verb: "describe", ...target(args) }, () => describe(args))
|
|
367
|
+
} : {}
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
world() {
|
|
371
|
+
const set = (name, change) => {
|
|
372
|
+
const machine = this.machines.get(name);
|
|
373
|
+
if (machine)
|
|
374
|
+
change(machine);
|
|
375
|
+
};
|
|
376
|
+
const phase = (machine, next) => {
|
|
377
|
+
machine.phase = next;
|
|
378
|
+
machine.phaseSince = this.clock;
|
|
379
|
+
machine.startAskedAt = null;
|
|
380
|
+
};
|
|
381
|
+
const condemn = (machine) => {
|
|
382
|
+
phase(machine, "destroying");
|
|
383
|
+
machine.destroyRequestedAt ??= this.clock;
|
|
384
|
+
machine.revoked = true;
|
|
385
|
+
machine.alive = false;
|
|
386
|
+
machine.connectsAt = null;
|
|
387
|
+
for (const work of machine.holding)
|
|
388
|
+
this.waitingWork.push({ ...work, waitingSince: this.now });
|
|
389
|
+
machine.holding = [];
|
|
390
|
+
};
|
|
391
|
+
return {
|
|
392
|
+
controlPlaneUrl: this.options.controlPlaneUrl ?? "https://work.example.test",
|
|
393
|
+
now: async () => this.now,
|
|
394
|
+
records: async () => this.records(),
|
|
395
|
+
work: async () => [...this.waitingWork],
|
|
396
|
+
people: async () => [...this.people],
|
|
397
|
+
intend: async ({ machine: planned }) => {
|
|
398
|
+
if (this.machines.has(planned.name))
|
|
399
|
+
return false;
|
|
400
|
+
const machine = this.blank({
|
|
401
|
+
name: planned.name,
|
|
402
|
+
managed: true,
|
|
403
|
+
for: planned.for,
|
|
404
|
+
labels: planned.labels,
|
|
405
|
+
trusted: planned.trusted,
|
|
406
|
+
options: planned.options,
|
|
407
|
+
lostAfterMinutes: planned.lostAfterMinutes,
|
|
408
|
+
reason: planned.reason
|
|
409
|
+
});
|
|
410
|
+
this.newEnrollment(machine);
|
|
411
|
+
this.machines.set(planned.name, machine);
|
|
412
|
+
return true;
|
|
413
|
+
},
|
|
414
|
+
enrollment: async ({ name }) => this.machines.get(name)?.enrollment ?? null,
|
|
415
|
+
reissue: async ({ name }) => set(name, (machine) => {
|
|
416
|
+
if (machine.managed && !machine.enrollment && machine.phase === "starting")
|
|
417
|
+
this.newEnrollment(machine);
|
|
418
|
+
}),
|
|
419
|
+
created: async ({ name, ref }) => set(name, (machine) => {
|
|
420
|
+
machine.ref = ref;
|
|
421
|
+
machine.refused = null;
|
|
422
|
+
if (machine.phase === "starting")
|
|
423
|
+
machine.connectsAt ??= this.clock + this.bootMs;
|
|
424
|
+
}),
|
|
425
|
+
refused: async ({ name, reason }) => set(name, (machine) => {
|
|
426
|
+
machine.enrollment = null;
|
|
427
|
+
machine.refused = {
|
|
428
|
+
count: (machine.refused?.count ?? 0) + 1,
|
|
429
|
+
at: this.clock
|
|
430
|
+
};
|
|
431
|
+
machine.lastError = {
|
|
432
|
+
verb: "create",
|
|
433
|
+
message: `Its platform refused: ${reason}`,
|
|
434
|
+
at: this.clock
|
|
435
|
+
};
|
|
436
|
+
}),
|
|
437
|
+
configure: async ({ name, ...settings }) => set(name, (machine) => {
|
|
438
|
+
machine.labels = settings.labels;
|
|
439
|
+
machine.trusted = settings.trusted;
|
|
440
|
+
machine.reason = settings.reason;
|
|
441
|
+
machine.lostAfterMinutes = settings.lostAfterMinutes;
|
|
442
|
+
}),
|
|
443
|
+
setFor: async ({ name, for: principals }) => set(name, (machine) => {
|
|
444
|
+
machine.for = principals;
|
|
445
|
+
machine.reset = null;
|
|
446
|
+
}),
|
|
447
|
+
beginReset: async ({ name, for: principals }) => set(name, (machine) => {
|
|
448
|
+
machine.reset = { for: principals };
|
|
449
|
+
}),
|
|
450
|
+
reset: async ({ name }) => {
|
|
451
|
+
const machine = this.require(name);
|
|
452
|
+
if (!this.live(machine))
|
|
453
|
+
return "offline";
|
|
454
|
+
if (machine.holding.length > 0)
|
|
455
|
+
return "busy";
|
|
456
|
+
machine.for = machine.reset?.for ?? machine.for;
|
|
457
|
+
machine.reset = null;
|
|
458
|
+
machine.resets += 1;
|
|
459
|
+
return "done";
|
|
460
|
+
},
|
|
461
|
+
drop: async ({ name }) => set(name, (machine) => {
|
|
462
|
+
machine.droppedAt ??= this.clock;
|
|
463
|
+
}),
|
|
464
|
+
undrop: async ({ name }) => set(name, (machine) => {
|
|
465
|
+
machine.droppedAt = null;
|
|
466
|
+
}),
|
|
467
|
+
retire: async ({ name }) => {
|
|
468
|
+
const machine = this.require(name);
|
|
469
|
+
if (machine.holding.length > 0 && !machine.revoked)
|
|
470
|
+
return false;
|
|
471
|
+
condemn(machine);
|
|
472
|
+
return true;
|
|
473
|
+
},
|
|
474
|
+
declareLost: async ({ name, unseenForMs }) => {
|
|
475
|
+
const machine = this.require(name);
|
|
476
|
+
if (this.live(machine) && machine.phase === "running")
|
|
477
|
+
return false;
|
|
478
|
+
const seen = machine.lastSeenAt ?? machine.phaseSince;
|
|
479
|
+
if (machine.phase === "running" && this.clock - seen < unseenForMs)
|
|
480
|
+
return false;
|
|
481
|
+
condemn(machine);
|
|
482
|
+
return true;
|
|
483
|
+
},
|
|
484
|
+
beginStop: async ({ name }) => {
|
|
485
|
+
const machine = this.require(name);
|
|
486
|
+
if (machine.holding.length > 0 || machine.phase !== "running")
|
|
487
|
+
return false;
|
|
488
|
+
phase(machine, "stopping");
|
|
489
|
+
return true;
|
|
490
|
+
},
|
|
491
|
+
stopped: async ({ name }) => set(name, (machine) => {
|
|
492
|
+
phase(machine, "stopped");
|
|
493
|
+
machine.alive = false;
|
|
494
|
+
}),
|
|
495
|
+
beginResume: async ({ name }) => {
|
|
496
|
+
const machine = this.require(name);
|
|
497
|
+
if (machine.phase !== "stopped")
|
|
498
|
+
return false;
|
|
499
|
+
phase(machine, "resuming");
|
|
500
|
+
return true;
|
|
501
|
+
},
|
|
502
|
+
startAsked: async ({ name }) => set(name, (machine) => {
|
|
503
|
+
machine.startAskedAt = this.clock;
|
|
504
|
+
machine.connectsAt = this.clock + this.bootMs;
|
|
505
|
+
}),
|
|
506
|
+
forget: async ({ name }) => {
|
|
507
|
+
this.machines.delete(name);
|
|
508
|
+
},
|
|
509
|
+
note: async ({ name, notice }) => set(name, (machine) => {
|
|
510
|
+
machine.notice = notice;
|
|
511
|
+
}),
|
|
512
|
+
failed: async ({ name, verb, message }) => set(name, (machine) => {
|
|
513
|
+
machine.lastError = { verb, message, at: this.clock };
|
|
514
|
+
}),
|
|
515
|
+
succeeded: async ({ name, verb }) => set(name, (machine) => {
|
|
516
|
+
if (machine.lastError?.verb === verb)
|
|
517
|
+
machine.lastError = null;
|
|
518
|
+
}),
|
|
519
|
+
event: async (event) => {
|
|
520
|
+
this.events.push(event);
|
|
521
|
+
await Promise.resolve(this.options.hook.onEvent?.(event)).catch(() => {});
|
|
522
|
+
},
|
|
523
|
+
planned: async ({ error }) => {
|
|
524
|
+
this.planError = error;
|
|
525
|
+
},
|
|
526
|
+
waiting: async ({ machines }) => {
|
|
527
|
+
this.waitingFor.clear();
|
|
528
|
+
for (const [work, machine] of machines)
|
|
529
|
+
this.waitingFor.set(work, machine);
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
resetsOf(name) {
|
|
534
|
+
return this.machines.get(name)?.resets ?? 0;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
function iso(time) {
|
|
538
|
+
return new Date(time).toISOString();
|
|
539
|
+
}
|
|
540
|
+
function quietSummary(summary) {
|
|
541
|
+
return summary.planError === undefined && summary.created.length + summary.updated.length + summary.reset.length + summary.released.length + summary.lost.length + summary.stopped.length + summary.resumed.length + summary.destroying.length + summary.destroyed.length + summary.failed.length === 0;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// src/machines/contract-kit.ts
|
|
545
|
+
class MachinesContractError extends Error {
|
|
546
|
+
check;
|
|
547
|
+
constructor(check, message) {
|
|
548
|
+
super(`machines hook contract: ${check}
|
|
549
|
+
${message}`);
|
|
550
|
+
this.check = check;
|
|
551
|
+
this.name = "MachinesContractError";
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
function fail(check, lines) {
|
|
555
|
+
throw new MachinesContractError(check, lines.join(`
|
|
556
|
+
`));
|
|
557
|
+
}
|
|
558
|
+
function machinesHook(args) {
|
|
559
|
+
return {
|
|
560
|
+
plan: args.plan,
|
|
561
|
+
...args.provisioner,
|
|
562
|
+
...args.onEvent ? { onEvent: args.onEvent } : {}
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
class MemoryCloud {
|
|
567
|
+
machines = [];
|
|
568
|
+
refusals = [];
|
|
569
|
+
count = 0;
|
|
570
|
+
alive() {
|
|
571
|
+
return this.machines.filter((machine) => machine.state !== "gone");
|
|
572
|
+
}
|
|
573
|
+
kill(ref) {
|
|
574
|
+
const machine = this.machines.find((entry) => entry.ref === ref);
|
|
575
|
+
if (machine)
|
|
576
|
+
machine.state = "gone";
|
|
577
|
+
}
|
|
578
|
+
provisioner(options = {}) {
|
|
579
|
+
const find = (target) => this.machines.filter((machine) => machine.state !== "gone" && (machine.ref === target.ref || target.idempotencyKey !== null && machine.idempotencyKey === target.idempotencyKey));
|
|
580
|
+
const stoppable = options.stoppable ?? true;
|
|
581
|
+
return {
|
|
582
|
+
create: async (request) => {
|
|
583
|
+
const key = request.enrollment.idempotencyKey;
|
|
584
|
+
const existing = this.machines.find((machine) => machine.idempotencyKey === key);
|
|
585
|
+
if (existing)
|
|
586
|
+
return { ref: existing.ref };
|
|
587
|
+
const refusal = this.refusals.shift();
|
|
588
|
+
if (refusal)
|
|
589
|
+
return { refused: refusal };
|
|
590
|
+
this.count += 1;
|
|
591
|
+
const ref = `memory-${this.count}`;
|
|
592
|
+
this.machines.push({
|
|
593
|
+
ref,
|
|
594
|
+
name: request.name,
|
|
595
|
+
idempotencyKey: key,
|
|
596
|
+
state: "running",
|
|
597
|
+
options: request.options
|
|
598
|
+
});
|
|
599
|
+
return { ref };
|
|
600
|
+
},
|
|
601
|
+
destroy: async (target) => {
|
|
602
|
+
for (const machine of find(target))
|
|
603
|
+
machine.state = "gone";
|
|
604
|
+
return { done: true };
|
|
605
|
+
},
|
|
606
|
+
...stoppable ? {
|
|
607
|
+
stop: async (target) => {
|
|
608
|
+
for (const machine of find(target))
|
|
609
|
+
machine.state = "stopped";
|
|
610
|
+
return { done: true };
|
|
611
|
+
},
|
|
612
|
+
start: async (target) => {
|
|
613
|
+
const machines = find(target);
|
|
614
|
+
if (machines.length === 0)
|
|
615
|
+
return { gone: true };
|
|
616
|
+
for (const machine of machines)
|
|
617
|
+
machine.state = "running";
|
|
618
|
+
return { done: true };
|
|
619
|
+
}
|
|
620
|
+
} : {},
|
|
621
|
+
describe: async (target) => {
|
|
622
|
+
const machine = find(target)[0];
|
|
623
|
+
return { state: machine ? machine.state : "gone" };
|
|
624
|
+
}
|
|
625
|
+
};
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
function requestFor(args) {
|
|
629
|
+
const code = `wke_contract_${args.name}_${args.generation}`;
|
|
630
|
+
return {
|
|
631
|
+
name: args.name,
|
|
632
|
+
options: args.options,
|
|
633
|
+
labels: args.labels,
|
|
634
|
+
enrollment: {
|
|
635
|
+
controlPlaneUrl: "https://work.example.test",
|
|
636
|
+
code,
|
|
637
|
+
idempotencyKey: createHash2("sha256").update(code).digest("hex")
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
async function repeat(args) {
|
|
642
|
+
let answer = await args.call();
|
|
643
|
+
for (let index = 1;index < (args.attempts ?? 20); index += 1) {
|
|
644
|
+
if (args.until(answer))
|
|
645
|
+
return answer;
|
|
646
|
+
await args.between?.();
|
|
647
|
+
answer = await args.call();
|
|
648
|
+
}
|
|
649
|
+
if (args.until(answer))
|
|
650
|
+
return answer;
|
|
651
|
+
return fail(args.check, [
|
|
652
|
+
`${args.what} never finished: after ${args.attempts ?? 20} calls it still answered ${JSON.stringify(answer)}.`,
|
|
653
|
+
args.hint
|
|
654
|
+
]);
|
|
655
|
+
}
|
|
656
|
+
async function checkMachineProvisioner(args) {
|
|
657
|
+
const { provisioner, platform } = args;
|
|
658
|
+
const name = args.name ?? "contract-check-1";
|
|
659
|
+
const options = args.options ?? {};
|
|
660
|
+
const labels = args.labels ?? {};
|
|
661
|
+
const between = args.between ?? (() => {});
|
|
662
|
+
const before = platform ? await platform.count() : 0;
|
|
663
|
+
const request = requestFor({ name, options, labels, generation: 1 });
|
|
664
|
+
const created = await repeat({
|
|
665
|
+
check: "create answers a ref",
|
|
666
|
+
what: "create",
|
|
667
|
+
call: () => provisioner.create(request),
|
|
668
|
+
until: (answer) => !("pending" in answer),
|
|
669
|
+
between,
|
|
670
|
+
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."
|
|
671
|
+
});
|
|
672
|
+
if ("refused" in created)
|
|
673
|
+
fail("create answers a ref", [
|
|
674
|
+
`create refused: ${created.refused}.`,
|
|
675
|
+
"The check needs one machine made: give it options and a fake cloud that can make one."
|
|
676
|
+
]);
|
|
677
|
+
if (!("ref" in created))
|
|
678
|
+
return;
|
|
679
|
+
const again = await provisioner.create(request);
|
|
680
|
+
if (!("ref" in again) || again.ref !== created.ref)
|
|
681
|
+
fail("create is idempotent", [
|
|
682
|
+
`Called twice with the same idempotencyKey, create answered ${JSON.stringify(created)} and then ${JSON.stringify(again)}.`,
|
|
683
|
+
"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."
|
|
684
|
+
]);
|
|
685
|
+
if (platform && await platform.count() !== before + 1)
|
|
686
|
+
fail("create is idempotent", [
|
|
687
|
+
`After two creates with one idempotencyKey the platform has ${await platform.count() - before} machine(s); it must have exactly 1.`,
|
|
688
|
+
"Hand enrollment.idempotencyKey to the platform as its idempotency token so a repeated create makes nothing new."
|
|
689
|
+
]);
|
|
690
|
+
const target = {
|
|
691
|
+
name,
|
|
692
|
+
ref: created.ref,
|
|
693
|
+
idempotencyKey: request.enrollment.idempotencyKey,
|
|
694
|
+
options,
|
|
695
|
+
labels
|
|
696
|
+
};
|
|
697
|
+
if (provisioner.describe) {
|
|
698
|
+
const described = await provisioner.describe(target);
|
|
699
|
+
if (described.state === "gone" || described.state === "stopped")
|
|
700
|
+
fail("describe sees a machine create made", [
|
|
701
|
+
`Right after create, describe answered ${JSON.stringify(described)} for ref ${created.ref}.`,
|
|
702
|
+
'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.'
|
|
703
|
+
]);
|
|
704
|
+
}
|
|
705
|
+
const requestedAt = new Date().toISOString();
|
|
706
|
+
const { stop, start } = provisioner;
|
|
707
|
+
if (stop && !start)
|
|
708
|
+
fail("stop comes with start", [
|
|
709
|
+
"The provisioner has stop but no start.",
|
|
710
|
+
"A machine Work stopped could never serve again. Add start, or remove stop so no plan can stop a machine."
|
|
711
|
+
]);
|
|
712
|
+
if (stop && start) {
|
|
713
|
+
const stopped = await repeat({
|
|
714
|
+
check: "stop finishes",
|
|
715
|
+
what: "stop",
|
|
716
|
+
call: () => stop({ ...target, requestedAt }),
|
|
717
|
+
until: (answer) => answer.done,
|
|
718
|
+
between,
|
|
719
|
+
hint: "Answer { done: false } while the machine is stopping and { done: true } once it is stopped with its disk kept."
|
|
720
|
+
});
|
|
721
|
+
const stoppedAgain = await stop({ ...target, requestedAt });
|
|
722
|
+
if (!stopped.done || !stoppedAgain.done)
|
|
723
|
+
fail("stop is idempotent", [
|
|
724
|
+
`stop on a machine that is already stopped answered ${JSON.stringify(stoppedAgain)}.`,
|
|
725
|
+
"Work repeats stop until it is done and may repeat it after: stopping a stopped machine answers { done: true } and changes nothing."
|
|
726
|
+
]);
|
|
727
|
+
if (provisioner.describe) {
|
|
728
|
+
const described = await provisioner.describe(target);
|
|
729
|
+
if (described.state === "gone")
|
|
730
|
+
fail("stop keeps the machine", [
|
|
731
|
+
'After stop, describe answered "gone".',
|
|
732
|
+
"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)."
|
|
733
|
+
]);
|
|
734
|
+
}
|
|
735
|
+
const started = await repeat({
|
|
736
|
+
check: "start finishes",
|
|
737
|
+
what: "start",
|
|
738
|
+
call: () => start({ ...target, requestedAt }),
|
|
739
|
+
until: (answer) => ("gone" in answer) || answer.done,
|
|
740
|
+
between,
|
|
741
|
+
hint: "Answer { done: false } while the machine is starting, { done: true } once the platform runs it, and { gone: true } when it no longer exists."
|
|
742
|
+
});
|
|
743
|
+
if ("gone" in started)
|
|
744
|
+
fail("start brings back a stopped machine", [
|
|
745
|
+
"start answered { gone: true } for a machine stop had just stopped.",
|
|
746
|
+
"stop must keep the machine and its disk. Answer { gone: true } from start only when the machine no longer exists."
|
|
747
|
+
]);
|
|
748
|
+
const startedAgain = await start({ ...target, requestedAt });
|
|
749
|
+
if ("gone" in startedAgain || !startedAgain.done)
|
|
750
|
+
fail("start is idempotent", [
|
|
751
|
+
`start on a machine that is already running answered ${JSON.stringify(startedAgain)}.`,
|
|
752
|
+
"Starting a running machine answers { done: true } and changes nothing."
|
|
753
|
+
]);
|
|
754
|
+
}
|
|
755
|
+
await repeat({
|
|
756
|
+
check: "destroy finishes",
|
|
757
|
+
what: "destroy",
|
|
758
|
+
call: () => provisioner.destroy({ ...target, requestedAt }),
|
|
759
|
+
until: (answer) => answer.done,
|
|
760
|
+
attempts: 60,
|
|
761
|
+
between,
|
|
762
|
+
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."
|
|
763
|
+
});
|
|
764
|
+
const destroyedAgain = await provisioner.destroy({ ...target, requestedAt });
|
|
765
|
+
if (!destroyedAgain.done)
|
|
766
|
+
fail("destroy is idempotent", [
|
|
767
|
+
`destroy on a machine that is already gone answered ${JSON.stringify(destroyedAgain)}.`,
|
|
768
|
+
"Destroying a machine that no longer exists answers { done: true }."
|
|
769
|
+
]);
|
|
770
|
+
if (platform && await platform.count() !== before)
|
|
771
|
+
fail("destroy removes the machine", [
|
|
772
|
+
`After destroy answered done, the platform still has ${await platform.count() - before} machine(s) from this check.`,
|
|
773
|
+
"Answer { done: true } only once the machine is gone."
|
|
774
|
+
]);
|
|
775
|
+
if (start) {
|
|
776
|
+
const gone = await start({ ...target, requestedAt });
|
|
777
|
+
if (!("gone" in gone))
|
|
778
|
+
fail("start says when a machine is gone", [
|
|
779
|
+
`start on a destroyed machine answered ${JSON.stringify(gone)}.`,
|
|
780
|
+
"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."
|
|
781
|
+
]);
|
|
782
|
+
}
|
|
783
|
+
const orphan = requestFor({ name, options, labels, generation: 2 });
|
|
784
|
+
const made = await repeat({
|
|
785
|
+
check: "create answers a ref",
|
|
786
|
+
what: "create",
|
|
787
|
+
call: () => provisioner.create(orphan),
|
|
788
|
+
until: (answer) => !("pending" in answer),
|
|
789
|
+
between,
|
|
790
|
+
hint: "Answer { ref } once the machine exists."
|
|
791
|
+
});
|
|
792
|
+
if (!("ref" in made))
|
|
793
|
+
return;
|
|
794
|
+
if (made.ref === created.ref)
|
|
795
|
+
fail("a new enrollment makes a new machine", [
|
|
796
|
+
`A create with a new idempotencyKey answered the destroyed machine's ref ${made.ref}.`,
|
|
797
|
+
"Key machines by enrollment.idempotencyKey, never by name alone: a later machine reuses the name of one that is gone."
|
|
798
|
+
]);
|
|
799
|
+
await repeat({
|
|
800
|
+
check: "destroy finds a machine whose ref was never recorded",
|
|
801
|
+
what: "destroy with ref: null",
|
|
802
|
+
call: () => provisioner.destroy({
|
|
803
|
+
name,
|
|
804
|
+
ref: null,
|
|
805
|
+
idempotencyKey: orphan.enrollment.idempotencyKey,
|
|
806
|
+
options,
|
|
807
|
+
labels,
|
|
808
|
+
requestedAt
|
|
809
|
+
}),
|
|
810
|
+
until: (answer) => answer.done,
|
|
811
|
+
attempts: 60,
|
|
812
|
+
between,
|
|
813
|
+
hint: "When ref is null, find the machine by idempotencyKey (and by name), destroy it, and answer { done: true } only once nothing is left."
|
|
814
|
+
});
|
|
815
|
+
if (platform && await platform.count() !== before)
|
|
816
|
+
fail("destroy finds a machine whose ref was never recorded", [
|
|
817
|
+
`After destroy with ref: null answered done, the platform still has ${await platform.count() - before} machine(s).`,
|
|
818
|
+
"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."
|
|
819
|
+
]);
|
|
820
|
+
}
|
|
821
|
+
function names(plan) {
|
|
822
|
+
return plan.map((machine) => machine.name).sort();
|
|
823
|
+
}
|
|
824
|
+
function creates(calls) {
|
|
825
|
+
return calls.filter((call) => call.verb === "create");
|
|
826
|
+
}
|
|
827
|
+
async function checkMachinesHook(args) {
|
|
828
|
+
const { hook } = args;
|
|
829
|
+
const sim = new SimulatedWork({
|
|
830
|
+
...args.simulation,
|
|
831
|
+
hook,
|
|
832
|
+
...args.facts?.people ? { people: args.facts.people } : {}
|
|
833
|
+
});
|
|
834
|
+
for (const work of args.facts?.work ?? [])
|
|
835
|
+
sim.addWork(work);
|
|
836
|
+
const advance = async (time) => {
|
|
837
|
+
sim.advance(time);
|
|
838
|
+
await args.onAdvance?.(sim.now);
|
|
839
|
+
};
|
|
840
|
+
const facts = {
|
|
841
|
+
now: sim.now,
|
|
842
|
+
work: [...sim.waiting()],
|
|
843
|
+
machines: sim.facts(),
|
|
844
|
+
people: sim.people
|
|
845
|
+
};
|
|
846
|
+
const first = MachinePlanSchema.safeParse(await hook.plan(facts));
|
|
847
|
+
const second = MachinePlanSchema.safeParse(await hook.plan(facts));
|
|
848
|
+
if (!first.success || !second.success) {
|
|
849
|
+
const issue = (first.success ? second : first).error?.issues[0];
|
|
850
|
+
fail("plan returns valid machines", [
|
|
851
|
+
`plan returned something Work cannot use${issue ? `: ${issue.path.join(".") || "result"}: ${issue.message}` : ""}.`,
|
|
852
|
+
"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."
|
|
853
|
+
]);
|
|
854
|
+
}
|
|
855
|
+
if (canonical(first.data) !== canonical(second.data))
|
|
856
|
+
fail("plan is stable", [
|
|
857
|
+
`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).`,
|
|
858
|
+
"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."
|
|
859
|
+
]);
|
|
860
|
+
if (first.data.length === 0)
|
|
861
|
+
fail("the check has something to check", [
|
|
862
|
+
"With the facts given, plan wants no machine.",
|
|
863
|
+
"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 } }))."
|
|
864
|
+
]);
|
|
865
|
+
sim.loseNextCreateAnswer();
|
|
866
|
+
await sim.pass();
|
|
867
|
+
await advance({ seconds: 10 });
|
|
868
|
+
await sim.pass();
|
|
869
|
+
const byName = new Map;
|
|
870
|
+
for (const call of creates(sim.calls))
|
|
871
|
+
byName.set(call.name, [...byName.get(call.name) ?? [], call]);
|
|
872
|
+
for (const [name, calls] of byName) {
|
|
873
|
+
const keys = new Set(calls.map((call) => call.idempotencyKey));
|
|
874
|
+
const refs = new Set(calls.flatMap((call) => {
|
|
875
|
+
const answer = call.answer;
|
|
876
|
+
return answer && typeof answer === "object" && "ref" in answer ? [String(answer.ref)] : [];
|
|
877
|
+
}));
|
|
878
|
+
if (keys.size === 1 && refs.size > 1)
|
|
879
|
+
fail("no machine is made twice", [
|
|
880
|
+
`create was repeated for '${name}' with one idempotencyKey (its first answer was lost) and answered different refs: ${[...refs].join(", ")}.`,
|
|
881
|
+
"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."
|
|
882
|
+
]);
|
|
883
|
+
}
|
|
884
|
+
const settled = await settleWith({ sim, advance, limit: 40 });
|
|
885
|
+
if (!settled)
|
|
886
|
+
fail("plan converges", [
|
|
887
|
+
`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)}.`,
|
|
888
|
+
"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."
|
|
889
|
+
]);
|
|
890
|
+
const settledAt = sim.calls.length;
|
|
891
|
+
for (let index = 0;index < 5; index += 1) {
|
|
892
|
+
await advance({ seconds: 10 });
|
|
893
|
+
await sim.pass();
|
|
894
|
+
}
|
|
895
|
+
const after = sim.calls.slice(settledAt).filter((call) => call.verb === "create" || call.verb === "destroy");
|
|
896
|
+
if (after.length > 0)
|
|
897
|
+
fail("plan does not flap", [
|
|
898
|
+
`Nothing changed, yet within a simulated minute the plan had machines made or destroyed: ${recent(after)}.`,
|
|
899
|
+
"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."
|
|
900
|
+
]);
|
|
901
|
+
for (const [name, calls] of groupByName(creates(sim.calls))) {
|
|
902
|
+
const keys = new Set(calls.map((call) => call.idempotencyKey));
|
|
903
|
+
if (keys.size > 1)
|
|
904
|
+
fail("plan does not flap", [
|
|
905
|
+
`'${name}' was created ${keys.size} times (under ${keys.size} enrollments) while nothing changed from outside.`,
|
|
906
|
+
'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.'
|
|
907
|
+
]);
|
|
908
|
+
}
|
|
909
|
+
const serving = sim.facts().filter((machine) => machine.managed && machine.state === "serving");
|
|
910
|
+
if (hook.describe) {
|
|
911
|
+
const describe = hook.describe.bind(hook);
|
|
912
|
+
for (const machine of serving) {
|
|
913
|
+
if (machine.holding.workspaces === 0)
|
|
914
|
+
continue;
|
|
915
|
+
const described = await describe({
|
|
916
|
+
name: machine.name,
|
|
917
|
+
ref: machine.ref,
|
|
918
|
+
idempotencyKey: null,
|
|
919
|
+
options: machine.options,
|
|
920
|
+
labels: machine.labels
|
|
921
|
+
});
|
|
922
|
+
if (described.state === "gone" || described.state === "stopped")
|
|
923
|
+
fail("nothing holding live work is stopped or destroyed", [
|
|
924
|
+
`'${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}.`,
|
|
925
|
+
"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)."
|
|
926
|
+
]);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
const victim = serving[0];
|
|
930
|
+
if (victim) {
|
|
931
|
+
const before = creates(sim.calls).filter((call) => call.name === victim.name);
|
|
932
|
+
const oldKey = before[before.length - 1]?.idempotencyKey ?? null;
|
|
933
|
+
sim.lose(victim.name);
|
|
934
|
+
await args.kill?.({ name: victim.name, ref: victim.ref });
|
|
935
|
+
for (let index = 0;index < 30; index += 1) {
|
|
936
|
+
await advance({ minutes: 1 });
|
|
937
|
+
await sim.pass();
|
|
938
|
+
const now = sim.machine(victim.name);
|
|
939
|
+
if (now?.state === "serving" && now.ref !== victim.ref)
|
|
940
|
+
break;
|
|
941
|
+
if (!now && !await wants({ hook, sim, name: victim.name }))
|
|
942
|
+
break;
|
|
943
|
+
}
|
|
944
|
+
const destroyed = sim.calls.some((call) => call.verb === "destroy" && call.name === victim.name && answerDone(call.answer));
|
|
945
|
+
if (!destroyed)
|
|
946
|
+
fail("a lost machine is destroyed", [
|
|
947
|
+
`'${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))}.`,
|
|
948
|
+
"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."
|
|
949
|
+
]);
|
|
950
|
+
if (await wants({ hook, sim, name: victim.name })) {
|
|
951
|
+
const remade = creates(sim.calls).filter((call) => call.name === victim.name && call.idempotencyKey !== oldKey);
|
|
952
|
+
const now = sim.machine(victim.name);
|
|
953
|
+
if (remade.length === 0 || now?.state !== "serving")
|
|
954
|
+
fail("a lost machine is replaced", [
|
|
955
|
+
`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})` : ""}.`,
|
|
956
|
+
"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."
|
|
957
|
+
]);
|
|
958
|
+
const refs = new Set(remade.flatMap((call) => {
|
|
959
|
+
const answer = call.answer;
|
|
960
|
+
return answer && typeof answer === "object" && "ref" in answer ? [String(answer.ref)] : [];
|
|
961
|
+
}));
|
|
962
|
+
if (victim.ref !== null && refs.has(victim.ref))
|
|
963
|
+
fail("a lost machine is replaced", [
|
|
964
|
+
`The replacement for '${victim.name}' got the lost machine's ref ${victim.ref} back.`,
|
|
965
|
+
"Key a create by enrollment.idempotencyKey, not by name: a new key is a new machine."
|
|
966
|
+
]);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
async function wants(args) {
|
|
971
|
+
const plan = MachinePlanSchema.safeParse(await args.hook.plan({
|
|
972
|
+
now: args.sim.now,
|
|
973
|
+
work: [...args.sim.waiting()],
|
|
974
|
+
machines: args.sim.facts(),
|
|
975
|
+
people: args.sim.people
|
|
976
|
+
}));
|
|
977
|
+
return plan.success && plan.data.some((machine) => machine.name === args.name);
|
|
978
|
+
}
|
|
979
|
+
async function settleWith(args) {
|
|
980
|
+
for (let index = 0;index < args.limit; index += 1) {
|
|
981
|
+
const { quiet } = await args.sim.settle({ limit: 1 });
|
|
982
|
+
if (quiet)
|
|
983
|
+
return true;
|
|
984
|
+
await args.advance({ seconds: 30 });
|
|
985
|
+
}
|
|
986
|
+
return false;
|
|
987
|
+
}
|
|
988
|
+
function groupByName(calls) {
|
|
989
|
+
const grouped = new Map;
|
|
990
|
+
for (const call of calls)
|
|
991
|
+
grouped.set(call.name, [...grouped.get(call.name) ?? [], call]);
|
|
992
|
+
return grouped;
|
|
993
|
+
}
|
|
994
|
+
function answerDone(answer) {
|
|
995
|
+
return typeof answer === "object" && answer !== null && "done" in answer && answer.done === true;
|
|
996
|
+
}
|
|
997
|
+
function recent(calls) {
|
|
998
|
+
if (calls.length === 0)
|
|
999
|
+
return "none";
|
|
1000
|
+
return calls.slice(-6).map((call) => `${call.verb} ${call.name} -> ${call.error ? `threw ${call.error}` : JSON.stringify(call.answer)}`).join("; ");
|
|
1001
|
+
}
|
|
1002
|
+
export {
|
|
1003
|
+
MachinesContractError,
|
|
1004
|
+
MemoryCloud,
|
|
1005
|
+
SimulatedWork,
|
|
1006
|
+
checkMachineProvisioner,
|
|
1007
|
+
checkMachinesHook,
|
|
1008
|
+
machinesHook,
|
|
1009
|
+
quietSummary
|
|
1010
|
+
};
|
|
1011
|
+
|
|
1012
|
+
//# debugId=12EE93366F9E1FE064756E2164756E21
|
|
1013
|
+
//# sourceMappingURL=testing.js.map
|