@tsplc/agent 0.2.13 → 0.2.16
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.
- package/dist/cli.js +310 -36
- package/dist/cli.js.map +7 -6
- package/dist/client.js +33 -5
- package/dist/client.js.map +4 -4
- package/dist/index.js +310 -35
- package/dist/index.js.map +6 -5
- package/package.json +4 -3
- package/src/agent.ts +281 -22
- package/src/cli.ts +9 -1
- package/src/client.ts +7 -2
- package/src/logs.ts +39 -0
- package/src/protocol.ts +46 -2
package/src/agent.ts
CHANGED
|
@@ -6,28 +6,47 @@ import { join } from "node:path";
|
|
|
6
6
|
import { setTimeout as delay } from "node:timers/promises";
|
|
7
7
|
import { promisify } from "node:util";
|
|
8
8
|
import {
|
|
9
|
+
type ControllerLogin,
|
|
9
10
|
explicitDownload,
|
|
11
|
+
failureReason,
|
|
10
12
|
findControllerLogin,
|
|
11
13
|
gatewayImage,
|
|
14
|
+
type LoginCommand,
|
|
12
15
|
loginCommandSchema,
|
|
13
16
|
openControllerLogin,
|
|
14
17
|
resolveConfig,
|
|
15
18
|
startWarmController,
|
|
16
19
|
updateWarmController,
|
|
17
20
|
} from "@tsplc/build";
|
|
21
|
+
import {
|
|
22
|
+
createDebugger,
|
|
23
|
+
createDebugHandler,
|
|
24
|
+
createLoginAdapter,
|
|
25
|
+
type Debugger,
|
|
26
|
+
loadManifest,
|
|
27
|
+
LoginUnavailable,
|
|
28
|
+
noLogin,
|
|
29
|
+
timelineEntries,
|
|
30
|
+
} from "@tsplc/debug";
|
|
18
31
|
import { z } from "zod";
|
|
19
32
|
import { discoverControllers, networkInterfaces } from "./discovery";
|
|
20
33
|
import {
|
|
21
34
|
type AgentEvent,
|
|
22
35
|
type AgentStatus,
|
|
36
|
+
type Audit,
|
|
37
|
+
auditSchema,
|
|
38
|
+
clientHeaders,
|
|
23
39
|
type Credentials,
|
|
24
40
|
credentialsSchema,
|
|
41
|
+
type Deployment,
|
|
42
|
+
deploymentSchema,
|
|
25
43
|
deployOptionsSchema,
|
|
26
44
|
type Release,
|
|
27
45
|
releaseSchema,
|
|
28
46
|
type Target,
|
|
29
47
|
targetSchema,
|
|
30
48
|
} from "./protocol";
|
|
49
|
+
import { appendJsonl, readJsonl } from "./logs";
|
|
31
50
|
import { loadRelease, readUpload, saveRelease } from "./releases";
|
|
32
51
|
import { createServerSupervisor } from "./server-process";
|
|
33
52
|
|
|
@@ -63,6 +82,49 @@ class AgentError extends Error {
|
|
|
63
82
|
|
|
64
83
|
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
65
84
|
|
|
85
|
+
const message = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
|
86
|
+
|
|
87
|
+
/** A login's state comes back within a second; one that takes this long waits on a hung worker. */
|
|
88
|
+
const loginStateTimeout = 30_000;
|
|
89
|
+
const stoppedAnswering = { error: "The login stopped answering" };
|
|
90
|
+
|
|
91
|
+
/** Log entries a new debugger starts its timeline with. */
|
|
92
|
+
const recentEntries = 500;
|
|
93
|
+
|
|
94
|
+
/** Who sent a request, as the client reports it. */
|
|
95
|
+
const clientOf = (request: Request) => {
|
|
96
|
+
const header = (name: string) => request.headers.get(name)?.slice(0, 200) || undefined;
|
|
97
|
+
return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/** How an audited login command reads in the log, or nothing for commands that only read. */
|
|
101
|
+
const auditOf = (command: LoginCommand) => {
|
|
102
|
+
switch (command.command) {
|
|
103
|
+
case "write":
|
|
104
|
+
case "force":
|
|
105
|
+
return { command: command.command, values: command.values };
|
|
106
|
+
case "unforce":
|
|
107
|
+
return {
|
|
108
|
+
command: command.restore ? "unforce --restore" : "unforce",
|
|
109
|
+
values: Object.fromEntries(command.expressions.map((expression) => [expression, ""])),
|
|
110
|
+
};
|
|
111
|
+
case "start":
|
|
112
|
+
case "stop":
|
|
113
|
+
return { command: command.command, values: {} };
|
|
114
|
+
case "reset":
|
|
115
|
+
return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
|
|
116
|
+
case "state":
|
|
117
|
+
case "read":
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
const matches = (presented: string, token: string) => {
|
|
123
|
+
const actual = Buffer.from(presented);
|
|
124
|
+
const expected = Buffer.from(token);
|
|
125
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
126
|
+
};
|
|
127
|
+
|
|
66
128
|
const readJson = async <T>(path: string, schema: z.ZodType<T>) =>
|
|
67
129
|
existsSync(path) ? schema.parse(JSON.parse(await readFile(path, "utf8"))) : null;
|
|
68
130
|
|
|
@@ -149,6 +211,8 @@ export interface AgentOptions {
|
|
|
149
211
|
/** Releases, the controller's download baseline and the selected target live here. */
|
|
150
212
|
state: string;
|
|
151
213
|
token: string;
|
|
214
|
+
/** Accepted only for the debugger (`/debug/*`) and `GET /status`. */
|
|
215
|
+
readToken?: string;
|
|
152
216
|
/** The deployed server's health route; without it a server that stays up 5 s counts as started. */
|
|
153
217
|
serverHealthUrl?: string;
|
|
154
218
|
log: (message: string) => void;
|
|
@@ -161,6 +225,9 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
161
225
|
controller: join(options.state, "controller"),
|
|
162
226
|
release: join(options.state, "release.json"),
|
|
163
227
|
target: join(options.state, "target.json"),
|
|
228
|
+
deployments: join(options.state, "deployments.jsonl"),
|
|
229
|
+
audit: join(options.state, "audit.jsonl"),
|
|
230
|
+
debug: join(options.state, "debug"),
|
|
164
231
|
};
|
|
165
232
|
await mkdir(options.state, { recursive: true });
|
|
166
233
|
const server = createServerSupervisor({ healthUrl: options.serverHealthUrl, log: options.log });
|
|
@@ -206,6 +273,88 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
206
273
|
);
|
|
207
274
|
});
|
|
208
275
|
|
|
276
|
+
/** Login commands, the debugger's reads among them, run one at a time. */
|
|
277
|
+
let loginGeneration = 0;
|
|
278
|
+
let commands: Promise<unknown> = Promise.resolve();
|
|
279
|
+
const enqueue = <Result>(run: () => Promise<Result>) => {
|
|
280
|
+
const generation = loginGeneration;
|
|
281
|
+
const sent = commands.then(() => {
|
|
282
|
+
if (generation !== loginGeneration) throw new AgentError("The login was closed", 409);
|
|
283
|
+
return run();
|
|
284
|
+
});
|
|
285
|
+
commands = sent.catch(() => undefined);
|
|
286
|
+
return sent;
|
|
287
|
+
};
|
|
288
|
+
const send = (login: ControllerLogin, loginCommand: LoginCommand) =>
|
|
289
|
+
enqueue(() => login.send(loginCommand));
|
|
290
|
+
|
|
291
|
+
/** What the debugger reads through: the open login, which it never opens itself. */
|
|
292
|
+
const readLogin = async ([first, ...rest]: string[]) => {
|
|
293
|
+
if (busy === "a login")
|
|
294
|
+
throw new LoginUnavailable("The engineering login is opening", { state: "connecting" });
|
|
295
|
+
if (busy) throw new LoginUnavailable(`Live values pause during ${busy}`);
|
|
296
|
+
const login = await findControllerLogin(loginContainer);
|
|
297
|
+
if (!login) throw new LoginUnavailable(noLogin);
|
|
298
|
+
if (!first) return {};
|
|
299
|
+
const result = await send(login, { command: "read", expressions: [first, ...rest] });
|
|
300
|
+
if (!("values" in result)) throw new Error("The login answered a read without values");
|
|
301
|
+
return result.values;
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* The deployed release's debugger, when it has a debug manifest. It reads the controller
|
|
306
|
+
* through the agent's engineering login, and the server's telemetry and requests through the
|
|
307
|
+
* server's health origin.
|
|
308
|
+
*/
|
|
309
|
+
const startDebugger = async () => {
|
|
310
|
+
const release = await readJson(paths.release, releaseSchema);
|
|
311
|
+
if (!release) return null;
|
|
312
|
+
const { directory, manifest: releaseManifest } = await loadRelease(paths.releases, release.id);
|
|
313
|
+
const manifestFile = join(directory, "debug.json");
|
|
314
|
+
if (!existsSync(manifestFile)) return null;
|
|
315
|
+
const manifest = await loadManifest(manifestFile);
|
|
316
|
+
const serverToken =
|
|
317
|
+
releaseManifest.serverTokenEnv && process.env[releaseManifest.serverTokenEnv];
|
|
318
|
+
const debug = await createDebugger({
|
|
319
|
+
manifest,
|
|
320
|
+
adapter: createLoginAdapter({
|
|
321
|
+
read: readLogin,
|
|
322
|
+
probe: manifest.build.target,
|
|
323
|
+
endpoint: "the agent's login",
|
|
324
|
+
}),
|
|
325
|
+
stateDirectory: paths.debug,
|
|
326
|
+
watch: releaseManifest.debug?.watch ?? {},
|
|
327
|
+
...(options.serverHealthUrl &&
|
|
328
|
+
serverToken && {
|
|
329
|
+
server: { url: new URL(options.serverHealthUrl).origin, token: serverToken },
|
|
330
|
+
}),
|
|
331
|
+
release: { id: release.id, deployedAt: release.deployedAt, operation: release.operation },
|
|
332
|
+
timeline: [
|
|
333
|
+
...(await readJsonl(paths.deployments, deploymentSchema, recentEntries)).map(
|
|
334
|
+
({ at, ...deployment }) => timelineEntries.deploy(at, deployment),
|
|
335
|
+
),
|
|
336
|
+
...(await readJsonl(paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) =>
|
|
337
|
+
timelineEntries.audit(at, audit),
|
|
338
|
+
),
|
|
339
|
+
],
|
|
340
|
+
log: options.log,
|
|
341
|
+
});
|
|
342
|
+
return { debug, handle: createDebugHandler(debug, options.log) };
|
|
343
|
+
};
|
|
344
|
+
type Debugging = { debug: Debugger; handle: ReturnType<typeof createDebugHandler> } | null;
|
|
345
|
+
const debuggerFailed = (error: unknown): Debugging => {
|
|
346
|
+
options.log(`Starting the debugger failed: ${message(error)}`);
|
|
347
|
+
return null;
|
|
348
|
+
};
|
|
349
|
+
let debugging: Promise<Debugging> = startDebugger().catch(debuggerFailed);
|
|
350
|
+
/** Replaces the debugger after the release changes. */
|
|
351
|
+
const restartDebugger = () => {
|
|
352
|
+
debugging = debugging.then(async (current) => {
|
|
353
|
+
await current?.debug.close();
|
|
354
|
+
return startDebugger().catch(debuggerFailed);
|
|
355
|
+
});
|
|
356
|
+
};
|
|
357
|
+
|
|
209
358
|
/** Streams one exclusive operation's events, then its result, as newline-delimited JSON. */
|
|
210
359
|
const operation = (
|
|
211
360
|
name: string,
|
|
@@ -250,7 +399,7 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
250
399
|
);
|
|
251
400
|
};
|
|
252
401
|
|
|
253
|
-
const deploy = async (form: FormData) => {
|
|
402
|
+
const deploy = async (form: FormData, client: ReturnType<typeof clientOf>) => {
|
|
254
403
|
const settings = deployOptionsSchema.parse(JSON.parse(z.string().parse(form.get("options"))));
|
|
255
404
|
const upload = await readUpload(form);
|
|
256
405
|
const target = await requireTarget();
|
|
@@ -303,6 +452,16 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
303
452
|
server: serverPath ?? previous?.server,
|
|
304
453
|
};
|
|
305
454
|
await writeFile(paths.release, JSON.stringify(deployedRelease, null, 2));
|
|
455
|
+
const debugManifest = join(release.directory, "debug.json");
|
|
456
|
+
const deployment: Deployment = {
|
|
457
|
+
at: deployedRelease.deployedAt,
|
|
458
|
+
release: release.id,
|
|
459
|
+
...(existsSync(debugManifest) && { build: (await loadManifest(debugManifest)).build.id }),
|
|
460
|
+
operation: kind,
|
|
461
|
+
...client,
|
|
462
|
+
};
|
|
463
|
+
await appendJsonl(paths.deployments, deployment);
|
|
464
|
+
restartDebugger();
|
|
306
465
|
return deployedRelease;
|
|
307
466
|
});
|
|
308
467
|
};
|
|
@@ -318,28 +477,87 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
318
477
|
const login = await withCredentials(credentials, () =>
|
|
319
478
|
openControllerLogin(config, loginContainer),
|
|
320
479
|
);
|
|
321
|
-
return
|
|
480
|
+
return send(login, { command: "state" });
|
|
322
481
|
});
|
|
323
482
|
};
|
|
324
483
|
|
|
325
484
|
const requireLogin = async () => {
|
|
485
|
+
if (busy) throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
486
|
+
const generation = loginGeneration;
|
|
326
487
|
const login = await findControllerLogin(loginContainer);
|
|
488
|
+
if (generation !== loginGeneration) throw new AgentError("The login was closed", 409);
|
|
489
|
+
if (busy) throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
327
490
|
if (!login) throw new AgentError("No login is open: tsplc login", 409);
|
|
328
491
|
return login;
|
|
329
492
|
};
|
|
330
493
|
|
|
331
|
-
|
|
494
|
+
/** Runs a login command; one that changes the controller goes to the audit log, with the values it replaces. */
|
|
495
|
+
const command = async (loginCommand: LoginCommand, client: ReturnType<typeof clientOf>) => {
|
|
496
|
+
const login = await requireLogin();
|
|
497
|
+
const change = auditOf(loginCommand);
|
|
498
|
+
if (!change) return send(login, loginCommand);
|
|
499
|
+
return enqueue(async () => {
|
|
500
|
+
const [first, ...rest] = Object.keys(change.values);
|
|
501
|
+
// Without the old values the command is still worth running and recording.
|
|
502
|
+
const previous = first
|
|
503
|
+
? await login
|
|
504
|
+
.send({ command: "read", expressions: [first, ...rest] })
|
|
505
|
+
.then((result) => ("values" in result ? result.values : undefined))
|
|
506
|
+
.catch(() => undefined)
|
|
507
|
+
: undefined;
|
|
508
|
+
const audit = async (error?: unknown) => {
|
|
509
|
+
const entry: Audit = {
|
|
510
|
+
at: new Date().toISOString(),
|
|
511
|
+
...change,
|
|
512
|
+
...(previous && { previous }),
|
|
513
|
+
...client,
|
|
514
|
+
release: (await readJson(paths.release, releaseSchema))?.id,
|
|
515
|
+
...(error !== undefined && { error: message(error) }),
|
|
516
|
+
};
|
|
517
|
+
await appendJsonl(paths.audit, entry);
|
|
518
|
+
const { at, ...details } = entry;
|
|
519
|
+
(await debugging)?.debug.record(timelineEntries.audit(at, details));
|
|
520
|
+
};
|
|
521
|
+
try {
|
|
522
|
+
const result = await login.send(loginCommand);
|
|
523
|
+
await audit();
|
|
524
|
+
return result;
|
|
525
|
+
} catch (error) {
|
|
526
|
+
await audit(error);
|
|
527
|
+
throw error;
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
};
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* The open login's state. A login that lost the controller, or whose worker died or hangs, is
|
|
534
|
+
* reported as failed, so the CLI can log it out and open a new one.
|
|
535
|
+
*/
|
|
536
|
+
const loginStatus = async (): Promise<AgentStatus["login"]> => {
|
|
332
537
|
const login = await findControllerLogin(loginContainer);
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
538
|
+
if (!login) return null;
|
|
539
|
+
if (!(await login.ready()))
|
|
540
|
+
// A login still opening has its container but doesn't answer yet.
|
|
541
|
+
return busy === "a login" ? null : stoppedAnswering;
|
|
542
|
+
try {
|
|
543
|
+
const state = await Promise.race([
|
|
544
|
+
send(login, { command: "state" }),
|
|
545
|
+
delay(loginStateTimeout, null),
|
|
546
|
+
]);
|
|
547
|
+
if (!state) return stoppedAnswering;
|
|
548
|
+
return "state" in state ? state : null;
|
|
549
|
+
} catch (error) {
|
|
550
|
+
return { error: failureReason(error) };
|
|
551
|
+
}
|
|
341
552
|
};
|
|
342
553
|
|
|
554
|
+
const status = async (): Promise<AgentStatus> => ({
|
|
555
|
+
target: await readJson(paths.target, targetSchema),
|
|
556
|
+
release: await readJson(paths.release, releaseSchema),
|
|
557
|
+
server: server.status() ?? null,
|
|
558
|
+
login: await loginStatus(),
|
|
559
|
+
});
|
|
560
|
+
|
|
343
561
|
const route = async (request: Request): Promise<Response> => {
|
|
344
562
|
const { pathname } = new URL(request.url);
|
|
345
563
|
const key = `${request.method} ${pathname}`;
|
|
@@ -362,28 +580,66 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
362
580
|
case "GET /variables":
|
|
363
581
|
return json((await currentRelease()).manifest.variables);
|
|
364
582
|
case "POST /deploy":
|
|
365
|
-
return deploy(await request.formData());
|
|
583
|
+
return deploy(await request.formData(), clientOf(request));
|
|
366
584
|
case "POST /login":
|
|
367
585
|
return openLogin(credentialsSchema.parse(await request.json()));
|
|
368
586
|
case "POST /login/command":
|
|
369
587
|
return json(
|
|
370
|
-
await (
|
|
588
|
+
await command(loginCommandSchema.parse(await request.json()), clientOf(request)),
|
|
371
589
|
);
|
|
372
|
-
case "DELETE /login":
|
|
373
|
-
|
|
374
|
-
|
|
590
|
+
case "DELETE /login": {
|
|
591
|
+
const login = await requireLogin();
|
|
592
|
+
busy = "a logout";
|
|
593
|
+
loginGeneration++;
|
|
594
|
+
try {
|
|
595
|
+
const failure = await login.close();
|
|
596
|
+
commands = Promise.resolve();
|
|
597
|
+
if (failure)
|
|
598
|
+
options.log(`The login couldn't log out (${failure}); its container was removed`);
|
|
599
|
+
return json(failure ? { failure } : {});
|
|
600
|
+
} finally {
|
|
601
|
+
busy = undefined;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
375
604
|
default:
|
|
376
605
|
return json({ error: `No route ${key}` }, 404);
|
|
377
606
|
}
|
|
378
607
|
};
|
|
379
608
|
|
|
380
|
-
|
|
609
|
+
/** The debugger's UI and API under `/debug`. */
|
|
610
|
+
const debugRoute = async (request: Request, route: string) => {
|
|
611
|
+
const current = await debugging;
|
|
612
|
+
if (!current)
|
|
613
|
+
return json(
|
|
614
|
+
{ error: "The deployed release has no debug manifest, or the debugger failed to start" },
|
|
615
|
+
503,
|
|
616
|
+
);
|
|
617
|
+
return current.handle(request, route);
|
|
618
|
+
};
|
|
619
|
+
|
|
381
620
|
return {
|
|
382
621
|
fetch: async (request: Request) => {
|
|
383
|
-
const
|
|
384
|
-
|
|
385
|
-
|
|
622
|
+
const { pathname, search, searchParams } = new URL(request.url);
|
|
623
|
+
const debugPath = pathname.startsWith("/debug/");
|
|
624
|
+
// The UI's relative links need the trailing slash.
|
|
625
|
+
if (pathname === "/debug")
|
|
626
|
+
return new Response(null, { status: 308, headers: { Location: `/debug/${search}` } });
|
|
627
|
+
// The page and its script hold no data, and a browser loads the script without the token.
|
|
628
|
+
if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js"))
|
|
629
|
+
return debugRoute(request, pathname.slice("/debug".length));
|
|
630
|
+
// EventSource can't send headers, so the debugger also takes `?token=`.
|
|
631
|
+
const presented =
|
|
632
|
+
/^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ??
|
|
633
|
+
(debugPath ? searchParams.get("token") : null) ??
|
|
634
|
+
"";
|
|
635
|
+
const full = matches(presented, options.token);
|
|
636
|
+
const read =
|
|
637
|
+
options.readToken !== undefined &&
|
|
638
|
+
matches(presented, options.readToken) &&
|
|
639
|
+
(debugPath || (request.method === "GET" && pathname === "/status"));
|
|
640
|
+
if (!full && !read) return json({ error: "Unauthorized" }, 401);
|
|
386
641
|
try {
|
|
642
|
+
if (debugPath) return await debugRoute(request, pathname.slice("/debug".length));
|
|
387
643
|
return await route(request);
|
|
388
644
|
} catch (error) {
|
|
389
645
|
if (error instanceof AgentError) return json({ error: error.message }, error.status);
|
|
@@ -394,7 +650,10 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
394
650
|
return json({ error: error instanceof Error ? error.message : String(error) }, 500);
|
|
395
651
|
}
|
|
396
652
|
},
|
|
397
|
-
/** Stops the supervised server; a login container keeps running for the next agent. */
|
|
398
|
-
stop: () =>
|
|
653
|
+
/** Stops the debugger and the supervised server; a login container keeps running for the next agent. */
|
|
654
|
+
stop: async () => {
|
|
655
|
+
await (await debugging)?.debug.close();
|
|
656
|
+
await server.stop();
|
|
657
|
+
},
|
|
399
658
|
};
|
|
400
659
|
};
|
package/src/cli.ts
CHANGED
|
@@ -11,7 +11,8 @@ const usage = `tsplc-agent setup|serve [--listen host:port] [--state directory]
|
|
|
11
11
|
setup Builds the CODESYS builder and gateway images. Run it once, and after updating tsPLC.
|
|
12
12
|
serve Serves deployments and logins. --listen is required: use the machine's Tailscale
|
|
13
13
|
address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
|
|
14
|
-
at least 32 characters, such as one from \`openssl rand -hex 32
|
|
14
|
+
at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
|
|
15
|
+
TSPLC_AGENT_READ_TOKEN, as long, only opens the debugger at /debug and GET /status.`;
|
|
15
16
|
|
|
16
17
|
const { values, positionals } = parseArgs({
|
|
17
18
|
allowPositionals: true,
|
|
@@ -38,9 +39,16 @@ if (command === "setup") {
|
|
|
38
39
|
.string({ error: "Set TSPLC_AGENT_TOKEN" })
|
|
39
40
|
.min(32, "TSPLC_AGENT_TOKEN must be at least 32 characters")
|
|
40
41
|
.parse(process.env["TSPLC_AGENT_TOKEN"]);
|
|
42
|
+
const readToken = z
|
|
43
|
+
.string()
|
|
44
|
+
.min(32, "TSPLC_AGENT_READ_TOKEN must be at least 32 characters")
|
|
45
|
+
.refine((value) => value !== token, "TSPLC_AGENT_READ_TOKEN must differ from TSPLC_AGENT_TOKEN")
|
|
46
|
+
.optional()
|
|
47
|
+
.parse(process.env["TSPLC_AGENT_READ_TOKEN"]);
|
|
41
48
|
const agent = await createAgent({
|
|
42
49
|
state: values.state ?? join(homedir(), ".tsplc-agent"),
|
|
43
50
|
token,
|
|
51
|
+
readToken,
|
|
44
52
|
serverHealthUrl: values["server-health"],
|
|
45
53
|
log: (message) => console.log(`${new Date().toISOString()} ${message}`),
|
|
46
54
|
});
|
package/src/client.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { hostname, userInfo } from "node:os";
|
|
1
2
|
import { type LoginCommand, loginResultSchema } from "@tsplc/build";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
import {
|
|
4
5
|
type AgentEvent,
|
|
6
|
+
clientHeaders,
|
|
5
7
|
controllerSchema,
|
|
6
8
|
type Credentials,
|
|
7
9
|
type DeployOptions,
|
|
8
10
|
eventSchema,
|
|
11
|
+
logoutSchema,
|
|
9
12
|
networkInterfaceSchema,
|
|
10
13
|
type ReleaseManifest,
|
|
11
14
|
releaseSchema,
|
|
@@ -34,10 +37,12 @@ export interface ReleaseFile {
|
|
|
34
37
|
|
|
35
38
|
/** Talks to a plant agent at `url`, such as its Tailscale name and port. */
|
|
36
39
|
export const createAgentClient = (options: { url: string; token: string }) => {
|
|
40
|
+
// The agent records who deployed and who changed the controller.
|
|
41
|
+
const identity = { [clientHeaders.user]: userInfo().username, [clientHeaders.host]: hostname() };
|
|
37
42
|
const call = async (path: string, init: RequestInit = {}) => {
|
|
38
43
|
const response = await fetch(new URL(path, options.url), {
|
|
39
44
|
...init,
|
|
40
|
-
headers: { ...init.headers, Authorization: `Bearer ${options.token}` },
|
|
45
|
+
headers: { ...init.headers, ...identity, Authorization: `Bearer ${options.token}` },
|
|
41
46
|
}).catch((cause: unknown) => {
|
|
42
47
|
throw new Error(`Cannot reach the plant agent at ${options.url}`, { cause });
|
|
43
48
|
});
|
|
@@ -121,7 +126,7 @@ export const createAgentClient = (options: { url: string; token: string }) => {
|
|
|
121
126
|
),
|
|
122
127
|
),
|
|
123
128
|
command: (command: LoginCommand) => send("POST", "/login/command", command, loginResultSchema),
|
|
124
|
-
logout: () => send("DELETE", "/login", undefined,
|
|
129
|
+
logout: () => send("DELETE", "/login", undefined, logoutSchema),
|
|
125
130
|
};
|
|
126
131
|
};
|
|
127
132
|
export type AgentClient = ReturnType<typeof createAgentClient>;
|
package/src/logs.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { open, readFile, rename, stat } from "node:fs/promises";
|
|
3
|
+
import type { z } from "zod";
|
|
4
|
+
|
|
5
|
+
/** A log rotates to `<file>.1`, replacing the one before, once it reaches this size. */
|
|
6
|
+
const rotateBytes = 5 * 2 ** 20;
|
|
7
|
+
|
|
8
|
+
/** Appends one JSON line to an append-only log, keeping it and its rotated copy bounded. */
|
|
9
|
+
export const appendJsonl = async (file: string, value: unknown) => {
|
|
10
|
+
if (existsSync(file) && (await stat(file)).size >= rotateBytes) await rename(file, `${file}.1`);
|
|
11
|
+
const log = await open(file, "a+");
|
|
12
|
+
try {
|
|
13
|
+
const { size } = await log.stat();
|
|
14
|
+
const last = Buffer.alloc(1);
|
|
15
|
+
if (size) await log.read(last, 0, 1, size - 1);
|
|
16
|
+
// A crash may leave a partial line; keep the next complete entry separate from it.
|
|
17
|
+
const separator = size && last[0] !== 10 ? "\n" : "";
|
|
18
|
+
await log.writeFile(`${separator}${JSON.stringify(value)}\n`);
|
|
19
|
+
} finally {
|
|
20
|
+
await log.close();
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** The newest `limit` lines of a log, oldest first. */
|
|
25
|
+
export const readJsonl = async <T>(file: string, schema: z.ZodType<T>, limit: number) => {
|
|
26
|
+
if (!existsSync(file)) return [];
|
|
27
|
+
return (await readFile(file, "utf8"))
|
|
28
|
+
.split("\n")
|
|
29
|
+
.filter(Boolean)
|
|
30
|
+
.slice(-limit)
|
|
31
|
+
.flatMap((line) => {
|
|
32
|
+
// A crash can leave the last line half written; it is skipped.
|
|
33
|
+
try {
|
|
34
|
+
return [schema.parse(JSON.parse(line))];
|
|
35
|
+
} catch {
|
|
36
|
+
return [];
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
};
|
package/src/protocol.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { tsplcConfigSchema } from "@tsplc/config";
|
|
1
2
|
import { z } from "zod";
|
|
2
3
|
|
|
3
4
|
/** The controller the agent deploys to, as its runtime's TCP block driver address. */
|
|
@@ -42,6 +43,10 @@ export const releaseManifestSchema = z.strictObject({
|
|
|
42
43
|
variables: z.array(variableSchema),
|
|
43
44
|
/** The server executable's path in the release, when the project builds one. */
|
|
44
45
|
server: z.string().nonempty().optional(),
|
|
46
|
+
/** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */
|
|
47
|
+
debug: tsplcConfigSchema.shape.debug,
|
|
48
|
+
/** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */
|
|
49
|
+
serverTokenEnv: z.string().nonempty().optional(),
|
|
45
50
|
});
|
|
46
51
|
export type ReleaseManifest = z.infer<typeof releaseManifestSchema>;
|
|
47
52
|
|
|
@@ -83,7 +88,46 @@ export const statusSchema = z.strictObject({
|
|
|
83
88
|
target: targetSchema.nullable(),
|
|
84
89
|
release: releaseSchema.nullable(),
|
|
85
90
|
server: z.strictObject({ executable: z.string(), running: z.boolean() }).nullable(),
|
|
86
|
-
/** The open login's application state and forced expressions. */
|
|
87
|
-
login: z
|
|
91
|
+
/** The open login's application state and forced expressions, or why it can't report them. */
|
|
92
|
+
login: z
|
|
93
|
+
.union([
|
|
94
|
+
z.strictObject({ state: z.string(), forced: z.array(z.string()) }),
|
|
95
|
+
z.strictObject({ error: z.string() }),
|
|
96
|
+
])
|
|
97
|
+
.nullable(),
|
|
88
98
|
});
|
|
89
99
|
export type AgentStatus = z.infer<typeof statusSchema>;
|
|
100
|
+
|
|
101
|
+
/** A logout's result: why the login couldn't log out, when its container had to be removed instead. */
|
|
102
|
+
export const logoutSchema = z.strictObject({ failure: z.string().optional() });
|
|
103
|
+
|
|
104
|
+
/** Who ran a command, as the client reports it in these headers. */
|
|
105
|
+
export const clientHeaders = { user: "x-tsplc-user", host: "x-tsplc-host" } as const;
|
|
106
|
+
|
|
107
|
+
/** A line of the agent's `deployments.jsonl`. */
|
|
108
|
+
export const deploymentSchema = z.strictObject({
|
|
109
|
+
at: z.iso.datetime(),
|
|
110
|
+
release: z.string(),
|
|
111
|
+
/** The debug manifest's build id, when the release has one. */
|
|
112
|
+
build: z.string().optional(),
|
|
113
|
+
operation: z.enum(["download", "online-change"]),
|
|
114
|
+
user: z.string().optional(),
|
|
115
|
+
host: z.string().optional(),
|
|
116
|
+
});
|
|
117
|
+
export type Deployment = z.infer<typeof deploymentSchema>;
|
|
118
|
+
|
|
119
|
+
/** A line of the agent's `audit.jsonl`: a login command that changed the controller. */
|
|
120
|
+
export const auditSchema = z.strictObject({
|
|
121
|
+
at: z.iso.datetime(),
|
|
122
|
+
/** As typed after `tsplc`, such as `force` or `reset cold`. */
|
|
123
|
+
command: z.string(),
|
|
124
|
+
/** Expressions written or forced, with their values; unforced expressions map to "". */
|
|
125
|
+
values: z.record(z.string(), z.string()),
|
|
126
|
+
/** The values read just before the command, when the read succeeded. */
|
|
127
|
+
previous: z.record(z.string(), z.string()).optional(),
|
|
128
|
+
user: z.string().optional(),
|
|
129
|
+
host: z.string().optional(),
|
|
130
|
+
release: z.string().optional(),
|
|
131
|
+
error: z.string().optional(),
|
|
132
|
+
});
|
|
133
|
+
export type Audit = z.infer<typeof auditSchema>;
|