@catamorphic/work-server 0.1.0-alpha.42 → 0.1.0-alpha.44

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 (74) hide show
  1. package/README.md +4 -1
  2. package/dist/agents.d.ts.map +1 -1
  3. package/dist/{chunk-kcck20aw.js → chunk-ynxz0am9.js} +80 -9
  4. package/dist/chunk-ynxz0am9.js.map +11 -0
  5. package/dist/cluster.d.ts +19 -1
  6. package/dist/cluster.d.ts.map +1 -1
  7. package/dist/execution-config.d.ts +2 -1
  8. package/dist/execution-config.d.ts.map +1 -1
  9. package/dist/index.d.ts +2 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +962 -268
  12. package/dist/index.js.map +21 -19
  13. package/dist/machines/contract.d.ts +138 -14
  14. package/dist/machines/contract.d.ts.map +1 -1
  15. package/dist/machines/sequencer.d.ts +33 -6
  16. package/dist/machines/sequencer.d.ts.map +1 -1
  17. package/dist/machines/simulation.d.ts +64 -0
  18. package/dist/machines/simulation.d.ts.map +1 -1
  19. package/dist/machines/work-machines.d.ts +40 -2
  20. package/dist/machines/work-machines.d.ts.map +1 -1
  21. package/dist/server.d.ts +11 -1
  22. package/dist/server.d.ts.map +1 -1
  23. package/dist/testing.d.ts +1 -1
  24. package/dist/testing.d.ts.map +1 -1
  25. package/dist/testing.js +208 -17
  26. package/dist/testing.js.map +4 -4
  27. package/dist/workers/cache-archive-routes.d.ts +24 -0
  28. package/dist/workers/cache-archive-routes.d.ts.map +1 -0
  29. package/dist/workers/disk-care.d.ts +36 -1
  30. package/dist/workers/disk-care.d.ts.map +1 -1
  31. package/dist/workers/harness-sign-ins.d.ts +32 -1
  32. package/dist/workers/harness-sign-ins.d.ts.map +1 -1
  33. package/dist/workers/machine-store.d.ts +37 -0
  34. package/dist/workers/machine-store.d.ts.map +1 -1
  35. package/dist/workers/member-machine-routes.d.ts +3 -0
  36. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  37. package/dist/workers/member-machines.d.ts +52 -5
  38. package/dist/workers/member-machines.d.ts.map +1 -1
  39. package/dist/workers/placement.d.ts +10 -0
  40. package/dist/workers/placement.d.ts.map +1 -1
  41. package/dist/workers/sign-in-store.d.ts +67 -0
  42. package/dist/workers/sign-in-store.d.ts.map +1 -0
  43. package/dist/workers/sign-ins.d.ts +4 -6
  44. package/dist/workers/sign-ins.d.ts.map +1 -1
  45. package/dist/workers/worker-protocol.d.ts +9 -1
  46. package/dist/workers/worker-protocol.d.ts.map +1 -1
  47. package/dist/workers/worker-registry.d.ts +20 -6
  48. package/dist/workers/worker-registry.d.ts.map +1 -1
  49. package/dist/workers/worker-runtime.d.ts.map +1 -1
  50. package/package.json +18 -19
  51. package/src/agents.ts +5 -0
  52. package/src/cluster.ts +62 -7
  53. package/src/execution-config.ts +2 -1
  54. package/src/index.ts +7 -0
  55. package/src/machines/contract-kit.ts +1 -1
  56. package/src/machines/contract.ts +191 -19
  57. package/src/machines/sequencer.ts +106 -11
  58. package/src/machines/simulation.ts +370 -20
  59. package/src/machines/work-machines.ts +71 -3
  60. package/src/server.ts +120 -29
  61. package/src/testing.ts +1 -0
  62. package/src/workers/cache-archive-routes.ts +125 -0
  63. package/src/workers/disk-care.ts +157 -6
  64. package/src/workers/harness-sign-ins.ts +207 -22
  65. package/src/workers/machine-store.ts +341 -58
  66. package/src/workers/member-machine-routes.ts +58 -3
  67. package/src/workers/member-machines.ts +168 -14
  68. package/src/workers/placement.ts +7 -0
  69. package/src/workers/sign-in-store.ts +241 -0
  70. package/src/workers/sign-ins.ts +9 -33
  71. package/src/workers/worker-protocol.ts +9 -1
  72. package/src/workers/worker-registry.ts +47 -6
  73. package/src/workers/worker-runtime.ts +9 -3
  74. package/dist/chunk-kcck20aw.js.map +0 -11
