@tsplc/agent 0.5.9 → 0.5.10

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 (49) hide show
  1. package/dist/cli.js +2462 -533
  2. package/dist/cli.js.map +30 -17
  3. package/dist/client.js +238 -36
  4. package/dist/client.js.map +4 -4
  5. package/dist/index.js +2162 -416
  6. package/dist/index.js.map +25 -13
  7. package/package.json +5 -5
  8. package/src/access.ts +257 -0
  9. package/src/agent.ts +101 -29
  10. package/src/audit.ts +64 -0
  11. package/src/cli.ts +58 -4
  12. package/src/client.ts +181 -36
  13. package/src/dashboard/index.ts +116 -0
  14. package/src/dashboard/ui/access.ts +192 -0
  15. package/src/dashboard/ui/actions.ts +142 -0
  16. package/src/dashboard/ui/api.ts +147 -0
  17. package/src/dashboard/ui/app.ts +41 -0
  18. package/src/dashboard/ui/approval.ts +132 -0
  19. package/src/dashboard/ui/audit.ts +115 -0
  20. package/src/dashboard/ui/contract.ts +16 -0
  21. package/src/dashboard/ui/dashboard.css +1332 -0
  22. package/src/dashboard/ui/deployment.ts +432 -0
  23. package/src/dashboard/ui/deployments.ts +317 -0
  24. package/src/dashboard/ui/details.ts +240 -0
  25. package/src/dashboard/ui/dom.ts +91 -0
  26. package/src/dashboard/ui/environment.ts +224 -0
  27. package/src/dashboard/ui/format.ts +118 -0
  28. package/src/dashboard/ui/logs.ts +127 -0
  29. package/src/dashboard/ui/main.ts +86 -0
  30. package/src/dashboard/ui/overlay.ts +146 -0
  31. package/src/dashboard/ui/shell.ts +171 -0
  32. package/src/dashboard/ui/source.ts +144 -0
  33. package/src/deploy.ts +138 -144
  34. package/src/deployments/health.ts +80 -0
  35. package/src/deployments/retention.ts +45 -0
  36. package/src/deployments/routes.ts +273 -0
  37. package/src/deployments/runner.ts +877 -0
  38. package/src/deployments/store.ts +233 -0
  39. package/src/environment.ts +205 -0
  40. package/src/index.ts +4 -0
  41. package/src/operations.ts +5 -1
  42. package/src/protocol.ts +218 -2
  43. package/src/releases.ts +73 -1
  44. package/src/routes.ts +52 -0
  45. package/src/secrets.ts +43 -2
  46. package/src/server-process.ts +33 -16
  47. package/src/sessions.ts +58 -0
  48. package/src/state.ts +2 -0
  49. package/src/tailscale.ts +112 -0
