@catamorphic/work-server 0.1.0-alpha.39 → 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.
Files changed (114) hide show
  1. package/NOTICE.txt +7 -0
  2. package/README.md +9 -9
  3. package/dist/admission/routes.d.ts +1 -1
  4. package/dist/admission/routes.d.ts.map +1 -1
  5. package/dist/agent-capabilities.d.ts.map +1 -1
  6. package/dist/agents.d.ts +5 -6
  7. package/dist/agents.d.ts.map +1 -1
  8. package/dist/auth/fastify-auth.d.ts.map +1 -1
  9. package/dist/auth/work-auth-types.d.ts +2 -0
  10. package/dist/auth/work-auth-types.d.ts.map +1 -1
  11. package/dist/auth/work-auth.d.ts.map +1 -1
  12. package/dist/chunk-kcck20aw.js +676 -0
  13. package/dist/chunk-kcck20aw.js.map +11 -0
  14. package/dist/cluster.d.ts +8 -7
  15. package/dist/cluster.d.ts.map +1 -1
  16. package/dist/config.d.ts +5 -15
  17. package/dist/config.d.ts.map +1 -1
  18. package/dist/execution-config.d.ts +22 -0
  19. package/dist/execution-config.d.ts.map +1 -1
  20. package/dist/fake-agent.d.ts +1 -0
  21. package/dist/fake-agent.d.ts.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2730 -2851
  25. package/dist/index.js.map +28 -28
  26. package/dist/machines/contract-kit.d.ts +91 -0
  27. package/dist/machines/contract-kit.d.ts.map +1 -0
  28. package/dist/machines/contract.d.ts +383 -0
  29. package/dist/machines/contract.d.ts.map +1 -0
  30. package/dist/machines/sequencer.d.ts +267 -0
  31. package/dist/machines/sequencer.d.ts.map +1 -0
  32. package/dist/machines/simulation.d.ts +124 -0
  33. package/dist/machines/simulation.d.ts.map +1 -0
  34. package/dist/machines/work-machines.d.ts +61 -0
  35. package/dist/machines/work-machines.d.ts.map +1 -0
  36. package/dist/server.d.ts +15 -11
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/setup/machines.d.ts +9 -17
  39. package/dist/setup/machines.d.ts.map +1 -1
  40. package/dist/shares/share-routes.d.ts +1 -1
  41. package/dist/shares/share-routes.d.ts.map +1 -1
  42. package/dist/testing.d.ts +8 -0
  43. package/dist/testing.d.ts.map +1 -0
  44. package/dist/testing.js +1013 -0
  45. package/dist/testing.js.map +11 -0
  46. package/dist/workers/disk-care.d.ts +41 -0
  47. package/dist/workers/disk-care.d.ts.map +1 -0
  48. package/dist/workers/harness-sign-ins.d.ts +146 -0
  49. package/dist/workers/harness-sign-ins.d.ts.map +1 -0
  50. package/dist/workers/machine-store.d.ts +196 -0
  51. package/dist/workers/machine-store.d.ts.map +1 -0
  52. package/dist/workers/member-machine-routes.d.ts +5 -3
  53. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  54. package/dist/workers/member-machines.d.ts +47 -28
  55. package/dist/workers/member-machines.d.ts.map +1 -1
  56. package/dist/workers/placement.d.ts +23 -40
  57. package/dist/workers/placement.d.ts.map +1 -1
  58. package/dist/workers/sign-ins.d.ts +44 -17
  59. package/dist/workers/sign-ins.d.ts.map +1 -1
  60. package/dist/workers/worker-protocol.d.ts +5 -2
  61. package/dist/workers/worker-protocol.d.ts.map +1 -1
  62. package/dist/workers/worker-registry.d.ts +174 -223
  63. package/dist/workers/worker-registry.d.ts.map +1 -1
  64. package/dist/workers/worker-routes.d.ts.map +1 -1
  65. package/dist/workers/worker-runtime.d.ts.map +1 -1
  66. package/package.json +31 -21
  67. package/src/admission/routes.ts +5 -2
  68. package/src/agent-capabilities.ts +22 -8
  69. package/src/agents.ts +52 -23
  70. package/src/auth/fastify-auth.ts +149 -17
  71. package/src/auth/work-auth-types.ts +2 -0
  72. package/src/auth/work-auth.ts +27 -0
  73. package/src/cluster.ts +115 -42
  74. package/src/config.ts +15 -41
  75. package/src/execution-config.ts +40 -0
  76. package/src/fake-agent.ts +21 -4
  77. package/src/index.ts +26 -12
  78. package/src/machines/contract-kit.ts +648 -0
  79. package/src/machines/contract.ts +522 -0
  80. package/src/machines/sequencer.ts +1010 -0
  81. package/src/machines/simulation.ts +833 -0
  82. package/src/machines/work-machines.ts +231 -0
  83. package/src/server.ts +235 -150
  84. package/src/setup/machines.ts +128 -121
  85. package/src/shares/share-routes.ts +17 -1
  86. package/src/testing.ts +22 -0
  87. package/src/workers/disk-care.ts +121 -0
  88. package/src/workers/fake-claude-cli.ts +95 -0
  89. package/src/workers/fake-codex-cli.ts +11 -4
  90. package/src/workers/harness-sign-ins.ts +580 -0
  91. package/src/workers/machine-store.ts +1065 -0
  92. package/src/workers/member-machine-routes.ts +92 -20
  93. package/src/workers/member-machines.ts +163 -99
  94. package/src/workers/placement.ts +59 -70
  95. package/src/workers/sign-ins.ts +109 -52
  96. package/src/workers/worker-protocol.ts +5 -2
  97. package/src/workers/worker-registry.ts +894 -754
  98. package/src/workers/worker-routes.ts +4 -1
  99. package/src/workers/worker-runtime.ts +55 -23
  100. package/dist/test-support.d.ts +0 -133
  101. package/dist/test-support.d.ts.map +0 -1
  102. package/dist/workers/codex-sign-ins.d.ts +0 -107
  103. package/dist/workers/codex-sign-ins.d.ts.map +0 -1
  104. package/dist/workers/install-script.d.ts +0 -71
  105. package/dist/workers/install-script.d.ts.map +0 -1
  106. package/dist/workers/machine-classes.d.ts +0 -115
  107. package/dist/workers/machine-classes.d.ts.map +0 -1
  108. package/dist/workers/machine-rules.d.ts +0 -402
  109. package/dist/workers/machine-rules.d.ts.map +0 -1
  110. package/src/test-support.ts +0 -404
  111. package/src/workers/codex-sign-ins.ts +0 -360
  112. package/src/workers/install-script.ts +0 -394
  113. package/src/workers/machine-classes.ts +0 -152
  114. package/src/workers/machine-rules.ts +0 -1954