@@ -1,15 +1,25 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import {
3
3
  PlacementWaitsService,
4
+ PollPacer,
4
5
  releaseReplicaClaim,
5
6
  renewReplicaClaim,
6
7
  takeReplicaClaim,
8
+ type WorkWakeups,
7
9
  } from "@catamorphic/core";
8
10
  import type { DB } from "@catamorphic/db";
9
11
  import { getTracer, withSpan } from "@catamorphic/otel";
10
12
  import type { Kysely } from "kysely";
11
- import type { WorkWorkerRegistry } from "../workers/worker-registry.js";
12
- import type { MachineEvent, MachinesHook, PersonFacts } from "./contract.js";
13
+ import {
14
+ WORKER_NODE_PREFIX,
15
+ type WorkWorkerRegistry,
16
+ } from "../workers/worker-registry.js";
17
+ import type {
18
+ MachineEvent,
19
+ MachinePreparation,
20
+ MachinesHook,
21
+ PersonFacts,
22
+ } from "./contract.js";
13
23
  import {
14
24
  emptySummary,
15
25
  MachinePassFencedError,
@@ -23,6 +33,11 @@ const tracer = getTracer("@catamorphic/work-server");
23
33
  /** How long a pass waits for one machine's reset; a slower one finishes later. */
24
34
  const RESET_WAIT_MS = 3 * 60_000;
25
35
 
36
+ /** How often a replica looks for change a plan reads (see `check`). */
37
+ export const MACHINE_CHECK_INTERVAL_MS = 10_000;
38
+ /** How often it looks for a while after work began waiting on it. */
39
+ export const MACHINE_CHECK_QUICK_MS = 500;
40
+
26
41
  /**
27
42
  * The sequencer's world on the Work server (ADR 0349): machines, their
28
43
  * workers and what they hold in Postgres, by the database's clock.
@@ -34,6 +49,21 @@ export function workMachineWorld(deps: {
34
49
  controlPlaneUrl: string;
35
50
  people: () => Promise<PersonFacts[]>;
36
51
  event: (event: MachineEvent) => Promise<void>;
52
+ /** Prepare a machine for an Environment of a project (ADR 0360). */
53
+ prepare: (args: {
54
+ name: string;
55
+ project: string;
56
+ environment: string;
57
+ commit?: string;
58
+ }) => Promise<MachinePreparation>;
59
+ /**
60
+ * Stop a machine's quiet workspaces before it stops (ADR 0361): core's
61
+ * `stopQuietWorkspaces`. Without it, a machine stops only once it holds
62
+ * no workspace at all.
63
+ */
64
+ stopQuietWorkspaces?: (args: {
65
+ workerNodeId: string;
66
+ }) => Promise<{ stopped: number; busy: number }>;
37
67
  resetWaitMs?: number;
38
68
  }): MachineWorld {
39
69
  const { workers } = deps;
@@ -51,6 +81,8 @@ export function workMachineWorld(deps: {
51
81
  created: (args) => machines.created(args),
52
82
  refused: (args) => machines.refused(args),
53
83
  configure: (args) => machines.configure(args),
84
+ prepare: (args) => deps.prepare(args),
85
+ heardConnected: (args) => machines.heardConnected(args),
54
86
  setFor: (args) => machines.setFor(args),
55
87
  beginReset: (args) => machines.beginReset(args),
56
88
  reset: ({ name }) =>
@@ -62,7 +94,12 @@ export function workMachineWorld(deps: {
62
94
  undrop: ({ name }) => machines.setDropped({ name, dropped: false }),
63
95
  retire: (args) => workers.retireMachine(args),
64
96
  declareLost: (args) => workers.declareLost(args),
65
- beginStop: (args) => workers.beginStop(args),
97
+ beginStop: async (args) => {
98
+ await deps.stopQuietWorkspaces?.({
99
+ workerNodeId: `${WORKER_NODE_PREFIX}${args.name}`,
100
+ });
101
+ return workers.beginStop(args);
102
+ },
66
103
  stopped: async ({ name }) => {
67
104
  await machines.setPhase({ name, phase: "stopped", from: ["stopping"] });
68
105
  },
@@ -147,6 +184,37 @@ export class WorkMachines {
147
184
  this.passSoon();
148
185
  }
149
186
 
187
+ /**
188
+ * {@link check} until `signal` aborts: every 10 seconds, and at once
189
+ * when work begins waiting for a machine on this replica, which a
190
+ * `placement` hint says (ADR 0229). The wait may not be committed when
191
+ * its hint arrives, so the looks stay half a second apart for a while
192
+ * after one; waits that begin together share those looks. Work that
193
+ * began waiting on another replica is seen at that replica's hint, or
194
+ * here within 10 seconds.
195
+ */
196
+ async watch(args: {
197
+ signal: AbortSignal;
198
+ wakeups: WorkWakeups;
199
+ intervalMs?: number;
200
+ quickMs?: number;
201
+ }): Promise<void> {
202
+ const pacer = new PollPacer({
203
+ quickMs: args.quickMs ?? MACHINE_CHECK_QUICK_MS,
204
+ idleMs: args.intervalMs ?? MACHINE_CHECK_INTERVAL_MS,
205
+ signal: args.signal,
206
+ wakeups: args.wakeups,
207
+ topic: "placement",
208
+ });
209
+ while (!args.signal.aborted) {
210
+ await pacer.wait();
211
+ if (args.signal.aborted) return;
212
+ await this.check().catch((error: unknown) =>
213
+ this.deps.log?.(`Machine check failed: ${message(error)}`),
214
+ );
215
+ }
216
+ }
217
+
150
218
  private get leaseMs(): number {
151
219
  return this.deps.leaseMs ?? 120_000;
152
220
  }
package/src/server.ts CHANGED
@@ -4,12 +4,14 @@ import path from "node:path";
4
4
  import { ACTIVE_TURN_STATUSES } from "@catamorphic/agent-protocol";
5
5
  import type { AgentCapabilityOptions } from "@catamorphic/core";
6
6
  import {
7
+ type CacheStore,
7
8
  type ConnectionActionGuard,
8
9
  type ConnectionProvider,
9
10
  FULL_TOKEN_SCOPE,
10
11
  hasTokenScope,
11
12
  type Identity,
12
13
  type ModelRequestRewrite,
14
+ projectPrincipalIdentity,
13
15
  startEventDispatcher,
14
16
  tokenScopesOf,
15
17
  WorkerNodesService,
@@ -32,6 +34,7 @@ import { gatewayHostOf, MACHINE_CAPABILITIES } from "@catamorphic/sandbox";
32
34
  import {
33
35
  aiToolCall,
34
36
  aiToolKind,
37
+ assertNativeGit,
35
38
  builtinModelConnectionProviders,
36
39
  type Catamorphic,
37
40
  type CreateCatamorphicConfig,
@@ -45,9 +48,11 @@ import {
45
48
  type GithubConnectionOptions,
46
49
  githubCodeHost,
47
50
  MACHINE_TRIGGER_KINDS,
51
+ machineEventProjects,
48
52
  machineProjectEvent,
49
53
  ObjectRemoteBackend,
50
54
  PostgresObjectStore,
55
+ PROJECT_TRIGGER_KINDS,
51
56
  ProjectManager,
52
57
  SESSION_TRIGGER_KINDS,
53
58
  schedule,
@@ -126,13 +131,20 @@ import {
126
131
  import { registerShareRoutes } from "./shares/share-routes.js";
127
132
  import { shareTools } from "./shares/share-tools.js";
128
133
  import { WorkSharesService } from "./shares/shares-service.js";
129
- import { startDiskCare } from "./workers/disk-care.js";
134
+ import {
135
+ cacheArchiveUrl,
136
+ registerCacheArchiveRoutes,
137
+ } from "./workers/cache-archive-routes.js";
138
+ import { RUNNING_TIME_FILE, startDiskCare } from "./workers/disk-care.js";
130
139
  import { HarnessSignIns } from "./workers/harness-sign-ins.js";
131
140
  import { registerMemberMachineRoutes } from "./workers/member-machine-routes.js";
132
141
  import { MemberMachines } from "./workers/member-machines.js";
133
142
  import { signInCapabilities } from "./workers/sign-ins.js";
134
143
  import { startVolumePruning } from "./workers/volume-pruning.js";
135
- import { WorkWorkerRegistry } from "./workers/worker-registry.js";
144
+ import {
145
+ WORKER_NODE_PREFIX,
146
+ WorkWorkerRegistry,
147
+ } from "./workers/worker-registry.js";
136
148
  import { registerWorkerRoutes } from "./workers/worker-routes.js";
137
149
 
138
150
  /**
@@ -211,6 +223,16 @@ export interface WorkServerHooks {
211
223
  * registry packs. With no hook, machines are enrolled by hand.
212
224
  */
213
225
  machines?: MachinesHook;
226
+ /**
227
+ * The host's cache store (ADR 0360): where every machine's copy of an
228
+ * Environment cache can come from. After a trusted fill publishes a cache
229
+ * on one machine Work saves it there, and a machine that lacks the cache
230
+ * restores it from there before it fills from nothing. Two verbs, `save`
231
+ * and `restore`, over streams; the registry ships one for a shared
232
+ * directory. Archives pass through this server on their way, a cache's
233
+ * size at a time. With no store, every machine fills its own.
234
+ */
235
+ cacheStore?: CacheStore;
214
236
  /** Mount additional host routes on the public application. */
215
237
  routes?: (args: {
216
238
  app: FastifyInstance;
@@ -280,6 +302,11 @@ async function createWorkServerInner(
280
302
  const log = options.log ?? (() => {});
281
303
  const data = config.dataDir;
282
304
  const publicBase = config.publicBases[0] ?? "http://127.0.0.1:4700";
305
+ // Every project is kept with the Git program (ADR 0356): a server
306
+ // without one, or with one too old, says so now instead of failing its
307
+ // first project.
308
+ const git = await assertNativeGit();
309
+ log(`Git ${git.version}`);
283
310
  // Config is data, validated by the schemas the image's files use; only
284
311
  // the image's environment layer reads files for it (ADR 0183).
285
312
  const workAuthConfig = parseWorkAuthConfig(config.auth ?? {});
@@ -430,6 +457,7 @@ async function createWorkServerInner(
430
457
  ? { criticalMb: execution.diskCriticalMb }
431
458
  : {}),
432
459
  graceMs: execution.imageRetentionMs,
460
+ runningFile: path.join(data, RUNNING_TIME_FILE),
433
461
  log,
434
462
  });
435
463
  disposers.push(async () => diskCare.stop());
@@ -512,6 +540,9 @@ async function createWorkServerInner(
512
540
  // Work retired from a machine that is gone (ADR 0348) is admitted again
513
541
  // by the same sweep.
514
542
  let workRetired = () => {};
543
+ // A machine gave a workspace's room back: queued runs that found no room
544
+ // are tried at once, by this process's queue.
545
+ let roomFreed = () => {};
515
546
  // Something happened to a machine (ADR 0349): delivered once the core
516
547
  // is up, to the projects it is for and to the host's own listener.
517
548
  let machineEvent: (event: MachineEvent) => Promise<void> = async () => {};
@@ -526,6 +557,7 @@ async function createWorkServerInner(
526
557
  enrollmentSecret: authSecret,
527
558
  connected: () => workerConnected(),
528
559
  retired: () => workRetired(),
560
+ roomFreed: () => roomFreed(),
529
561
  event: (event) => machineEvent(event),
530
562
  log,
531
563
  });
@@ -555,6 +587,7 @@ async function createWorkServerInner(
555
587
  disk: () => diskCare.latest(),
556
588
  sandboxProvider,
557
589
  placement: { workers: () => workers.placements() },
590
+ roomFreed: () => roomFreed(),
558
591
  });
559
592
  disposers.push(() => machine.stop());
560
593
  let maintaining: Promise<void> | undefined;
@@ -635,6 +668,33 @@ async function createWorkServerInner(
635
668
  retentionDays: Math.round(
636
669
  execution.volumeRetentionMs / (24 * 60 * 60 * 1000),
637
670
  ),
671
+ // A fill or a preparation names only a machine that takes its
672
+ // project's work (ADR 0360).
673
+ machineAdmits: ({ projectId, machine }) =>
674
+ workers.machines.admitsProjectWork({ nodeId: machine, projectId }),
675
+ // Machines stream archives to and from this server (ADR 0360).
676
+ ...(hooks.cacheStore
677
+ ? {
678
+ store: hooks.cacheStore,
679
+ transferUrl: ({ transferId }) =>
680
+ cacheArchiveUrl({ base: publicBase, transferId }),
681
+ }
682
+ : {}),
683
+ },
684
+ // A spare is handed to the first chat key placed on it, under its
685
+ // machine's lock (ADR 0360).
686
+ allocationPlaced: async ({
687
+ transaction,
688
+ workerNodeId,
689
+ projectId,
690
+ policy,
691
+ }) => {
692
+ await workers.machines.claimSpare({
693
+ transaction,
694
+ nodeId: workerNodeId,
695
+ projectId,
696
+ chatKey: policy.chatKey,
697
+ });
638
698
  },
639
699
  clientExecution: true,
640
700
  database: databaseConfig,
@@ -645,6 +705,9 @@ async function createWorkServerInner(
645
705
  new ObjectRemoteBackend({
646
706
  store: objectStore,
647
707
  keyPrefix: "origins/",
708
+ // Large histories are stored as packs; this replica reads
709
+ // them here, beside the copies that borrow from them.
710
+ cachePath: path.join(data, "projects", ".origins"),
648
711
  }),
649
712
  ),
650
713
  }
@@ -700,6 +763,8 @@ async function createWorkServerInner(
700
763
  schedule,
701
764
  webhook,
702
765
  ...SESSION_TRIGGER_KINDS,
766
+ // A revision's deploy is an event workflows bind (ADR 0355).
767
+ ...PROJECT_TRIGGER_KINDS,
703
768
  ...DIRECTORY_TRIGGER_KINDS,
704
769
  // What happens to machines, for projects' own workflows (ADR 0349).
705
770
  ...MACHINE_TRIGGER_KINDS,
@@ -779,6 +844,7 @@ async function createWorkServerInner(
779
844
  const core = catamorphic.core;
780
845
  workerConnected = () => core.wakeups.notify("agent");
781
846
  workRetired = () => core.wakeups.notify("agent");
847
+ roomFreed = () => core.wakeups.notify("capacity");
782
848
  // Any replica recovers the work of replicas that are gone for good: runs
783
849
  // move to a live machine, chats are admitted again on their next turn.
784
850
  {
@@ -891,15 +957,11 @@ async function createWorkServerInner(
891
957
  tenantId: SERVER_TENANT_ID,
892
958
  publicBase,
893
959
  });
894
- // A machine event reaches the projects the machine is for, as a project
895
- // event their workflows may trigger on, and the host's own listener.
896
- // Work itself depends on neither (ADR 0349).
960
+ // A machine event reaches the project the machine names and the projects
961
+ // it is for, as a project event their workflows may trigger on, and the
962
+ // host's own listener. Work itself depends on neither (ADRs 0349, 0364).
897
963
  machineEvent = async (event) => {
898
- const projects = new Set(
899
- (event.machine.for ?? []).flatMap((principal) =>
900
- "project" in principal ? [principal.project] : [],
901
- ),
902
- );
964
+ const projects = machineEventProjects(event.machine);
903
965
  const record = machineProjectEvent({
904
966
  kind: event.kind,
905
967
  at: event.at,
@@ -952,6 +1014,7 @@ async function createWorkServerInner(
952
1014
  }))
953
1015
  .sort((left, right) => left.id.localeCompare(right.id));
954
1016
  };
1017
+ const machineSessions = core.agentSessions;
955
1018
  const workMachines = hooks.machines
956
1019
  ? new WorkMachines({
957
1020
  db: core.db,
@@ -964,6 +1027,39 @@ async function createWorkServerInner(
964
1027
  workers,
965
1028
  controlPlaneUrl: publicBase,
966
1029
  people,
1030
+ // A machine stops with its quiet workspaces kept (ADR 0361).
1031
+ ...(machineSessions
1032
+ ? {
1033
+ stopQuietWorkspaces: (args: { workerNodeId: string }) =>
1034
+ machineSessions.stopQuietWorkspaces(args),
1035
+ }
1036
+ : {}),
1037
+ prepare: async ({ name, project, environment, commit }) => {
1038
+ const preparation = await core.machinePreparations.request({
1039
+ identity: projectPrincipalIdentity({
1040
+ tenantId: SERVER_TENANT_ID,
1041
+ projectId: project,
1042
+ environment,
1043
+ }),
1044
+ projectId: project,
1045
+ environment,
1046
+ machine: `${WORKER_NODE_PREFIX}${name}`,
1047
+ ...(commit !== undefined ? { commit } : {}),
1048
+ });
1049
+ return {
1050
+ project,
1051
+ environment,
1052
+ status:
1053
+ preparation.status === "succeeded"
1054
+ ? "prepared"
1055
+ : preparation.status === "failed"
1056
+ ? "failed"
1057
+ : "preparing",
1058
+ commit: preparation.commit,
1059
+ error: preparation.error,
1060
+ since: preparation.finishedAt ?? preparation.createdAt,
1061
+ };
1062
+ },
967
1063
  event: async (event) => {
968
1064
  await machineEvent(event).catch((error: unknown) =>
969
1065
  log(
@@ -981,30 +1077,20 @@ async function createWorkServerInner(
981
1077
  if (workMachines) {
982
1078
  // A pass every minute, and at once when what a plan reads changed:
983
1079
  // waiting work, what machines hold, a machine connecting or going
984
- // unseen, accounts and roles. That is one cheap look every few seconds.
1080
+ // unseen, accounts and roles. That is one cheap look every few seconds,
1081
+ // and one as soon as work begins waiting for a machine on this replica.
985
1082
  const machineTimer = setInterval(planMachines, 60_000);
986
1083
  machineTimer.unref();
987
- let checking: Promise<void> | undefined;
988
- const checkTimer = setInterval(() => {
989
- checking ??= workMachines
990
- .check()
991
- .catch((error: unknown) =>
992
- log(
993
- `Machine check failed: ${
994
- error instanceof Error ? error.message : String(error)
995
- }`,
996
- ),
997
- )
998
- .finally(() => {
999
- checking = undefined;
1000
- });
1001
- }, 10_000);
1002
- checkTimer.unref();
1084
+ const watching = new AbortController();
1085
+ const watched = workMachines.watch({
1086
+ signal: watching.signal,
1087
+ wakeups: core.wakeups,
1088
+ });
1003
1089
  planMachines();
1004
1090
  disposers.push(async () => {
1005
1091
  clearInterval(machineTimer);
1006
- clearInterval(checkTimer);
1007
- await checking;
1092
+ watching.abort();
1093
+ await watched;
1008
1094
  await workMachines.settle();
1009
1095
  });
1010
1096
  }
@@ -1258,6 +1344,7 @@ async function createWorkServerInner(
1258
1344
  done(null, payload);
1259
1345
  });
1260
1346
  registerWorkerRoutes(app, workers);
1347
+ if (core.cacheArchives) registerCacheArchiveRoutes(app, core.cacheArchives);
1261
1348
  // Machines: the operator on the loopback listener, and organization
1262
1349
  // administrators through the API (ADR 0205).
1263
1350
  const machineManagement = {
@@ -1317,6 +1404,8 @@ async function createWorkServerInner(
1317
1404
  dataDir: data,
1318
1405
  env: { ...process.env, PATH: config.execution.path },
1319
1406
  onChange: () => machine.refreshSignIns(),
1407
+ // Where its sandboxes run images, a login runs in one (ADR 0363).
1408
+ provider: sandboxProvider,
1320
1409
  })
1321
1410
  : undefined;
1322
1411
  if (ownSignIns) disposers.push(async () => ownSignIns.stop());
@@ -1332,6 +1421,8 @@ async function createWorkServerInner(
1332
1421
  ? { ownMachine: { nodeId: machine.lease.id, signIns: ownSignIns } }
1333
1422
  : {}),
1334
1423
  worker: (args) => workers.harnessSignIn(args),
1424
+ environments: core.executionEnvironments,
1425
+ signIns: workers.machines.signIns,
1335
1426
  }),
1336
1427
  });
1337
1428
  registerWorkAdmissionRoutes(app, {
package/src/testing.ts CHANGED
@@ -17,6 +17,7 @@ export {
17
17
  export {
18
18
  quietSummary,
19
19
  type SimulatedCall,
20
+ type SimulatedStart,
20
21
  SimulatedWork,
21
22
  type SimulatedWorkOptions,
22
23
  } from "./machines/simulation.js";
@@ -0,0 +1,125 @@
1
+ import { Readable } from "node:stream";
2
+ import {
3
+ type CacheArchivesService,
4
+ CacheArchiveTooLargeError,
5
+ CacheTransferRefusedError,
6
+ } from "@catamorphic/core";
7
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
8
+
9
+ /** Where a machine streams one cache archive to or from (ADR 0360). */
10
+ export const CACHE_ARCHIVE_ROUTE = "/api/cache-archives";
11
+
12
+ /** The URL of one transfer on a control plane at `base`. */
13
+ export function cacheArchiveUrl(args: {
14
+ base: string;
15
+ transferId: string;
16
+ }): string {
17
+ return `${args.base.replace(/\/+$/, "")}${CACHE_ARCHIVE_ROUTE}/${args.transferId}`;
18
+ }
19
+
20
+ /**
21
+ * Answer a machine whose upload is not taken, then drop its connection:
22
+ * what it still sends is not read to its end. Until the answer is out the
23
+ * rest is read and dropped, so the machine hears it instead of a reset.
24
+ */
25
+ function refuseUpload(args: {
26
+ reply: FastifyReply;
27
+ body: Readable;
28
+ status: number;
29
+ error: string;
30
+ }) {
31
+ const { reply, body } = args;
32
+ body.resume();
33
+ reply.raw.once("finish", () => body.destroy());
34
+ return reply
35
+ .header("connection", "close")
36
+ .status(args.status)
37
+ .send({ error: args.error });
38
+ }
39
+
40
+ function bearerOf(request: FastifyRequest): string {
41
+ const header = request.headers.authorization;
42
+ const value = Array.isArray(header) ? header[0] : header;
43
+ return value?.startsWith("Bearer ") ? value.slice("Bearer ".length) : "";
44
+ }
45
+
46
+ /**
47
+ * The streams of a host's cache store (ADR 0360). A machine PUTs the
48
+ * archive of a cache generation a trusted fill wrote, and GETs one to
49
+ * restore, each with the one-time token Work handed it for that transfer.
50
+ * The bytes pass through this process into or out of the host's store one
51
+ * chunk at a time: nothing is buffered, each side waits for the other, and
52
+ * no transaction or lock is held while they move. A token opens one stream,
53
+ * and a stream carries no more than Work set for it: a save its cache's
54
+ * limit with an allowance for the archive's format (answered 413 past it,
55
+ * and the store keeps nothing), a restore the size Work recorded (cut off
56
+ * past it). Any replica serves any transfer; what passed is recorded for
57
+ * the fill's replica to read.
58
+ */
59
+ export function registerCacheArchiveRoutes(
60
+ app: FastifyInstance,
61
+ archives: CacheArchivesService,
62
+ ): void {
63
+ void app.register(async (scope) => {
64
+ // The archive is handed on as it arrives, never parsed or collected.
65
+ scope.addContentTypeParser("application/x-tar", (_request, payload, done) =>
66
+ done(null, payload),
67
+ );
68
+ scope.put<{ Params: { id: string } }>(
69
+ `${CACHE_ARCHIVE_ROUTE}/:id`,
70
+ async (request, reply) => {
71
+ const body = request.body;
72
+ if (!(body instanceof Readable))
73
+ return reply
74
+ .status(415)
75
+ .send({ error: "Send the archive as application/x-tar" });
76
+ try {
77
+ return await archives.receive({
78
+ transferId: request.params.id,
79
+ token: bearerOf(request),
80
+ body,
81
+ });
82
+ } catch (error) {
83
+ if (error instanceof CacheTransferRefusedError)
84
+ return refuseUpload({
85
+ reply,
86
+ body,
87
+ status: 404,
88
+ error: error.message,
89
+ });
90
+ if (error instanceof CacheArchiveTooLargeError)
91
+ return refuseUpload({
92
+ reply,
93
+ body,
94
+ status: 413,
95
+ error: error.message,
96
+ });
97
+ body.destroy();
98
+ throw error;
99
+ }
100
+ },
101
+ );
102
+ scope.get<{ Params: { id: string } }>(
103
+ `${CACHE_ARCHIVE_ROUTE}/:id`,
104
+ async (request, reply) => {
105
+ try {
106
+ const archive = await archives.send({
107
+ transferId: request.params.id,
108
+ token: bearerOf(request),
109
+ });
110
+ if (!archive)
111
+ return reply
112
+ .status(404)
113
+ .send({ error: "The store has no archive of this cache" });
114
+ return reply
115
+ .header("content-type", "application/x-tar")
116
+ .send(Readable.from(archive));
117
+ } catch (error) {
118
+ if (error instanceof CacheTransferRefusedError)
119
+ return reply.status(404).send({ error: error.message });
120
+ throw error;
121
+ }
122
+ },
123
+ );
124
+ });
125
+ }