@tsplc/agent 0.5.8 → 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,80 @@
1
+ import { z } from "zod";
2
+ import type { DeploymentRecord } from "../protocol";
3
+ import type { ServerSupervisor } from "../server-process";
4
+
5
+ type Health = NonNullable<DeploymentRecord["health"]>;
6
+
7
+ /** What tsPLC's server answers on its health route; anything else there leaves the PLC unknown. */
8
+ const serverHealthSchema = z.looseObject({ plcConnected: z.boolean() });
9
+
10
+ /** How long the server's health route may take to answer. */
11
+ const healthTimeoutMs = 5000;
12
+
13
+ const plcHealth = (body: unknown): Health["plc"] => {
14
+ const parsed = serverHealthSchema.safeParse(body);
15
+ if (!parsed.success) {
16
+ return "unknown";
17
+ }
18
+ return parsed.data.plcConnected ? "ok" : "failed";
19
+ };
20
+
21
+ const serverHealth = async (
22
+ healthUrl: string | undefined,
23
+ server: ServerSupervisor,
24
+ ): Promise<Pick<Health, "server" | "plc">> => {
25
+ if (!healthUrl) {
26
+ return {
27
+ server: server.status()?.running ? "ok" : "failed",
28
+ plc: "unknown",
29
+ };
30
+ }
31
+ const response = await fetch(healthUrl, {
32
+ signal: AbortSignal.timeout(healthTimeoutMs),
33
+ }).catch(() => null);
34
+ if (!response?.ok) {
35
+ return { server: "failed", plc: "unknown" };
36
+ }
37
+ return {
38
+ server: "ok",
39
+ plc: plcHealth(await response.json().catch(() => null)),
40
+ };
41
+ };
42
+
43
+ const noServer: Pick<Health, "server" | "plc"> = {
44
+ server: "none",
45
+ plc: "unknown",
46
+ };
47
+
48
+ /**
49
+ * The check after a deployment applied: the controller runs its application, the release's server
50
+ * answers, and the server reaches the PLC.
51
+ */
52
+ export const checkHealth = async (options: {
53
+ /** The application's state in the controller's receipt. */
54
+ controllerState: string;
55
+ /** The release has a server, which the agent started. */
56
+ hasServer: boolean;
57
+ healthUrl: string | undefined;
58
+ server: ServerSupervisor;
59
+ }): Promise<Health> => {
60
+ const controller = options.controllerState === "run" ? "ok" : "failed";
61
+ const { server, plc } = options.hasServer
62
+ ? await serverHealth(options.healthUrl, options.server)
63
+ : noServer;
64
+ const problems = [
65
+ controller === "failed" &&
66
+ `The controller's application is in state ${options.controllerState}`,
67
+ server === "failed" && "The server isn't running",
68
+ plc === "failed" && "The server isn't connected to the PLC",
69
+ ].filter((problem) => typeof problem === "string");
70
+ return {
71
+ controller,
72
+ server,
73
+ plc,
74
+ detail: problems.length ? problems.join(". ") : null,
75
+ };
76
+ };
77
+
78
+ /** Whether a deployment with this health counts as ready; a server still connecting to the PLC doesn't fail it. */
79
+ export const healthy = (health: Health) =>
80
+ health.controller === "ok" && health.server !== "failed";
@@ -0,0 +1,45 @@
1
+ import type { Release } from "../protocol";
2
+ import { pruneReleases } from "../releases";
3
+ import { activeDeployments, type DeploymentStore, isFinished } from "./store";
4
+
5
+ /** Every deployment created within this long is kept. */
6
+ export const retentionMs = 14 * 24 * 60 * 60 * 1000;
7
+
8
+ /**
9
+ * Deletes the deployments created before the retention window, except the running one, the last
10
+ * healthy one and any not yet finished, then every release that no kept deployment and not the
11
+ * deployed release names. The deployed release's server may be an earlier release's.
12
+ */
13
+ export const pruneDeployments = async (options: {
14
+ store: DeploymentStore;
15
+ releases: string;
16
+ deployed: Release | null;
17
+ now: () => Date;
18
+ }) => {
19
+ const { store } = options;
20
+ const records = store.list();
21
+ const { current, lastGood } = activeDeployments(records);
22
+ const cutoff = options.now().getTime() - retentionMs;
23
+ const expired = records.filter(
24
+ (record) =>
25
+ Date.parse(record.createdAt) < cutoff &&
26
+ record.id !== current &&
27
+ record.id !== lastGood &&
28
+ isFinished(record),
29
+ );
30
+ for (const record of expired) {
31
+ await store.remove(record.id);
32
+ }
33
+ const kept = new Set(store.list().map((record) => record.release));
34
+ if (options.deployed) {
35
+ kept.add(options.deployed.id);
36
+ const server = options.deployed.server?.split("/")[0];
37
+ if (server) {
38
+ kept.add(server);
39
+ }
40
+ }
41
+ return {
42
+ deployments: expired.map((record) => record.id),
43
+ releases: await pruneReleases(options.releases, kept),
44
+ };
45
+ };
@@ -0,0 +1,273 @@
1
+ import { z } from "zod";
2
+ import { clientWarnings, requester } from "../deploy";
3
+ import {
4
+ approveSchema,
5
+ clientIdentity,
6
+ clientRelease,
7
+ type DeploymentLogLine,
8
+ type DeploymentRecord,
9
+ type deploymentCreatedSchema,
10
+ type deploymentListSchema,
11
+ type deploymentSourceSchema,
12
+ redeploySchema,
13
+ } from "../protocol";
14
+ import { type ReleaseStore, readDeployRequest } from "../releases";
15
+ import type { ApiRoute } from "../routes";
16
+ import type { DeploymentRunner } from "./runner";
17
+ import { type DeploymentEvent, isFinished } from "./store";
18
+
19
+ /** Server-sent events stay open through proxies that close a silent connection. */
20
+ const heartbeatMs = 15_000;
21
+
22
+ /** `?after=`, or the `Last-Event-ID` an `EventSource` reconnects with: the last log line it has. */
23
+ const afterSchema = z.coerce.number().int().nonnegative();
24
+
25
+ const after = (request: Request) =>
26
+ afterSchema.parse(
27
+ new URL(request.url).searchParams.get("after") ??
28
+ request.headers.get("last-event-id") ??
29
+ 0,
30
+ );
31
+
32
+ /** An open event stream's progress. */
33
+ interface EventStreamState {
34
+ open: boolean;
35
+ /** The last log line sent. */
36
+ sent: number;
37
+ /** Changes heard while the log is replayed, sent after it; null once it has been. */
38
+ held: DeploymentEvent[] | null;
39
+ stop: () => void;
40
+ }
41
+
42
+ /**
43
+ * The record, then its log after `from`, then each change until the deployment finishes, which
44
+ * ends the stream with the finished record.
45
+ */
46
+ const eventStream = (runner: DeploymentRunner, id: string, from: number) => {
47
+ runner.get(id);
48
+ const encoder = new TextEncoder();
49
+ const stream: EventStreamState = {
50
+ open: true,
51
+ sent: from,
52
+ held: [],
53
+ stop: () => {},
54
+ };
55
+ return new Response(
56
+ new ReadableStream({
57
+ start: async (controller) => {
58
+ const write = (text: string) => {
59
+ if (stream.open) {
60
+ controller.enqueue(encoder.encode(text));
61
+ }
62
+ };
63
+ const sendLine = (line: DeploymentLogLine) => {
64
+ if (line.seq <= stream.sent) {
65
+ return;
66
+ }
67
+ stream.sent = line.seq;
68
+ write(
69
+ `id: ${line.seq}\nevent: log\ndata: ${JSON.stringify(line)}\n\n`,
70
+ );
71
+ };
72
+ const end = () => {
73
+ if (stream.open) {
74
+ stream.stop();
75
+ controller.close();
76
+ }
77
+ };
78
+ const sendRecord = (record: DeploymentRecord) =>
79
+ write(`event: record\ndata: ${JSON.stringify(record)}\n\n`);
80
+ /** Sends the lines still on their way to disk, then the finished record last, and ends. */
81
+ const finish = () =>
82
+ runner.lines(id, stream.sent).then((lines) => {
83
+ lines.forEach(sendLine);
84
+ sendRecord(runner.get(id));
85
+ end();
86
+ }, end);
87
+ const deliver = (event: DeploymentEvent) => {
88
+ if (event.kind === "log") {
89
+ sendLine(event.line);
90
+ return;
91
+ }
92
+ if (isFinished(event.record)) {
93
+ void finish();
94
+ return;
95
+ }
96
+ sendRecord(event.record);
97
+ };
98
+ const unsubscribe = runner.subscribe(id, (event) => {
99
+ if (stream.held) {
100
+ stream.held.push(event);
101
+ return;
102
+ }
103
+ deliver(event);
104
+ });
105
+ const heartbeat = setInterval(
106
+ () => write(": heartbeat\n\n"),
107
+ heartbeatMs,
108
+ );
109
+ stream.stop = () => {
110
+ stream.open = false;
111
+ clearInterval(heartbeat);
112
+ unsubscribe();
113
+ };
114
+ // A finished deployment's record comes once, after its log.
115
+ if (!isFinished(runner.get(id))) {
116
+ sendRecord(runner.get(id));
117
+ }
118
+ (await runner.lines(id, from)).forEach(sendLine);
119
+ const held = stream.held ?? [];
120
+ stream.held = null;
121
+ held.forEach(deliver);
122
+ if (isFinished(runner.get(id))) {
123
+ void finish();
124
+ }
125
+ },
126
+ cancel: () => stream.stop(),
127
+ }),
128
+ {
129
+ headers: {
130
+ "Content-Type": "text/event-stream",
131
+ "Cache-Control": "no-cache",
132
+ },
133
+ },
134
+ );
135
+ };
136
+
137
+ /** The deployments API the dashboard and `tsplc deploy` use: `/api/deployments` and below. */
138
+ export const createDeploymentRoutes = (context: {
139
+ runner: DeploymentRunner;
140
+ releases: ReleaseStore;
141
+ }): ApiRoute[] => {
142
+ const { runner } = context;
143
+ const created = (request: Request, record: DeploymentRecord) =>
144
+ Response.json(
145
+ {
146
+ id: record.id,
147
+ url: `${new URL(request.url).origin}/deployments/${record.id}`,
148
+ } satisfies z.infer<typeof deploymentCreatedSchema>,
149
+ { status: 202 },
150
+ );
151
+ const id = (params: Readonly<Record<string, string>>) => params.id ?? "";
152
+ return [
153
+ {
154
+ method: "POST",
155
+ pattern: "/api/deployments",
156
+ role: "deployer",
157
+ handle: async (request, { identity }) => {
158
+ const warnings = await clientWarnings(clientRelease(request));
159
+ const { settings, upload } = await readDeployRequest(
160
+ context.releases,
161
+ request,
162
+ );
163
+ const record = await runner.submit(upload, {
164
+ git: settings.deployment?.git ?? null,
165
+ requestedBy: requester(identity, clientIdentity(request)),
166
+ mode: settings.deployment?.mode ?? "apply",
167
+ download: settings.download,
168
+ credentials: settings.credentials,
169
+ initializeUser: settings.initializeUser,
170
+ warnings,
171
+ });
172
+ return created(request, record);
173
+ },
174
+ },
175
+ {
176
+ method: "GET",
177
+ pattern: "/api/deployments",
178
+ role: "viewer",
179
+ handle: async () =>
180
+ Response.json(
181
+ runner.list() satisfies z.infer<typeof deploymentListSchema>,
182
+ ),
183
+ },
184
+ {
185
+ method: "GET",
186
+ pattern: "/api/deployments/:id",
187
+ role: "viewer",
188
+ handle: async (_request, { params }) =>
189
+ Response.json(runner.get(id(params))),
190
+ },
191
+ {
192
+ method: "GET",
193
+ pattern: "/api/deployments/:id/logs",
194
+ role: "viewer",
195
+ handle: async (request, { params }) =>
196
+ Response.json({
197
+ lines: await runner.lines(id(params), after(request)),
198
+ }),
199
+ },
200
+ {
201
+ method: "GET",
202
+ pattern: "/api/deployments/:id/events",
203
+ role: "viewer",
204
+ handle: async (request, { params }) =>
205
+ eventStream(runner, id(params), after(request)),
206
+ },
207
+ {
208
+ method: "POST",
209
+ pattern: "/api/deployments/:id/approve",
210
+ role: "deployer",
211
+ handle: async (request, { identity, params }) => {
212
+ const { download } = approveSchema.parse(await request.json());
213
+ return Response.json(
214
+ await runner.approve(id(params), download, identity.name),
215
+ );
216
+ },
217
+ },
218
+ {
219
+ method: "POST",
220
+ pattern: "/api/deployments/:id/cancel",
221
+ role: "deployer",
222
+ handle: async (_request, { identity, params }) =>
223
+ Response.json(await runner.cancel(id(params), identity.name)),
224
+ },
225
+ {
226
+ method: "POST",
227
+ pattern: "/api/deployments/:id/redeploy",
228
+ role: "deployer",
229
+ handle: async (request, { identity, params }) => {
230
+ const { mode } = redeploySchema.parse(await request.json());
231
+ return created(
232
+ request,
233
+ await runner.redeploy(
234
+ id(params),
235
+ mode,
236
+ requester(identity, clientIdentity(request)),
237
+ ),
238
+ );
239
+ },
240
+ },
241
+ {
242
+ method: "POST",
243
+ pattern: "/api/deployments/:id/rollback",
244
+ role: "deployer",
245
+ handle: async (request, { identity, params }) =>
246
+ created(
247
+ request,
248
+ await runner.rollback(
249
+ id(params),
250
+ requester(identity, clientIdentity(request)),
251
+ ),
252
+ ),
253
+ },
254
+ {
255
+ method: "GET",
256
+ pattern: "/api/deployments/:id/source",
257
+ role: "viewer",
258
+ handle: async (_request, { params }) =>
259
+ Response.json({
260
+ files: await runner.source(id(params)),
261
+ } satisfies z.infer<typeof deploymentSourceSchema>),
262
+ },
263
+ {
264
+ method: "GET",
265
+ pattern: "/api/deployments/:id/source/*",
266
+ role: "viewer",
267
+ handle: async (_request, { params }) =>
268
+ new Response(await runner.sourceFile(id(params), params["*"] ?? ""), {
269
+ headers: { "Content-Type": "text/plain; charset=utf-8" },
270
+ }),
271
+ },
272
+ ];
273
+ };