@@ -1,1954 +0,0 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import {
3
- PLACEMENT_WAIT_FRESH_SECONDS,
4
- releaseReplicaClaim,
5
- renewReplicaClaim,
6
- takeReplicaClaim,
7
- } from "@catamorphic/core";
8
- import type { DB } from "@catamorphic/db";
9
- import {
10
- HetznerCloudError,
11
- type HetznerCloudMachines,
12
- } from "@catamorphic/hetzner";
13
- import { getTracer, withSpan } from "@catamorphic/otel";
14
- import { environmentSatisfies, poolMatches } from "@catamorphic/sandbox";
15
- import { type Kysely, sql } from "kysely";
16
- import { z } from "zod";
17
- import {
18
- type InstallTarget,
19
- workerCloudInit,
20
- workerInstallScript,
21
- } from "./install-script.js";
22
- import {
23
- type MachineClass,
24
- MachineName,
25
- type MachinePlatform,
26
- } from "./machine-classes.js";
27
- import {
28
- accessGroupsOf,
29
- NodeLabelsSchema,
30
- WorkerAccessSchema,
31
- type WorkerPlacement,
32
- WorkerPlacementSchema,
33
- } from "./placement.js";
34
- import type {
35
- MachineLoad,
36
- PooledMachine,
37
- ProvisionedMachine,
38
- WorkWorkerRegistry,
39
- } from "./worker-registry.js";
40
-
41
- const tracer = getTracer("@catamorphic/work-server");
42
-
43
- /** Days a released machine keeps its disk unless its rule says otherwise. */
44
- export const DEFAULT_RETAIN_DAYS = 7;
45
-
46
- /** Minutes a machine on demand stays once idle, unless its rule says otherwise. */
47
- export const DEFAULT_IDLE_MINUTES = 10;
48
-
49
- /** Minutes a machine on demand has to enroll before it is replaced. */
50
- export const DEFAULT_ENROLL_MINUTES = 15;
51
-
52
- const DAY_MS = 24 * 60 * 60_000;
53
-
54
- /**
55
- * Machines that come and go with the work waiting for them (ADR 0258): up
56
- * to `max`, keeping `min` warm, each destroyed once idle for
57
- * `idleMinutes`, and replaced when it does not enroll within
58
- * `enrollMinutes`.
59
- */
60
- const DemandSchema = z
61
- .strictObject({
62
- max: z.number().int().positive().max(100),
63
- min: z.number().int().min(0).max(100).default(0),
64
- // At least a minute: a machine that just enrolled is idle until the
65
- // work it was made for lands on it.
66
- idleMinutes: z
67
- .number()
68
- .int()
69
- .min(1)
70
- .max(24 * 60)
71
- .default(DEFAULT_IDLE_MINUTES),
72
- enrollMinutes: z
73
- .number()
74
- .int()
75
- .positive()
76
- .max(24 * 60)
77
- .default(DEFAULT_ENROLL_MINUTES),
78
- })
79
- .refine((demand) => demand.min <= demand.max, {
80
- message: "min may not be more than max",
81
- path: ["min"],
82
- });
83
- export type MachineDemand = z.output<typeof DemandSchema>;
84
-
85
- /** How many machines a rule gives, and to whom. */
86
- const RuleMachinesSchema = z.union([
87
- z.literal("each-member"),
88
- z.strictObject({ shared: z.number().int().positive().max(100) }),
89
- z.strictObject({ demand: DemandSchema }),
90
- ]);
91
- type RuleMachines = z.output<typeof RuleMachinesSchema>;
92
-
93
- /**
94
- * A machine rule (ADRs 0167, 0205, 0258): every active member of a
95
- * directory group gets a machine of their own, the group shares a fixed
96
- * number of machines, or machines come and go with the work waiting for
97
- * them, of a machine class. Machines on demand serve a group's members or
98
- * named projects' own work (project chats and automations). A machine
99
- * nobody should have any more is released and kept for `retainDays` before
100
- * it is destroyed or reset; a machine on demand keeps nothing.
101
- */
102
- export const MachineRuleSchema = z
103
- .strictObject({
104
- group: z.email().toLowerCase().optional(),
105
- /** Machines on demand only: the projects whose own work they take. */
106
- projects: z.array(z.uuid()).min(1).max(100).optional(),
107
- machines: RuleMachinesSchema,
108
- /** A class from `WORK_MACHINES_CONFIG`, or the provisioner hook's. */
109
- class: z.string().min(1).max(64),
110
- /** Labels a created machine carries; a pooled one keeps its own. */
111
- labels: NodeLabelsSchema.default({}),
112
- /**
113
- * Shared machines and machines on demand: the people (or projects)
114
- * they serve trust each other, so processes are isolation enough.
115
- */
116
- trusted: z.boolean().default(false),
117
- /** Days a released machine keeps its disk; 0 destroys or resets it at once. */
118
- retainDays: z.number().int().min(0).max(365).optional(),
119
- })
120
- .superRefine((rule, context) => {
121
- const demand = demandOf(rule) !== undefined;
122
- if ((rule.group === undefined) === (rule.projects === undefined))
123
- context.addIssue({
124
- code: "custom",
125
- message: "Name either a group or projects",
126
- path: ["group"],
127
- });
128
- if (rule.projects !== undefined && !demand)
129
- context.addIssue({
130
- code: "custom",
131
- message:
132
- "Only machines on demand serve projects; give each-member and shared machines a group",
133
- path: ["projects"],
134
- });
135
- if (demand && rule.retainDays !== undefined && rule.retainDays !== 0)
136
- context.addIssue({
137
- code: "custom",
138
- message:
139
- "A machine on demand is destroyed once it is idle; leave out retainDays",
140
- path: ["retainDays"],
141
- });
142
- })
143
- .transform((rule) => ({
144
- ...rule,
145
- retainDays: rule.retainDays ?? (demandOf(rule) ? 0 : DEFAULT_RETAIN_DAYS),
146
- }));
147
- export type MachineRule = z.output<typeof MachineRuleSchema>;
148
-
149
- /** A rule's demand settings, when its machines come and go with demand. */
150
- export function demandOf(rule: {
151
- machines: RuleMachines;
152
- }): MachineDemand | undefined {
153
- return typeof rule.machines === "object" && "demand" in rule.machines
154
- ? rule.machines.demand
155
- : undefined;
156
- }
157
-
158
- /**
159
- * Creates and destroys worker machines on a platform (a cloud, a
160
- * virtualization host) for `custom` classes. A created machine starts the
161
- * Work worker with the given control plane and one-time enrollment code,
162
- * for example by running `enrollment.cloudInit` through cloud-init; it
163
- * enrolls itself. `create` throws {@link MachineProvisioningRefusedError}
164
- * when the platform refused and created nothing, so the next pass tries
165
- * again with a new code; any other error keeps the code, since the machine
166
- * may still come up and enroll.
167
- *
168
- * Work never calls `create` twice with one enrollment code, so `create` is
169
- * idempotent per code: use `enrollment.idempotencyKey`, a hash of the code,
170
- * as the platform's idempotency token, never the name, which a
171
- * later machine of the same rule reuses once this one is gone. `destroy`
172
- * removes the machine `ref` names and every machine named `name` (a create
173
- * that failed uncertainly may have made one with no recorded ref), and
174
- * says whether they are gone: `{ done: false }` while a destruction is
175
- * under way or a machine may still appear, and Work asks again on later
176
- * passes, forgetting the machine only once it is done.
177
- */
178
- export interface MachineProvisioner {
179
- create(args: {
180
- name: string;
181
- class: string;
182
- /** The rule the machine is for. */
183
- rule: string;
184
- /** The class's `options` from `WORK_MACHINES_CONFIG`, as written. */
185
- options?: Readonly<Record<string, unknown>>;
186
- /**
187
- * Machines on demand (ADR 0258): what the work waiting for this
188
- * machine needs, to size it. Absent for a machine kept warm.
189
- */
190
- waiting?: {
191
- resources: Readonly<{
192
- cpuMillis?: number;
193
- memoryMb?: number;
194
- storageMb?: number;
195
- gpu?: boolean;
196
- }>;
197
- capabilities: readonly string[];
198
- };
199
- labels: Readonly<Record<string, string>>;
200
- enrollment: {
201
- controlPlaneUrl: string;
202
- code: string;
203
- /** A hash of `code`: the platform's idempotency token for this create. */
204
- idempotencyKey: string;
205
- /**
206
- * Cloud-init user data that installs the worker with this code (ADR
207
- * 0205), when the server knows its worker image.
208
- */
209
- cloudInit?: string;
210
- };
211
- }): Promise<{ ref: string }>;
212
- /**
213
- * Destroy the machine `ref` names and every machine named `name`; done
214
- * once none is left.
215
- */
216
- destroy(args: { name: string; ref: string | null }): Promise<{
217
- done: boolean;
218
- }>;
219
- }
220
-
221
- /** A platform refused to create a machine, and created nothing. */
222
- export class MachineProvisioningRefusedError extends Error {
223
- constructor(message: string) {
224
- super(message);
225
- this.name = "MachineProvisioningRefusedError";
226
- }
227
- }
228
-
229
- /** What one pass changed. */
230
- export interface ReconcileSummary {
231
- /** Machines created on a platform. */
232
- created: string[];
233
- /** Pooled machines handed to a rule, and released machines handed back. */
234
- assigned: string[];
235
- /** Machines whose placement drifted from their rule's. */
236
- updated: string[];
237
- /** Machines that now serve nobody and keep their disk for a while. */
238
- released: string[];
239
- /** Machines destroyed on their platform. */
240
- removed: string[];
241
- /** Machines whose destruction is under way (a snapshot being written). */
242
- destroying: string[];
243
- /** Pooled machines reset and free again. */
244
- reset: string[];
245
- /** What went wrong, by machine (or rule) and the rule it belongs to. */
246
- failed: Array<{ name: string; error: string; rule?: string }>;
247
- /** Another replica was reconciling; its pass covers this one. */
248
- busy?: true;
249
- }
250
-
251
- /** How a rule's machines stand, for the operator. */
252
- export interface MachineRuleStatus {
253
- platform: MachinePlatform | null;
254
- /** Machines the rule calls for now. */
255
- desired: number;
256
- /** Enrolled and serving their people. */
257
- ready: number;
258
- /** Created and not yet enrolled. */
259
- starting: number;
260
- /** Without a machine: a pool with none free, or not created yet. */
261
- waiting: number;
262
- /** Released and kept for their retention. */
263
- released: number;
264
- /** Machines on demand: work waiting for one of this rule's machines. */
265
- queued?: number;
266
- /**
267
- * What keeps the rule from being acted on fully: an unknown class (its
268
- * machines are left as they are), a machine on demand that never
269
- * connected (no more are made until the rule is written again), or work
270
- * its machines cannot take.
271
- */
272
- problem?: string;
273
- /** What failed for the rule's machines in the latest pass. */
274
- failure?: { error: string; at: string };
275
- }
276
-
277
- /** A machine a provisioned rule calls for, by its stable name. */
278
- interface DesiredMachine {
279
- name: string;
280
- rule: string;
281
- class: string;
282
- placement: WorkerPlacement;
283
- retainDays: number;
284
- /** Minutes it has to enroll once created (machines on demand). */
285
- enrollMinutes?: number;
286
- /** What the work it is created for needs (machines on demand). */
287
- waiting?: {
288
- resources: DemandWait["requirements"]["resources"];
289
- capabilities: string[];
290
- };
291
- }
292
-
293
- /** Work waiting for a machine, as machine rules on demand read it. */
294
- interface DemandWait {
295
- projectId: string;
296
- /** Null for a project's own work. */
297
- owner: string | null;
298
- /** The owner's directory groups, for a group's machines. */
299
- groups: readonly string[];
300
- pool: Readonly<Record<string, string>>;
301
- requirements: z.output<typeof DemandWaitRequirements>;
302
- }
303
-
304
- const DemandWaitPool = z.record(z.string(), z.string());
305
- const DemandWaitRequirements = z.object({
306
- resources: z
307
- .object({
308
- cpuMillis: z.number().optional(),
309
- memoryMb: z.number().optional(),
310
- storageMb: z.number().optional(),
311
- gpu: z.boolean().optional(),
312
- })
313
- .default({}),
314
- capabilities: z.array(z.string()).default([]),
315
- trust: z.enum(["local", "managed"]).optional(),
316
- isolation: z.enum(["none", "process", "sandbox"]).optional(),
317
- topology: z
318
- .enum(["controller", "contained", "native", "external"])
319
- .optional(),
320
- });
321
-
322
- /** A place a pool rule fills with one of its class's free machines. */
323
- interface DesiredSlot {
324
- rule: string;
325
- class: string;
326
- holder: { member: string } | { slot: number };
327
- /** For a shared place: the group it serves, part of its identity. */
328
- group: string | null;
329
- access: WorkerPlacement["access"];
330
- trusted: boolean;
331
- retainDays: number;
332
- }
333
-
334
- /** What rules call for now. */
335
- interface Desired {
336
- rules: Record<string, MachineRule>;
337
- provisioned: Map<string, DesiredMachine>;
338
- slots: DesiredSlot[];
339
- /** Rules that cannot be acted on, and why; their machines stay as they are. */
340
- problems: Map<string, string>;
341
- /** Machines on demand: work waiting for each rule's machines. */
342
- queued: Map<string, number>;
343
- /** What keeps rules on demand from serving all their work, by rule. */
344
- notices: Map<string, string[]>;
345
- }
346
-
347
- /** Marks a ref as a Hetzner Cloud server id. */
348
- const HETZNER_REF = "hcloud:";
349
-
350
- /**
351
- * Keeps workers in step with machine rules and the directory (ADR 0205):
352
- * creates cloud machines and assigns pooled ones that are missing, updates
353
- * placement that drifted, releases machines nobody should have any more,
354
- * and destroys or resets them once their retention ends. Retention runs on
355
- * the database's clock, so replicas agree on it.
356
- */
357
- export class MachineReconciler {
358
- private running: Promise<ReconcileSummary> | undefined;
359
- private readonly holder = randomUUID();
360
-
361
- constructor(
362
- private readonly deps: {
363
- db: Kysely<DB>;
364
- tenantId: string;
365
- workers: WorkWorkerRegistry;
366
- /** `WORK_MACHINES_CONFIG` classes; none means every class is custom. */
367
- classes: Readonly<Record<string, MachineClass>>;
368
- /** The `machineProvisioner` hook, for custom classes. */
369
- provisioner?: MachineProvisioner;
370
- /** For hetzner-cloud classes. */
371
- hetzner?: HetznerCloudMachines;
372
- /** What machines install, or why they cannot. */
373
- install: { target: InstallTarget } | { unavailable: string };
374
- controlPlaneUrl: string;
375
- /** A user's sign-in email, for dedicated machines' access. */
376
- emailOf: (userId: string) => Promise<string | undefined>;
377
- /** How long a pass holds its claim without renewing (default 2 minutes). */
378
- leaseMs?: number;
379
- /**
380
- * How long a pass waits for one pooled machine's reset (default 3
381
- * minutes); a slower reset finishes on a later pass.
382
- */
383
- resetWaitMs?: number;
384
- log?: (line: string) => void;
385
- },
386
- ) {}
387
-
388
- async rules(): Promise<Record<string, MachineRule>> {
389
- const rows = await this.deps.db
390
- .selectFrom("work_machine_rules")
391
- .select(["name", "definition"])
392
- .where("tenant_id", "=", this.deps.tenantId)
393
- .orderBy("name")
394
- .execute();
395
- return Object.fromEntries(
396
- rows.map((row) => [row.name, MachineRuleSchema.parse(row.definition)]),
397
- );
398
- }
399
-
400
- /**
401
- * Write a rule. Its class must be one the server knows: a configured
402
- * class, or any class when only the provisioner hook is configured.
403
- */
404
- async setRule(args: { name: string; rule: unknown }): Promise<MachineRule> {
405
- const name = MachineName.parse(args.name);
406
- const rule = MachineRuleSchema.parse(args.rule);
407
- const machineClass = this.classOf(rule.class);
408
- if (!machineClass)
409
- throw new Error(
410
- `Machine class '${rule.class}' is not configured. Classes: ${
411
- Object.keys(this.deps.classes).join(", ") || "none"
412
- }. Add it to the WORK_MACHINES_CONFIG file.`,
413
- );
414
- if (machineClass.platform === "pool" && Object.keys(rule.labels).length > 0)
415
- throw new Error(
416
- "A pooled machine keeps the labels it enrolled with; remove labels from this rule",
417
- );
418
- if (machineClass.platform === "pool" && demandOf(rule))
419
- throw new Error(
420
- `Machines on demand are created on a platform, and class '${rule.class}' is a pool of enrolled machines. Use a hetzner-cloud or custom class`,
421
- );
422
- // A machine serving several owners must isolate its agents to connect
423
- // (ADR 0167): refuse a rule whose class's machines are known not to.
424
- if (
425
- demandOf(rule) &&
426
- !rule.trusted &&
427
- servesSeveral(rule) &&
428
- (await this.runsPlainProcesses(rule.class))
429
- )
430
- throw new Error(
431
- `Machines of class '${rule.class}' run agents as plain processes, so a machine serving ${rule.group ? "a group" : "several projects"} would be refused when it connects. Give the class machines that isolate agents (microsandbox or gVisor), or add "trusted": true if everyone it serves trusts each other`,
432
- );
433
- await this.deps.db
434
- .insertInto("work_machine_rules")
435
- .values({
436
- name,
437
- tenant_id: this.deps.tenantId,
438
- definition: JSON.stringify(rule),
439
- })
440
- .onConflict((oc) =>
441
- oc.columns(["tenant_id", "name"]).doUpdateSet({
442
- definition: JSON.stringify(rule),
443
- updated_at: sql`now()`,
444
- }),
445
- )
446
- .execute();
447
- return rule;
448
- }
449
-
450
- /**
451
- * Remove a rule. Its machines keep the rule's retention, which outlives
452
- * it, and are released by the next pass.
453
- */
454
- async deleteRule(name: string): Promise<boolean> {
455
- return this.deps.db.transaction().execute(async (trx) => {
456
- const deleted = await trx
457
- .deleteFrom("work_machine_rules")
458
- .where("tenant_id", "=", this.deps.tenantId)
459
- .where("name", "=", name)
460
- .returning("definition")
461
- .executeTakeFirst();
462
- if (!deleted) return false;
463
- const parsed = MachineRuleSchema.safeParse(deleted.definition);
464
- if (parsed.success)
465
- await trx
466
- .updateTable("work_workers")
467
- .set({ retain_days: parsed.data.retainDays })
468
- .where("tenant_id", "=", this.deps.tenantId)
469
- .where("machine_rule", "=", name)
470
- .where("revoked_at", "is", null)
471
- .where("released_at", "is", null)
472
- .execute();
473
- return true;
474
- });
475
- }
476
-
477
- /** Directory groups rules name, for the directory mirror. */
478
- async groups(): Promise<string[]> {
479
- return [
480
- ...new Set(
481
- Object.values(await this.rules()).flatMap((rule) =>
482
- rule.group ? [rule.group] : [],
483
- ),
484
- ),
485
- ];
486
- }
487
-
488
- /** How each rule's machines stand right now. */
489
- async status(): Promise<Record<string, MachineRuleStatus>> {
490
- const desired = await this.desired();
491
- const [machines, pooled, failures] = await Promise.all([
492
- this.deps.workers.machines(),
493
- this.deps.workers.pooledMachines(),
494
- this.deps.db
495
- .selectFrom("work_machine_rules")
496
- .select(["name", "last_failure", "last_failure_at"])
497
- .where("tenant_id", "=", this.deps.tenantId)
498
- .where("last_failure", "is not", null)
499
- .execute(),
500
- ]);
501
- const status: Record<string, MachineRuleStatus> = {};
502
- for (const [name, rule] of Object.entries(desired.rules)) {
503
- const platform = this.classOf(rule.class)?.platform ?? null;
504
- const problem =
505
- desired.problems.get(name) ?? desired.notices.get(name)?.join(" ");
506
- const failed = failures.find((row) => row.name === name);
507
- const extra = {
508
- ...(problem ? { problem } : {}),
509
- ...(failed?.last_failure && failed.last_failure_at
510
- ? {
511
- failure: {
512
- error: failed.last_failure,
513
- at: failed.last_failure_at.toISOString(),
514
- },
515
- }
516
- : {}),
517
- };
518
- if (platform === "pool") {
519
- const slots = desired.slots.filter((slot) => slot.rule === name);
520
- const held = pooled.filter((machine) => machine.rule === name);
521
- const ready = held.filter(
522
- (machine) => machine.releasedForMs === null,
523
- ).length;
524
- status[name] = {
525
- platform,
526
- desired: slots.length,
527
- ready,
528
- starting: 0,
529
- waiting: Math.max(0, slots.length - ready),
530
- released: held.length - ready,
531
- ...extra,
532
- };
533
- continue;
534
- }
535
- const wanted = [...desired.provisioned.values()].filter(
536
- (machine) => machine.rule === name,
537
- );
538
- const own = machines.filter((machine) => machine.rule === name);
539
- const isWanted = (machineName: string) =>
540
- wanted.some((machine) => machine.name === machineName);
541
- const ready = own.filter(
542
- (machine) =>
543
- machine.state === "enrolled" &&
544
- machine.releasedForMs === null &&
545
- isWanted(machine.name),
546
- ).length;
547
- const starting = own.filter(
548
- (machine) => machine.state === "pending" && isWanted(machine.name),
549
- ).length;
550
- status[name] = {
551
- platform,
552
- desired: wanted.length,
553
- ready,
554
- starting,
555
- waiting: Math.max(0, wanted.length - ready - starting),
556
- released: own.filter(
557
- (machine) =>
558
- machine.state === "enrolled" && machine.releasedForMs !== null,
559
- ).length,
560
- ...(demandOf(rule) ? { queued: desired.queued.get(name) ?? 0 } : {}),
561
- ...extra,
562
- };
563
- }
564
- return status;
565
- }
566
-
567
- /**
568
- * One pass; concurrent callers share it, and replicas take turns: a pass
569
- * runs only while this replica holds the tenant's reconciler claim (ADR
570
- * 0193), renewed as it goes and checked before every change it makes.
571
- */
572
- reconcile(): Promise<ReconcileSummary> {
573
- this.running ??= withSpan(
574
- {
575
- tracer,
576
- name: "machines.reconcile",
577
- attributes: { "catamorphic.tenant.id": this.deps.tenantId },
578
- },
579
- () => this.guardedPass(),
580
- ).finally(() => {
581
- this.running = undefined;
582
- });
583
- return this.running;
584
- }
585
-
586
- /**
587
- * Start a pass without waiting for it, as after a rule changed: its
588
- * outcome reaches the rule's status and the log.
589
- */
590
- reconcileSoon(): void {
591
- void this.reconcile().catch((error: unknown) =>
592
- this.deps.log?.(`Machine reconciliation failed: ${message(error)}`),
593
- );
594
- }
595
-
596
- /** Waits for a pass in progress (shutdown); starts none. */
597
- async settle(): Promise<void> {
598
- await this.running?.catch(() => undefined);
599
- }
600
-
601
- private get leaseMs(): number {
602
- return this.deps.leaseMs ?? 120_000;
603
- }
604
-
605
- private async guardedPass(): Promise<ReconcileSummary> {
606
- const claim = {
607
- db: this.deps.db,
608
- name: `machine-reconciler:${this.deps.tenantId}`,
609
- holder: this.holder,
610
- };
611
- const ttlSeconds = Math.max(1, Math.ceil(this.leaseMs / 1000));
612
- const summary: ReconcileSummary = {
613
- created: [],
614
- assigned: [],
615
- updated: [],
616
- released: [],
617
- removed: [],
618
- destroying: [],
619
- reset: [],
620
- failed: [],
621
- };
622
- if (!(await takeReplicaClaim({ ...claim, ttlSeconds }))) {
623
- // Another replica is reconciling; its pass covers this one.
624
- return { ...summary, busy: true };
625
- }
626
- // Demand this pass sees; a change after this starts another pass.
627
- this.demandSeen = await this.demandSignature().catch(() => this.demandSeen);
628
- const lease = { lost: false };
629
- // A platform call can outlast the claim; keep it while the pass runs.
630
- const heartbeat = setInterval(
631
- () => {
632
- void renewReplicaClaim({ ...claim, ttlSeconds })
633
- .then((held) => {
634
- if (!held) lease.lost = true;
635
- })
636
- .catch(() => undefined);
637
- },
638
- Math.max(1_000, this.leaseMs / 4),
639
- );
640
- heartbeat.unref();
641
- const fence = async () => {
642
- if (lease.lost || !(await renewReplicaClaim({ ...claim, ttlSeconds }))) {
643
- lease.lost = true;
644
- throw new ReconcilerLeaseLostError();
645
- }
646
- };
647
- try {
648
- const desired = await this.pass({ fence, summary });
649
- await fence();
650
- await this.recordFailures({ rules: Object.keys(desired.rules), summary });
651
- } catch (error) {
652
- if (!(error instanceof ReconcilerLeaseLostError)) throw error;
653
- this.deps.log?.(
654
- "Machine reconciliation stopped: another replica took over the pass",
655
- );
656
- } finally {
657
- clearInterval(heartbeat);
658
- await releaseReplicaClaim(claim).catch(() => undefined);
659
- }
660
- const changed =
661
- summary.created.length +
662
- summary.assigned.length +
663
- summary.updated.length +
664
- summary.released.length +
665
- summary.removed.length +
666
- summary.reset.length;
667
- if (changed > 0 || summary.failed.length > 0) {
668
- this.deps.log?.(
669
- `Machines: ${summary.created.length} created, ${summary.assigned.length} assigned, ${summary.updated.length} updated, ${summary.released.length} released, ${summary.removed.length} removed, ${summary.reset.length} reset, ${summary.failed.length} failed`,
670
- );
671
- }
672
- return summary;
673
- }
674
-
675
- /** Each rule's failures in this pass, or none, for its status. */
676
- private async recordFailures(args: {
677
- rules: readonly string[];
678
- summary: ReconcileSummary;
679
- }): Promise<void> {
680
- for (const rule of args.rules) {
681
- const failures = args.summary.failed.filter(
682
- (failure) => failure.rule === rule,
683
- );
684
- await this.deps.db
685
- .updateTable("work_machine_rules")
686
- .set(
687
- failures.length > 0
688
- ? {
689
- last_failure: failures
690
- .map((failure) =>
691
- failure.name === rule
692
- ? failure.error
693
- : `${failure.name}: ${failure.error}`,
694
- )
695
- .join("\n")
696
- .slice(0, 4_000),
697
- last_failure_at: sql`now()`,
698
- }
699
- : { last_failure: null, last_failure_at: null },
700
- )
701
- .where("tenant_id", "=", this.deps.tenantId)
702
- .where("name", "=", rule)
703
- .execute();
704
- }
705
- }
706
-
707
- /**
708
- * Records what it changes in `summary`; `fence` throws once another
709
- * reconciler holds the claim, ending the pass with what it did so far.
710
- */
711
- private async pass(args: {
712
- fence: () => Promise<void>;
713
- summary: ReconcileSummary;
714
- }): Promise<Desired> {
715
- const desired = await this.desired();
716
- for (const [rule, problem] of desired.problems)
717
- args.summary.failed.push({ name: rule, error: problem, rule });
718
- for (const [rule, notices] of desired.notices)
719
- for (const notice of notices)
720
- args.summary.failed.push({ name: rule, error: notice, rule });
721
- await this.reconcileProvisioned({ ...args, desired });
722
- await this.reconcilePooled({ ...args, desired });
723
- return desired;
724
- }
725
-
726
- /**
727
- * Run one machine's step; a failure is recorded for it and the pass goes
728
- * on with the next machine. Losing the claim still ends the pass.
729
- */
730
- private async step(args: {
731
- summary: ReconcileSummary;
732
- name: string;
733
- rule: string | null;
734
- run: () => Promise<void>;
735
- }): Promise<boolean> {
736
- try {
737
- await args.run();
738
- return true;
739
- } catch (error) {
740
- if (error instanceof ReconcilerLeaseLostError) throw error;
741
- args.summary.failed.push({
742
- name: args.name,
743
- error: message(error),
744
- ...(args.rule ? { rule: args.rule } : {}),
745
- });
746
- return false;
747
- }
748
- }
749
-
750
- /** Cloud and custom machines: one per desired name. */
751
- private async reconcileProvisioned({
752
- fence,
753
- summary,
754
- desired,
755
- }: {
756
- fence: () => Promise<void>;
757
- summary: ReconcileSummary;
758
- desired: Desired;
759
- }): Promise<void> {
760
- const machines = await this.deps.workers.machines();
761
-
762
- // Expired codes, machines an operator revoked, and machines nobody
763
- // should have go first, and a name is reused only after its old
764
- // machine is gone. An enrolled machine is released before that and
765
- // kept for its retention. A machine stays listed until its platform
766
- // confirmed it is gone, so a failed destruction is tried again.
767
- const pendingDestroy = new Set<string>();
768
- for (const machine of machines) {
769
- if (desired.problems.has(machine.rule)) continue;
770
- const wanted = desired.provisioned.has(machine.name);
771
- if (wanted && machine.state !== "expired" && machine.state !== "revoked")
772
- continue;
773
- const settled = await this.step({
774
- summary,
775
- name: machine.name,
776
- rule: machine.rule,
777
- run: async () => {
778
- if (machine.state === "enrolled") {
779
- const retainDays = this.retainDaysOf({ machine, desired });
780
- if (machine.releasedForMs === null) {
781
- await fence();
782
- await this.deps.workers.release({
783
- name: machine.name,
784
- retainDays,
785
- });
786
- summary.released.push(machine.name);
787
- }
788
- if (
789
- !retentionEnded({
790
- releasedForMs: machine.releasedForMs ?? 0,
791
- retainDays,
792
- })
793
- )
794
- return;
795
- // Chats on it give their workspaces back saved once they idle
796
- // (ADR 0173); a machine that can no longer save them goes at
797
- // once. Revoked under its node's lock, so no Allocation lands
798
- // on it between this check and its revocation (ADR 0258).
799
- await fence();
800
- if (
801
- !(await this.deps.workers.drain({
802
- name: machine.name,
803
- unseenForMs: this.lostAfterMs(machine.rule, desired),
804
- }))
805
- )
806
- return;
807
- }
808
- if (machine.state === "enrolled" || machine.state === "pending") {
809
- await fence();
810
- // Its code stops working, and it stays listed until destroyed.
811
- await this.deps.workers.expireEnrollments({ name: machine.name });
812
- }
813
- await fence();
814
- if (!(await this.unprovision(machine))) {
815
- summary.destroying.push(machine.name);
816
- pendingDestroy.add(machine.name);
817
- return;
818
- }
819
- await this.deps.workers.forgetMachine(machine);
820
- summary.removed.push(machine.name);
821
- },
822
- });
823
- if (!settled) pendingDestroy.add(machine.name);
824
- }
825
-
826
- for (const machine of desired.provisioned.values()) {
827
- if (pendingDestroy.has(machine.name)) continue;
828
- const current = machines.find(
829
- (candidate) =>
830
- candidate.name === machine.name &&
831
- (candidate.state === "enrolled" || candidate.state === "pending"),
832
- );
833
- if (current?.state === "pending") continue;
834
- await this.step({
835
- summary,
836
- name: machine.name,
837
- rule: machine.rule,
838
- run: async () => {
839
- if (current && current.releasedForMs !== null) {
840
- // Their person or group is back before the machine went.
841
- await fence();
842
- await this.deps.workers.reassign(machine);
843
- summary.assigned.push(machine.name);
844
- return;
845
- }
846
- if (current) {
847
- if (canonical(current.placement) !== canonical(machine.placement)) {
848
- await fence();
849
- await this.deps.workers.setPlacement(machine);
850
- summary.updated.push(machine.name);
851
- }
852
- if (current.retainDays !== machine.retainDays) {
853
- await fence();
854
- await this.deps.workers.setRetainDays(machine);
855
- }
856
- return;
857
- }
858
- await this.create({ machine, fence, summary });
859
- },
860
- });
861
- }
862
- }
863
-
864
- /**
865
- * Create a missing machine. Nothing is issued while machines cannot
866
- * install from this server. A platform that refused creates nothing, so
867
- * its code is withdrawn and the next pass tries again; after any other
868
- * failure the code stays, since the machine may still come up and enroll.
869
- */
870
- private async create(args: {
871
- machine: DesiredMachine;
872
- fence: () => Promise<void>;
873
- summary: ReconcileSummary;
874
- }): Promise<void> {
875
- const { machine } = args;
876
- const machineClass = this.classOf(machine.class);
877
- if (
878
- machineClass?.platform === "hetzner-cloud" &&
879
- "unavailable" in this.deps.install
880
- )
881
- throw new Error(this.deps.install.unavailable);
882
- await args.fence();
883
- const enrollment = await this.deps.workers.createMachineEnrollment({
884
- name: machine.name,
885
- rule: machine.rule,
886
- // A machine on demand that does not enroll in time is replaced.
887
- ttlMinutes: machine.enrollMinutes ?? 60,
888
- placement: machine.placement,
889
- });
890
- // Its machine enrolled or is being created since this pass looked.
891
- if (!enrollment) return;
892
- try {
893
- const ref = await this.provision({ machine, code: enrollment.code });
894
- await this.deps.workers.recordMachineRef({
895
- code: enrollment.code,
896
- ref,
897
- });
898
- args.summary.created.push(machine.name);
899
- } catch (error) {
900
- if (
901
- (error instanceof HetznerCloudError && error.definite) ||
902
- error instanceof MachineProvisioningRefusedError
903
- )
904
- await this.deps.workers.cancelEnrollments({ name: machine.name });
905
- throw error;
906
- }
907
- }
908
-
909
- /**
910
- * Pooled machines (ADR 0205): each place a pool rule calls for holds one
911
- * free machine of its class. Machines nobody holds any more are released,
912
- * then reset through their worker once their retention ends.
913
- */
914
- private async reconcilePooled({
915
- fence,
916
- summary,
917
- desired,
918
- }: {
919
- fence: () => Promise<void>;
920
- summary: ReconcileSummary;
921
- desired: Desired;
922
- }): Promise<void> {
923
- const pooled = await this.deps.workers.pooledMachines();
924
- const slots = new Map(desired.slots.map((slot) => [slotKey(slot), slot]));
925
- /** Places with a machine serving them. */
926
- const held = new Set<string>();
927
- const placementFor = (machine: PooledMachine, slot: DesiredSlot) =>
928
- WorkerPlacementSchema.parse({
929
- labels: machine.placement.labels,
930
- access: slot.access,
931
- trusted: slot.trusted,
932
- });
933
- const fits = (machine: PooledMachine, slot: DesiredSlot | undefined) =>
934
- slot !== undefined &&
935
- machine.placement.labels.class === slot.class &&
936
- !held.has(slotKey(slot));
937
-
938
- // Held machines keep their place, follow its placement, or are released.
939
- const released: PooledMachine[] = [];
940
- for (const machine of pooled) {
941
- if (!machine.rule) continue;
942
- const rule = machine.rule;
943
- if (desired.problems.has(rule)) {
944
- if (machine.releasedForMs === null)
945
- held.add(slotKey(machineSlot(machine)));
946
- continue;
947
- }
948
- if (machine.releasedForMs !== null) {
949
- released.push(machine);
950
- continue;
951
- }
952
- const slot = slots.get(slotKey(machineSlot(machine)));
953
- if (slot && fits(machine, slot)) {
954
- held.add(slotKey(slot));
955
- await this.step({
956
- summary,
957
- name: machine.name,
958
- rule,
959
- run: async () => {
960
- const placement = placementFor(machine, slot);
961
- if (canonical(machine.placement) !== canonical(placement)) {
962
- await fence();
963
- await this.deps.workers.setPlacement({
964
- name: machine.name,
965
- placement,
966
- });
967
- summary.updated.push(machine.name);
968
- }
969
- if (machine.retainDays !== slot.retainDays) {
970
- await fence();
971
- await this.deps.workers.setRetainDays({
972
- name: machine.name,
973
- retainDays: slot.retainDays,
974
- });
975
- }
976
- },
977
- });
978
- continue;
979
- }
980
- const retainDays = this.retainDaysOf({ machine, desired });
981
- await this.step({
982
- summary,
983
- name: machine.name,
984
- rule,
985
- run: async () => {
986
- await fence();
987
- await this.deps.workers.release({ name: machine.name, retainDays });
988
- summary.released.push(machine.name);
989
- released.push({ ...machine, releasedForMs: 0, retainDays });
990
- },
991
- });
992
- }
993
-
994
- // Released machines go back to their person or group within their
995
- // retention; afterwards they are reset.
996
- const resets = pooled
997
- .filter((machine) => !machine.rule && machine.releasedForMs !== null)
998
- .map((machine) => machine.name);
999
- for (const machine of released) {
1000
- const slot = slots.get(slotKey(machineSlot(machine)));
1001
- const retainDays = this.retainDaysOf({ machine, desired });
1002
- const ended = retentionEnded({
1003
- releasedForMs: machine.releasedForMs ?? 0,
1004
- retainDays,
1005
- });
1006
- await this.step({
1007
- summary,
1008
- name: machine.name,
1009
- rule: machine.rule,
1010
- run: async () => {
1011
- if (slot && fits(machine, slot) && !ended) {
1012
- await fence();
1013
- await this.deps.workers.reassign({
1014
- name: machine.name,
1015
- placement: placementFor(machine, slot),
1016
- retainDays: slot.retainDays,
1017
- });
1018
- held.add(slotKey(slot));
1019
- summary.assigned.push(machine.name);
1020
- return;
1021
- }
1022
- if (!ended) return;
1023
- await fence();
1024
- await this.deps.workers.beginReset({ name: machine.name });
1025
- resets.push(machine.name);
1026
- },
1027
- });
1028
- }
1029
-
1030
- // Resets run at once, each waiting a bounded time. A machine that is
1031
- // not connected is reset when it reconnects, one whose chats still hold
1032
- // workspaces once they idle and give them back saved (ADR 0173), and a
1033
- // reset that takes longer than the wait on a later pass.
1034
- const freed = new Set<string>();
1035
- await Promise.all(
1036
- resets.map((name) =>
1037
- this.step({
1038
- summary,
1039
- name,
1040
- rule: null,
1041
- run: async () => {
1042
- if (!(await this.deps.workers.connected({ name }))) return;
1043
- if ((await this.deps.workers.activeWorkspaces({ name })) > 0)
1044
- return;
1045
- await fence();
1046
- await this.deps.workers.resetPooled({
1047
- name,
1048
- timeoutMs: this.deps.resetWaitMs ?? 3 * 60_000,
1049
- });
1050
- await fence();
1051
- await this.deps.workers.freePooled({ name });
1052
- freed.add(name);
1053
- summary.reset.push(name);
1054
- },
1055
- }),
1056
- ),
1057
- );
1058
-
1059
- // Places still without a machine take a free one of their class.
1060
- const free = pooled.filter(
1061
- (machine) =>
1062
- (!machine.rule && machine.releasedForMs === null) ||
1063
- freed.has(machine.name),
1064
- );
1065
- for (const slot of desired.slots) {
1066
- if (held.has(slotKey(slot)) || desired.problems.has(slot.rule)) continue;
1067
- const index = free.findIndex(
1068
- (machine) => machine.placement.labels.class === slot.class,
1069
- );
1070
- const [machine] = index >= 0 ? free.splice(index, 1) : [];
1071
- if (!machine) continue;
1072
- await this.step({
1073
- summary,
1074
- name: machine.name,
1075
- rule: slot.rule,
1076
- run: async () => {
1077
- await fence();
1078
- if (
1079
- await this.deps.workers.assignPooled({
1080
- name: machine.name,
1081
- rule: slot.rule,
1082
- holder: slot.holder,
1083
- placement: placementFor(machine, slot),
1084
- retainDays: slot.retainDays,
1085
- })
1086
- ) {
1087
- held.add(slotKey(slot));
1088
- summary.assigned.push(machine.name);
1089
- }
1090
- },
1091
- });
1092
- }
1093
- }
1094
-
1095
- /** Create a machine on its class's platform; resolves with its ref. */
1096
- private async provision(args: {
1097
- machine: DesiredMachine;
1098
- code: string;
1099
- }): Promise<string> {
1100
- const { machine, code } = args;
1101
- const machineClass = this.classOf(machine.class);
1102
- const idempotencyKey = createHash("sha256").update(code).digest("hex");
1103
- const cloudInit =
1104
- "target" in this.deps.install
1105
- ? workerCloudInit({
1106
- script: workerInstallScript(this.deps.install.target),
1107
- code,
1108
- ...(machineClass?.platform !== "pool" && machineClass?.sandbox
1109
- ? { sandbox: machineClass.sandbox }
1110
- : {}),
1111
- })
1112
- : undefined;
1113
- if (machineClass?.platform === "hetzner-cloud") {
1114
- if (!this.deps.hetzner)
1115
- throw new MachineProvisioningRefusedError(
1116
- "Set WORK_HETZNER_TOKEN to create Hetzner Cloud machines",
1117
- );
1118
- if (!cloudInit)
1119
- throw new MachineProvisioningRefusedError(
1120
- "unavailable" in this.deps.install
1121
- ? this.deps.install.unavailable
1122
- : "Machines cannot install from this server",
1123
- );
1124
- const { ref } = await this.deps.hetzner.create({
1125
- name: machine.name,
1126
- serverType: machineClass.serverType,
1127
- location: machineClass.location,
1128
- image: machineClass.image,
1129
- ...(machineClass.sshKeys ? { sshKeys: machineClass.sshKeys } : {}),
1130
- ...(machineClass.firewalls
1131
- ? { firewalls: machineClass.firewalls }
1132
- : {}),
1133
- ...(machineClass.networks ? { networks: machineClass.networks } : {}),
1134
- labels: {
1135
- ...machineClass.labels,
1136
- "work-rule": machine.rule,
1137
- "work-class": machine.class,
1138
- },
1139
- userData: cloudInit,
1140
- });
1141
- return `${HETZNER_REF}${ref}`;
1142
- }
1143
- if (machineClass?.platform === "custom" && this.deps.provisioner) {
1144
- const { ref } = await this.deps.provisioner.create({
1145
- name: machine.name,
1146
- class: machine.class,
1147
- rule: machine.rule,
1148
- ...(machineClass.options ? { options: machineClass.options } : {}),
1149
- ...(machine.waiting ? { waiting: machine.waiting } : {}),
1150
- labels: machine.placement.labels,
1151
- enrollment: {
1152
- controlPlaneUrl: this.deps.controlPlaneUrl,
1153
- code,
1154
- idempotencyKey,
1155
- ...(cloudInit ? { cloudInit } : {}),
1156
- },
1157
- });
1158
- return ref;
1159
- }
1160
- throw new MachineProvisioningRefusedError(
1161
- `Machine class '${machine.class}' creates no machines`,
1162
- );
1163
- }
1164
-
1165
- /**
1166
- * Destroy a machine on the platform that made it, by its reference or
1167
- * else by its name. False while the destruction is still under way.
1168
- */
1169
- private async unprovision(machine: ProvisionedMachine): Promise<boolean> {
1170
- const className = machine.placement.labels.class;
1171
- const machineClass = className ? this.classOf(className) : undefined;
1172
- if (
1173
- machine.ref?.startsWith(HETZNER_REF) ||
1174
- machineClass?.platform === "hetzner-cloud"
1175
- ) {
1176
- if (!this.deps.hetzner)
1177
- throw new Error(
1178
- "Set WORK_HETZNER_TOKEN to destroy Hetzner Cloud machines",
1179
- );
1180
- // Only a machine that enrolled can hold anyone's work.
1181
- const snapshot =
1182
- machineClass?.platform === "hetzner-cloud" &&
1183
- machineClass.snapshot &&
1184
- (machine.state === "enrolled" || machine.state === "revoked");
1185
- const destroyed = await this.deps.hetzner.destroy({
1186
- name: machine.name,
1187
- ref: machine.ref?.startsWith(HETZNER_REF)
1188
- ? machine.ref.slice(HETZNER_REF.length)
1189
- : null,
1190
- ...(snapshot
1191
- ? {
1192
- snapshot: {
1193
- description: `Work machine ${machine.name} of rule ${machine.rule}`,
1194
- labels: { "work-rule": machine.rule },
1195
- },
1196
- }
1197
- : {}),
1198
- });
1199
- return destroyed.done;
1200
- }
1201
- if (!this.deps.provisioner)
1202
- throw new Error(
1203
- `No platform destroys machines of class '${className ?? "unknown"}'`,
1204
- );
1205
- const destroyed = await this.deps.provisioner.destroy({
1206
- name: machine.name,
1207
- ref: machine.ref,
1208
- });
1209
- return destroyed.done;
1210
- }
1211
-
1212
- /**
1213
- * How long a machine holding workspaces may go unseen before it is lost
1214
- * and revoked anyway: its rule's `enrollMinutes` for machines on demand.
1215
- */
1216
- private lostAfterMs(rule: string, desired: Desired): number {
1217
- const definition = desired.rules[rule];
1218
- const demand = definition ? demandOf(definition) : undefined;
1219
- return (demand?.enrollMinutes ?? DEFAULT_ENROLL_MINUTES) * 60_000;
1220
- }
1221
-
1222
- /** Whether machines of this class are known to run plain processes. */
1223
- private async runsPlainProcesses(machineClass: string): Promise<boolean> {
1224
- const row = await this.deps.db
1225
- .selectFrom("work_workers")
1226
- .innerJoin("worker_nodes", "worker_nodes.id", "work_workers.node_id")
1227
- .select("work_workers.name")
1228
- .where("work_workers.tenant_id", "=", this.deps.tenantId)
1229
- .where(sql<boolean>`work_workers.labels ->> 'class' = ${machineClass}`)
1230
- .where(sql<boolean>`worker_nodes.descriptor ->> 'isolation' = 'process'`)
1231
- .executeTakeFirst();
1232
- return Boolean(row);
1233
- }
1234
-
1235
- /**
1236
- * The class a name refers to: a configured one, or with none configured
1237
- * any class, handled by the provisioner hook.
1238
- */
1239
- private classOf(name: string): MachineClass | undefined {
1240
- if (Object.keys(this.deps.classes).length > 0)
1241
- return this.deps.classes[name];
1242
- return this.deps.provisioner ? { platform: "custom" } : undefined;
1243
- }
1244
-
1245
- /** Retention: the rule's now, else what the machine recorded. */
1246
- private retainDaysOf(args: {
1247
- machine: { rule: string | null; retainDays: number | null };
1248
- desired: Desired;
1249
- }): number {
1250
- const rule = args.machine.rule
1251
- ? args.desired.rules[args.machine.rule]
1252
- : undefined;
1253
- return rule?.retainDays ?? args.machine.retainDays ?? DEFAULT_RETAIN_DAYS;
1254
- }
1255
-
1256
- private async desired(): Promise<Desired> {
1257
- const rules = await this.rules();
1258
- const desired: Desired = {
1259
- rules,
1260
- provisioned: new Map(),
1261
- slots: [],
1262
- problems: new Map(),
1263
- queued: new Map(),
1264
- notices: new Map(),
1265
- };
1266
- const demand = Object.values(rules).some((rule) => demandOf(rule))
1267
- ? await this.demandState()
1268
- : undefined;
1269
- const { notices } = desired;
1270
- // Each piece of waiting work is one rule's to serve: the first by name
1271
- // that takes it and whose machines are not known to fall short of it.
1272
- const assigned = new Map<string, DemandWait[]>();
1273
- if (demand)
1274
- for (const wait of demand.waits)
1275
- for (const [rule, definition] of Object.entries(rules)) {
1276
- const machineClass = this.classOf(definition.class);
1277
- if (
1278
- !demandOf(definition) ||
1279
- !machineClass ||
1280
- machineClass.platform === "pool" ||
1281
- !demandWaitMatches(definition, wait)
1282
- )
1283
- continue;
1284
- const short = demandShortfall({
1285
- machines: demand.machines.filter(
1286
- (machine) => machine.rule === rule,
1287
- ),
1288
- loads: demand.loads,
1289
- wait,
1290
- });
1291
- if (short) {
1292
- const said = notices.get(rule) ?? [];
1293
- const notice = `Work waiting for this rule needs what its machines do not offer (${short}); they take none of it.`;
1294
- if (!said.includes(notice)) notices.set(rule, [...said, notice]);
1295
- continue;
1296
- }
1297
- assigned.set(rule, [...(assigned.get(rule) ?? []), wait]);
1298
- break;
1299
- }
1300
- for (const [rule, definition] of Object.entries(rules)) {
1301
- const machineClass = this.classOf(definition.class);
1302
- if (!machineClass) {
1303
- desired.problems.set(
1304
- rule,
1305
- `Machine class '${definition.class}' is not configured; this rule's machines are left as they are`,
1306
- );
1307
- continue;
1308
- }
1309
- const ruleDemand = demandOf(definition);
1310
- if (ruleDemand && demand) {
1311
- if (machineClass.platform === "pool") {
1312
- desired.problems.set(
1313
- rule,
1314
- `Machines on demand are created on a platform, and class '${definition.class}' is a pool; this rule's machines are left as they are`,
1315
- );
1316
- continue;
1317
- }
1318
- const waits = assigned.get(rule) ?? [];
1319
- desired.queued.set(rule, waits.length);
1320
- const stalled = demand.stalled.find(
1321
- (machine) =>
1322
- machine.rule === rule &&
1323
- machine.enrolledForMs >= ruleDemand.enrollMinutes * 60_000,
1324
- );
1325
- if (stalled)
1326
- notices.set(rule, [
1327
- ...(notices.get(rule) ?? []),
1328
- neverConnectedNotice({
1329
- name: stalled.name,
1330
- minutes: ruleDemand.enrollMinutes,
1331
- definition,
1332
- }),
1333
- ]);
1334
- for (const machine of demandMachines({
1335
- rule,
1336
- definition,
1337
- demand: ruleDemand,
1338
- machines: demand.machines.filter((machine) => machine.rule === rule),
1339
- loads: demand.loads,
1340
- waits,
1341
- stalled: Boolean(stalled),
1342
- }))
1343
- desired.provisioned.set(machine.name, machine);
1344
- continue;
1345
- }
1346
- const group = definition.group ?? "";
1347
- const members =
1348
- definition.machines === "each-member" ? await this.members(group) : [];
1349
- if (machineClass.platform === "pool") {
1350
- const holders =
1351
- definition.machines === "each-member"
1352
- ? members.map((member) => ({
1353
- holder: { member: member.userId },
1354
- group: null,
1355
- access: WorkerAccessSchema.parse({
1356
- people: [member.email],
1357
- }),
1358
- trusted: false,
1359
- }))
1360
- : Array.from(
1361
- {
1362
- length:
1363
- "shared" in definition.machines
1364
- ? definition.machines.shared
1365
- : 0,
1366
- },
1367
- (_, index) => ({
1368
- holder: { slot: index + 1 },
1369
- group,
1370
- access: WorkerAccessSchema.parse({ groups: [group] }),
1371
- trusted: definition.trusted,
1372
- }),
1373
- );
1374
- for (const holder of holders)
1375
- desired.slots.push({
1376
- rule,
1377
- class: definition.class,
1378
- retainDays: definition.retainDays,
1379
- ...holder,
1380
- });
1381
- continue;
1382
- }
1383
- const labels = { ...definition.labels, class: definition.class };
1384
- const add = (name: string, placement: unknown) =>
1385
- desired.provisioned.set(name, {
1386
- name,
1387
- rule,
1388
- class: definition.class,
1389
- placement: WorkerPlacementSchema.parse(placement),
1390
- retainDays: definition.retainDays,
1391
- });
1392
- if (definition.machines === "each-member") {
1393
- for (const member of members)
1394
- add(dedicatedName(rule, member.userId, definition.class), {
1395
- labels,
1396
- access: { people: [member.email] },
1397
- });
1398
- continue;
1399
- }
1400
- const shared =
1401
- "shared" in definition.machines ? definition.machines.shared : 0;
1402
- for (let index = 1; index <= shared; index += 1)
1403
- add(sharedName(rule, definition.class, group, index), {
1404
- labels,
1405
- access: { groups: [group] },
1406
- trusted: definition.trusted,
1407
- });
1408
- }
1409
- return desired;
1410
- }
1411
-
1412
- /**
1413
- * What machines on demand decide on (ADR 0258): the work waiting for a
1414
- * machine with a turn queued, tried recently and oldest first, with its
1415
- * owner's directory groups; every machine a rule provisioned; how busy
1416
- * each enrolled one is; and machines that enrolled since their rule was
1417
- * last written and never connected.
1418
- */
1419
- private async demandState(): Promise<{
1420
- waits: DemandWait[];
1421
- machines: ProvisionedMachine[];
1422
- loads: Map<string, MachineLoad>;
1423
- stalled: Array<{ rule: string; name: string; enrolledForMs: number }>;
1424
- }> {
1425
- const [rows, machines, loads, stalled] = await Promise.all([
1426
- this.deps.db
1427
- .selectFrom("placement_waits")
1428
- .leftJoin(
1429
- "work_accounts",
1430
- "work_accounts.user_id",
1431
- "placement_waits.owner",
1432
- )
1433
- .select([
1434
- "placement_waits.project_id",
1435
- "placement_waits.owner",
1436
- "placement_waits.pool",
1437
- "placement_waits.requirements",
1438
- "work_accounts.directory_groups",
1439
- "work_accounts.disabled_at",
1440
- ])
1441
- .where("placement_waits.tenant_id", "=", this.deps.tenantId)
1442
- .where("placement_waits.last_tried_at", ">", waitFresh())
1443
- .where(queuedPlacementWait(this.deps.db))
1444
- .orderBy("placement_waits.waiting_since")
1445
- .execute(),
1446
- this.deps.workers.machines(),
1447
- this.deps.workers.machineLoad(),
1448
- this.deps.db
1449
- .selectFrom("work_workers")
1450
- .innerJoin("work_machine_rules", (join) =>
1451
- join
1452
- .onRef(
1453
- "work_machine_rules.tenant_id",
1454
- "=",
1455
- "work_workers.tenant_id",
1456
- )
1457
- .onRef("work_machine_rules.name", "=", "work_workers.machine_rule"),
1458
- )
1459
- .select([
1460
- "work_workers.machine_rule",
1461
- "work_workers.name",
1462
- sql<number>`(extract(epoch from (now() - work_workers.enrolled_at)) * 1000)::float8`.as(
1463
- "enrolled_for_ms",
1464
- ),
1465
- ])
1466
- .where("work_workers.tenant_id", "=", this.deps.tenantId)
1467
- .where("work_workers.pool", "=", false)
1468
- .where("work_workers.last_seen_at", "is", null)
1469
- .whereRef(
1470
- "work_workers.enrolled_at",
1471
- ">",
1472
- "work_machine_rules.updated_at",
1473
- )
1474
- .orderBy("work_workers.enrolled_at")
1475
- .execute(),
1476
- ]);
1477
- const waits: DemandWait[] = [];
1478
- for (const row of rows) {
1479
- const pool = DemandWaitPool.safeParse(row.pool);
1480
- const requirements = DemandWaitRequirements.safeParse(row.requirements);
1481
- if (!pool.success || !requirements.success) continue;
1482
- // A disabled member's work gets no machine.
1483
- if (row.owner !== null && row.disabled_at !== null) continue;
1484
- waits.push({
1485
- projectId: row.project_id,
1486
- owner: row.owner,
1487
- groups: Array.isArray(row.directory_groups)
1488
- ? row.directory_groups.flatMap((group) =>
1489
- typeof group === "string" ? [group.toLowerCase()] : [],
1490
- )
1491
- : [],
1492
- pool: pool.data,
1493
- requirements: requirements.data,
1494
- });
1495
- }
1496
- return {
1497
- waits,
1498
- machines,
1499
- loads,
1500
- stalled: stalled.map((row) => ({
1501
- rule: row.machine_rule ?? "",
1502
- name: row.name,
1503
- enrolledForMs: Number(row.enrolled_for_ms),
1504
- })),
1505
- };
1506
- }
1507
-
1508
- /**
1509
- * Whether demand changed since a pass of this replica last looked (ADR
1510
- * 0258): one indexed statement every few seconds, a full pass only when
1511
- * the work waiting for machines, or the work on rules' machines, changed
1512
- * since the latest pass started. A change that came during a pass, or
1513
- * while another replica held the claim, starts one on the next look. Idle
1514
- * machines go on the regular pass. What it remembers is this replica's
1515
- * own shortcut (ADR 0193): another replica looks for itself, and the pass
1516
- * runs under the tenant's claim either way.
1517
- */
1518
- async checkDemand(): Promise<void> {
1519
- const seen = await this.demandSignature();
1520
- if (seen === undefined || seen === this.demandSeen) return;
1521
- this.reconcileSoon();
1522
- }
1523
-
1524
- /** What the latest pass of this replica saw; see {@link checkDemand}. */
1525
- private demandSeen: string | undefined;
1526
-
1527
- /** Demand, in one statement; undefined while no rule is on demand. */
1528
- private async demandSignature(): Promise<string | undefined> {
1529
- const row = await this.deps.db
1530
- .selectNoFrom((eb) => [
1531
- eb
1532
- .exists(
1533
- eb
1534
- .selectFrom("work_machine_rules")
1535
- .select("name")
1536
- .where("tenant_id", "=", this.deps.tenantId)
1537
- .where(sql<boolean>`definition -> 'machines' ? 'demand'`),
1538
- )
1539
- .as("demand"),
1540
- eb
1541
- .selectFrom("placement_waits")
1542
- .select(
1543
- sql<string>`count(*)::text || '/' || coalesce(max(waiting_since)::text, '')`.as(
1544
- "waits",
1545
- ),
1546
- )
1547
- .where("tenant_id", "=", this.deps.tenantId)
1548
- .where("last_tried_at", ">", waitFresh())
1549
- .where(queuedPlacementWait(this.deps.db))
1550
- .as("waits"),
1551
- eb
1552
- .selectFrom("execution_allocations")
1553
- .select(
1554
- sql<string>`count(*) FILTER (WHERE capacity_released_at IS NULL)::text || '/' || coalesce(max(capacity_released_at)::text, '')`.as(
1555
- "work",
1556
- ),
1557
- )
1558
- .where(
1559
- "worker_node_id",
1560
- "in",
1561
- eb
1562
- .selectFrom("work_workers")
1563
- .select("node_id")
1564
- .where("tenant_id", "=", this.deps.tenantId)
1565
- .where("machine_rule", "is not", null)
1566
- .where("revoked_at", "is", null),
1567
- )
1568
- .as("work"),
1569
- ])
1570
- .executeTakeFirst();
1571
- if (!row?.demand) return undefined;
1572
- return `${row.waits ?? ""}|${row.work ?? ""}`;
1573
- }
1574
-
1575
- /** Active accounts the directory last placed in the group. */
1576
- private async members(
1577
- group: string,
1578
- ): Promise<Array<{ userId: string; email: string }>> {
1579
- const rows = await this.deps.db
1580
- .selectFrom("work_accounts")
1581
- .select("user_id")
1582
- .where("disabled_at", "is", null)
1583
- .where(
1584
- sql<boolean>`directory_groups @> ${JSON.stringify([group])}::jsonb`,
1585
- )
1586
- .orderBy("user_id")
1587
- .execute();
1588
- const members: Array<{ userId: string; email: string }> = [];
1589
- for (const row of rows) {
1590
- const email = await this.deps.emailOf(row.user_id);
1591
- if (email) members.push({ userId: row.user_id, email });
1592
- }
1593
- return members;
1594
- }
1595
- }
1596
-
1597
- /** Another reconciler holds the claim: this pass stops before changing more. */
1598
- class ReconcilerLeaseLostError extends Error {
1599
- constructor() {
1600
- super("The machine reconciler's claim moved to another replica");
1601
- this.name = "ReconcilerLeaseLostError";
1602
- }
1603
- }
1604
-
1605
- /** Retention measured by the database's clock (`releasedForMs`). */
1606
- function retentionEnded(args: {
1607
- releasedForMs: number;
1608
- retainDays: number;
1609
- }): boolean {
1610
- return args.releasedForMs >= args.retainDays * DAY_MS;
1611
- }
1612
-
1613
- /** The place a held pooled machine fills, as its rule last assigned it. */
1614
- function machineSlot(
1615
- machine: PooledMachine,
1616
- ): Pick<DesiredSlot, "rule" | "holder" | "group"> {
1617
- return {
1618
- rule: machine.rule ?? "",
1619
- ...(machine.member !== null
1620
- ? { holder: { member: machine.member }, group: null }
1621
- : {
1622
- holder: { slot: machine.slot ?? 0 },
1623
- group: accessGroupsOf(machine.placement.access)[0] ?? "",
1624
- }),
1625
- };
1626
- }
1627
-
1628
- /**
1629
- * A place's identity. A shared place includes its group, so a rule whose
1630
- * group changes releases its machines rather than handing them over.
1631
- */
1632
- function slotKey(slot: Pick<DesiredSlot, "rule" | "holder" | "group">): string {
1633
- return "member" in slot.holder
1634
- ? `${slot.rule}\0member\0${slot.holder.member}`
1635
- : `${slot.rule}\0slot\0${slot.group ?? ""}\0${slot.holder.slot}`;
1636
- }
1637
-
1638
- /**
1639
- * A stable worker name for one person's machine under one rule. The class
1640
- * is part of it: a new class means a new machine, never a relabeled one.
1641
- */
1642
- export function dedicatedName(
1643
- rule: string,
1644
- userId: string,
1645
- machineClass: string,
1646
- ): string {
1647
- return `${rule}-${digest(`${userId}\0${machineClass}`, 12)}`;
1648
- }
1649
-
1650
- /**
1651
- * A stable worker name for a group's shared machine. The class and the
1652
- * group are part of it: another group never inherits a machine and its disk.
1653
- */
1654
- export function sharedName(
1655
- rule: string,
1656
- machineClass: string,
1657
- group: string,
1658
- index: number,
1659
- ): string {
1660
- return `${rule}-${digest(`${machineClass}\0${group}`, 6)}-${index}`;
1661
- }
1662
-
1663
- /**
1664
- * A stable worker name for a machine on demand. The class and whom it
1665
- * serves (a group, or the projects) are part of it: a machine never moves
1666
- * to other people's work with its disk.
1667
- */
1668
- export function demandName(args: {
1669
- rule: string;
1670
- machineClass: string;
1671
- scope: { group: string } | { projects: readonly string[] };
1672
- index: number;
1673
- }): string {
1674
- return `${demandPrefix(args)}${args.index}`;
1675
- }
1676
-
1677
- function demandPrefix(args: {
1678
- rule: string;
1679
- machineClass: string;
1680
- scope: { group: string } | { projects: readonly string[] };
1681
- }): string {
1682
- const scope =
1683
- "group" in args.scope
1684
- ? `group\0${args.scope.group}`
1685
- : `projects\0${[...args.scope.projects].sort().join(",")}`;
1686
- return `${args.rule}-${digest(`${args.machineClass}\0${scope}`, 6)}-`;
1687
- }
1688
-
1689
- /**
1690
- * Whether a rule on demand serves this waiting work: a machine with the
1691
- * rule's labels (and its class, on a worker) satisfies the work's pool,
1692
- * and its access takes the work's owner. A group's machines take its
1693
- * members' chats; projects' machines take those projects' own work.
1694
- */
1695
- function demandWaitMatches(rule: MachineRule, wait: DemandWait): boolean {
1696
- const labels = { ...rule.labels, class: rule.class, plane: "worker" };
1697
- if (!poolMatches(labels, wait.pool)) return false;
1698
- if (rule.projects)
1699
- return wait.owner === null && rule.projects.includes(wait.projectId);
1700
- return (
1701
- wait.owner !== null &&
1702
- rule.group !== undefined &&
1703
- wait.groups.includes(rule.group)
1704
- );
1705
- }
1706
-
1707
- /** Since when a wait for a machine still counts as demand (ADR 0258). */
1708
- function waitFresh() {
1709
- return sql<Date>`now() - make_interval(secs => ${PLACEMENT_WAIT_FRESH_SECONDS})`;
1710
- }
1711
-
1712
- /** A rule whose machines serve more than one person or project. */
1713
- function servesSeveral(rule: MachineRule): boolean {
1714
- return rule.group !== undefined || (rule.projects?.length ?? 0) > 1;
1715
- }
1716
-
1717
- /**
1718
- * What a rule's connected machines lack for a piece of waiting work, from
1719
- * what they report, or undefined when one could take it or none reported
1720
- * yet. The work's own needs are checked as admission checks them; a
1721
- * machine's free room is not.
1722
- */
1723
- function demandShortfall(args: {
1724
- machines: readonly ProvisionedMachine[];
1725
- loads: ReadonlyMap<string, MachineLoad>;
1726
- wait: DemandWait;
1727
- }): string | undefined {
1728
- const { requirements } = args.wait;
1729
- const reasons: string[][] = [];
1730
- for (const machine of args.machines) {
1731
- const descriptor = args.loads.get(machine.name)?.live?.descriptor;
1732
- if (!descriptor) continue;
1733
- const fit = environmentSatisfies(descriptor, {
1734
- workload: "agent",
1735
- capabilities: requirements.capabilities,
1736
- resources: requirements.resources,
1737
- ...(requirements.trust ? { trust: requirements.trust } : {}),
1738
- ...(requirements.isolation ? { isolation: requirements.isolation } : {}),
1739
- ...(requirements.topology ? { topology: requirements.topology } : {}),
1740
- });
1741
- if (fit.compatible) return undefined;
1742
- reasons.push([...fit.reasons]);
1743
- }
1744
- return reasons[0]?.join("; ");
1745
- }
1746
-
1747
- /** Why a rule on demand makes no more machines: one never connected. */
1748
- function neverConnectedNotice(args: {
1749
- name: string;
1750
- minutes: number;
1751
- definition: MachineRule;
1752
- }): string {
1753
- const why =
1754
- !args.definition.trusted && servesSeveral(args.definition)
1755
- ? `It serves ${args.definition.group ? "a group" : "several projects"}, so it must isolate agents (microsandbox or gVisor) to connect; one running plain processes is refused. Check its log, or add "trusted": true if everyone it serves trusts each other.`
1756
- : "Check its log: it may not reach this server, or its sandboxes may not start.";
1757
- return `Machine ${args.name} enrolled but did not connect within ${args.minutes} minutes, so this rule makes no more machines until it is written again. ${why}`;
1758
- }
1759
-
1760
- /** What one machine has room for, as admission charges it. */
1761
- function roomFor(
1762
- room: { workspaces: number; cpuMillis?: number; memoryMb?: number },
1763
- defaults: { cpuMillis?: number; memoryMb?: number },
1764
- wait: DemandWait,
1765
- ): { cpuMillis: number; memoryMb: number } | undefined {
1766
- const cpuMillis =
1767
- wait.requirements.resources.cpuMillis ?? defaults.cpuMillis ?? 0;
1768
- const memoryMb =
1769
- wait.requirements.resources.memoryMb ?? defaults.memoryMb ?? 0;
1770
- if (room.workspaces < 1) return undefined;
1771
- if (room.cpuMillis !== undefined && room.cpuMillis < cpuMillis)
1772
- return undefined;
1773
- if (room.memoryMb !== undefined && room.memoryMb < memoryMb) return undefined;
1774
- return { cpuMillis, memoryMb };
1775
- }
1776
-
1777
- /**
1778
- * The machines a rule on demand calls for now (ADR 0258). It keeps every
1779
- * machine still enrolling, every machine that enrolled and is still
1780
- * connecting, every machine holding work, every machine idle for less than
1781
- * `idleMinutes`, then the most recently idle up to `min`. A machine not
1782
- * seen for `enrollMinutes` (since it enrolled, when it never connected) is
1783
- * lost and kept for nothing. Work no connected machine has room for (each
1784
- * piece charged its resources, or the machine's defaults), beyond one
1785
- * piece per machine still enrolling or connecting, gets new machines up to
1786
- * `max`, counting the rule's machines for whom it served before. A rule
1787
- * whose machine never connected makes none.
1788
- */
1789
- function demandMachines(args: {
1790
- rule: string;
1791
- definition: MachineRule;
1792
- demand: MachineDemand;
1793
- machines: readonly ProvisionedMachine[];
1794
- loads: ReadonlyMap<string, MachineLoad>;
1795
- waits: readonly DemandWait[];
1796
- stalled: boolean;
1797
- }): DesiredMachine[] {
1798
- const { rule, definition, demand } = args;
1799
- const scope: { group: string } | { projects: readonly string[] } =
1800
- definition.projects
1801
- ? { projects: definition.projects }
1802
- : { group: definition.group ?? "" };
1803
- const prefix = demandPrefix({
1804
- rule,
1805
- machineClass: definition.class,
1806
- scope,
1807
- });
1808
- const placement = WorkerPlacementSchema.parse({
1809
- labels: { ...definition.labels, class: definition.class },
1810
- access:
1811
- "projects" in scope
1812
- ? { projects: [...scope.projects] }
1813
- : { groups: [scope.group] },
1814
- trusted: definition.trusted,
1815
- });
1816
- const desired = (name: string, waiting?: DesiredMachine["waiting"]) => ({
1817
- name,
1818
- rule,
1819
- class: definition.class,
1820
- placement,
1821
- retainDays: 0,
1822
- enrollMinutes: demand.enrollMinutes,
1823
- ...(waiting ? { waiting } : {}),
1824
- });
1825
- // Only machines for whom the rule serves now: another group's or
1826
- // projects' machines go once their work is done, and count meanwhile.
1827
- const own = args.machines.filter((machine) =>
1828
- machine.name.startsWith(prefix),
1829
- );
1830
- const before = args.machines.filter(
1831
- (machine) =>
1832
- !machine.name.startsWith(prefix) &&
1833
- (machine.state === "pending" || machine.state === "enrolled"),
1834
- ).length;
1835
- const lostAfter = demand.enrollMinutes * 60_000;
1836
- const kept: ProvisionedMachine[] = [];
1837
- /** Kept machines that will take a piece of work once they connect. */
1838
- let coming = 0;
1839
- const idle: Array<{ machine: ProvisionedMachine; idleForMs: number }> = [];
1840
- for (const machine of own) {
1841
- if (machine.state === "pending") {
1842
- kept.push(machine);
1843
- coming += 1;
1844
- continue;
1845
- }
1846
- if (machine.state !== "enrolled") continue;
1847
- const load = args.loads.get(machine.name);
1848
- if (!load) continue;
1849
- if (!load.live && load.unseenForMs >= lostAfter) continue;
1850
- if (load.holding > 0) kept.push(machine);
1851
- else if (load.neverConnected) {
1852
- // Enrolled, and still starting its worker.
1853
- kept.push(machine);
1854
- coming += 1;
1855
- } else if (load.idleForMs < demand.idleMinutes * 60_000) kept.push(machine);
1856
- else idle.push({ machine, idleForMs: load.idleForMs });
1857
- }
1858
- idle.sort((left, right) => left.idleForMs - right.idleForMs);
1859
- for (const { machine } of idle) {
1860
- if (kept.length >= demand.min) break;
1861
- kept.push(machine);
1862
- }
1863
- // Work a connected kept machine has room for is admitted there on its
1864
- // next try.
1865
- const free = kept.flatMap((machine) => {
1866
- const live = args.loads.get(machine.name)?.live;
1867
- return live ? [{ room: { ...live.free }, defaults: live.defaults }] : [];
1868
- });
1869
- const uncovered = args.waits.filter((wait) => {
1870
- for (const slot of free) {
1871
- const charged = roomFor(slot.room, slot.defaults, wait);
1872
- if (!charged) continue;
1873
- slot.room.workspaces -= 1;
1874
- if (slot.room.cpuMillis !== undefined)
1875
- slot.room.cpuMillis -= charged.cpuMillis;
1876
- if (slot.room.memoryMb !== undefined)
1877
- slot.room.memoryMb -= charged.memoryMb;
1878
- return false;
1879
- }
1880
- return true;
1881
- });
1882
- const unmet = uncovered.slice(coming);
1883
- const room = Math.max(0, demand.max - kept.length - before);
1884
- const add = args.stalled
1885
- ? 0
1886
- : Math.min(room, Math.max(unmet.length, demand.min - kept.length, 0));
1887
- const machines = kept.map((machine) => desired(machine.name));
1888
- const taken = new Set(own.map((machine) => machine.name));
1889
- for (let index = 1, made = 0; made < add; index += 1) {
1890
- const name = `${prefix}${index}`;
1891
- if (taken.has(name)) continue;
1892
- const wait = unmet[made];
1893
- machines.push(
1894
- desired(
1895
- name,
1896
- wait
1897
- ? {
1898
- resources: wait.requirements.resources,
1899
- capabilities: wait.requirements.capabilities,
1900
- }
1901
- : undefined,
1902
- ),
1903
- );
1904
- made += 1;
1905
- }
1906
- return machines;
1907
- }
1908
-
1909
- function digest(value: string, length: number): string {
1910
- return createHash("sha256").update(value).digest("hex").slice(0, length);
1911
- }
1912
-
1913
- function message(error: unknown): string {
1914
- return error instanceof Error ? error.message : String(error);
1915
- }
1916
-
1917
- /** JSON with sorted keys: stored jsonb reorders keys, so compare this way. */
1918
- function canonical(value: unknown): string {
1919
- return JSON.stringify(value, (_key, entry: unknown) =>
1920
- entry && typeof entry === "object" && !Array.isArray(entry)
1921
- ? Object.fromEntries(
1922
- Object.entries(entry).sort(([left], [right]) =>
1923
- left.localeCompare(right),
1924
- ),
1925
- )
1926
- : entry,
1927
- );
1928
- }
1929
-
1930
- /** Both kinds of work reuse placement demand; waiting journals alone are no demand. */
1931
- function queuedPlacementWait(db: Kysely<DB>) {
1932
- const turns = db
1933
- .selectFrom("agent_turns")
1934
- .select("id")
1935
- .where("session_id", "=", sql<string>`placement_waits.root_workload_id`)
1936
- .where("status", "=", "queued");
1937
- const jobs = db
1938
- .selectFrom("workflow_runs as root")
1939
- .innerJoin(
1940
- "workflow_runs as run",
1941
- "run.allocation_id",
1942
- "root.allocation_id",
1943
- )
1944
- .innerJoin("execution_jobs as job", "job.workflow_run_id", "run.id")
1945
- .select("job.id")
1946
- .where("root.id", "=", sql<string>`placement_waits.root_workload_id`)
1947
- .where("root.status", "in", ["pending", "running", "waiting"])
1948
- .where("run.status", "in", ["pending", "running", "waiting"])
1949
- .where("job.status", "=", "pending")
1950
- .where("job.kind", "!=", "durable_pause_timeout")
1951
- .where("job.available_at", "<=", sql<Date>`now()`);
1952
- return sql<boolean>`((placement_waits.workload_kind = 'agent' AND EXISTS (${turns})) OR
1953
- (placement_waits.workload_kind = 'workflow' AND EXISTS (${jobs})))`;
1954
- }