@@ -0,0 +1,171 @@
1
+ import { errorMessage } from "../../errors";
2
+ import type { Identity } from "../../protocol";
3
+ import { agentVersion, api } from "./api";
4
+ import { type App, attempt } from "./app";
5
+ import { badge, fill, h, icon, icons } from "./dom";
6
+
7
+ /** The top-level pages, by the path that opens them; the debugger is its own app under `/debug/`. */
8
+ const sections = [
9
+ { path: "/deployments", label: "Deployments", role: "viewer" },
10
+ { path: "/environment", label: "Environment", role: "viewer" },
11
+ { path: "/audit", label: "Audit", role: "viewer" },
12
+ { path: "/access", label: "Access", role: "admin" },
13
+ ] as const;
14
+
15
+ const themeKey = "tsplc-theme";
16
+
17
+ /** Light, dark, or the system's, cycled by the header's button and kept in local storage. */
18
+ const themeButton = () => {
19
+ const button = h("button", { class: "icon-button", title: "Theme" });
20
+ const render = () => {
21
+ const theme = document.documentElement.dataset.theme ?? "";
22
+ fill(button, icon(theme === "light" ? icons.sun : icons.moon));
23
+ button.title = `Theme: ${theme || "system"}`;
24
+ };
25
+ button.addEventListener("click", () => {
26
+ const order = ["", "dark", "light"];
27
+ const theme = document.documentElement.dataset.theme ?? "";
28
+ const next = order[(order.indexOf(theme) + 1) % order.length] ?? "";
29
+ document.documentElement.dataset.theme = next;
30
+ localStorage.setItem(themeKey, next);
31
+ render();
32
+ });
33
+ render();
34
+ return button;
35
+ };
36
+
37
+ /** Whether the identity signed in with a cookie, which signing out clears; Tailscale and the agent's PC can't sign out. */
38
+ const signedInByToken = (identity: Identity) => identity.via === "token";
39
+
40
+ /** The header: the agent and controller, who is signed in, and the pages. */
41
+ export const shell = (app: App) => {
42
+ const where = h("span", { class: "muted mono" });
43
+ const version = h("span", { class: "muted mono version" });
44
+ const nav = h("nav", { class: "nav" });
45
+ void api.status().then(
46
+ (status) => {
47
+ where.textContent = status.target
48
+ ? `${status.target.host}:${status.target.port}`
49
+ : "No controller selected";
50
+ version.textContent = agentVersion() ? `tsPLC ${agentVersion()}` : "";
51
+ },
52
+ () => {
53
+ version.textContent = agentVersion() ? `tsPLC ${agentVersion()}` : "";
54
+ },
55
+ );
56
+
57
+ const setActive = (pathname: string) => {
58
+ const active = pathname === "/" ? "/deployments" : pathname;
59
+ fill(
60
+ nav,
61
+ ...sections
62
+ .filter((section) => app.can(section.role))
63
+ .map((section) =>
64
+ h(
65
+ "a",
66
+ {
67
+ class: `nav-link${active === section.path || active.startsWith(`${section.path}/`) ? " on" : ""}`,
68
+ href: section.path,
69
+ onclick: (event) => {
70
+ event.preventDefault();
71
+ app.navigate(section.path);
72
+ },
73
+ },
74
+ section.label,
75
+ ),
76
+ ),
77
+ h("a", { class: "nav-link", href: "/debug/" }, "Debugger"),
78
+ );
79
+ };
80
+
81
+ const element = h(
82
+ "header",
83
+ { class: "topbar" },
84
+ h(
85
+ "div",
86
+ { class: "topbar-row" },
87
+ h(
88
+ "a",
89
+ {
90
+ class: "brand",
91
+ href: "/deployments",
92
+ onclick: (event) => {
93
+ event.preventDefault();
94
+ app.navigate("/deployments");
95
+ },
96
+ },
97
+ h("span", { class: "logo", "aria-hidden": "true" }),
98
+ h("b", {}, "tsPLC"),
99
+ h("span", { class: "muted" }, "plant agent"),
100
+ ),
101
+ h("span", { class: "slash" }, "/"),
102
+ where,
103
+ h(
104
+ "div",
105
+ { class: "topbar-end" },
106
+ version,
107
+ themeButton(),
108
+ h(
109
+ "span",
110
+ { class: "who", title: app.identity.login ?? app.identity.name },
111
+ app.identity.name,
112
+ badge(app.identity.role, "neutral"),
113
+ ),
114
+ signedInByToken(app.identity)
115
+ ? h(
116
+ "button",
117
+ {
118
+ class: "button small",
119
+ onclick: () =>
120
+ void attempt(() => api.signOut(), null).then(() =>
121
+ location.reload(),
122
+ ),
123
+ },
124
+ "Sign out",
125
+ )
126
+ : null,
127
+ ),
128
+ ),
129
+ nav,
130
+ );
131
+ return { element, setActive };
132
+ };
133
+
134
+ /** Asks for the agent's token, which signs this browser in with a cookie. */
135
+ export const signInForm = (onSignedIn: () => void) => {
136
+ const token = h("input", {
137
+ class: "input mono",
138
+ type: "password",
139
+ autocomplete: "current-password",
140
+ placeholder: "Agent token",
141
+ required: true,
142
+ });
143
+ const error = h("p", { class: "error-text" });
144
+ return h(
145
+ "div",
146
+ { class: "sign-in" },
147
+ h(
148
+ "form",
149
+ {
150
+ class: "card",
151
+ onsubmit: (event) => {
152
+ event.preventDefault();
153
+ error.textContent = "";
154
+ api.signIn(token.value).then(onSignedIn, (failure: unknown) => {
155
+ error.textContent = errorMessage(failure);
156
+ });
157
+ },
158
+ },
159
+ h("span", { class: "logo large", "aria-hidden": "true" }),
160
+ h("h1", {}, "Sign in to the plant agent"),
161
+ h(
162
+ "p",
163
+ { class: "muted" },
164
+ "Your Tailscale login has no role on this agent. Sign in with the agent's token, or ask an admin for a role.",
165
+ ),
166
+ token,
167
+ error,
168
+ h("button", { class: "button primary", type: "submit" }, "Sign in"),
169
+ ),
170
+ );
171
+ };
@@ -0,0 +1,144 @@
1
+ import { errorMessage } from "../../errors";
2
+ import { api, type SourceFile } from "./api";
3
+ import { type App, deploymentHref } from "./app";
4
+ import { empty, fill, h, icon, icons } from "./dom";
5
+ import { formatSize } from "./format";
6
+
7
+ interface Folder {
8
+ folders: Map<string, Folder>;
9
+ files: SourceFile[];
10
+ }
11
+
12
+ const tree = (files: readonly SourceFile[]) => {
13
+ const root: Folder = { folders: new Map(), files: [] };
14
+ for (const file of files) {
15
+ const parts = file.path.split("/");
16
+ const folder = parts.slice(0, -1).reduce((parent, name) => {
17
+ const existing = parent.folders.get(name);
18
+ if (existing) {
19
+ return existing;
20
+ }
21
+ const created: Folder = { folders: new Map(), files: [] };
22
+ parent.folders.set(name, created);
23
+ return created;
24
+ }, root);
25
+ folder.files.push(file);
26
+ }
27
+ return root;
28
+ };
29
+
30
+ const fileName = (path: string) => path.slice(path.lastIndexOf("/") + 1);
31
+
32
+ /** The release's files as a tree, and the selected one's text with line numbers. */
33
+ export const sourceView = (app: App, id: string) => {
34
+ const files = h("nav", { class: "file-tree" }, empty("Loading files…"));
35
+ const content = h(
36
+ "div",
37
+ { class: "file-view" },
38
+ empty("Select a file to see its text."),
39
+ );
40
+ const sourceHref = (path: string) =>
41
+ `${deploymentHref(id, "source")}/${path.split("/").map(encodeURIComponent).join("/")}`;
42
+ let selected: string | null = null;
43
+ let listing: SourceFile[] | null = null;
44
+
45
+ const fileLink = (file: SourceFile) =>
46
+ h(
47
+ "a",
48
+ {
49
+ class: `file${file.path === selected ? " on" : ""}`,
50
+ href: sourceHref(file.path),
51
+ title: `${file.path} · ${formatSize(file.size)}`,
52
+ onclick: (event) => {
53
+ event.preventDefault();
54
+ app.navigate(sourceHref(file.path));
55
+ },
56
+ },
57
+ icon(icons.file),
58
+ fileName(file.path),
59
+ );
60
+
61
+ const folderElement = (folder: Folder, path: string): HTMLElement[] => [
62
+ ...[...folder.folders]
63
+ .sort(([a], [b]) => a.localeCompare(b))
64
+ .map(([name, child]) => {
65
+ const childPath = path ? `${path}/${name}` : name;
66
+ return h(
67
+ "details",
68
+ {
69
+ open:
70
+ !selected || selected.startsWith(`${childPath}/`) || path === "",
71
+ },
72
+ h("summary", {}, icon(icons.folder), name),
73
+ h("div", { class: "folder" }, ...folderElement(child, childPath)),
74
+ );
75
+ }),
76
+ ...folder.files
77
+ .slice()
78
+ .sort((a, b) => a.path.localeCompare(b.path))
79
+ .map(fileLink),
80
+ ];
81
+
82
+ const renderTree = () => {
83
+ if (listing) {
84
+ fill(
85
+ files,
86
+ ...(listing.length
87
+ ? folderElement(tree(listing), "")
88
+ : [empty("This release has no files.")]),
89
+ );
90
+ }
91
+ };
92
+
93
+ const show = async (path: string | null) => {
94
+ selected = path;
95
+ renderTree();
96
+ if (!path) {
97
+ fill(content, empty("Select a file to see its text."));
98
+ return;
99
+ }
100
+ const size = listing?.find((file) => file.path === path)?.size;
101
+ fill(content, empty(`Loading ${path}…`));
102
+ try {
103
+ const text = await api.sourceFile(id, path);
104
+ if (selected !== path) {
105
+ return;
106
+ }
107
+ fill(
108
+ content,
109
+ h(
110
+ "div",
111
+ { class: "file-header" },
112
+ h("span", { class: "mono" }, path),
113
+ size === undefined
114
+ ? null
115
+ : h("span", { class: "muted" }, formatSize(size)),
116
+ ),
117
+ h(
118
+ "pre",
119
+ { class: "code" },
120
+ ...text
121
+ .replace(/\n$/, "")
122
+ .split("\n")
123
+ .map((line) => h("span", { class: "code-line" }, line, "\n")),
124
+ ),
125
+ );
126
+ } catch (error) {
127
+ fill(content, h("p", { class: "error-text" }, errorMessage(error)));
128
+ }
129
+ };
130
+
131
+ void api.source(id).then(
132
+ (loaded) => {
133
+ listing = loaded;
134
+ renderTree();
135
+ },
136
+ (error: unknown) =>
137
+ fill(files, h("p", { class: "error-text" }, errorMessage(error))),
138
+ );
139
+
140
+ return {
141
+ element: h("div", { class: "source" }, files, content),
142
+ show,
143
+ };
144
+ };
package/src/deploy.ts CHANGED
@@ -1,15 +1,12 @@
1
- import { existsSync } from "node:fs";
2
- import { join } from "node:path";
3
1
  import {
4
2
  controllerBaseline,
5
3
  findControllerLogin,
4
+ reviewWarmController,
6
5
  settleWarmController,
7
6
  startWarmController,
8
7
  updateWarmController,
9
8
  workerScriptsDigest,
10
9
  } from "@tsplc/build";
