@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
|
@@ -1,7 +1,14 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
createHash,
|
|
3
|
+
randomBytes,
|
|
4
|
+
randomUUID,
|
|
5
|
+
timingSafeEqual,
|
|
6
|
+
} from "node:crypto";
|
|
2
7
|
import {
|
|
3
8
|
cleanupWorkerAllocations,
|
|
4
9
|
forgetExecutorKey,
|
|
10
|
+
MachineDiskSchema,
|
|
11
|
+
type NodeRetireReason,
|
|
5
12
|
nodeExecutor,
|
|
6
13
|
PlacementWaitsService,
|
|
7
14
|
REMOTE_EPOCH_PATTERN,
|
|
@@ -9,29 +16,43 @@ import {
|
|
|
9
16
|
RemoteExecutorLeaseLostError,
|
|
10
17
|
RemoteOperationQueue,
|
|
11
18
|
registerExecutorKey,
|
|
19
|
+
releaseReplicaClaim,
|
|
20
|
+
retireNodeWork,
|
|
21
|
+
takeReplicaClaim,
|
|
12
22
|
type WorkerCapacity,
|
|
13
23
|
WorkerNodeLeaseHeldError,
|
|
14
24
|
type WorkerNodesService,
|
|
15
25
|
} from "@catamorphic/core";
|
|
16
26
|
import type { DB } from "@catamorphic/db";
|
|
17
27
|
import {
|
|
28
|
+
describeDisk,
|
|
29
|
+
diskBudgetMb,
|
|
18
30
|
type EnvironmentBinding,
|
|
19
31
|
ExecutorPublicKeySchema,
|
|
32
|
+
MACHINE_CAPABILITIES,
|
|
33
|
+
type MachineDisk,
|
|
34
|
+
SANDBOX_CAPABILITIES,
|
|
20
35
|
} from "@catamorphic/sandbox";
|
|
21
|
-
import { type Kysely, sql } from "kysely";
|
|
36
|
+
import { type Kysely, sql, type Transaction } from "kysely";
|
|
22
37
|
import { z } from "zod";
|
|
23
|
-
import type { CodexSignInRequest } from "./codex-sign-ins.js";
|
|
24
38
|
import {
|
|
25
|
-
|
|
39
|
+
type MachineEvent,
|
|
40
|
+
type MachineEventKind,
|
|
41
|
+
type MachineFacts,
|
|
42
|
+
principalsChangeNeedsReset,
|
|
43
|
+
} from "../machines/contract.js";
|
|
44
|
+
import type { HarnessSignInRequest } from "./harness-sign-ins.js";
|
|
45
|
+
import { MachineStore, WORKER_NODE_PREFIX } from "./machine-store.js";
|
|
46
|
+
import {
|
|
26
47
|
type ScheduledPlacement,
|
|
27
48
|
servesNobody,
|
|
28
49
|
servesOneOwner,
|
|
29
|
-
storedPlacement,
|
|
30
50
|
type WorkerPlacement,
|
|
31
|
-
WorkerPlacementSchema,
|
|
51
|
+
type WorkerPlacementSchema,
|
|
52
|
+
workerPlacement,
|
|
32
53
|
} from "./placement.js";
|
|
33
54
|
|
|
34
|
-
export
|
|
55
|
+
export { WORKER_NODE_PREFIX };
|
|
35
56
|
|
|
36
57
|
const WorkerName = z
|
|
37
58
|
.string()
|
|
@@ -53,21 +74,12 @@ export const WorkerOfferSchema = z.strictObject({
|
|
|
53
74
|
capabilities: z
|
|
54
75
|
.array(
|
|
55
76
|
z.union([
|
|
77
|
+
// What its sandboxes can be given (ADR 0176) and what the machine
|
|
78
|
+
// offers beside its provider (ADR 0184), named by the same
|
|
79
|
+
// constants the providers list, so a new one is never refused.
|
|
56
80
|
z.enum([
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
"containers",
|
|
60
|
-
"network.policy",
|
|
61
|
-
// It widens a running sandbox for its setup, for a while (ADR 0257).
|
|
62
|
-
"network.setup",
|
|
63
|
-
// It keeps volumes across sandboxes (ADR 0208).
|
|
64
|
-
"volumes",
|
|
65
|
-
// What the machine offers beside its provider (ADR 0184).
|
|
66
|
-
"credentials.personal",
|
|
67
|
-
"harness.claude-code",
|
|
68
|
-
"harness.codex",
|
|
69
|
-
// Its sandboxes mount members' own sign-ins (ADR 0199).
|
|
70
|
-
"sign-ins",
|
|
81
|
+
...Object.values(SANDBOX_CAPABILITIES),
|
|
82
|
+
...Object.values(MACHINE_CAPABILITIES),
|
|
71
83
|
]),
|
|
72
84
|
// A member signed in to a harness on it: the fact, never the value.
|
|
73
85
|
z.string().regex(/^sign-in:(claude-code|codex):\S{1,255}$/),
|
|
@@ -87,6 +99,11 @@ export const WorkerOfferSchema = z.strictObject({
|
|
|
87
99
|
})
|
|
88
100
|
.default({}),
|
|
89
101
|
version: z.string().max(100).optional(),
|
|
102
|
+
/**
|
|
103
|
+
* Its disk (ADR 0336): the filesystem it writes to with the least room
|
|
104
|
+
* above its floor. Later measurements come with its lease renewals.
|
|
105
|
+
*/
|
|
106
|
+
disk: MachineDiskSchema.optional(),
|
|
90
107
|
/** What runs its sandboxes and why it was chosen (ADR 0204). */
|
|
91
108
|
backend: z
|
|
92
109
|
.strictObject({
|
|
@@ -133,87 +150,15 @@ export class WorkerIsolationError extends Error {
|
|
|
133
150
|
}
|
|
134
151
|
}
|
|
135
152
|
|
|
136
|
-
/** Nobody may hold a pooled machine's access but its rule (ADR 0205). */
|
|
137
|
-
const NOBODY = { nobody: true } as const;
|
|
138
|
-
|
|
139
|
-
/**
|
|
140
|
-
* What a worker is doing for machine rules (ADR 0205): serving its access,
|
|
141
|
-
* released (serving nobody, its disk kept for its retention), free in its
|
|
142
|
-
* pool, being reset before it returns to its pool, revoked and still being
|
|
143
|
-
* destroyed on its platform, or revoked.
|
|
144
|
-
*/
|
|
145
|
-
export type WorkerState =
|
|
146
|
-
| "serving"
|
|
147
|
-
| "released"
|
|
148
|
-
| "free"
|
|
149
|
-
| "resetting"
|
|
150
|
-
| "destroying"
|
|
151
|
-
| "revoked";
|
|
152
|
-
|
|
153
|
-
/** A machine of a pool (`"pool": true` at enrollment), for the reconciler. */
|
|
154
|
-
export interface PooledMachine {
|
|
155
|
-
name: string;
|
|
156
|
-
nodeId: string;
|
|
157
|
-
/** The rule that holds it; absent while it is free or being reset. */
|
|
158
|
-
rule: string | null;
|
|
159
|
-
/** The user id it serves under an `each-member` rule. */
|
|
160
|
-
member: string | null;
|
|
161
|
-
/** Its place among a group's shared machines. */
|
|
162
|
-
slot: number | null;
|
|
163
|
-
/** How long ago it was released, by the database's clock. */
|
|
164
|
-
releasedForMs: number | null;
|
|
165
|
-
retainDays: number | null;
|
|
166
|
-
placement: WorkerPlacement;
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
/** A machine a rule provisioned on a platform, for the reconciler. */
|
|
170
|
-
export interface ProvisionedMachine {
|
|
171
|
-
name: string;
|
|
172
|
-
ref: string | null;
|
|
173
|
-
rule: string;
|
|
174
|
-
/**
|
|
175
|
-
* Enrolled, still pending enrollment, expired before enrolling (or its
|
|
176
|
-
* code withdrawn for destruction), or revoked and not yet destroyed.
|
|
177
|
-
*/
|
|
178
|
-
state: "enrolled" | "pending" | "expired" | "revoked";
|
|
179
|
-
/** How long ago it was released, by the database's clock. */
|
|
180
|
-
releasedForMs: number | null;
|
|
181
|
-
retainDays: number | null;
|
|
182
|
-
placement: WorkerPlacement;
|
|
183
|
-
}
|
|
184
|
-
|
|
185
153
|
/**
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
* one (or enrolled), how long since it last called (or enrolled, when it
|
|
189
|
-
* never did), and while it is connected what it offers and has free.
|
|
154
|
+
* This worker's node is disabled: an operator disabled it, or Work stopped
|
|
155
|
+
* its machine (ADR 0350). It may connect once enabled or resumed.
|
|
190
156
|
*/
|
|
191
|
-
export interface MachineLoad {
|
|
192
|
-
holding: number;
|
|
193
|
-
idleForMs: number;
|
|
194
|
-
unseenForMs: number;
|
|
195
|
-
/** It enrolled and has not connected yet. */
|
|
196
|
-
neverConnected: boolean;
|
|
197
|
-
/**
|
|
198
|
-
* While its lease is live: what it offers, what it has free, and what a
|
|
199
|
-
* workspace naming no resources is charged there.
|
|
200
|
-
*/
|
|
201
|
-
live: {
|
|
202
|
-
descriptor: EnvironmentBinding;
|
|
203
|
-
free: { workspaces: number; cpuMillis?: number; memoryMb?: number };
|
|
204
|
-
defaults: { cpuMillis?: number; memoryMb?: number };
|
|
205
|
-
} | null;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
/** Milliseconds since `released_at`, measured by the database. */
|
|
209
|
-
const releasedFor = sql<
|
|
210
|
-
number | null
|
|
211
|
-
>`(extract(epoch from (now() - released_at)) * 1000)::float8`;
|
|
212
|
-
|
|
213
|
-
/** The operator disabled this worker's node; it may connect once enabled. */
|
|
214
157
|
export class WorkerDisabledError extends Error {
|
|
215
158
|
constructor() {
|
|
216
|
-
super(
|
|
159
|
+
super(
|
|
160
|
+
"This worker is disabled or its machine is stopped; it connects once it is enabled or resumed",
|
|
161
|
+
);
|
|
217
162
|
this.name = "WorkerDisabledError";
|
|
218
163
|
}
|
|
219
164
|
}
|
|
@@ -274,22 +219,59 @@ export class WorkWorkerRegistry {
|
|
|
274
219
|
|
|
275
220
|
private readonly waits: PlacementWaitsService;
|
|
276
221
|
|
|
222
|
+
/** The machines Work knows: whom each is for and where it stands. */
|
|
223
|
+
readonly machines: MachineStore;
|
|
224
|
+
|
|
277
225
|
constructor(
|
|
278
226
|
private readonly deps: {
|
|
279
227
|
db: Kysely<DB>;
|
|
280
228
|
nodes: WorkerNodesService;
|
|
281
229
|
tenantId: string;
|
|
282
230
|
authorityId: string;
|
|
231
|
+
/**
|
|
232
|
+
* Derives the enrollment codes of machines the machines hook makes
|
|
233
|
+
* (ADR 0349); every replica of a deployment shares it.
|
|
234
|
+
*/
|
|
235
|
+
enrollmentSecret?: string;
|
|
283
236
|
/**
|
|
284
237
|
* A worker connected: hint this process's agent sweep, which tries
|
|
285
238
|
* chats waiting for a machine (ADR 0258) again at once.
|
|
286
239
|
*/
|
|
287
240
|
connected?: () => void;
|
|
241
|
+
/**
|
|
242
|
+
* Something happened to a machine (ADR 0349): it connected, started
|
|
243
|
+
* again, was lost, or fell short of disk. Delivery is the host's;
|
|
244
|
+
* nothing here waits on it.
|
|
245
|
+
*/
|
|
246
|
+
event?: (event: MachineEvent) => Promise<void>;
|
|
247
|
+
/**
|
|
248
|
+
* Work was retired from a machine (ADR 0348): hint this process's
|
|
249
|
+
* agent sweep, which admits its chats again at once.
|
|
250
|
+
*/
|
|
251
|
+
retired?: () => void;
|
|
252
|
+
/**
|
|
253
|
+
* Minutes unseen that make a machine whose plan sets no limit lost
|
|
254
|
+
* (default 5).
|
|
255
|
+
*/
|
|
256
|
+
lostMinutes?: number;
|
|
288
257
|
log?: (line: string) => void;
|
|
289
258
|
},
|
|
290
259
|
) {
|
|
291
260
|
this.queue = new RemoteOperationQueue(deps.db);
|
|
292
261
|
this.waits = new PlacementWaitsService(deps.db);
|
|
262
|
+
this.machines = new MachineStore({
|
|
263
|
+
db: deps.db,
|
|
264
|
+
nodes: deps.nodes,
|
|
265
|
+
tenantId: deps.tenantId,
|
|
266
|
+
authorityId: deps.authorityId,
|
|
267
|
+
// A registry that makes no machines (a test, a worker-only tool)
|
|
268
|
+
// still needs a secret no one else knows.
|
|
269
|
+
enrollmentSecret:
|
|
270
|
+
deps.enrollmentSecret ?? randomBytes(32).toString("base64url"),
|
|
271
|
+
...(deps.lostMinutes !== undefined
|
|
272
|
+
? { lostMinutes: deps.lostMinutes }
|
|
273
|
+
: {}),
|
|
274
|
+
});
|
|
293
275
|
}
|
|
294
276
|
|
|
295
277
|
/**
|
|
@@ -347,8 +329,116 @@ export class WorkWorkerRegistry {
|
|
|
347
329
|
}
|
|
348
330
|
|
|
349
331
|
/** A keepalive while operations run and no poll is pending. */
|
|
350
|
-
async renew(args: {
|
|
332
|
+
async renew(args: {
|
|
333
|
+
nodeId: string;
|
|
334
|
+
session: string;
|
|
335
|
+
/** Its latest disk measurement (ADR 0336). */
|
|
336
|
+
disk?: MachineDisk;
|
|
337
|
+
}): Promise<void> {
|
|
351
338
|
await this.renewOrThrow(args);
|
|
339
|
+
if (args.disk)
|
|
340
|
+
await this.reportDisk({
|
|
341
|
+
nodeId: args.nodeId,
|
|
342
|
+
session: args.session,
|
|
343
|
+
disk: args.disk,
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Store a worker's disk report under its epoch (ADR 0336). One that
|
|
349
|
+
* begins an episode under the floor is logged and told as
|
|
350
|
+
* `machine.disk-low` once, whichever replica heard it.
|
|
351
|
+
*/
|
|
352
|
+
private async reportDisk(args: {
|
|
353
|
+
nodeId: string;
|
|
354
|
+
session: string;
|
|
355
|
+
disk: MachineDisk;
|
|
356
|
+
}): Promise<void> {
|
|
357
|
+
const episode = await this.deps.nodes.reportDisk({
|
|
358
|
+
lease: { id: args.nodeId, token: args.session },
|
|
359
|
+
disk: args.disk,
|
|
360
|
+
});
|
|
361
|
+
// Every report in an episode whose event is not recorded tries again;
|
|
362
|
+
// the event names its episode, so it is never recorded twice.
|
|
363
|
+
if (
|
|
364
|
+
(episode.state !== "started" && episode.state !== "ongoing") ||
|
|
365
|
+
!episode.unrecorded
|
|
366
|
+
)
|
|
367
|
+
return;
|
|
368
|
+
const name = workerNameOf(args.nodeId);
|
|
369
|
+
if (episode.state === "started")
|
|
370
|
+
this.deps.log?.(
|
|
371
|
+
`Worker ${name} is short of disk: ${describeDisk(args.disk)}`,
|
|
372
|
+
);
|
|
373
|
+
try {
|
|
374
|
+
await this.emit({
|
|
375
|
+
kind: "machine.disk-low",
|
|
376
|
+
name,
|
|
377
|
+
at: episode.since,
|
|
378
|
+
disk: args.disk,
|
|
379
|
+
rethrow: true,
|
|
380
|
+
});
|
|
381
|
+
await this.deps.nodes.diskLowRecorded({
|
|
382
|
+
nodeId: args.nodeId,
|
|
383
|
+
since: episode.since,
|
|
384
|
+
});
|
|
385
|
+
} catch (error) {
|
|
386
|
+
this.deps.log?.(
|
|
387
|
+
`Machine ${name} is short of disk, and recording it failed (tried again on its next report): ${
|
|
388
|
+
error instanceof Error ? error.message : String(error)
|
|
389
|
+
}`,
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Tell the host something happened to a machine. A failure is logged;
|
|
396
|
+
* with `rethrow` the caller hears it and tries again.
|
|
397
|
+
*/
|
|
398
|
+
private async emit(args: {
|
|
399
|
+
kind: MachineEventKind;
|
|
400
|
+
name: string;
|
|
401
|
+
at?: Date;
|
|
402
|
+
disk?: MachineDisk;
|
|
403
|
+
rethrow?: boolean;
|
|
404
|
+
}): Promise<void> {
|
|
405
|
+
if (!this.deps.event) return;
|
|
406
|
+
try {
|
|
407
|
+
const row = await this.machines.row({ name: args.name });
|
|
408
|
+
if (!row) return;
|
|
409
|
+
const placement = await this.machines.placementOf({ name: args.name });
|
|
410
|
+
await this.deps.event({
|
|
411
|
+
kind: args.kind,
|
|
412
|
+
at: (args.at ?? new Date()).toISOString(),
|
|
413
|
+
machine: {
|
|
414
|
+
name: row.name,
|
|
415
|
+
ref: row.ref,
|
|
416
|
+
managed: row.managed,
|
|
417
|
+
labels: placement.labels,
|
|
418
|
+
for: placement.for,
|
|
419
|
+
options: z.record(z.string(), z.unknown()).parse(row.options),
|
|
420
|
+
reason: row.reason,
|
|
421
|
+
},
|
|
422
|
+
...(args.disk
|
|
423
|
+
? {
|
|
424
|
+
disk: {
|
|
425
|
+
path: args.disk.path,
|
|
426
|
+
totalBytes: args.disk.totalBytes,
|
|
427
|
+
freeBytes: args.disk.freeBytes,
|
|
428
|
+
floorBytes: args.disk.floorBytes,
|
|
429
|
+
measuredAt: args.disk.measuredAt,
|
|
430
|
+
},
|
|
431
|
+
}
|
|
432
|
+
: {}),
|
|
433
|
+
});
|
|
434
|
+
} catch (error) {
|
|
435
|
+
if (args.rethrow) throw error;
|
|
436
|
+
this.deps.log?.(
|
|
437
|
+
`Recording ${args.kind} for machine ${args.name} failed: ${
|
|
438
|
+
error instanceof Error ? error.message : String(error)
|
|
439
|
+
}`,
|
|
440
|
+
);
|
|
441
|
+
}
|
|
352
442
|
}
|
|
353
443
|
|
|
354
444
|
/**
|
|
@@ -385,6 +475,49 @@ export class WorkWorkerRegistry {
|
|
|
385
475
|
.execute();
|
|
386
476
|
}
|
|
387
477
|
|
|
478
|
+
/**
|
|
479
|
+
* A worker connected: a machine that was starting or resuming serves
|
|
480
|
+
* from now on (ADRs 0349, 0350), and one that was lost and came back
|
|
481
|
+
* with its disk is lost no more.
|
|
482
|
+
*/
|
|
483
|
+
private async serving(args: { nodeId: string; name: string }): Promise<void> {
|
|
484
|
+
await this.deps.db
|
|
485
|
+
.updateTable("work_workers")
|
|
486
|
+
.set({ last_seen_at: sql`now()` })
|
|
487
|
+
.where("node_id", "=", args.nodeId)
|
|
488
|
+
.where("last_seen_at", "is", null)
|
|
489
|
+
.execute();
|
|
490
|
+
const { name } = args;
|
|
491
|
+
if (
|
|
492
|
+
await this.machines.setPhase({
|
|
493
|
+
name,
|
|
494
|
+
phase: "running",
|
|
495
|
+
from: ["starting"],
|
|
496
|
+
})
|
|
497
|
+
) {
|
|
498
|
+
await this.emit({ kind: "machine.connected", name });
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
if (
|
|
502
|
+
await this.machines.setPhase({
|
|
503
|
+
name,
|
|
504
|
+
phase: "running",
|
|
505
|
+
from: ["resuming"],
|
|
506
|
+
})
|
|
507
|
+
) {
|
|
508
|
+
await this.emit({ kind: "machine.started", name });
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
await this.deps.db
|
|
512
|
+
.updateTable("work_machines")
|
|
513
|
+
.set({ lost_at: null })
|
|
514
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
515
|
+
.where("name", "=", name)
|
|
516
|
+
.where("phase", "=", "running")
|
|
517
|
+
.where("lost_at", "is not", null)
|
|
518
|
+
.execute();
|
|
519
|
+
}
|
|
520
|
+
|
|
388
521
|
/** Why this epoch's session ended: superseded, or disabled and lapsed. */
|
|
389
522
|
private async ended(args: {
|
|
390
523
|
nodeId: string;
|
|
@@ -401,61 +534,21 @@ export class WorkWorkerRegistry {
|
|
|
401
534
|
}
|
|
402
535
|
|
|
403
536
|
/**
|
|
404
|
-
* Operator: a one-time code a new worker exchanges for its credential
|
|
405
|
-
*
|
|
406
|
-
*
|
|
537
|
+
* Operator: a one-time code a new worker exchanges for its credential,
|
|
538
|
+
* for a machine enrolled by hand (ADR 0349): Work places work on it by
|
|
539
|
+
* its labels and whom it is for, and never creates, stops or destroys
|
|
540
|
+
* it. The machines hook's own machines are enrolled by the sequencer.
|
|
407
541
|
*/
|
|
408
542
|
async createEnrollment(args: {
|
|
409
543
|
name: string;
|
|
410
544
|
ttlMinutes?: number;
|
|
411
545
|
placement?: z.input<typeof WorkerPlacementSchema>;
|
|
412
|
-
pool?: boolean;
|
|
413
546
|
}): Promise<{ code: string; nodeId: string; expiresAt: Date }> {
|
|
414
|
-
const enrollment = await this.issueEnrollment(
|
|
415
|
-
args.pool
|
|
416
|
-
? {
|
|
417
|
-
...args,
|
|
418
|
-
placement: { labels: args.placement?.labels ?? {}, access: NOBODY },
|
|
419
|
-
}
|
|
420
|
-
: args,
|
|
421
|
-
);
|
|
422
|
-
if (!enrollment) {
|
|
423
|
-
throw new Error(
|
|
424
|
-
`A worker named '${args.name}' is already enrolled; revoke it first`,
|
|
425
|
-
);
|
|
426
|
-
}
|
|
427
|
-
return enrollment;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
/**
|
|
431
|
-
* Machine reconciler: the code for a machine it is about to provision
|
|
432
|
-
* under a rule, or null when that machine already enrolled or has a code
|
|
433
|
-
* waiting. Replicas asking at once get one code, so a person never gets
|
|
434
|
-
* two machines.
|
|
435
|
-
*/
|
|
436
|
-
createMachineEnrollment(args: {
|
|
437
|
-
name: string;
|
|
438
|
-
rule: string;
|
|
439
|
-
ttlMinutes: number;
|
|
440
|
-
placement: z.input<typeof WorkerPlacementSchema>;
|
|
441
|
-
}): Promise<{ code: string; nodeId: string; expiresAt: Date } | null> {
|
|
442
|
-
return this.issueEnrollment({ ...args, machineRule: args.rule });
|
|
443
|
-
}
|
|
444
|
-
|
|
445
|
-
private async issueEnrollment(args: {
|
|
446
|
-
name: string;
|
|
447
|
-
ttlMinutes?: number;
|
|
448
|
-
placement?: z.input<typeof WorkerPlacementSchema>;
|
|
449
|
-
machineRule?: string;
|
|
450
|
-
pool?: boolean;
|
|
451
|
-
}): Promise<{ code: string; nodeId: string; expiresAt: Date } | null> {
|
|
452
547
|
const name = WorkerName.parse(args.name);
|
|
453
|
-
const placement =
|
|
548
|
+
const placement = workerPlacement(args.placement ?? {});
|
|
454
549
|
return this.deps.db.transaction().execute(async (trx) => {
|
|
455
550
|
// One issuer per name at a time, across replicas, until commit.
|
|
456
|
-
await
|
|
457
|
-
trx,
|
|
458
|
-
);
|
|
551
|
+
await this.machines.lockName({ name, transaction: trx });
|
|
459
552
|
const enrolled = await trx
|
|
460
553
|
.selectFrom("work_workers")
|
|
461
554
|
.select("node_id")
|
|
@@ -463,20 +556,29 @@ export class WorkWorkerRegistry {
|
|
|
463
556
|
.where("name", "=", name)
|
|
464
557
|
.where("revoked_at", "is", null)
|
|
465
558
|
.executeTakeFirst();
|
|
466
|
-
if (enrolled)
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
559
|
+
if (enrolled)
|
|
560
|
+
throw new Error(
|
|
561
|
+
`A worker named '${name}' is already enrolled; revoke it first`,
|
|
562
|
+
);
|
|
563
|
+
const known = await this.machines.row({ name, transaction: trx });
|
|
564
|
+
if (known?.managed)
|
|
565
|
+
throw new Error(
|
|
566
|
+
`The machines hook's plan already names a machine '${name}'; enroll this one under another name`,
|
|
567
|
+
);
|
|
568
|
+
// A code nobody used: this enrollment replaces it.
|
|
569
|
+
await this.machines.forget({ name, transaction: trx });
|
|
570
|
+
await trx
|
|
571
|
+
.insertInto("work_machines")
|
|
572
|
+
.values({
|
|
573
|
+
tenant_id: this.deps.tenantId,
|
|
574
|
+
name,
|
|
575
|
+
managed: false,
|
|
576
|
+
labels: JSON.stringify(placement.labels),
|
|
577
|
+
serves: placement.for === null ? null : JSON.stringify(placement.for),
|
|
578
|
+
trusted: placement.trusted,
|
|
579
|
+
phase: "starting",
|
|
580
|
+
})
|
|
581
|
+
.execute();
|
|
480
582
|
const code = `wke_${randomBytes(24).toString("base64url")}`;
|
|
481
583
|
const expiresAt = new Date(Date.now() + (args.ttlMinutes ?? 30) * 60_000);
|
|
482
584
|
await trx
|
|
@@ -485,12 +587,6 @@ export class WorkWorkerRegistry {
|
|
|
485
587
|
code_hash: hash(code),
|
|
486
588
|
tenant_id: this.deps.tenantId,
|
|
487
589
|
name,
|
|
488
|
-
labels: JSON.stringify(placement.labels),
|
|
489
|
-
access: JSON.stringify(placement.access),
|
|
490
|
-
trusted: placement.trusted,
|
|
491
|
-
machine_rule: args.machineRule ?? null,
|
|
492
|
-
machine_ref: null,
|
|
493
|
-
pool: args.pool ?? false,
|
|
494
590
|
expires_at: expiresAt,
|
|
495
591
|
})
|
|
496
592
|
.execute();
|
|
@@ -508,37 +604,67 @@ export class WorkWorkerRegistry {
|
|
|
508
604
|
}): Promise<{ nodeId: string; name: string; credential: string }> {
|
|
509
605
|
const publicKey = ExecutorPublicKeySchema.parse(args.publicKey);
|
|
510
606
|
return this.deps.db.transaction().execute(async (trx) => {
|
|
607
|
+
const codeHash = hash(args.code);
|
|
511
608
|
const enrollment = await trx
|
|
609
|
+
.selectFrom("work_worker_enrollments")
|
|
610
|
+
.select("name")
|
|
611
|
+
.where("code_hash", "=", codeHash)
|
|
612
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
613
|
+
.executeTakeFirst();
|
|
614
|
+
const invalid = () =>
|
|
615
|
+
new Error("The enrollment code is invalid, used, or expired");
|
|
616
|
+
if (!enrollment) throw invalid();
|
|
617
|
+
|
|
618
|
+
// The same name lock orders this with issuance, refusal, replacement,
|
|
619
|
+
// and revocation. Recheck the code after acquiring the lock.
|
|
620
|
+
await this.machines.lockName({ name: enrollment.name, transaction: trx });
|
|
621
|
+
const machine = await trx
|
|
622
|
+
.selectFrom("work_machines")
|
|
623
|
+
.select(["phase", "disabled_at", "dropped_at"])
|
|
624
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
625
|
+
.where("name", "=", enrollment.name)
|
|
626
|
+
.forUpdate()
|
|
627
|
+
.executeTakeFirst();
|
|
628
|
+
if (machine?.phase !== "starting" || machine.dropped_at) throw invalid();
|
|
629
|
+
const consumed = await trx
|
|
512
630
|
.updateTable("work_worker_enrollments")
|
|
513
631
|
.set({ used_at: sql`now()` })
|
|
514
|
-
.where("code_hash", "=",
|
|
632
|
+
.where("code_hash", "=", codeHash)
|
|
515
633
|
.where("tenant_id", "=", this.deps.tenantId)
|
|
516
634
|
.where("used_at", "is", null)
|
|
517
635
|
.where("expires_at", ">", sql<Date>`now()`)
|
|
518
|
-
.returning(
|
|
519
|
-
"name",
|
|
520
|
-
"labels",
|
|
521
|
-
"access",
|
|
522
|
-
"trusted",
|
|
523
|
-
"machine_rule",
|
|
524
|
-
"machine_ref",
|
|
525
|
-
"pool",
|
|
526
|
-
])
|
|
636
|
+
.returning("code_hash")
|
|
527
637
|
.executeTakeFirst();
|
|
528
|
-
if (!
|
|
529
|
-
throw new Error("The enrollment code is invalid, used, or expired");
|
|
530
|
-
}
|
|
638
|
+
if (!consumed) throw invalid();
|
|
531
639
|
const nodeId = `${WORKER_NODE_PREFIX}${enrollment.name}`;
|
|
532
640
|
const secret = randomBytes(32).toString("base64url");
|
|
641
|
+
// A name enrolling again is a new machine under the old node id (ADR
|
|
642
|
+
// 0348): whatever the old one still held is retired in this
|
|
643
|
+
// transaction, before the node is enabled, so the new machine never
|
|
644
|
+
// inherits an Allocation, a reservation or a cache copy.
|
|
645
|
+
await this.retire({
|
|
646
|
+
nodeId,
|
|
647
|
+
name: enrollment.name,
|
|
648
|
+
reason: "replaced",
|
|
649
|
+
transaction: trx,
|
|
650
|
+
});
|
|
533
651
|
await trx
|
|
534
652
|
.deleteFrom("work_workers")
|
|
535
653
|
.where("node_id", "=", nodeId)
|
|
536
654
|
.where("revoked_at", "is not", null)
|
|
537
655
|
.execute();
|
|
538
|
-
// A re-enrolled name gets its (revoked, disabled) node back
|
|
656
|
+
// A re-enrolled name gets its (revoked, disabled) node back, as a
|
|
657
|
+
// new machine: nothing of the old one's disk (ADR 0336).
|
|
539
658
|
await trx
|
|
540
659
|
.updateTable("worker_nodes")
|
|
541
|
-
.set({
|
|
660
|
+
.set({
|
|
661
|
+
enabled: machine.disabled_at === null,
|
|
662
|
+
admission_revision: null,
|
|
663
|
+
lease_expires_at: sql`now()`,
|
|
664
|
+
disk: null,
|
|
665
|
+
disk_low_at: null,
|
|
666
|
+
disk_low_recorded_at: null,
|
|
667
|
+
})
|
|
542
668
|
.where("id", "=", nodeId)
|
|
543
669
|
.where("tenant_id", "=", this.deps.tenantId)
|
|
544
670
|
.execute();
|
|
@@ -549,12 +675,6 @@ export class WorkWorkerRegistry {
|
|
|
549
675
|
tenant_id: this.deps.tenantId,
|
|
550
676
|
name: enrollment.name,
|
|
551
677
|
credential_hash: hash(secret),
|
|
552
|
-
labels: JSON.stringify(enrollment.labels),
|
|
553
|
-
access: JSON.stringify(enrollment.access),
|
|
554
|
-
trusted: enrollment.trusted,
|
|
555
|
-
machine_rule: enrollment.machine_rule,
|
|
556
|
-
machine_ref: enrollment.machine_ref,
|
|
557
|
-
pool: enrollment.pool,
|
|
558
678
|
})
|
|
559
679
|
.execute();
|
|
560
680
|
await registerExecutorKey({
|
|
@@ -749,8 +869,8 @@ export class WorkWorkerRegistry {
|
|
|
749
869
|
const policy = await this.placement(args.nodeId);
|
|
750
870
|
if (
|
|
751
871
|
args.offer.isolation === "process" &&
|
|
752
|
-
!servesOneOwner(policy.
|
|
753
|
-
!servesNobody(policy.
|
|
872
|
+
!servesOneOwner(policy.for) &&
|
|
873
|
+
!servesNobody(policy.for) &&
|
|
754
874
|
!policy.trusted
|
|
755
875
|
) {
|
|
756
876
|
throw new WorkerIsolationError(args.name);
|
|
@@ -772,7 +892,14 @@ export class WorkWorkerRegistry {
|
|
|
772
892
|
// Workflow runs carry project secrets; they stay on the control plane.
|
|
773
893
|
workloads: ["agent"],
|
|
774
894
|
agentTopologies: ["controller"],
|
|
775
|
-
capabilities: [
|
|
895
|
+
capabilities: [
|
|
896
|
+
"network.egress",
|
|
897
|
+
...args.offer.capabilities.filter(
|
|
898
|
+
(capability) => capability !== MACHINE_CAPABILITIES.disk,
|
|
899
|
+
),
|
|
900
|
+
// It reports its disk, so admission reserves storage here (ADR 0336).
|
|
901
|
+
...(args.offer.disk ? [MACHINE_CAPABILITIES.disk] : []),
|
|
902
|
+
],
|
|
776
903
|
resources: {
|
|
777
904
|
...(args.offer.capacity.cpuMillis
|
|
778
905
|
? { cpuMillis: args.offer.capacity.cpuMillis }
|
|
@@ -780,6 +907,9 @@ export class WorkWorkerRegistry {
|
|
|
780
907
|
...(args.offer.capacity.memoryMb
|
|
781
908
|
? { memoryMb: args.offer.capacity.memoryMb }
|
|
782
909
|
: {}),
|
|
910
|
+
...(args.offer.disk
|
|
911
|
+
? { storageMb: diskBudgetMb(args.offer.disk) }
|
|
912
|
+
: {}),
|
|
783
913
|
},
|
|
784
914
|
resourceLimits: args.offer.resourceLimits,
|
|
785
915
|
labels: { ...policy.labels, node: args.nodeId, plane: "worker" },
|
|
@@ -798,7 +928,15 @@ export class WorkWorkerRegistry {
|
|
|
798
928
|
processes: args.offer.processes,
|
|
799
929
|
},
|
|
800
930
|
});
|
|
931
|
+
await this.serving({ nodeId: args.nodeId, name: args.name });
|
|
932
|
+
await this.machines.openPlacement({ name: args.name });
|
|
801
933
|
await this.seen(args.nodeId);
|
|
934
|
+
if (args.offer.disk)
|
|
935
|
+
await this.reportDisk({
|
|
936
|
+
nodeId: args.nodeId,
|
|
937
|
+
session: args.session,
|
|
938
|
+
disk: args.offer.disk,
|
|
939
|
+
});
|
|
802
940
|
if (connected.superseded)
|
|
803
941
|
this.deps.log?.(`Worker ${args.name} restarted and connected`);
|
|
804
942
|
else this.deps.log?.(`Worker ${args.name} connected`);
|
|
@@ -815,82 +953,92 @@ export class WorkWorkerRegistry {
|
|
|
815
953
|
}
|
|
816
954
|
}
|
|
817
955
|
|
|
818
|
-
/**
|
|
819
|
-
* One enrolled worker's placement policy, as its connection is checked
|
|
820
|
-
* against: a released machine takes no new work (ADR 0205), so it serves
|
|
821
|
-
* nobody whatever access it keeps.
|
|
822
|
-
*/
|
|
956
|
+
/** One enrolled worker's placement, as its connection is checked against. */
|
|
823
957
|
async placement(nodeId: string): Promise<WorkerPlacement> {
|
|
824
|
-
|
|
825
|
-
.selectFrom("work_workers")
|
|
826
|
-
.select(["labels", "access", "trusted", "released_at"])
|
|
827
|
-
.where("node_id", "=", nodeId)
|
|
828
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
829
|
-
.executeTakeFirstOrThrow();
|
|
830
|
-
const stored = storedPlacement(row);
|
|
831
|
-
return row.released_at ? { ...stored, access: NOBODY } : stored;
|
|
958
|
+
return this.machines.placementOf({ name: workerNameOf(nodeId) });
|
|
832
959
|
}
|
|
833
960
|
|
|
834
|
-
/**
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
* takes no new work from the moment it is released, and the Allocations
|
|
838
|
-
* it already holds keep reaching it until their chats give their
|
|
839
|
-
* workspaces back.
|
|
840
|
-
*/
|
|
841
|
-
async placements(): Promise<Map<string, ScheduledPlacement>> {
|
|
842
|
-
const rows = await this.deps.db
|
|
843
|
-
.selectFrom("work_workers")
|
|
844
|
-
.select(["node_id", "labels", "access", "trusted", "released_at"])
|
|
845
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
846
|
-
.where("revoked_at", "is", null)
|
|
847
|
-
.execute();
|
|
848
|
-
return new Map(
|
|
849
|
-
rows.map((row) => [
|
|
850
|
-
row.node_id,
|
|
851
|
-
{ ...storedPlacement(row), released: row.released_at !== null },
|
|
852
|
-
]),
|
|
853
|
-
);
|
|
961
|
+
/** Placement of every machine, by node, for the scheduler. */
|
|
962
|
+
placements(): Promise<Map<string, ScheduledPlacement>> {
|
|
963
|
+
return this.machines.placements();
|
|
854
964
|
}
|
|
855
965
|
|
|
856
|
-
/**
|
|
966
|
+
/**
|
|
967
|
+
* Operator: change whom a machine enrolled by hand is for, its labels and
|
|
968
|
+
* whether those it serves trust each other. A machine the machines hook
|
|
969
|
+
* made follows its plan instead. Work on it is not moved: change whom it
|
|
970
|
+
* is for while it holds none, or leave that to the plan, which resets a
|
|
971
|
+
* machine before someone new may use it.
|
|
972
|
+
*/
|
|
857
973
|
async setPlacement(args: {
|
|
858
974
|
name: string;
|
|
859
975
|
placement: Partial<z.input<typeof WorkerPlacementSchema>>;
|
|
860
976
|
}): Promise<WorkerPlacement> {
|
|
861
|
-
const
|
|
862
|
-
const row = await this.
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
const current =
|
|
869
|
-
const next =
|
|
870
|
-
|
|
871
|
-
.
|
|
872
|
-
.
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
.
|
|
878
|
-
.
|
|
879
|
-
.
|
|
977
|
+
const name = WorkerName.parse(args.name);
|
|
978
|
+
const row = await this.machines.row({ name });
|
|
979
|
+
if (!row) throw new Error(`Work knows no machine named '${name}'`);
|
|
980
|
+
if (row.managed)
|
|
981
|
+
throw new Error(
|
|
982
|
+
`Machine '${name}' follows the machines hook's plan: change its plan entry instead`,
|
|
983
|
+
);
|
|
984
|
+
const current = await this.machines.placementOf({ name });
|
|
985
|
+
const next = workerPlacement({
|
|
986
|
+
labels: current.labels,
|
|
987
|
+
...(current.for === null ? {} : { for: [...current.for] }),
|
|
988
|
+
trusted: current.trusted,
|
|
989
|
+
...args.placement,
|
|
990
|
+
});
|
|
991
|
+
await this.machines.configure({
|
|
992
|
+
name,
|
|
993
|
+
labels: next.labels,
|
|
994
|
+
trusted: next.trusted,
|
|
995
|
+
reason: row.reason,
|
|
996
|
+
lostAfterMinutes: row.lost_after_minutes,
|
|
997
|
+
});
|
|
998
|
+
if (
|
|
999
|
+
row.reset_pending ||
|
|
1000
|
+
(row.phase !== "starting" &&
|
|
1001
|
+
principalsChangeNeedsReset({ from: current.for, to: next.for }))
|
|
1002
|
+
) {
|
|
1003
|
+
await this.machines.beginReset({ name, for: next.for });
|
|
1004
|
+
await this.resetPlacement({ name });
|
|
1005
|
+
return this.machines.placementOf({ name });
|
|
1006
|
+
}
|
|
1007
|
+
await this.machines.setFor({ name, for: next.for });
|
|
880
1008
|
return next;
|
|
881
1009
|
}
|
|
882
1010
|
|
|
883
1011
|
/**
|
|
884
|
-
*
|
|
885
|
-
*
|
|
1012
|
+
* Operator: disable a machine, or enable it again (ADR 0190). Disabled,
|
|
1013
|
+
* it takes no work and its work waits for it; it is never called lost.
|
|
886
1014
|
*/
|
|
887
|
-
async
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
1015
|
+
async setDisabled(args: {
|
|
1016
|
+
name: string;
|
|
1017
|
+
disabled: boolean;
|
|
1018
|
+
}): Promise<boolean> {
|
|
1019
|
+
const name = WorkerName.parse(args.name);
|
|
1020
|
+
const row = await this.deps.db
|
|
1021
|
+
.updateTable("work_machines")
|
|
1022
|
+
.set({
|
|
1023
|
+
disabled_at: args.disabled
|
|
1024
|
+
? sql<Date>`coalesce(disabled_at, now())`
|
|
1025
|
+
: null,
|
|
1026
|
+
updated_at: sql`now()`,
|
|
1027
|
+
})
|
|
1028
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1029
|
+
.where("name", "=", name)
|
|
1030
|
+
.returning("phase")
|
|
1031
|
+
.executeTakeFirst();
|
|
1032
|
+
if (!row) return false;
|
|
1033
|
+
// A machine Work stopped stays off until it is resumed.
|
|
1034
|
+
const serves = ["starting", "running", "resuming"].includes(row.phase);
|
|
1035
|
+
await this.deps.nodes.setEnabled({
|
|
1036
|
+
tenantId: this.deps.tenantId,
|
|
1037
|
+
authorityId: this.deps.authorityId,
|
|
1038
|
+
nodeId: `${WORKER_NODE_PREFIX}${name}`,
|
|
1039
|
+
enabled: !args.disabled && serves,
|
|
1040
|
+
});
|
|
1041
|
+
return true;
|
|
894
1042
|
}
|
|
895
1043
|
|
|
896
1044
|
/**
|
|
@@ -902,6 +1050,14 @@ export class WorkWorkerRegistry {
|
|
|
902
1050
|
*/
|
|
903
1051
|
async maintain(): Promise<void> {
|
|
904
1052
|
await this.queue.sweep().catch(() => {});
|
|
1053
|
+
await this.retireGone().catch((error: unknown) =>
|
|
1054
|
+
this.deps.log?.(
|
|
1055
|
+
`Retiring lost machines' work failed (tried again on the next pass): ${
|
|
1056
|
+
error instanceof Error ? error.message : String(error)
|
|
1057
|
+
}`,
|
|
1058
|
+
),
|
|
1059
|
+
);
|
|
1060
|
+
await this.forgetNeverEnrolled().catch(() => {});
|
|
905
1061
|
this.cleaning ??= this.cleanup().finally(() => {
|
|
906
1062
|
this.cleaning = undefined;
|
|
907
1063
|
});
|
|
@@ -909,7 +1065,171 @@ export class WorkWorkerRegistry {
|
|
|
909
1065
|
|
|
910
1066
|
private cleaning: Promise<void> | undefined;
|
|
911
1067
|
|
|
1068
|
+
/** A machine enrolled by hand whose code expired unused is known no more. */
|
|
1069
|
+
private async forgetNeverEnrolled(): Promise<void> {
|
|
1070
|
+
await this.deps.db
|
|
1071
|
+
.deleteFrom("work_machines")
|
|
1072
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1073
|
+
.where("managed", "=", false)
|
|
1074
|
+
.where("phase", "=", "starting")
|
|
1075
|
+
.where(({ not, exists, selectFrom }) =>
|
|
1076
|
+
not(
|
|
1077
|
+
exists(
|
|
1078
|
+
selectFrom("work_workers")
|
|
1079
|
+
.select("work_workers.node_id")
|
|
1080
|
+
.whereRef(
|
|
1081
|
+
"work_workers.tenant_id",
|
|
1082
|
+
"=",
|
|
1083
|
+
"work_machines.tenant_id",
|
|
1084
|
+
)
|
|
1085
|
+
.whereRef("work_workers.name", "=", "work_machines.name")
|
|
1086
|
+
.where("work_workers.revoked_at", "is", null),
|
|
1087
|
+
),
|
|
1088
|
+
),
|
|
1089
|
+
)
|
|
1090
|
+
.where(({ not, exists, selectFrom }) =>
|
|
1091
|
+
not(
|
|
1092
|
+
exists(
|
|
1093
|
+
selectFrom("work_worker_enrollments")
|
|
1094
|
+
.select("work_worker_enrollments.code_hash")
|
|
1095
|
+
.whereRef(
|
|
1096
|
+
"work_worker_enrollments.tenant_id",
|
|
1097
|
+
"=",
|
|
1098
|
+
"work_machines.tenant_id",
|
|
1099
|
+
)
|
|
1100
|
+
.whereRef(
|
|
1101
|
+
"work_worker_enrollments.name",
|
|
1102
|
+
"=",
|
|
1103
|
+
"work_machines.name",
|
|
1104
|
+
)
|
|
1105
|
+
.where("work_worker_enrollments.used_at", "is", null)
|
|
1106
|
+
.where(
|
|
1107
|
+
"work_worker_enrollments.expires_at",
|
|
1108
|
+
">",
|
|
1109
|
+
sql<Date>`now()`,
|
|
1110
|
+
),
|
|
1111
|
+
),
|
|
1112
|
+
),
|
|
1113
|
+
)
|
|
1114
|
+
.execute();
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
/**
|
|
1118
|
+
* Retire the work of machines that are gone (ADR 0348), on any replica:
|
|
1119
|
+
* a revoked worker's, when the process that revoked it stopped before
|
|
1120
|
+
* retiring it, and a lost machine's, whoever enrolled it. Its chats are
|
|
1121
|
+
* admitted again on a machine open to their owner, or wait for one; the
|
|
1122
|
+
* plan replaces a machine it still names, and a machine enrolled by hand
|
|
1123
|
+
* that comes back removes the sandboxes whose Allocations are gone. A
|
|
1124
|
+
* machine an operator disabled, or one Work stopped, is never lost.
|
|
1125
|
+
*/
|
|
1126
|
+
private async retireGone(): Promise<void> {
|
|
1127
|
+
const revoked = await this.deps.db
|
|
1128
|
+
.selectFrom("work_workers")
|
|
1129
|
+
.select(["node_id", "name"])
|
|
1130
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1131
|
+
.where("revoked_at", "is not", null)
|
|
1132
|
+
.where(({ exists, selectFrom }) =>
|
|
1133
|
+
exists(
|
|
1134
|
+
selectFrom("execution_allocations")
|
|
1135
|
+
.select("execution_allocations.id")
|
|
1136
|
+
.whereRef(
|
|
1137
|
+
"execution_allocations.worker_node_id",
|
|
1138
|
+
"=",
|
|
1139
|
+
"work_workers.node_id",
|
|
1140
|
+
)
|
|
1141
|
+
.where("execution_allocations.capacity_released_at", "is", null),
|
|
1142
|
+
),
|
|
1143
|
+
)
|
|
1144
|
+
.execute();
|
|
1145
|
+
for (const worker of revoked)
|
|
1146
|
+
await this.retireRevoked({ name: worker.name, nodeId: worker.node_id });
|
|
1147
|
+
const lost = [...(await this.machines.reach())].filter(
|
|
1148
|
+
([, machine]) => machine.state === "lost",
|
|
1149
|
+
);
|
|
1150
|
+
if (lost.length === 0) return;
|
|
1151
|
+
const holding = await this.deps.db
|
|
1152
|
+
.selectFrom("execution_allocations")
|
|
1153
|
+
.select("worker_node_id")
|
|
1154
|
+
.distinct()
|
|
1155
|
+
.where(
|
|
1156
|
+
"worker_node_id",
|
|
1157
|
+
"in",
|
|
1158
|
+
lost.map(([, machine]) => machine.nodeId),
|
|
1159
|
+
)
|
|
1160
|
+
.where("capacity_released_at", "is", null)
|
|
1161
|
+
.execute();
|
|
1162
|
+
const held = new Set(holding.map((row) => row.worker_node_id));
|
|
1163
|
+
for (const [name, machine] of lost) {
|
|
1164
|
+
if (held.has(machine.nodeId))
|
|
1165
|
+
await this.retire({ nodeId: machine.nodeId, name, reason: "lost" });
|
|
1166
|
+
// The sequencer says so for the machines it makes, as it replaces them.
|
|
1167
|
+
if (machine.managed || machine.lostNoted) continue;
|
|
1168
|
+
const noted = await this.deps.db
|
|
1169
|
+
.updateTable("work_machines")
|
|
1170
|
+
.set({ lost_at: sql`now()` })
|
|
1171
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1172
|
+
.where("name", "=", name)
|
|
1173
|
+
.where("lost_at", "is", null)
|
|
1174
|
+
.returning("name")
|
|
1175
|
+
.executeTakeFirst();
|
|
1176
|
+
if (noted) await this.emit({ kind: "machine.lost", name });
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
private async retireRevoked(args: {
|
|
1181
|
+
name: string;
|
|
1182
|
+
nodeId: string;
|
|
1183
|
+
}): Promise<void> {
|
|
1184
|
+
await this.deps.db.transaction().execute(async (trx) => {
|
|
1185
|
+
await this.machines.lockName({ name: args.name, transaction: trx });
|
|
1186
|
+
const revoked = await trx
|
|
1187
|
+
.selectFrom("work_workers")
|
|
1188
|
+
.select("name")
|
|
1189
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1190
|
+
.where("node_id", "=", args.nodeId)
|
|
1191
|
+
.where("revoked_at", "is not", null)
|
|
1192
|
+
.executeTakeFirst();
|
|
1193
|
+
if (revoked)
|
|
1194
|
+
await this.retire({ ...args, reason: "revoked", transaction: trx });
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/**
|
|
1199
|
+
* Retire what a machine held, through core's one retirement (ADR 0348).
|
|
1200
|
+
* Safe to call again, from any replica.
|
|
1201
|
+
*/
|
|
1202
|
+
private async retire(args: {
|
|
1203
|
+
nodeId: string;
|
|
1204
|
+
name: string;
|
|
1205
|
+
reason: NodeRetireReason;
|
|
1206
|
+
transaction?: Transaction<DB>;
|
|
1207
|
+
}): Promise<void> {
|
|
1208
|
+
const retired = await retireNodeWork({
|
|
1209
|
+
db: this.deps.db,
|
|
1210
|
+
nodeId: args.nodeId,
|
|
1211
|
+
reason: args.reason,
|
|
1212
|
+
...(args.transaction ? { transaction: args.transaction } : {}),
|
|
1213
|
+
});
|
|
1214
|
+
if (retired.released + retired.freed === 0) return;
|
|
1215
|
+
this.deps.log?.(
|
|
1216
|
+
`Machine ${args.name} is ${args.reason === "lost" ? "lost" : "gone"}: ${retired.released} workspace(s) retired, ${retired.freed} released workspace(s) freed; their chats continue from their last save`,
|
|
1217
|
+
);
|
|
1218
|
+
this.deps.retired?.();
|
|
1219
|
+
}
|
|
1220
|
+
|
|
912
1221
|
private async cleanup(): Promise<void> {
|
|
1222
|
+
const pending = await this.deps.db
|
|
1223
|
+
.selectFrom("work_machines")
|
|
1224
|
+
.select("name")
|
|
1225
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1226
|
+
.where("managed", "=", false)
|
|
1227
|
+
.where("reset_pending", "=", true)
|
|
1228
|
+
.execute();
|
|
1229
|
+
for (const { name } of pending)
|
|
1230
|
+
await this.resetPlacement({ name }).catch((error: unknown) =>
|
|
1231
|
+
this.deps.log?.(`Machine reset deferred for ${name}: ${String(error)}`),
|
|
1232
|
+
);
|
|
913
1233
|
const nodes = await this.deps.nodes.list({
|
|
914
1234
|
tenantId: this.deps.tenantId,
|
|
915
1235
|
authorityId: this.deps.authorityId,
|
|
@@ -941,49 +1261,112 @@ export class WorkWorkerRegistry {
|
|
|
941
1261
|
|
|
942
1262
|
/**
|
|
943
1263
|
* Operator: end a worker's authority now. Its credential, any rotated one
|
|
944
|
-
* still pending, and its key stop working.
|
|
1264
|
+
* still pending, and its key stop working. A machine enrolled by hand is
|
|
1265
|
+
* known no more; one the machines hook made is destroyed by the next
|
|
1266
|
+
* pass, and made again if the plan still names it.
|
|
945
1267
|
*/
|
|
946
1268
|
async revoke(args: { name: string }): Promise<boolean> {
|
|
947
|
-
const row = await this.deps.db
|
|
948
|
-
|
|
949
|
-
.
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
1269
|
+
const row = await this.deps.db.transaction().execute(async (trx) => {
|
|
1270
|
+
const { name } = args;
|
|
1271
|
+
await this.machines.lockName({ name, transaction: trx });
|
|
1272
|
+
const nodeId = `${WORKER_NODE_PREFIX}${name}`;
|
|
1273
|
+
await trx
|
|
1274
|
+
.selectFrom("worker_nodes")
|
|
1275
|
+
.select("id")
|
|
1276
|
+
.where("id", "=", nodeId)
|
|
1277
|
+
.forUpdate()
|
|
1278
|
+
.executeTakeFirst();
|
|
1279
|
+
const worker = await trx
|
|
1280
|
+
.updateTable("work_workers")
|
|
1281
|
+
.set({
|
|
1282
|
+
revoked_at: sql`now()`,
|
|
1283
|
+
pending_credential_hash: null,
|
|
1284
|
+
pending_public_key: null,
|
|
1285
|
+
pending_issued_at: null,
|
|
1286
|
+
pending_rotation: null,
|
|
1287
|
+
})
|
|
1288
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1289
|
+
.where("name", "=", name)
|
|
1290
|
+
.where("revoked_at", "is", null)
|
|
1291
|
+
.returning("node_id")
|
|
1292
|
+
.executeTakeFirst();
|
|
1293
|
+
if (!worker) return undefined;
|
|
1294
|
+
await forgetExecutorKey({
|
|
1295
|
+
db: trx,
|
|
1296
|
+
executor: nodeExecutor(worker.node_id),
|
|
1297
|
+
});
|
|
1298
|
+
await trx
|
|
1299
|
+
.updateTable("worker_nodes")
|
|
1300
|
+
.set({ enabled: false })
|
|
1301
|
+
.where("id", "=", worker.node_id)
|
|
1302
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1303
|
+
.execute();
|
|
1304
|
+
const machine = await this.machines.row({ name, transaction: trx });
|
|
1305
|
+
if (machine && !machine.managed)
|
|
1306
|
+
await this.machines.forget({ name, transaction: trx });
|
|
1307
|
+
return worker;
|
|
1308
|
+
});
|
|
1309
|
+
if (!row) return false;
|
|
1310
|
+
await this.retireRevoked({ name: args.name, nodeId: row.node_id });
|
|
1311
|
+
return true;
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
/**
|
|
1315
|
+
* Take a machine out of service for good, unless work landed on it (ADRs
|
|
1316
|
+
* 0258, 0349): under its node's row lock, which creating an Allocation
|
|
1317
|
+
* takes too, it is revoked and disabled and becomes `destroying` only
|
|
1318
|
+
* while no Allocation holds its capacity, so nothing is placed on a
|
|
1319
|
+
* machine about to be destroyed. One whose worker an operator revoked,
|
|
1320
|
+
* and one that never enrolled, hold nothing. False when it was kept.
|
|
1321
|
+
*/
|
|
1322
|
+
async retireMachine(args: { name: string }): Promise<boolean> {
|
|
1323
|
+
const taken = await this.takeOutOfService({ ...args, lost: null });
|
|
1324
|
+
if (taken)
|
|
1325
|
+
await this.retire({
|
|
1326
|
+
nodeId: `${WORKER_NODE_PREFIX}${args.name}`,
|
|
1327
|
+
name: args.name,
|
|
1328
|
+
reason: "revoked",
|
|
1329
|
+
});
|
|
1330
|
+
return taken;
|
|
1331
|
+
}
|
|
974
1332
|
|
|
975
1333
|
/**
|
|
976
|
-
*
|
|
977
|
-
*
|
|
978
|
-
*
|
|
979
|
-
*
|
|
980
|
-
*
|
|
981
|
-
* connected and has not called for `unseenForMs`, is revoked anyway. False
|
|
982
|
-
* when it was kept, or was not enrolled.
|
|
1334
|
+
* A machine has been unseen for `unseenForMs` (ADR 0348): take it out of
|
|
1335
|
+
* service for good and retire what it held, so its chats continue from
|
|
1336
|
+
* their last save and its plan may replace it. Under its node's row
|
|
1337
|
+
* lock, and only while it is still unseen: a machine that called again
|
|
1338
|
+
* meanwhile is kept. False when it was kept.
|
|
983
1339
|
*/
|
|
984
|
-
async
|
|
1340
|
+
async declareLost(args: {
|
|
1341
|
+
name: string;
|
|
1342
|
+
unseenForMs: number;
|
|
1343
|
+
}): Promise<boolean> {
|
|
1344
|
+
const lost = await this.takeOutOfService({
|
|
1345
|
+
name: args.name,
|
|
1346
|
+
lost: { unseenForMs: args.unseenForMs },
|
|
1347
|
+
});
|
|
1348
|
+
if (lost)
|
|
1349
|
+
await this.retire({
|
|
1350
|
+
nodeId: `${WORKER_NODE_PREFIX}${args.name}`,
|
|
1351
|
+
name: args.name,
|
|
1352
|
+
reason: "lost",
|
|
1353
|
+
});
|
|
1354
|
+
return lost;
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
/**
|
|
1358
|
+
* Revoke and disable a machine under its node's row lock and make it
|
|
1359
|
+
* `destroying`. Retiring what it held follows once this commits:
|
|
1360
|
+
* disabled, it takes nothing new.
|
|
1361
|
+
*/
|
|
1362
|
+
private async takeOutOfService(args: {
|
|
1363
|
+
name: string;
|
|
1364
|
+
/** Only a machine still unseen this long, whatever it holds. */
|
|
1365
|
+
lost: { unseenForMs: number } | null;
|
|
1366
|
+
}): Promise<boolean> {
|
|
985
1367
|
const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
|
|
986
1368
|
return this.deps.db.transaction().execute(async (trx) => {
|
|
1369
|
+
await this.machines.lockName({ name: args.name, transaction: trx });
|
|
987
1370
|
const node = await trx
|
|
988
1371
|
.selectFrom("worker_nodes")
|
|
989
1372
|
.select(sql<boolean>`enabled AND lease_expires_at > now()`.as("live"))
|
|
@@ -991,27 +1374,50 @@ export class WorkWorkerRegistry {
|
|
|
991
1374
|
.where("tenant_id", "=", this.deps.tenantId)
|
|
992
1375
|
.forUpdate()
|
|
993
1376
|
.executeTakeFirst();
|
|
994
|
-
const
|
|
995
|
-
.selectFrom("
|
|
996
|
-
.select(
|
|
997
|
-
|
|
998
|
-
|
|
1377
|
+
const worker = await trx
|
|
1378
|
+
.selectFrom("work_workers")
|
|
1379
|
+
.select([
|
|
1380
|
+
"revoked_at",
|
|
1381
|
+
sql<number>`(extract(epoch from (now() - coalesce(last_seen_at, enrolled_at))) * 1000)::float8`.as(
|
|
1382
|
+
"unseen_for_ms",
|
|
1383
|
+
),
|
|
1384
|
+
])
|
|
1385
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1386
|
+
.where("name", "=", args.name)
|
|
999
1387
|
.executeTakeFirst();
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
.
|
|
1009
|
-
|
|
1010
|
-
)
|
|
1388
|
+
const serving = worker !== undefined && worker.revoked_at === null;
|
|
1389
|
+
if (args.lost) {
|
|
1390
|
+
// It called again meanwhile: it is kept as it is.
|
|
1391
|
+
if (serving && node?.live) return false;
|
|
1392
|
+
if (serving && Number(worker.unseen_for_ms) < args.lost.unseenForMs)
|
|
1393
|
+
return false;
|
|
1394
|
+
} else if (serving) {
|
|
1395
|
+
const held = await trx
|
|
1396
|
+
.selectFrom("execution_allocations")
|
|
1397
|
+
.select((eb) => eb.fn.countAll<string>().as("count"))
|
|
1398
|
+
.where("worker_node_id", "=", nodeId)
|
|
1399
|
+
.where("capacity_released_at", "is", null)
|
|
1011
1400
|
.executeTakeFirst();
|
|
1012
|
-
|
|
1401
|
+
// Connected, it gives them back as its chats idle (ADR 0173).
|
|
1402
|
+
if (Number(held?.count ?? 0) > 0) return false;
|
|
1013
1403
|
}
|
|
1014
|
-
const
|
|
1404
|
+
const moved = await this.machines.setPhase({
|
|
1405
|
+
name: args.name,
|
|
1406
|
+
phase: "destroying",
|
|
1407
|
+
...(args.lost ? { lost: true } : {}),
|
|
1408
|
+
transaction: trx,
|
|
1409
|
+
});
|
|
1410
|
+
if (!moved) return false;
|
|
1411
|
+
// Its code stops working: nothing enrolls under this name until its
|
|
1412
|
+
// platform confirmed it gone.
|
|
1413
|
+
await trx
|
|
1414
|
+
.deleteFrom("work_worker_enrollments")
|
|
1415
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1416
|
+
.where("name", "=", args.name)
|
|
1417
|
+
.where("used_at", "is", null)
|
|
1418
|
+
.execute();
|
|
1419
|
+
if (!serving) return true;
|
|
1420
|
+
await trx
|
|
1015
1421
|
.updateTable("work_workers")
|
|
1016
1422
|
.set({
|
|
1017
1423
|
revoked_at: sql`now()`,
|
|
@@ -1023,9 +1429,7 @@ export class WorkWorkerRegistry {
|
|
|
1023
1429
|
.where("tenant_id", "=", this.deps.tenantId)
|
|
1024
1430
|
.where("name", "=", args.name)
|
|
1025
1431
|
.where("revoked_at", "is", null)
|
|
1026
|
-
.
|
|
1027
|
-
.executeTakeFirst();
|
|
1028
|
-
if (!revoked) return false;
|
|
1432
|
+
.execute();
|
|
1029
1433
|
await forgetExecutorKey({ db: trx, executor: nodeExecutor(nodeId) });
|
|
1030
1434
|
await trx
|
|
1031
1435
|
.updateTable("worker_nodes")
|
|
@@ -1039,323 +1443,100 @@ export class WorkWorkerRegistry {
|
|
|
1039
1443
|
}
|
|
1040
1444
|
|
|
1041
1445
|
/**
|
|
1042
|
-
*
|
|
1043
|
-
*
|
|
1446
|
+
* Begin stopping a machine (ADR 0350): under its node's row lock, only
|
|
1447
|
+
* while no Allocation holds its capacity, it takes no new work and
|
|
1448
|
+
* becomes `stopping`. It keeps its worker, its credential and its disk.
|
|
1449
|
+
* False when it holds something, or is not serving.
|
|
1044
1450
|
*/
|
|
1045
|
-
async
|
|
1046
|
-
const
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
const load = this.deps.db
|
|
1053
|
-
.selectFrom("execution_allocations")
|
|
1054
|
-
.select([
|
|
1055
|
-
"worker_node_id",
|
|
1056
|
-
sql<string>`count(*) FILTER (WHERE capacity_released_at IS NULL)`.as(
|
|
1057
|
-
"holding",
|
|
1058
|
-
),
|
|
1059
|
-
sql<Date | null>`max(capacity_released_at)`.as("last_released"),
|
|
1060
|
-
])
|
|
1061
|
-
.where("worker_node_id", "in", machines)
|
|
1062
|
-
.groupBy("worker_node_id")
|
|
1063
|
-
.as("load");
|
|
1064
|
-
const [rows, nodes] = await Promise.all([
|
|
1065
|
-
this.deps.db
|
|
1066
|
-
.selectFrom("work_workers")
|
|
1067
|
-
.leftJoin(load, "load.worker_node_id", "work_workers.node_id")
|
|
1068
|
-
.select([
|
|
1069
|
-
"work_workers.name",
|
|
1070
|
-
"work_workers.node_id",
|
|
1071
|
-
"load.holding",
|
|
1072
|
-
sql<boolean>`work_workers.last_seen_at IS NULL`.as("never_connected"),
|
|
1073
|
-
sql<number>`(extract(epoch from (now() - greatest(work_workers.enrolled_at, load.last_released))) * 1000)::float8`.as(
|
|
1074
|
-
"idle_for_ms",
|
|
1075
|
-
),
|
|
1076
|
-
sql<number>`(extract(epoch from (now() - coalesce(work_workers.last_seen_at, work_workers.enrolled_at))) * 1000)::float8`.as(
|
|
1077
|
-
"unseen_for_ms",
|
|
1078
|
-
),
|
|
1079
|
-
])
|
|
1080
|
-
.where("work_workers.tenant_id", "=", this.deps.tenantId)
|
|
1081
|
-
.where("work_workers.machine_rule", "is not", null)
|
|
1082
|
-
.where("work_workers.revoked_at", "is", null)
|
|
1083
|
-
.execute(),
|
|
1084
|
-
this.deps.nodes.list({
|
|
1085
|
-
tenantId: this.deps.tenantId,
|
|
1086
|
-
authorityId: this.deps.authorityId,
|
|
1087
|
-
}),
|
|
1088
|
-
]);
|
|
1089
|
-
const byId = new Map(nodes.map((node) => [node.id, node]));
|
|
1090
|
-
return new Map(
|
|
1091
|
-
rows.map((row) => {
|
|
1092
|
-
const node = byId.get(row.node_id);
|
|
1093
|
-
const capacity = node?.capacity;
|
|
1094
|
-
const live =
|
|
1095
|
-
node?.available && capacity
|
|
1096
|
-
? {
|
|
1097
|
-
descriptor: node.descriptor,
|
|
1098
|
-
defaults: node.defaults,
|
|
1099
|
-
free: {
|
|
1100
|
-
workspaces: Math.max(
|
|
1101
|
-
0,
|
|
1102
|
-
capacity.workspaces - node.usage.workspaces,
|
|
1103
|
-
),
|
|
1104
|
-
...(capacity.cpuMillis !== undefined
|
|
1105
|
-
? {
|
|
1106
|
-
cpuMillis: Math.max(
|
|
1107
|
-
0,
|
|
1108
|
-
capacity.cpuMillis - node.usage.cpuMillis,
|
|
1109
|
-
),
|
|
1110
|
-
}
|
|
1111
|
-
: {}),
|
|
1112
|
-
...(capacity.memoryMb !== undefined
|
|
1113
|
-
? {
|
|
1114
|
-
memoryMb: Math.max(
|
|
1115
|
-
0,
|
|
1116
|
-
capacity.memoryMb - node.usage.memoryMb,
|
|
1117
|
-
),
|
|
1118
|
-
}
|
|
1119
|
-
: {}),
|
|
1120
|
-
},
|
|
1121
|
-
}
|
|
1122
|
-
: null;
|
|
1123
|
-
return [
|
|
1124
|
-
row.name,
|
|
1125
|
-
{
|
|
1126
|
-
holding: Number(row.holding ?? 0),
|
|
1127
|
-
idleForMs: Number(row.idle_for_ms),
|
|
1128
|
-
unseenForMs: Number(row.unseen_for_ms),
|
|
1129
|
-
neverConnected: row.never_connected,
|
|
1130
|
-
live,
|
|
1131
|
-
},
|
|
1132
|
-
];
|
|
1133
|
-
}),
|
|
1134
|
-
);
|
|
1135
|
-
}
|
|
1136
|
-
|
|
1137
|
-
/** The platform's id for the machine created with this enrollment code. */
|
|
1138
|
-
async recordMachineRef(args: { code: string; ref: string }): Promise<void> {
|
|
1139
|
-
const enrollment = await this.deps.db
|
|
1140
|
-
.updateTable("work_worker_enrollments")
|
|
1141
|
-
.set({ machine_ref: args.ref })
|
|
1142
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1143
|
-
.where("code_hash", "=", hash(args.code))
|
|
1144
|
-
.returning(["name", "used_at"])
|
|
1145
|
-
.executeTakeFirst();
|
|
1146
|
-
// The machine may have enrolled before the platform answered.
|
|
1147
|
-
if (enrollment?.used_at)
|
|
1148
|
-
await this.deps.db
|
|
1149
|
-
.updateTable("work_workers")
|
|
1150
|
-
.set({ machine_ref: args.ref })
|
|
1451
|
+
async beginStop(args: { name: string; at?: string }): Promise<boolean> {
|
|
1452
|
+
const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
|
|
1453
|
+
return this.deps.db.transaction().execute(async (trx) => {
|
|
1454
|
+
await trx
|
|
1455
|
+
.selectFrom("worker_nodes")
|
|
1456
|
+
.select("id")
|
|
1457
|
+
.where("id", "=", nodeId)
|
|
1151
1458
|
.where("tenant_id", "=", this.deps.tenantId)
|
|
1152
|
-
.
|
|
1153
|
-
.
|
|
1154
|
-
|
|
1459
|
+
.forUpdate()
|
|
1460
|
+
.executeTakeFirst();
|
|
1461
|
+
const held = await trx
|
|
1462
|
+
.selectFrom("execution_allocations")
|
|
1463
|
+
.select((eb) => eb.fn.countAll<string>().as("count"))
|
|
1464
|
+
.where("worker_node_id", "=", nodeId)
|
|
1465
|
+
.where("capacity_released_at", "is", null)
|
|
1466
|
+
.executeTakeFirst();
|
|
1467
|
+
if (Number(held?.count ?? 0) > 0) return false;
|
|
1468
|
+
const moved = await this.machines.setPhase({
|
|
1469
|
+
name: args.name,
|
|
1470
|
+
phase: "stopping",
|
|
1471
|
+
from: ["running"],
|
|
1472
|
+
...(args.at ? { at: args.at } : {}),
|
|
1473
|
+
transaction: trx,
|
|
1474
|
+
});
|
|
1475
|
+
if (!moved) return false;
|
|
1476
|
+
await trx
|
|
1477
|
+
.updateTable("worker_nodes")
|
|
1478
|
+
.set({ enabled: false })
|
|
1479
|
+
.where("id", "=", nodeId)
|
|
1480
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1481
|
+
.where("authority_id", "=", this.deps.authorityId)
|
|
1155
1482
|
.execute();
|
|
1483
|
+
return true;
|
|
1484
|
+
});
|
|
1156
1485
|
}
|
|
1157
1486
|
|
|
1158
1487
|
/**
|
|
1159
|
-
*
|
|
1160
|
-
*
|
|
1161
|
-
*
|
|
1162
|
-
* ({@link forgetMachine}), whether or not its reference was recorded.
|
|
1488
|
+
* Begin resuming a stopped machine (ADR 0350): it becomes `resuming`,
|
|
1489
|
+
* and its worker, which kept its credential and data directory, may
|
|
1490
|
+
* connect again under a new epoch.
|
|
1163
1491
|
*/
|
|
1164
|
-
async
|
|
1165
|
-
const
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
.
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
.
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
.
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
sql<boolean>`expires_at <= now()`.as("expired"),
|
|
1194
|
-
])
|
|
1492
|
+
async beginResume(args: { name: string; at: string }): Promise<boolean> {
|
|
1493
|
+
const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
|
|
1494
|
+
return this.deps.db.transaction().execute(async (trx) => {
|
|
1495
|
+
await trx
|
|
1496
|
+
.selectFrom("worker_nodes")
|
|
1497
|
+
.select("id")
|
|
1498
|
+
.where("id", "=", nodeId)
|
|
1499
|
+
.forUpdate()
|
|
1500
|
+
.executeTakeFirst();
|
|
1501
|
+
const moved = await this.machines.setPhase({
|
|
1502
|
+
name: args.name,
|
|
1503
|
+
phase: "resuming",
|
|
1504
|
+
from: ["stopped"],
|
|
1505
|
+
at: args.at,
|
|
1506
|
+
transaction: trx,
|
|
1507
|
+
});
|
|
1508
|
+
if (!moved) return false;
|
|
1509
|
+
const machine = await this.machines.row({
|
|
1510
|
+
name: args.name,
|
|
1511
|
+
transaction: trx,
|
|
1512
|
+
});
|
|
1513
|
+
await trx
|
|
1514
|
+
.updateTable("worker_nodes")
|
|
1515
|
+
.set({
|
|
1516
|
+
enabled: machine?.disabled_at === null,
|
|
1517
|
+
admission_revision: null,
|
|
1518
|
+
lease_expires_at: sql`now()`,
|
|
1519
|
+
})
|
|
1520
|
+
.where("id", "=", nodeId)
|
|
1195
1521
|
.where("tenant_id", "=", this.deps.tenantId)
|
|
1196
|
-
.where("
|
|
1197
|
-
.
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
return [
|
|
1201
|
-
...workers.map((row) => ({
|
|
1202
|
-
name: row.name,
|
|
1203
|
-
ref: row.machine_ref,
|
|
1204
|
-
rule: row.machine_rule ?? "",
|
|
1205
|
-
state: row.revoked_at ? ("revoked" as const) : ("enrolled" as const),
|
|
1206
|
-
releasedForMs: msOrNull(row.released_for_ms),
|
|
1207
|
-
retainDays: row.retain_days,
|
|
1208
|
-
placement: storedPlacement(row),
|
|
1209
|
-
})),
|
|
1210
|
-
...enrollments.map((row) => ({
|
|
1211
|
-
name: row.name,
|
|
1212
|
-
ref: row.machine_ref,
|
|
1213
|
-
rule: row.machine_rule ?? "",
|
|
1214
|
-
state: row.expired ? ("expired" as const) : ("pending" as const),
|
|
1215
|
-
releasedForMs: null,
|
|
1216
|
-
retainDays: null,
|
|
1217
|
-
placement: storedPlacement(row),
|
|
1218
|
-
})),
|
|
1219
|
-
];
|
|
1220
|
-
}
|
|
1221
|
-
|
|
1222
|
-
/** Every pooled machine still enrolled, free or held (ADR 0205). */
|
|
1223
|
-
async pooledMachines(): Promise<PooledMachine[]> {
|
|
1224
|
-
const rows = await this.deps.db
|
|
1225
|
-
.selectFrom("work_workers")
|
|
1226
|
-
.select([
|
|
1227
|
-
"name",
|
|
1228
|
-
"node_id",
|
|
1229
|
-
"machine_rule",
|
|
1230
|
-
"machine_member",
|
|
1231
|
-
"machine_slot",
|
|
1232
|
-
"retain_days",
|
|
1233
|
-
"labels",
|
|
1234
|
-
"access",
|
|
1235
|
-
"trusted",
|
|
1236
|
-
releasedFor.as("released_for_ms"),
|
|
1237
|
-
])
|
|
1238
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1239
|
-
.where("pool", "=", true)
|
|
1240
|
-
.where("revoked_at", "is", null)
|
|
1241
|
-
.orderBy("name")
|
|
1242
|
-
.execute();
|
|
1243
|
-
return rows.map((row) => ({
|
|
1244
|
-
name: row.name,
|
|
1245
|
-
nodeId: row.node_id,
|
|
1246
|
-
rule: row.machine_rule,
|
|
1247
|
-
member: row.machine_member,
|
|
1248
|
-
slot: row.machine_slot,
|
|
1249
|
-
releasedForMs: msOrNull(row.released_for_ms),
|
|
1250
|
-
retainDays: row.retain_days,
|
|
1251
|
-
placement: storedPlacement(row),
|
|
1252
|
-
}));
|
|
1522
|
+
.where("authority_id", "=", this.deps.authorityId)
|
|
1523
|
+
.execute();
|
|
1524
|
+
return true;
|
|
1525
|
+
});
|
|
1253
1526
|
}
|
|
1254
1527
|
|
|
1255
1528
|
/**
|
|
1256
|
-
*
|
|
1257
|
-
*
|
|
1529
|
+
* Allocations still holding a machine's capacity: live workspaces, and
|
|
1530
|
+
* ones given back whose sandboxes are not destroyed yet.
|
|
1258
1531
|
*/
|
|
1259
|
-
async
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
}): Promise<boolean> {
|
|
1266
|
-
const assigned = await this.deps.db
|
|
1267
|
-
.updateTable("work_workers")
|
|
1268
|
-
.set({
|
|
1269
|
-
machine_rule: args.rule,
|
|
1270
|
-
machine_member: "member" in args.holder ? args.holder.member : null,
|
|
1271
|
-
machine_slot: "slot" in args.holder ? args.holder.slot : null,
|
|
1272
|
-
retain_days: args.retainDays,
|
|
1273
|
-
access: JSON.stringify(args.placement.access),
|
|
1274
|
-
trusted: args.placement.trusted,
|
|
1275
|
-
})
|
|
1276
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1277
|
-
.where("name", "=", args.name)
|
|
1278
|
-
.where("pool", "=", true)
|
|
1279
|
-
.where("machine_rule", "is", null)
|
|
1280
|
-
.where("released_at", "is", null)
|
|
1281
|
-
.where("revoked_at", "is", null)
|
|
1282
|
-
.returning("node_id")
|
|
1532
|
+
async holding(args: { name: string }): Promise<number> {
|
|
1533
|
+
const row = await this.deps.db
|
|
1534
|
+
.selectFrom("execution_allocations")
|
|
1535
|
+
.select((eb) => eb.fn.countAll<number>().as("count"))
|
|
1536
|
+
.where("worker_node_id", "=", `${WORKER_NODE_PREFIX}${args.name}`)
|
|
1537
|
+
.where("capacity_released_at", "is", null)
|
|
1283
1538
|
.executeTakeFirst();
|
|
1284
|
-
return
|
|
1285
|
-
}
|
|
1286
|
-
|
|
1287
|
-
/**
|
|
1288
|
-
* Release a machine nobody should have any more (ADR 0205): it serves
|
|
1289
|
-
* nobody from now on and keeps its disk for `retainDays`, counted from
|
|
1290
|
-
* the database's clock.
|
|
1291
|
-
*/
|
|
1292
|
-
async release(args: { name: string; retainDays: number }): Promise<void> {
|
|
1293
|
-
await this.deps.db
|
|
1294
|
-
.updateTable("work_workers")
|
|
1295
|
-
.set({ released_at: sql`now()`, retain_days: args.retainDays })
|
|
1296
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1297
|
-
.where("name", "=", args.name)
|
|
1298
|
-
.where("revoked_at", "is", null)
|
|
1299
|
-
.where("released_at", "is", null)
|
|
1300
|
-
.execute();
|
|
1301
|
-
}
|
|
1302
|
-
|
|
1303
|
-
/**
|
|
1304
|
-
* A released machine's person or group is back within its retention: it
|
|
1305
|
-
* is theirs again, with the placement its rule gives it now.
|
|
1306
|
-
*/
|
|
1307
|
-
async reassign(args: {
|
|
1308
|
-
name: string;
|
|
1309
|
-
placement: WorkerPlacement;
|
|
1310
|
-
retainDays: number;
|
|
1311
|
-
}): Promise<void> {
|
|
1312
|
-
await this.deps.db
|
|
1313
|
-
.updateTable("work_workers")
|
|
1314
|
-
.set({
|
|
1315
|
-
released_at: null,
|
|
1316
|
-
retain_days: args.retainDays,
|
|
1317
|
-
labels: JSON.stringify(args.placement.labels),
|
|
1318
|
-
access: JSON.stringify(args.placement.access),
|
|
1319
|
-
trusted: args.placement.trusted,
|
|
1320
|
-
})
|
|
1321
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1322
|
-
.where("name", "=", args.name)
|
|
1323
|
-
.where("revoked_at", "is", null)
|
|
1324
|
-
.where("released_at", "is not", null)
|
|
1325
|
-
.execute();
|
|
1326
|
-
}
|
|
1327
|
-
|
|
1328
|
-
/** Keep the retention a machine's rule gives it, for after the rule. */
|
|
1329
|
-
async setRetainDays(args: { name: string; retainDays: number }) {
|
|
1330
|
-
await this.deps.db
|
|
1331
|
-
.updateTable("work_workers")
|
|
1332
|
-
.set({ retain_days: args.retainDays })
|
|
1333
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1334
|
-
.where("name", "=", args.name)
|
|
1335
|
-
.where("revoked_at", "is", null)
|
|
1336
|
-
.execute();
|
|
1337
|
-
}
|
|
1338
|
-
|
|
1339
|
-
/**
|
|
1340
|
-
* A released pooled machine's retention ended: it leaves its rule, and
|
|
1341
|
-
* stays released (taking no new work) until its reset is done. It keeps
|
|
1342
|
-
* its access until then, so the chats still on it reach their workspaces
|
|
1343
|
-
* and give them back when they idle.
|
|
1344
|
-
*/
|
|
1345
|
-
async beginReset(args: { name: string }): Promise<void> {
|
|
1346
|
-
await this.deps.db
|
|
1347
|
-
.updateTable("work_workers")
|
|
1348
|
-
.set({
|
|
1349
|
-
machine_rule: null,
|
|
1350
|
-
machine_member: null,
|
|
1351
|
-
machine_slot: null,
|
|
1352
|
-
})
|
|
1353
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1354
|
-
.where("name", "=", args.name)
|
|
1355
|
-
.where("pool", "=", true)
|
|
1356
|
-
.where("released_at", "is not", null)
|
|
1357
|
-
.where("revoked_at", "is", null)
|
|
1358
|
-
.execute();
|
|
1539
|
+
return Number(row?.count ?? 0);
|
|
1359
1540
|
}
|
|
1360
1541
|
|
|
1361
1542
|
/**
|
|
@@ -1382,16 +1563,16 @@ export class WorkWorkerRegistry {
|
|
|
1382
1563
|
}
|
|
1383
1564
|
|
|
1384
1565
|
/**
|
|
1385
|
-
* A member's
|
|
1386
|
-
* queue: the worker runs
|
|
1566
|
+
* A member's harness sign-in on a worker (ADRs 0213, 0342), through the
|
|
1567
|
+
* operation queue: the worker runs the harness's own login and answers.
|
|
1387
1568
|
* Fails at once while the worker is not connected.
|
|
1388
1569
|
*/
|
|
1389
|
-
async
|
|
1570
|
+
async harnessSignIn(args: {
|
|
1390
1571
|
nodeId: string;
|
|
1391
|
-
request:
|
|
1572
|
+
request: HarnessSignInRequest;
|
|
1392
1573
|
}): Promise<unknown> {
|
|
1393
1574
|
const { nodeId } = args;
|
|
1394
|
-
return this.queue.
|
|
1575
|
+
return this.queue.machineHarnessSignIn({
|
|
1395
1576
|
executor: nodeExecutor(nodeId),
|
|
1396
1577
|
leaseToken: () => this.deps.nodes.liveToken({ nodeId }),
|
|
1397
1578
|
leaseHeld: async (token) =>
|
|
@@ -1402,13 +1583,48 @@ export class WorkWorkerRegistry {
|
|
|
1402
1583
|
});
|
|
1403
1584
|
}
|
|
1404
1585
|
|
|
1586
|
+
/** A drained worker can be wiped without handing its disk to two owners. */
|
|
1587
|
+
async resetPlacement(args: {
|
|
1588
|
+
name: string;
|
|
1589
|
+
timeoutMs?: number;
|
|
1590
|
+
}): Promise<"busy" | "offline" | "done"> {
|
|
1591
|
+
const { name } = args;
|
|
1592
|
+
if (!(await this.connected({ name }))) return "offline";
|
|
1593
|
+
const timeoutMs = args.timeoutMs ?? 180_000;
|
|
1594
|
+
const claim = {
|
|
1595
|
+
db: this.deps.db,
|
|
1596
|
+
name: `machine-reset:${this.deps.tenantId}:${name}`,
|
|
1597
|
+
holder: randomUUID(),
|
|
1598
|
+
};
|
|
1599
|
+
if (
|
|
1600
|
+
!(await takeReplicaClaim({
|
|
1601
|
+
...claim,
|
|
1602
|
+
ttlSeconds: Math.ceil(timeoutMs / 1000) + 60,
|
|
1603
|
+
}))
|
|
1604
|
+
)
|
|
1605
|
+
return "busy";
|
|
1606
|
+
try {
|
|
1607
|
+
const machine = await this.machines.row({ name });
|
|
1608
|
+
if (!machine?.reset_pending) return "done";
|
|
1609
|
+
if ((await this.holding({ name })) > 0) return "busy";
|
|
1610
|
+
await this.resetMachine({ name, timeoutMs });
|
|
1611
|
+
await this.machines.finishReset({ name });
|
|
1612
|
+
return "done";
|
|
1613
|
+
} finally {
|
|
1614
|
+
await releaseReplicaClaim(claim);
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1405
1618
|
/**
|
|
1406
|
-
* Reset a
|
|
1407
|
-
* every sandbox it holds and deletes members' volumes
|
|
1408
|
-
* Resolves once its receipt arrived; fails while it is not
|
|
1409
|
-
* and once `timeoutMs` passed without a receipt.
|
|
1619
|
+
* Reset a machine through the operation queue (ADRs 0205, 0349): the
|
|
1620
|
+
* worker destroys every sandbox it holds and deletes members' volumes
|
|
1621
|
+
* and sign-ins. Resolves once its receipt arrived; fails while it is not
|
|
1622
|
+
* connected, and once `timeoutMs` passed without a receipt.
|
|
1410
1623
|
*/
|
|
1411
|
-
async
|
|
1624
|
+
async resetMachine(args: {
|
|
1625
|
+
name: string;
|
|
1626
|
+
timeoutMs?: number;
|
|
1627
|
+
}): Promise<void> {
|
|
1412
1628
|
const nodeId = `${WORKER_NODE_PREFIX}${args.name}`;
|
|
1413
1629
|
await this.queue.resetMachine({
|
|
1414
1630
|
executor: nodeExecutor(nodeId),
|
|
@@ -1419,151 +1635,75 @@ export class WorkWorkerRegistry {
|
|
|
1419
1635
|
attributes: { "catamorphic.worker.id": nodeId },
|
|
1420
1636
|
...(args.timeoutMs !== undefined ? { timeoutMs: args.timeoutMs } : {}),
|
|
1421
1637
|
});
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
/** A reset pooled machine is free in its pool again, serving nobody. */
|
|
1425
|
-
async freePooled(args: { name: string }): Promise<void> {
|
|
1638
|
+
// Its volumes are gone, cache copies included (ADR 0334): none is
|
|
1639
|
+
// mounted again, and the next workspace there queues a fill.
|
|
1426
1640
|
await this.deps.db
|
|
1427
|
-
.updateTable("
|
|
1428
|
-
.set({
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
access: JSON.stringify(NOBODY),
|
|
1432
|
-
trusted: false,
|
|
1433
|
-
})
|
|
1434
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1435
|
-
.where("name", "=", args.name)
|
|
1436
|
-
.where("pool", "=", true)
|
|
1437
|
-
.where("machine_rule", "is", null)
|
|
1641
|
+
.updateTable("environment_cache_fills")
|
|
1642
|
+
.set({ status: "evicted" })
|
|
1643
|
+
.where("worker_node_id", "=", nodeId)
|
|
1644
|
+
.where("status", "=", "succeeded")
|
|
1438
1645
|
.execute();
|
|
1439
1646
|
}
|
|
1440
1647
|
|
|
1441
1648
|
/**
|
|
1442
|
-
*
|
|
1443
|
-
*
|
|
1649
|
+
* Every machine Work knows, for the operator and administrators: its
|
|
1650
|
+
* facts as the plan reads them, and its worker's credential standing.
|
|
1444
1651
|
*/
|
|
1445
|
-
async
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
/** Invalidate every unused enrollment code for a name. */
|
|
1478
|
-
async cancelEnrollments(args: { name: string }): Promise<void> {
|
|
1479
|
-
await this.deps.db
|
|
1480
|
-
.deleteFrom("work_worker_enrollments")
|
|
1481
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1482
|
-
.where("name", "=", args.name)
|
|
1483
|
-
.where("used_at", "is", null)
|
|
1484
|
-
.execute();
|
|
1485
|
-
}
|
|
1486
|
-
|
|
1487
|
-
async list(): Promise<
|
|
1488
|
-
Array<{
|
|
1489
|
-
name: string;
|
|
1490
|
-
nodeId: string;
|
|
1491
|
-
enrolledAt: string;
|
|
1492
|
-
lastSeenAt: string | null;
|
|
1493
|
-
revoked: boolean;
|
|
1494
|
-
/** Enrolled into a pool rules draw on (ADR 0205). */
|
|
1495
|
-
pool: boolean;
|
|
1496
|
-
state: WorkerState;
|
|
1497
|
-
/** Since when it serves nobody, and for how many days it is kept. */
|
|
1498
|
-
released: { at: string; retainDays: number | null } | null;
|
|
1499
|
-
/** When its current credential was issued (ADR 0207). */
|
|
1500
|
-
credentialIssuedAt: string;
|
|
1501
|
-
/** The operator asked for a rotation the worker has not made yet. */
|
|
1502
|
-
rotationRequested: boolean;
|
|
1503
|
-
placement: WorkerPlacement;
|
|
1504
|
-
machine: {
|
|
1505
|
-
rule: string;
|
|
1506
|
-
ref: string | null;
|
|
1507
|
-
member?: string;
|
|
1508
|
-
slot?: number;
|
|
1509
|
-
} | null;
|
|
1510
|
-
}>
|
|
1511
|
-
> {
|
|
1512
|
-
const rows = await this.deps.db
|
|
1513
|
-
.selectFrom("work_workers")
|
|
1514
|
-
.selectAll()
|
|
1515
|
-
.where("tenant_id", "=", this.deps.tenantId)
|
|
1516
|
-
.orderBy("name")
|
|
1517
|
-
.execute();
|
|
1518
|
-
return rows.map((row) => ({
|
|
1519
|
-
name: row.name,
|
|
1520
|
-
nodeId: row.node_id,
|
|
1521
|
-
enrolledAt: row.enrolled_at.toISOString(),
|
|
1522
|
-
lastSeenAt: row.last_seen_at?.toISOString() ?? null,
|
|
1523
|
-
revoked: row.revoked_at !== null,
|
|
1524
|
-
pool: row.pool,
|
|
1525
|
-
state: workerState(row),
|
|
1526
|
-
released: row.released_at
|
|
1527
|
-
? { at: row.released_at.toISOString(), retainDays: row.retain_days }
|
|
1528
|
-
: null,
|
|
1529
|
-
credentialIssuedAt: row.credential_issued_at.toISOString(),
|
|
1530
|
-
rotationRequested: row.rotation_requested_at !== null,
|
|
1531
|
-
placement: storedPlacement(row),
|
|
1532
|
-
machine: row.machine_rule
|
|
1533
|
-
? {
|
|
1534
|
-
rule: row.machine_rule,
|
|
1535
|
-
ref: row.machine_ref,
|
|
1536
|
-
...(row.machine_member ? { member: row.machine_member } : {}),
|
|
1537
|
-
...(row.machine_slot !== null ? { slot: row.machine_slot } : {}),
|
|
1538
|
-
}
|
|
1539
|
-
: null,
|
|
1540
|
-
}));
|
|
1652
|
+
async list(): Promise<WorkerListing[]> {
|
|
1653
|
+
const [records, workers] = await Promise.all([
|
|
1654
|
+
this.machines.records(),
|
|
1655
|
+
this.deps.db
|
|
1656
|
+
.selectFrom("work_workers")
|
|
1657
|
+
.select([
|
|
1658
|
+
"name",
|
|
1659
|
+
"enrolled_at",
|
|
1660
|
+
"revoked_at",
|
|
1661
|
+
"credential_issued_at",
|
|
1662
|
+
"rotation_requested_at",
|
|
1663
|
+
])
|
|
1664
|
+
.where("tenant_id", "=", this.deps.tenantId)
|
|
1665
|
+
.execute(),
|
|
1666
|
+
]);
|
|
1667
|
+
const workerOf = new Map(workers.map((worker) => [worker.name, worker]));
|
|
1668
|
+
return records.map(({ facts }) => {
|
|
1669
|
+
const worker = workerOf.get(facts.name);
|
|
1670
|
+
const enrolled =
|
|
1671
|
+
worker && worker.revoked_at === null ? worker : undefined;
|
|
1672
|
+
return {
|
|
1673
|
+
...facts,
|
|
1674
|
+
nodeId: `${WORKER_NODE_PREFIX}${facts.name}`,
|
|
1675
|
+
// Its lease is live: an operation sent to it now runs (ADR 0348).
|
|
1676
|
+
connected: facts.state === "serving" || facts.state === "draining",
|
|
1677
|
+
enrolledAt: enrolled?.enrolled_at.toISOString() ?? null,
|
|
1678
|
+
credentialIssuedAt:
|
|
1679
|
+
enrolled?.credential_issued_at.toISOString() ?? null,
|
|
1680
|
+
rotationRequested: Boolean(enrolled?.rotation_requested_at),
|
|
1681
|
+
};
|
|
1682
|
+
});
|
|
1541
1683
|
}
|
|
1542
1684
|
}
|
|
1543
1685
|
|
|
1686
|
+
/** A machine in the operator's and administrators' listing. */
|
|
1687
|
+
export type WorkerListing = MachineFacts & {
|
|
1688
|
+
nodeId: string;
|
|
1689
|
+
connected: boolean;
|
|
1690
|
+
/** When its worker enrolled; null before it did. */
|
|
1691
|
+
enrolledAt: string | null;
|
|
1692
|
+
/** When its current credential was issued (ADR 0207). */
|
|
1693
|
+
credentialIssuedAt: string | null;
|
|
1694
|
+
/** The operator asked for a rotation the worker has not made yet. */
|
|
1695
|
+
rotationRequested: boolean;
|
|
1696
|
+
};
|
|
1697
|
+
|
|
1544
1698
|
function hash(value: string): string {
|
|
1545
1699
|
return createHash("sha256").update(value).digest("hex");
|
|
1546
1700
|
}
|
|
1547
1701
|
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
machine_destroyed_at: Date | null;
|
|
1554
|
-
}): WorkerState {
|
|
1555
|
-
if (row.revoked_at)
|
|
1556
|
-
return row.machine_rule && !row.pool && !row.machine_destroyed_at
|
|
1557
|
-
? "destroying"
|
|
1558
|
-
: "revoked";
|
|
1559
|
-
if (row.released_at) return row.machine_rule ? "released" : "resetting";
|
|
1560
|
-
if (row.pool && !row.machine_rule) return "free";
|
|
1561
|
-
return "serving";
|
|
1562
|
-
}
|
|
1563
|
-
|
|
1564
|
-
/** A duration the database measured, as a number. */
|
|
1565
|
-
function msOrNull(value: number | string | null): number | null {
|
|
1566
|
-
return value === null ? null : Number(value);
|
|
1702
|
+
/** The worker name in a worker node's id. */
|
|
1703
|
+
function workerNameOf(nodeId: string): string {
|
|
1704
|
+
return nodeId.startsWith(WORKER_NODE_PREFIX)
|
|
1705
|
+
? nodeId.slice(WORKER_NODE_PREFIX.length)
|
|
1706
|
+
: nodeId;
|
|
1567
1707
|
}
|
|
1568
1708
|
|
|
1569
1709
|
/** Two hex digests compared in constant time. */
|