@tsplc/tmp-agent 0.0.0-stage → 0.6.3

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 (65) hide show
  1. package/README.md +26 -2
  2. package/dist/cli.js +4888 -0
  3. package/dist/cli.js.map +53 -0
  4. package/dist/client.js +514 -0
  5. package/dist/client.js.map +12 -0
  6. package/dist/index.js +3680 -0
  7. package/dist/index.js.map +41 -0
  8. package/package.json +61 -4
  9. package/src/access.ts +260 -0
  10. package/src/agent.ts +461 -0
  11. package/src/audit.ts +74 -0
  12. package/src/cli.ts +290 -0
  13. package/src/client.ts +407 -0
  14. package/src/codesys.ts +195 -0
  15. package/src/dashboard/index.ts +159 -0
  16. package/src/dashboard/ui/access.ts +191 -0
  17. package/src/dashboard/ui/actions.ts +207 -0
  18. package/src/dashboard/ui/api.ts +138 -0
  19. package/src/dashboard/ui/app.ts +41 -0
  20. package/src/dashboard/ui/approval.ts +131 -0
  21. package/src/dashboard/ui/audit.ts +115 -0
  22. package/src/dashboard/ui/contract.ts +19 -0
  23. package/src/dashboard/ui/dashboard.css +1332 -0
  24. package/src/dashboard/ui/deployment.ts +431 -0
  25. package/src/dashboard/ui/deployments.ts +319 -0
  26. package/src/dashboard/ui/details.ts +214 -0
  27. package/src/dashboard/ui/dom.ts +87 -0
  28. package/src/dashboard/ui/environment.ts +345 -0
  29. package/src/dashboard/ui/format.ts +124 -0
  30. package/src/dashboard/ui/logs.ts +126 -0
  31. package/src/dashboard/ui/main.ts +88 -0
  32. package/src/dashboard/ui/overlay.ts +144 -0
  33. package/src/dashboard/ui/shell.ts +185 -0
  34. package/src/dashboard/ui/source.ts +144 -0
  35. package/src/debugging.ts +142 -0
  36. package/src/deploy.ts +203 -0
  37. package/src/deployments/health.ts +98 -0
  38. package/src/deployments/retention.ts +44 -0
  39. package/src/deployments/routes.ts +281 -0
  40. package/src/deployments/runner.ts +900 -0
  41. package/src/deployments/store.ts +209 -0
  42. package/src/deployments/submission.ts +78 -0
  43. package/src/discovery.ts +90 -0
  44. package/src/environment.ts +214 -0
  45. package/src/errors.ts +12 -0
  46. package/src/index.ts +36 -0
  47. package/src/instance.ts +51 -0
  48. package/src/login.ts +267 -0
  49. package/src/logs.ts +115 -0
  50. package/src/maintenance.ts +303 -0
  51. package/src/operations.ts +149 -0
  52. package/src/processes.ts +41 -0
  53. package/src/protocol.ts +557 -0
  54. package/src/releases.ts +414 -0
  55. package/src/restarts.ts +96 -0
  56. package/src/routes.ts +128 -0
  57. package/src/secrets.ts +174 -0
  58. package/src/server-process.ts +264 -0
  59. package/src/service.ts +194 -0
  60. package/src/sessions.ts +58 -0
  61. package/src/state.ts +126 -0
  62. package/src/tailscale.ts +112 -0
  63. package/src/terminal.ts +57 -0
  64. package/src/transfer.ts +94 -0
  65. package/src/upgrade.ts +153 -0