11
- import { loadManifest } from "@tsplc/debug";
12
- import { debugManifestFile } from "@tsplc/debug/manifest";
13
10
  import {
14
11
  type CodesysSettings,
15
12
  controllerConfig,
@@ -20,35 +17,79 @@ import {
20
17
  requireBuilder,
21
18
  } from "./codesys";
22
19
  import type { Debugging } from "./debugging";
20
+ import {
21
+ createDeploymentRunner,
22
+ type DeploymentController,
23
+ } from "./deployments/runner";
24
+ import { openDeploymentStore } from "./deployments/store";
23
25
  import { AgentError, errorMessage } from "./errors";
24
- import { appendJsonl } from "./logs";
25
26
  import type { Operations } from "./operations";
26
27
  import {
27
28
  type ClientIdentity,
28
29
  type ClientRelease,
29
- type Deployment,
30
- type Release,
30
+ type Identity,
31
31
  tsplcVersion,
32
32
  versionMismatch,
33
33
  } from "./protocol";
34
- import { type DeployRequest, loadRelease, saveRelease } from "./releases";
35
- import { controllerCredentials, readSecrets, withSecrets } from "./secrets";
34
+ import { type DeployRequest, loadRelease } from "./releases";
35
+ import { controllerCredentials, readSecrets } from "./secrets";
36
36
  import type { ServerSupervisor } from "./server-process";
37
37
  import type { AgentState } from "./state";
38
38
 
39
+ /**
40
+ * Refuses a client of another tsPLC version, which compiles for scripts this agent doesn't run,
41
+ * and returns what to warn the deployment about. A client from before version checks reports none
42
+ * and is only warned, so it can still deploy.
43
+ */
44
+ export const clientWarnings = async (clientTsplc: ClientRelease) => {
45
+ if (clientTsplc.version === undefined) {
46
+ return [
47
+ `the deploying tsPLC predates version checks, while this plant agent runs tsPLC ${tsplcVersion}; update the client to ${tsplcVersion}`,
48
+ ];
49
+ }
50
+ if (clientTsplc.version !== tsplcVersion) {
51
+ throw new AgentError(
52
+ versionMismatch({
53
+ agent: tsplcVersion,
54
+ client: clientTsplc.version,
55
+ agentUpgrades: true,
56
+ }),
57
+ 409,
58
+ );
59
+ }
60
+ if (
61
+ clientTsplc.scripts !== undefined &&
62
+ clientTsplc.scripts !== (await workerScriptsDigest())
63
+ ) {
64
+ return [
65
+ `the plant agent's CODESYS scripts differ from the deploying tsPLC's, though both are ${tsplcVersion}, so one is a local build. The deployment runs the agent's scripts: update the plant agent to run the client's`,
66
+ ];
67
+ }
68
+ return [];
69
+ };
70
+
71
+ /** Who asked for a deployment: the identity behind the request, and the deploying machine's user and host. */
72
+ export const requester = (identity: Identity, client: ClientIdentity) => ({
73
+ identity: { login: identity.login, name: identity.name, via: identity.via },
74
+ user: client.user ?? null,
75
+ host: client.host ?? null,
76
+ });
77
+
39
78
  /**
40
79
  * Deployments of uploaded releases: a download or online change through the CODESYS that stays
41
80
  * running between them, then the release's server once the controller has its program.
42
81
  */
43
- export const createDeployments = (context: {
82
+ export const createDeployments = async (context: {
44
83
  state: AgentState;
45
84
  operations: Operations;
46
85
  codesys: CodesysSettings;
47
86
  server: ServerSupervisor;
48
87
  debugging: Debugging;
88
+ serverHealthUrl: string | undefined;
89
+ now: () => Date;
49
90
  log: (message: string) => void;
50
91
  }) => {
51
- const { state, server } = context;
92
+ const { state } = context;
52
93
 
53
94
  /** CODESYS starts for the deployed release in the background, so the first deployment finds it running. */
54
95
  const warming = (async () => {
@@ -73,7 +114,57 @@ export const createDeployments = (context: {
73
114
  context.log(`Starting CODESYS failed: ${errorMessage(error)}`);
74
115
  });
75
116
 
117
+ const controller: DeploymentController = {
118
+ ready: async () => {
119
+ const builder = await requireBuilder();
120
+ if (await findControllerLogin(loginContainer)) {
121
+ throw new AgentError(
122
+ "A login is open; log out before deploying: tsplc logout",
123
+ 409,
124
+ );
125
+ }
126
+ return builder.kind === "unverified"
127
+ ? [
128
+ `${builder.reason}. Run tsplc-agent setup on the plant PC once to rebuild and label it`,
129
+ ]
130
+ : [];
131
+ },
132
+ settle: (config) => settleWarmController(config, deployContainer),
133
+ baseline: () => controllerBaseline(state.paths.controller),
134
+ review: async (config, options) => {
135
+ await ensureGateway();
136
+ await warming;
137
+ return reviewWarmController(config, deployContainer, options);
138
+ },
139
+ // The previous server keeps running until the controller has the new program, so a failed
140
+ // transfer leaves both as they were.
141
+ apply: async (config, operation, options) => {
142
+ await ensureGateway();
143
+ await warming;
144
+ return updateWarmController(config, deployContainer, operation, options);
145
+ },
146
+ };
147
+
148
+ const runner = createDeploymentRunner({
149
+ store: await openDeploymentStore({
150
+ directory: state.paths.deploymentRecords,
151
+ now: context.now,
152
+ log: context.log,
153
+ }),
154
+ state,
155
+ operations: context.operations,
156
+ codesys: context.codesys,
157
+ server: context.server,
158
+ controller,
159
+ serverHealthUrl: context.serverHealthUrl,
160
+ onActivated: () => context.debugging.restart(),
161
+ now: context.now,
162
+ log: context.log,
163
+ });
164
+ await runner.start();
165
+
76
166
  return {
167
+ runner,
77
168
  /**
78
169
  * Stops the warm container once it has committed the last deployment, so an upgraded agent
79
170
  * starts one running its own code and none keeps the installed package's files in use.
@@ -95,154 +186,57 @@ export const createDeployments = (context: {
95
186
  }
96
187
  await removeContainer(deployContainer);
97
188
  },
189
+ /**
190
+ * `POST /deploy`: runs a deployment at once and streams its progress, as clients from before
191
+ * `/api/deployments` expect. One that needs a download fails, for the client to ask again.
192
+ */
98
193
  deploy: async (
99
194
  /** Reads the upload once the client's version is checked, so a mismatch is reported before a large body is read. */
100
195
  readRequest: () => Promise<DeployRequest>,
196
+ identity: Identity,
101
197
  client: ClientIdentity,
102
198
  clientTsplc: ClientRelease,
103
199
  ) => {
104
- // A client of another version compiles for scripts this agent doesn't run. One from before
105
- // version checks reports none and is only warned, so it can still deploy.
106
- if (
107
- clientTsplc.version !== undefined &&
108
- clientTsplc.version !== tsplcVersion
109
- ) {
110
- throw new AgentError(
111
- versionMismatch({
112
- agent: tsplcVersion,
113
- client: clientTsplc.version,
114
- agentUpgrades: true,
115
- }),
116
- 409,
117
- );
118
- }
200
+ const warnings = await clientWarnings(clientTsplc);
119
201
  context.operations.requireIdle();
120
- const builder = await requireBuilder();
202
+ runner.requireIdle();
203
+ await requireBuilder();
121
204
  const { settings, upload } = await readRequest();
122
- const target = await state.requireTarget();
123
- if (await findControllerLogin(loginContainer)) {
124
- throw new AgentError(
125
- "A login is open; log out before deploying: tsplc logout",
126
- 409,
127
- );
128
- }
129
- const credentials = await controllerCredentials(settings.credentials);
130
- const secrets = await readSecrets(upload.manifest.secrets);
131
- const scripts = await workerScriptsDigest();
205
+ await state.requireTarget();
206
+ await controllerCredentials(settings.credentials);
207
+ // A missing secret fails before anything stops.
208
+ await readSecrets(upload.manifest.secrets);
132
209
  return context.operations.stream(
133
210
  "a deployment",
134
- async (emit) => {
135
- if (builder.kind === "unverified") {
136
- emit({
137
- kind: "progress",
138
- message: `Warning: ${builder.reason}. Run tsplc-agent setup on the plant PC once to rebuild and label it`,
139
- });
140
- }
141
- if (clientTsplc.version === undefined) {
142
- emit({
143
- kind: "progress",
144
- message: `Warning: the deploying tsPLC predates version checks, while this plant agent runs tsPLC ${tsplcVersion}; update the client to ${tsplcVersion}`,
145
- });
146
- } else if (
147
- clientTsplc.scripts !== undefined &&
148
- clientTsplc.scripts !== scripts
149
- ) {
150
- emit({
151
- kind: "progress",
152
- message: `Warning: the plant agent's CODESYS scripts differ from the deploying tsPLC's, though both are ${tsplcVersion}, so one is a local build. The deployment runs the agent's scripts: update the plant agent to run the client's`,
153
- });
154
- }
155
- const release = await saveRelease(state.paths.releases, upload);
156
- const config = await withSecrets(
157
- controllerConfig(
158
- release,
159
- target,
160
- state.paths.controller,
161
- context.codesys,
162
- ),
163
- secrets,
164
- state.paths.sources,
165
- );
166
- // The last deployment's project may still be saving, and its commit decides the baseline.
167
- await settleWarmController(config, deployContainer);
168
- const baseline = settings.download
169
- ? "valid"
170
- : await controllerBaseline(state.paths.controller);
171
- if (baseline !== "valid") {
172
- throw new AgentError(
173
- baseline === "missing"
174
- ? "The controller has no application downloaded by this agent; only a full download can deploy"
175
- : "This agent's record of the controller's download can't be read; only a full download can deploy",
176
- 409,
177
- { downloadRequired: true },
178
- );
179
- }
180
- const previous = await state.release();
181
- const kind = settings.download ? "download" : "online-change";
182
- emit({ kind: "progress", message: `Starting the ${kind}` });
183
- await ensureGateway();
184
- await warming;
185
- // The previous server keeps running until the controller has the new program, so a
186
- // failed transfer leaves both as they were.
187
- const receipt = await updateWarmController(
188
- config,
189
- deployContainer,
190
- kind,
211
+ (emit) =>
212
+ runner.runNow(
213
+ upload,
191
214
  {
215
+ git: settings.deployment?.git ?? null,
216
+ requestedBy: requester(identity, client),
217
+ mode: "apply",
218
+ download: settings.download,
219
+ credentials: settings.credentials,
192
220
  initializeUser: settings.initializeUser,
193
- credentials,
194
- onProgress: (message) => emit({ kind: "progress", message }),
221
+ warnings,
195
222
  },
196
- );
197
- // Server paths are relative to the releases directory.
198
- const serverPath =
199
- release.manifest.server &&
200
- `${release.id}/${release.manifest.server}`;
201
- if (serverPath) {
202
- emit({ kind: "progress", message: "Starting the new server" });
203
- }
204
- // A server that fails to start is replaced by the previous one again, and the
205
- // controller keeps the new program, which is recorded before reporting the failure.
206
- const serverFailure = serverPath
207
- ? await server.replace(join(state.paths.releases, serverPath)).then(
208
- () => undefined,
209
- (error: unknown) => errorMessage(error),
210
- )
211
- : undefined;
212
- const deployed: Release = {
213
- id: release.id,
214
- deployedAt: new Date().toISOString(),
215
- operation: kind,
216
- controllerIds: receipt.controllerIds,
217
- // A release without a server, or whose server failed, leaves the previous one running.
218
- server:
219
- serverFailure === undefined
220
- ? (serverPath ?? previous?.server)
221
- : previous?.server,
222
- };
223
- await state.setRelease(deployed);
224
- const debugManifest = join(release.directory, debugManifestFile);
225
- const deployment: Deployment = {
226
- at: deployed.deployedAt,
227
- release: release.id,
228
- ...(existsSync(debugManifest) && {
229
- build: (await loadManifest(debugManifest)).build.id,
230
- }),
231
- operation: kind,
232
- credentials: settings.credentials ? "provided" : "stored",
233
- ...client,
234
- };
235
- await appendJsonl(state.paths.deployments, deployment);
236
- context.debugging.restart();
237
- if (serverFailure !== undefined) {
238
- throw new Error(
239
- `The controller runs release ${release.id}. ${serverFailure}`,
240
- );
241
- }
242
- return deployed;
243
- },
223
+ (line) => {
224
+ // The failure itself ends the stream as its error.
225
+ if (line.level === "error") {
226
+ return;
227
+ }
228
+ emit({
229
+ kind: "progress",
230
+ message:
231
+ line.level === "warning"
232
+ ? `Warning: ${line.message}`
233
+ : line.message,
234
+ });
235
+ },
236
+ ),
244
237
  { reportsRollback: clientTsplc.version !== undefined },
245
238
  );
246
239
  },
247
240
  };
248
241
  };
242
+ export type Deployments = Awaited<ReturnType<typeof createDeployments>>;