@@ -0,0 +1,900 @@
1
+ import { once } from "node:events";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import {
5
+ type ControllerResult,
6
+ DownloadRequiredError,
7
+ describeFinding,
8
+ type OnlineChangeReview,
9
+ requiresDownload,
10
+ } from "@tsplc/build";
11
+ import type { ResolvedConfig } from "@tsplc/config/build";
12
+ import { loadManifest } from "@tsplc/debug";
13
+ import { debugManifestFile } from "@tsplc/debug/manifest";
14
+ import { type CodesysSettings, controllerConfig } from "../codesys";
15
+ import { AgentError, errorMessage } from "../errors";
16
+ import { appendJsonl } from "../logs";
17
+ import { failureReport, type Operations } from "../operations";
18
+ import {
19
+ type Credentials,
20
+ cancelableStates,
21
+ type Deployment,
22
+ type DeploymentEvent,
23
+ type DeploymentLogLine,
24
+ type DeploymentMode,
25
+ type DeploymentRecord,
26
+ type DeploymentState,
27
+ type GitSource,
28
+ type Release,
29
+ } from "../protocol";
30
+ import {
31
+ isStored,
32
+ listReleaseFiles,
33
+ loadRelease,
34
+ readReleaseFile,
35
+ releaseServerFile,
36
+ releaseServerPath,
37
+ type StoredRelease,
38
+ saveRelease,
39
+ type Upload,
40
+ } from "../releases";
41
+ import { controllerCredentials, readSecrets, withSecrets } from "../secrets";
42
+ import type { ServerSupervisor } from "../server-process";
43
+ import type { AgentState } from "../state";
44
+ import { checkHealth, healthy } from "./health";
45
+ import { pruneDeployments } from "./retention";
46
+ import { activeDeployments, type DeploymentStore, isFinished } from "./store";
47
+ import { checkSubmission } from "./submission";
48
+
49
+ type Operation = DeploymentRecord["operation"];
50
+ type PhaseName = DeploymentRecord["phases"][number]["name"];
51
+ type Outcome = DeploymentRecord["phases"][number]["outcome"];
52
+ type ApprovalReason = NonNullable<DeploymentRecord["approval"]>["reason"];
53
+ type Phase = DeploymentRecord["phases"][number];
54
+
55
+ /** What a deployment asks of CODESYS and Docker, which the runner sequences. */
56
+ export interface DeploymentController {
57
+ /** Checks that Docker answers, the images can deploy and no login holds the controller; returns what to warn about. */
58
+ ready: () => Promise<string[]>;
59
+ /** Waits until the last deployment's project is committed, which decides the download baseline. */
60
+ settle: (config: ResolvedConfig) => Promise<void>;
61
+ /** Whether the controller has a download from this agent that an online change can build on. */
62
+ baseline: () => Promise<"valid" | "missing" | "malformed">;
63
+ review: (
64
+ config: ResolvedConfig,
65
+ options: {
66
+ credentials: Credentials;
67
+ onProgress: (message: string) => void;
68
+ },
69
+ ) => Promise<OnlineChangeReview>;
70
+ apply: (
71
+ config: ResolvedConfig,
72
+ operation: Operation,
73
+ options: {
74
+ initializeUser: boolean;
75
+ credentials: Credentials;
76
+ onProgress: (message: string) => void;
77
+ },
78
+ ) => Promise<ControllerResult>;
79
+ }
80
+
81
+ /** A deployment to queue, and who asked for it. */
82
+ export interface Submission {
83
+ git: GitSource | null;
84
+ requestedBy: DeploymentRecord["requestedBy"];
85
+ mode: DeploymentMode;
86
+ /** A full download was asked for up front. */
87
+ download: boolean;
88
+ /** The controller user the request sent, held in memory only; null uses the one stored on the PC. */
89
+ credentials: Credentials | null;
90
+ initializeUser: boolean;
91
+ /** Said first in the deployment's log. */
92
+ warnings: string[];
93
+ }
94
+
95
+ /** What a deployment keeps only in memory, and how it is run. */
96
+ interface Handling {
97
+ credentials: Credentials | null;
98
+ initializeUser: boolean;
99
+ /** A deployment that needs a download waits for approval; `POST /deploy`'s fail instead, as their clients expect. */
100
+ waitsForApproval: boolean;
101
+ }
102
+
103
+ /** An unfinished deployment, with what it keeps only in memory. */
104
+ interface Pending extends Handling {
105
+ id: string;
106
+ release: StoredRelease;
107
+ cancellation: AbortController;
108
+ /** Approved while `awaitingApproval`, and not yet picked up. */
109
+ approved: boolean;
110
+ /** Being advanced right now, so a cancel takes effect at its next step. */
111
+ running: boolean;
112
+ }
113
+
114
+ /** Where `advance` left a deployment: the release it deployed, or the error it failed with; neither while it waits or once canceled. */
115
+ interface Advanced {
116
+ deployed: Release | null;
117
+ failure: { error: unknown } | null;
118
+ }
119
+
120
+ class Canceled extends Error {}
121
+
122
+ const releaseBuild = async (release: StoredRelease) => {
123
+ const file = join(release.directory, debugManifestFile);
124
+ return existsSync(file) ? (await loadManifest(file)).build.id : null;
125
+ };
126
+
127
+ /**
128
+ * Runs deployments one at a time, in the order they were queued, each as the agent's one
129
+ * operation: build, review, apply, start the server, check health. A deployment waiting for
130
+ * approval holds its place, but not the agent, so logins still open meanwhile.
131
+ */
132
+ export const createDeploymentRunner = (context: {
133
+ store: DeploymentStore;
134
+ state: AgentState;
135
+ operations: Operations;
136
+ codesys: CodesysSettings;
137
+ server: ServerSupervisor;
138
+ controller: DeploymentController;
139
+ /** Called once a deployment's release runs on the line, to replace what depends on it. */
140
+ onActivated: () => void;
141
+ now: () => Date;
142
+ log: (message: string) => void;
143
+ }) => {
144
+ const { store, state, operations, controller } = context;
145
+ const pending = new Map<string, Pending>();
146
+ /** Deployments from `/api/deployments`, oldest first; `POST /deploy`'s run at once instead. */
147
+ const queue: Pending[] = [];
148
+ let draining = false;
149
+ /** Saving a release and naming it in a record happen together, never between a prune's reads and deletes. */
150
+ let releasesTurn: Promise<unknown> = Promise.resolve();
151
+
152
+ const withReleases = <Result>(run: () => Promise<Result>) => {
153
+ const next = releasesTurn.then(run);
154
+ releasesTurn = next.catch(() => undefined);
155
+ return next;
156
+ };
157
+
158
+ const timestamp = () => context.now().toISOString();
159
+
160
+ const recordOf = store.get;
161
+
162
+ const say = (
163
+ item: Pending,
164
+ level: DeploymentLogLine["level"],
165
+ message: string,
166
+ ) => {
167
+ const phase =
168
+ recordOf(item.id).phases.find((entry) => entry.outcome === "running")
169
+ ?.name ?? null;
170
+ // The store logs a write that fails.
171
+ store.log(item.id, { level, phase, message }).catch(() => undefined);
172
+ };
173
+
174
+ const update = (
175
+ item: Pending,
176
+ change: (record: DeploymentRecord) => DeploymentRecord,
177
+ ) => store.update(item.id, change);
178
+
179
+ const startPhase = (item: Pending, name: PhaseName) =>
180
+ update(item, (record) => ({
181
+ ...record,
182
+ phases: [
183
+ ...record.phases,
184
+ { name, startedAt: timestamp(), finishedAt: null, outcome: "running" },
185
+ ],
186
+ }));
187
+
188
+ const closeRunning = (
189
+ phases: readonly Phase[],
190
+ outcome: Exclude<Outcome, "running">,
191
+ ) => {
192
+ const at = timestamp();
193
+ return phases.map((phase) =>
194
+ phase.outcome === "running"
195
+ ? { ...phase, finishedAt: at, outcome }
196
+ : phase,
197
+ );
198
+ };
199
+
200
+ const finishPhase = (item: Pending, outcome: Exclude<Outcome, "running">) =>
201
+ update(item, (record) => ({
202
+ ...record,
203
+ phases: closeRunning(record.phases, outcome),
204
+ }));
205
+
206
+ const skipPhase = (item: Pending, name: PhaseName) =>
207
+ update(item, (record) => ({
208
+ ...record,
209
+ phases: [
210
+ ...record.phases,
211
+ {
212
+ name,
213
+ startedAt: timestamp(),
214
+ finishedAt: timestamp(),
215
+ outcome: "skipped",
216
+ },
217
+ ],
218
+ }));
219
+
220
+ const enter = (
221
+ item: Pending,
222
+ state: DeploymentState,
223
+ changes: Partial<DeploymentRecord> = {},
224
+ ) => update(item, (record) => ({ ...record, ...changes, state }));
225
+
226
+ const requireNotCanceled = (item: Pending) => {
227
+ if (item.cancellation.signal.aborted) {
228
+ throw new Canceled();
229
+ }
230
+ };
231
+
232
+ /** Runs `run` as the agent's one operation once no login, logout or upgrade holds it. */
233
+ const whenFree = async <Result>(
234
+ item: Pending,
235
+ run: () => Promise<Result>,
236
+ ) => {
237
+ const waitingFor = operations.blockedBy();
238
+ if (waitingFor) {
239
+ say(item, "info", `Waiting for ${waitingFor} to finish`);
240
+ }
241
+ while (operations.blockedBy()) {
242
+ requireNotCanceled(item);
243
+ await Promise.race([
244
+ operations.whenIdle(),
245
+ once(item.cancellation.signal, "abort"),
246
+ ]);
247
+ }
248
+ return operations.exclusive("a deployment", run);
249
+ };
250
+
251
+ /** Stops to wait for a person; `POST /deploy`'s deployments fail instead. */
252
+ const awaitApproval = async (
253
+ item: Pending,
254
+ reason: ApprovalReason,
255
+ message: string,
256
+ ) => {
257
+ if (!item.waitsForApproval) {
258
+ throw reason === "downloadRequired"
259
+ ? new DownloadRequiredError(message)
260
+ : new AgentError(message, 409);
261
+ }
262
+ item.approved = false;
263
+ // Waiting holds nothing, so a cancel from now on takes effect at once.
264
+ item.running = false;
265
+ say(item, "warning", message);
266
+ await enter(item, "awaitingApproval", { approval: { reason, message } });
267
+ return null;
268
+ };
269
+
270
+ const announce = (item: Pending, warnings: readonly string[]) => {
271
+ for (const warning of warnings) {
272
+ say(item, "warning", warning);
273
+ }
274
+ };
275
+
276
+ /** The release's config for the selected controller with its secrets, once the last deployment is committed. */
277
+ const prepare = async (item: Pending) => {
278
+ const warnings = await controller.ready();
279
+ const target = await state.requireTarget();
280
+ const config = await withSecrets(
281
+ controllerConfig(
282
+ item.release,
283
+ target,
284
+ state.paths.controller,
285
+ context.codesys,
286
+ ),
287
+ await readSecrets(item.release.manifest.secrets),
288
+ state.paths.sources,
289
+ );
290
+ await controller.settle(config);
291
+ return { config, warnings };
292
+ };
293
+
294
+ const progress = (item: Pending) => (message: string) =>
295
+ say(item, "info", message);
296
+
297
+ const review = async (item: Pending, config: ResolvedConfig) => {
298
+ const { mode } = recordOf(item.id);
299
+ await startPhase(item, "review");
300
+ const result = await controller.review(config, {
301
+ credentials: await controllerCredentials(item.credentials),
302
+ onProgress: progress(item),
303
+ });
304
+ await update(item, (record) => ({ ...record, findings: result.findings }));
305
+ await finishPhase(item, "ok");
306
+ for (const finding of result.findings) {
307
+ say(item, finding.refuses ? "warning" : "info", describeFinding(finding));
308
+ }
309
+ requireNotCanceled(item);
310
+ if (!result.possible) {
311
+ return awaitApproval(
312
+ item,
313
+ "downloadRequired",
314
+ `CODESYS can't apply this as an online change${result.messages.length ? `: ${result.messages.join(" ")}` : ""}. Only a full download, which stops the application, can deploy it`,
315
+ );
316
+ }
317
+ if (mode === "review") {
318
+ return awaitApproval(
319
+ item,
320
+ "review",
321
+ "Review the online change's findings, then approve it to apply",
322
+ );
323
+ }
324
+ return config;
325
+ };
326
+
327
+ /** Builds the deployment and reviews it; the config to apply, or null when it waits for approval. */
328
+ const build = async (item: Pending) => {
329
+ await finishPhase(item, "ok");
330
+ await enter(item, "building");
331
+ await startPhase(item, "build");
332
+ const { config, warnings } = await prepare(item);
333
+ announce(item, warnings);
334
+ const { operation, mode } = recordOf(item.id);
335
+ const baseline =
336
+ operation === "download" ? "valid" : await controller.baseline();
337
+ await finishPhase(item, "ok");
338
+ requireNotCanceled(item);
339
+ if (baseline !== "valid") {
340
+ await skipPhase(item, "review");
341
+ return awaitApproval(
342
+ item,
343
+ "downloadRequired",
344
+ baseline === "missing"
345
+ ? "The controller has no application downloaded by this agent; only a full download can deploy"
346
+ : "This agent's record of the controller's download can't be read; only a full download can deploy",
347
+ );
348
+ }
349
+ if (operation === "online-change") {
350
+ return review(item, config);
351
+ }
352
+ await skipPhase(item, "review");
353
+ if (mode === "review") {
354
+ return awaitApproval(
355
+ item,
356
+ "review",
357
+ "Approve it to apply as a full download, which stops the application",
358
+ );
359
+ }
360
+ return config;
361
+ };
362
+
363
+ /** Applies the release; the receipt, or null when an online change turned out to need a download. */
364
+ const apply = async (item: Pending, config: ResolvedConfig) => {
365
+ requireNotCanceled(item);
366
+ const { operation } = recordOf(item.id);
367
+ await enter(item, "applying", { approval: null });
368
+ await startPhase(item, "apply");
369
+ say(item, "info", `Starting the ${operation}`);
370
+ const receipt = await controller
371
+ .apply(config, operation, {
372
+ initializeUser: item.initializeUser,
373
+ credentials: await controllerCredentials(item.credentials),
374
+ onProgress: progress(item),
375
+ })
376
+ .catch(async (error: unknown) => {
377
+ if (operation === "download" || !requiresDownload(error)) {
378
+ throw error;
379
+ }
380
+ await finishPhase(item, "failed");
381
+ if (error instanceof DownloadRequiredError) {
382
+ await update(item, (record) => ({
383
+ ...record,
384
+ findings: error.findings,
385
+ }));
386
+ }
387
+ return awaitApproval(item, "downloadRequired", errorMessage(error));
388
+ });
389
+ if (!receipt) {
390
+ return null;
391
+ }
392
+ await update(item, (record) => ({
393
+ ...record,
394
+ controllerIds: receipt.controllerIds,
395
+ }));
396
+ await finishPhase(item, "ok");
397
+ return receipt;
398
+ };
399
+
400
+ /** Starts the release's server, if it has one; why it failed, or undefined. */
401
+ const startServer = async (item: Pending, serverPath: string | undefined) => {
402
+ if (!serverPath) {
403
+ await skipPhase(item, "server");
404
+ return undefined;
405
+ }
406
+ await startPhase(item, "server");
407
+ say(item, "info", "Starting the new server");
408
+ // A server that fails to start is replaced by the previous one again.
409
+ const failure = await context.server
410
+ .replace(releaseServerFile(state.paths.releases, serverPath))
411
+ .then(
412
+ () => undefined,
413
+ (error: unknown) => errorMessage(error),
414
+ );
415
+ await finishPhase(item, failure === undefined ? "ok" : "failed");
416
+ return failure;
417
+ };
418
+
419
+ /** Marks the deployment as the one running on the line, and ends the previous one's time. */
420
+ const activate = async (item: Pending) => {
421
+ const at = timestamp();
422
+ const { current } = activeDeployments(store.list());
423
+ if (current && current !== item.id) {
424
+ await store.update(current, (record) => ({
425
+ ...record,
426
+ activeUntil: at,
427
+ }));
428
+ }
429
+ await update(item, (record) => ({
430
+ ...record,
431
+ activeFrom: at,
432
+ activeUntil: null,
433
+ }));
434
+ };
435
+
436
+ /** Starts the server and records the release as deployed; the controller already runs it. */
437
+ const startRelease = async (item: Pending, receipt: ControllerResult) => {
438
+ const { release } = item;
439
+ const record = recordOf(item.id);
440
+ await enter(item, "starting");
441
+ const serverPath = releaseServerPath(release);
442
+ const previous = await state.release();
443
+ const serverFailure = await startServer(item, serverPath);
444
+ const deployed: Release = {
445
+ id: release.id,
446
+ deployedAt: timestamp(),
447
+ operation: record.operation,
448
+ controllerIds: receipt.controllerIds,
449
+ // A release without a server, or whose server failed, leaves the previous one running.
450
+ server:
451
+ serverFailure === undefined
452
+ ? (serverPath ?? previous?.server)
453
+ : previous?.server,
454
+ };
455
+ await state.setRelease(deployed);
456
+ const line: Deployment = {
457
+ at: deployed.deployedAt,
458
+ release: release.id,
459
+ ...(record.build !== null && { build: record.build }),
460
+ operation: record.operation,
461
+ credentials: item.credentials ? "provided" : "stored",
462
+ ...(record.requestedBy.user !== null && {
463
+ user: record.requestedBy.user,
464
+ }),
465
+ ...(record.requestedBy.host !== null && {
466
+ host: record.requestedBy.host,
467
+ }),
468
+ };
469
+ await appendJsonl(state.paths.deployments, line);
470
+ await activate(item);
471
+ context.onActivated();
472
+ if (serverFailure !== undefined) {
473
+ throw new Error(
474
+ `The controller runs release ${release.id}. ${serverFailure}`,
475
+ );
476
+ }
477
+ return deployed;
478
+ };
479
+
480
+ const verify = async (item: Pending, receipt: ControllerResult) => {
481
+ await enter(item, "verifying");
482
+ await startPhase(item, "health");
483
+ const health = await checkHealth({
484
+ controllerState: receipt.state,
485
+ hasServer: item.release.manifest.server !== undefined,
486
+ server: context.server,
487
+ });
488
+ await update(item, (record) => ({ ...record, health }));
489
+ if (!healthy(health)) {
490
+ throw new Error(health.detail ?? "The deployment isn't healthy");
491
+ }
492
+ await finishPhase(item, "ok");
493
+ say(item, "info", health.detail ? `Ready. ${health.detail}` : "Ready");
494
+ await enter(item, "ready");
495
+ };
496
+
497
+ const fail = async (item: Pending, error: unknown) => {
498
+ if (error instanceof Canceled) {
499
+ await finishPhase(item, "skipped");
500
+ await enter(item, "canceled", { approval: null });
501
+ return;
502
+ }
503
+ context.log(
504
+ `Deployment ${item.id} failed: ${error instanceof Error ? error.stack : String(error)}`,
505
+ );
506
+ await finishPhase(item, "failed");
507
+ say(item, "error", errorMessage(error));
508
+ await enter(item, "error", { approval: null, error: failureReport(error) });
509
+ };
510
+
511
+ const prune = () =>
512
+ withReleases(async () => {
513
+ const pruned = await pruneDeployments({
514
+ store,
515
+ releases: state.paths.releases,
516
+ deployed: await state.release(),
517
+ now: context.now,
518
+ });
519
+ if (pruned.deployments.length || pruned.releases.length) {
520
+ context.log(
521
+ `Removed ${pruned.deployments.length} deployments and ${pruned.releases.length} releases older than the retention`,
522
+ );
523
+ }
524
+ }).catch((error: unknown) =>
525
+ context.log(`Pruning deployments failed: ${errorMessage(error)}`),
526
+ );
527
+
528
+ const waitsForPerson = (item: Pending) =>
529
+ recordOf(item.id).state === "awaitingApproval" && !item.approved;
530
+
531
+ const conclude = (item: Pending) => {
532
+ if (recordOf(item.id).state === "awaitingApproval") {
533
+ return;
534
+ }
535
+ pending.delete(item.id);
536
+ const index = queue.indexOf(item);
537
+ if (index >= 0) {
538
+ queue.splice(index, 1);
539
+ }
540
+ void prune();
541
+ };
542
+
543
+ /** Takes the deployment as far as it goes: finished, or waiting for approval. */
544
+ const advance = async (
545
+ item: Pending,
546
+ lock: (run: () => Promise<Release | null>) => Promise<Release | null>,
547
+ ): Promise<Advanced> => {
548
+ item.running = true;
549
+ try {
550
+ const deployed = await lock(async () => {
551
+ requireNotCanceled(item);
552
+ const config =
553
+ recordOf(item.id).state === "queued"
554
+ ? await build(item)
555
+ : (await prepare(item)).config;
556
+ if (!config) {
557
+ return null;
558
+ }
559
+ const receipt = await apply(item, config);
560
+ if (!receipt) {
561
+ return null;
562
+ }
563
+ const release = await startRelease(item, receipt);
564
+ await verify(item, receipt);
565
+ return release;
566
+ });
567
+ return { deployed, failure: null };
568
+ } catch (error) {
569
+ await fail(item, error).catch((failure: unknown) =>
570
+ context.log(
571
+ `Recording deployment ${item.id}'s failure failed: ${errorMessage(failure)}`,
572
+ ),
573
+ );
574
+ return {
575
+ deployed: null,
576
+ failure: error instanceof Canceled ? null : { error },
577
+ };
578
+ } finally {
579
+ item.running = false;
580
+ conclude(item);
581
+ }
582
+ };
583
+
584
+ const advanceQueue = async (): Promise<void> => {
585
+ const [head] = queue;
586
+ if (!head || waitsForPerson(head)) {
587
+ return;
588
+ }
589
+ await advance(head, (run) => whenFree(head, run));
590
+ return advanceQueue();
591
+ };
592
+
593
+ const drain = async () => {
594
+ if (draining) {
595
+ return;
596
+ }
597
+ draining = true;
598
+ try {
599
+ await advanceQueue();
600
+ } finally {
601
+ draining = false;
602
+ }
603
+ };
604
+
605
+ const create = async (
606
+ release: StoredRelease,
607
+ requested: Pick<
608
+ DeploymentRecord,
609
+ "origin" | "git" | "requestedBy" | "mode" | "operation"
610
+ >,
611
+ handling: Handling,
612
+ ) => {
613
+ const at = timestamp();
614
+ const record: DeploymentRecord = {
615
+ id: store.newId(),
616
+ release: release.id,
617
+ build: await releaseBuild(release),
618
+ createdAt: at,
619
+ updatedAt: at,
620
+ ...requested,
621
+ state: "queued",
622
+ phases: [
623
+ { name: "queue", startedAt: at, finishedAt: null, outcome: "running" },
624
+ ],
625
+ findings: [],
626
+ approval: null,
627
+ error: null,
628
+ controllerIds: null,
629
+ health: null,
630
+ activeFrom: null,
631
+ activeUntil: null,
632
+ };
633
+ await store.create(record);
634
+ const item: Pending = {
635
+ id: record.id,
636
+ release,
637
+ ...handling,
638
+ cancellation: new AbortController(),
639
+ approved: false,
640
+ running: false,
641
+ };
642
+ pending.set(item.id, item);
643
+ return item;
644
+ };
645
+
646
+ const createUpload = (
647
+ release: StoredRelease,
648
+ submission: Submission,
649
+ options: { waitsForApproval: boolean },
650
+ ) =>
651
+ create(
652
+ release,
653
+ {
654
+ origin: { kind: "upload" },
655
+ git: submission.git,
656
+ requestedBy: submission.requestedBy,
657
+ mode: submission.mode,
658
+ operation: submission.download ? "download" : "online-change",
659
+ },
660
+ {
661
+ credentials: submission.credentials,
662
+ initializeUser: submission.initializeUser,
663
+ waitsForApproval: options.waitsForApproval,
664
+ },
665
+ );
666
+
667
+ const enqueue = (item: Pending, warnings: readonly string[]) => {
668
+ announce(item, warnings);
669
+ queue.push(item);
670
+ void drain();
671
+ return recordOf(item.id);
672
+ };
673
+
674
+ /** A new deployment of `source`'s release, with the controller user stored on the PC. */
675
+ const again = async (
676
+ source: DeploymentRecord,
677
+ origin: DeploymentRecord["origin"],
678
+ mode: DeploymentMode,
679
+ requestedBy: DeploymentRecord["requestedBy"],
680
+ ) => {
681
+ await checkSubmission(state, null);
682
+ return withReleases(async () => {
683
+ if (!isStored(state.paths.releases, source.release)) {
684
+ throw new AgentError(
685
+ `The release of ${source.id}, ${source.release}, is no longer stored`,
686
+ 409,
687
+ );
688
+ }
689
+ const release = await loadRelease(state.paths.releases, source.release);
690
+ const item = await create(
691
+ release,
692
+ {
693
+ origin,
694
+ git: source.git,
695
+ requestedBy,
696
+ mode,
697
+ operation: "online-change",
698
+ },
699
+ { credentials: null, initializeUser: false, waitsForApproval: true },
700
+ );
701
+ return enqueue(item, []);
702
+ });
703
+ };
704
+
705
+ return {
706
+ /** Ends what a previous agent left unfinished, then prunes. */
707
+ start: async () => {
708
+ for (const record of store.list().filter((entry) => !isFinished(entry))) {
709
+ await store.update(record.id, (unfinished) => ({
710
+ ...unfinished,
711
+ state: "error",
712
+ approval: null,
713
+ phases: closeRunning(unfinished.phases, "failed"),
714
+ error: {
715
+ message: "The plant agent stopped before this deployment finished",
716
+ downloadRequired: false,
717
+ },
718
+ }));
719
+ }
720
+ await prune();
721
+ },
722
+ /** Stores an uploaded release and queues its deployment. */
723
+ submit: async (upload: Upload, submission: Submission) => {
724
+ await checkSubmission(state, submission.credentials);
725
+ return withReleases(async () => {
726
+ const item = await createUpload(
727
+ await saveRelease(state.paths.releases, upload),
728
+ submission,
729
+ { waitsForApproval: true },
730
+ );
731
+ return enqueue(item, submission.warnings);
732
+ });
733
+ },
734
+ /** Deploys a finished deployment's release again. */
735
+ redeploy: async (
736
+ id: string,
737
+ mode: DeploymentMode,
738
+ requestedBy: DeploymentRecord["requestedBy"],
739
+ ) => {
740
+ const source = recordOf(id);
741
+ if (!isFinished(source)) {
742
+ throw new AgentError(
743
+ `Deployment ${id} is ${source.state}; only a finished deployment can be redeployed`,
744
+ 409,
745
+ );
746
+ }
747
+ return again(source, { kind: "redeploy", from: id }, mode, requestedBy);
748
+ },
749
+ /** Deploys again the release of a deployment that ran healthy, but not the one running now. */
750
+ rollback: async (
751
+ id: string,
752
+ requestedBy: DeploymentRecord["requestedBy"],
753
+ ) => {
754
+ const source = recordOf(id);
755
+ if (source.state !== "ready") {
756
+ throw new AgentError(
757
+ `Deployment ${id} is ${source.state}; only a ready deployment can be rolled back to`,
758
+ 409,
759
+ );
760
+ }
761
+ if (activeDeployments(store.list()).current === id) {
762
+ throw new AgentError(
763
+ `Deployment ${id} runs now; there is nothing to roll back`,
764
+ 409,
765
+ );
766
+ }
767
+ return again(
768
+ source,
769
+ { kind: "rollback", from: id },
770
+ "apply",
771
+ requestedBy,
772
+ );
773
+ },
774
+ approve: async (
775
+ id: string,
776
+ { download }: { download: boolean },
777
+ by: string,
778
+ ) => {
779
+ const record = recordOf(id);
780
+ const item = pending.get(id);
781
+ if (!item || record.state !== "awaitingApproval" || item.approved) {
782
+ throw new AgentError(`Deployment ${id} isn't awaiting approval`, 409);
783
+ }
784
+ if (record.approval?.reason === "downloadRequired" && !download) {
785
+ throw new AgentError(
786
+ `Only a full download can apply deployment ${id}; approve it with a download`,
787
+ 409,
788
+ );
789
+ }
790
+ item.approved = true;
791
+ say(
792
+ item,
793
+ "info",
794
+ `${by} approved it${download ? " as a full download" : ""}`,
795
+ );
796
+ const approved = await update(item, (current) => ({
797
+ ...current,
798
+ operation: download ? "download" : current.operation,
799
+ }));
800
+ void drain();
801
+ return approved;
802
+ },
803
+ /** Cancels a deployment before it applies; one being built stops at its next step, and its record says so then. */
804
+ cancel: async (id: string, by: string) => {
805
+ const record = recordOf(id);
806
+ const item = pending.get(id);
807
+ if (!item || !cancelableStates.includes(record.state)) {
808
+ throw new AgentError(
809
+ `Deployment ${id} is ${record.state}; a deployment can only be canceled before it applies`,
810
+ 409,
811
+ );
812
+ }
813
+ item.cancellation.abort();
814
+ say(item, "info", `${by} canceled it`);
815
+ if (item.running) {
816
+ return record;
817
+ }
818
+ // Off the queue before anything awaits, so the queue never picks it up.
819
+ const index = queue.indexOf(item);
820
+ if (index >= 0) {
821
+ queue.splice(index, 1);
822
+ }
823
+ await fail(item, new Canceled());
824
+ conclude(item);
825
+ void drain();
826
+ return recordOf(id);
827
+ },
828
+ /**
829
+ * Refuses `POST /deploy` while deployments are queued, since it runs at once: one waiting for
830
+ * approval would otherwise be applied over.
831
+ */
832
+ requireIdle: () => {
833
+ const [head] = queue;
834
+ if (!head) {
835
+ return;
836
+ }
837
+ throw new AgentError(
838
+ waitsForPerson(head)
839
+ ? `Deployment ${head.id} waits for approval on the dashboard; approve or cancel it first`
840
+ : "The agent is busy with a deployment",
841
+ 409,
842
+ );
843
+ },
844
+ /**
845
+ * Stores and runs a `POST /deploy` deployment at once, inside the caller's operation, telling
846
+ * `onLine` each line of its log. Fails as the deployment did.
847
+ */
848
+ runNow: async (
849
+ upload: Upload,
850
+ submission: Submission,
851
+ onLine: (line: DeploymentLogLine) => void,
852
+ ) => {
853
+ const item = await withReleases(async () =>
854
+ createUpload(
855
+ await saveRelease(state.paths.releases, upload),
856
+ submission,
857
+ { waitsForApproval: false },
858
+ ),
859
+ );
860
+ const unsubscribe = store.subscribe(item.id, (event) => {
861
+ if (event.kind === "log") {
862
+ onLine(event.line);
863
+ }
864
+ });
865
+ try {
866
+ announce(item, submission.warnings);
867
+ const { deployed, failure } = await advance(item, (run) => run());
868
+ await store.flush(item.id);
869
+ if (failure) {
870
+ throw failure.error;
871
+ }
872
+ if (!deployed) {
873
+ throw new AgentError(`Deployment ${item.id} was canceled`, 409);
874
+ }
875
+ return deployed;
876
+ } finally {
877
+ unsubscribe();
878
+ }
879
+ },
880
+ list: () => {
881
+ const deployments = store.list();
882
+ return { deployments, ...activeDeployments(deployments) };
883
+ },
884
+ get: recordOf,
885
+ lines: (id: string, after: number) => {
886
+ recordOf(id);
887
+ return store.lines(id, after);
888
+ },
889
+ subscribe: (id: string, listener: (event: DeploymentEvent) => void) => {
890
+ recordOf(id);
891
+ return store.subscribe(id, listener);
892
+ },
893
+ /** The deployment's release files, by path, with their sizes. */
894
+ source: (id: string) =>
895
+ listReleaseFiles(state.paths.releases, recordOf(id).release),
896
+ sourceFile: (id: string, path: string) =>
897
+ readReleaseFile(state.paths.releases, recordOf(id).release, path),
898
+ };
899
+ };
900
+ export type DeploymentRunner = ReturnType<typeof createDeploymentRunner>;