@tsplc/tmp-agent 0.0.0-stage → 0.6.2
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/README.md +26 -2
- package/dist/cli.js +4888 -0
- package/dist/cli.js.map +53 -0
- package/dist/client.js +514 -0
- package/dist/client.js.map +12 -0
- package/dist/index.js +3680 -0
- package/dist/index.js.map +41 -0
- package/package.json +61 -4
- package/src/access.ts +260 -0
- package/src/agent.ts +461 -0
- package/src/audit.ts +74 -0
- package/src/cli.ts +290 -0
- package/src/client.ts +407 -0
- package/src/codesys.ts +195 -0
- package/src/dashboard/index.ts +159 -0
- package/src/dashboard/ui/access.ts +191 -0
- package/src/dashboard/ui/actions.ts +207 -0
- package/src/dashboard/ui/api.ts +138 -0
- package/src/dashboard/ui/app.ts +41 -0
- package/src/dashboard/ui/approval.ts +131 -0
- package/src/dashboard/ui/audit.ts +115 -0
- package/src/dashboard/ui/contract.ts +19 -0
- package/src/dashboard/ui/dashboard.css +1332 -0
- package/src/dashboard/ui/deployment.ts +431 -0
- package/src/dashboard/ui/deployments.ts +319 -0
- package/src/dashboard/ui/details.ts +214 -0
- package/src/dashboard/ui/dom.ts +87 -0
- package/src/dashboard/ui/environment.ts +345 -0
- package/src/dashboard/ui/format.ts +124 -0
- package/src/dashboard/ui/logs.ts +126 -0
- package/src/dashboard/ui/main.ts +88 -0
- package/src/dashboard/ui/overlay.ts +144 -0
- package/src/dashboard/ui/shell.ts +185 -0
- package/src/dashboard/ui/source.ts +144 -0
- package/src/debugging.ts +142 -0
- package/src/deploy.ts +203 -0
- package/src/deployments/health.ts +98 -0
- package/src/deployments/retention.ts +44 -0
- package/src/deployments/routes.ts +281 -0
- package/src/deployments/runner.ts +900 -0
- package/src/deployments/store.ts +209 -0
- package/src/deployments/submission.ts +78 -0
- package/src/discovery.ts +90 -0
- package/src/environment.ts +214 -0
- package/src/errors.ts +12 -0
- package/src/index.ts +36 -0
- package/src/instance.ts +51 -0
- package/src/login.ts +267 -0
- package/src/logs.ts +115 -0
- package/src/maintenance.ts +303 -0
- package/src/operations.ts +149 -0
- package/src/processes.ts +41 -0
- package/src/protocol.ts +557 -0
- package/src/releases.ts +414 -0
- package/src/restarts.ts +96 -0
- package/src/routes.ts +128 -0
- package/src/secrets.ts +174 -0
- package/src/server-process.ts +264 -0
- package/src/service.ts +194 -0
- package/src/sessions.ts +58 -0
- package/src/state.ts +126 -0
- package/src/tailscale.ts +112 -0
- package/src/terminal.ts +57 -0
- package/src/transfer.ts +94 -0
- package/src/upgrade.ts +153 -0
package/src/state.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { mkdir, readFile } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { AgentError } from "./errors";
|
|
7
|
+
import {
|
|
8
|
+
type Release,
|
|
9
|
+
releaseSchema,
|
|
10
|
+
type Target,
|
|
11
|
+
targetSchema,
|
|
12
|
+
} from "./protocol";
|
|
13
|
+
import { loadRelease } from "./releases";
|
|
14
|
+
|
|
15
|
+
/** The text of the file at `path`, or null when there is none. Failing to read it is an error. */
|
|
16
|
+
export const readTextIfPresent = (path: string) =>
|
|
17
|
+
readFile(path, "utf8").catch((error: unknown) => {
|
|
18
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
throw error;
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
/** The JSON file at `path`, checked against `schema`, or null when there is none. */
|
|
25
|
+
export const readJsonFile = async <T>(path: string, schema: z.ZodType<T>) => {
|
|
26
|
+
const text = await readTextIfPresent(path);
|
|
27
|
+
return text === null ? null : schema.parse(JSON.parse(text));
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The JSON file at `path`, or null when there is none or its content isn't `schema`'s, such as a
|
|
32
|
+
* record an agent of another version wrote. Failing to read it is an error.
|
|
33
|
+
*/
|
|
34
|
+
export const readJsonFileIfValid = <T>(path: string, schema: z.ZodType<T>) =>
|
|
35
|
+
readJsonFile(path, schema).catch((error: unknown) => {
|
|
36
|
+
if (error instanceof SyntaxError || error instanceof z.ZodError) {
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
throw error;
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Replaces the JSON file at `path` whole, before anything else runs: a reader never sees half of
|
|
44
|
+
* it, and each write has a temporary file of its own, so writers in other processes don't collide.
|
|
45
|
+
*/
|
|
46
|
+
export const writeJsonFile = (path: string, value: unknown) => {
|
|
47
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
48
|
+
writeFileSync(temporary, JSON.stringify(value, null, 2));
|
|
49
|
+
renameSync(temporary, path);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** Each file and directory of the agent's state directory `directory`. */
|
|
53
|
+
export const statePaths = (directory: string) => ({
|
|
54
|
+
releases: join(directory, "releases"),
|
|
55
|
+
controller: join(directory, "controller"),
|
|
56
|
+
/** The deploying release's ST with its secrets filled in. */
|
|
57
|
+
sources: join(directory, "sources"),
|
|
58
|
+
release: join(directory, "release.json"),
|
|
59
|
+
target: join(directory, "target.json"),
|
|
60
|
+
deployments: join(directory, "deployments.jsonl"),
|
|
61
|
+
/** Each deployment's record and log, under its id. */
|
|
62
|
+
deploymentRecords: join(directory, "deployments"),
|
|
63
|
+
audit: join(directory, "audit.jsonl"),
|
|
64
|
+
/** Who on the tailnet has which role. */
|
|
65
|
+
access: join(directory, "access.json"),
|
|
66
|
+
/**
|
|
67
|
+
* The names the dashboard stored by Bun.secrets service, since Bun.secrets can't list a
|
|
68
|
+
* service's names. Never a value.
|
|
69
|
+
*/
|
|
70
|
+
environment: join(directory, "environment.json"),
|
|
71
|
+
/** The plain variables set on this PC, by name. */
|
|
72
|
+
variables: join(directory, "variables.json"),
|
|
73
|
+
debug: join(directory, "debug"),
|
|
74
|
+
/** The running server's process, for the agent that takes it over. */
|
|
75
|
+
server: join(directory, "server.json"),
|
|
76
|
+
/** The running agent: its process, address and serve arguments. */
|
|
77
|
+
agent: join(directory, "agent.json"),
|
|
78
|
+
logs: join(directory, "logs"),
|
|
79
|
+
/** The server's output. */
|
|
80
|
+
serverLog: join(directory, "logs", "server.log"),
|
|
81
|
+
/** The agent's output when `tsplc-agent service run` or `upgrade` starts it. */
|
|
82
|
+
agentLog: join(directory, "logs", "agent.log"),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The agent's state directory: releases, the controller's download baseline, the selected
|
|
87
|
+
* target, the deployed release and the logs.
|
|
88
|
+
*/
|
|
89
|
+
export const openState = async (directory: string) => {
|
|
90
|
+
const paths = statePaths(directory);
|
|
91
|
+
await mkdir(paths.logs, { recursive: true });
|
|
92
|
+
|
|
93
|
+
const target = () => readJsonFile(paths.target, targetSchema);
|
|
94
|
+
const release = () => readJsonFile(paths.release, releaseSchema);
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
paths,
|
|
98
|
+
/** The selected controller, or null before `tsplc target`. */
|
|
99
|
+
target,
|
|
100
|
+
setTarget: async (selected: Target) =>
|
|
101
|
+
writeJsonFile(paths.target, selected),
|
|
102
|
+
requireTarget: async () => {
|
|
103
|
+
const selected = await target();
|
|
104
|
+
if (!selected) {
|
|
105
|
+
throw new AgentError("Select the controller first: tsplc target", 409);
|
|
106
|
+
}
|
|
107
|
+
return selected;
|
|
108
|
+
},
|
|
109
|
+
/** The deployed release, or null before the first deployment. */
|
|
110
|
+
release,
|
|
111
|
+
setRelease: async (deployed: Release) =>
|
|
112
|
+
writeJsonFile(paths.release, deployed),
|
|
113
|
+
/** The deployed release's files and manifest. */
|
|
114
|
+
requireRelease: async () => {
|
|
115
|
+
const deployed = await release();
|
|
116
|
+
if (!deployed) {
|
|
117
|
+
throw new AgentError(
|
|
118
|
+
"Nothing has been deployed yet: tsplc deploy",
|
|
119
|
+
409,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
return loadRelease(paths.releases, deployed.id);
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
export type AgentState = Awaited<ReturnType<typeof openState>>;
|
package/src/tailscale.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { BlockList, isIP } from "node:net";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { errorMessage } from "./errors";
|
|
4
|
+
|
|
5
|
+
const tailnet = new BlockList();
|
|
6
|
+
tailnet.addSubnet("100.64.0.0", 10, "ipv4");
|
|
7
|
+
tailnet.addSubnet("fd7a:115c:a1e0::", 48, "ipv6");
|
|
8
|
+
const loopback = new BlockList();
|
|
9
|
+
loopback.addSubnet("127.0.0.0", 8, "ipv4");
|
|
10
|
+
loopback.addAddress("::1", "ipv6");
|
|
11
|
+
|
|
12
|
+
/** Where a peer address is: this PC, a Tailscale address, or anywhere else. */
|
|
13
|
+
export const peerKind = (address: string) => {
|
|
14
|
+
const version = isIP(address);
|
|
15
|
+
if (version === 0) {
|
|
16
|
+
return "other";
|
|
17
|
+
}
|
|
18
|
+
const family = version === 6 ? "ipv6" : "ipv4";
|
|
19
|
+
if (loopback.check(address, family)) {
|
|
20
|
+
return "loopback";
|
|
21
|
+
}
|
|
22
|
+
return tailnet.check(address, family) ? "tailnet" : "other";
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** A Tailscale user, as `tailscale whois` names them. */
|
|
26
|
+
export interface TailnetUser {
|
|
27
|
+
login: string;
|
|
28
|
+
name: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The part of `tailscale whois --json` the agent reads; Tailscale adds fields between versions. */
|
|
32
|
+
const whoisSchema = z.object({
|
|
33
|
+
UserProfile: z.object({
|
|
34
|
+
LoginName: z.string().nonempty(),
|
|
35
|
+
DisplayName: z.string(),
|
|
36
|
+
}),
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
/** Runs a command to completion, with its standard output. */
|
|
40
|
+
export type RunCommand = (
|
|
41
|
+
command: string[],
|
|
42
|
+
) => Promise<{ exitCode: number; stdout: string }>;
|
|
43
|
+
|
|
44
|
+
export const runCommand: RunCommand = async (command) => {
|
|
45
|
+
const child = Bun.spawn(command, {
|
|
46
|
+
stdout: "pipe",
|
|
47
|
+
stderr: "ignore",
|
|
48
|
+
timeout: 5000,
|
|
49
|
+
});
|
|
50
|
+
const [stdout, exitCode] = await Promise.all([
|
|
51
|
+
new Response(child.stdout).text(),
|
|
52
|
+
child.exited,
|
|
53
|
+
]);
|
|
54
|
+
return { stdout, exitCode };
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** How long a lookup's answer, a user or none, is reused. */
|
|
58
|
+
export const whoisCacheMs = 60_000;
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Who owns a tailnet address, from the local `tailscale` CLI, or null when it can't say: the
|
|
62
|
+
* address isn't a member's, or Tailscale isn't installed or running.
|
|
63
|
+
*/
|
|
64
|
+
export const createWhois = (context: {
|
|
65
|
+
run: RunCommand;
|
|
66
|
+
now: () => number;
|
|
67
|
+
log: (message: string) => void;
|
|
68
|
+
}) => {
|
|
69
|
+
const cache = new Map<
|
|
70
|
+
string,
|
|
71
|
+
{ expires: number; user: Promise<TailnetUser | null> }
|
|
72
|
+
>();
|
|
73
|
+
|
|
74
|
+
const lookUp = async (address: string) => {
|
|
75
|
+
try {
|
|
76
|
+
const { exitCode, stdout } = await context.run([
|
|
77
|
+
"tailscale",
|
|
78
|
+
"whois",
|
|
79
|
+
"--json",
|
|
80
|
+
address,
|
|
81
|
+
]);
|
|
82
|
+
if (exitCode !== 0) {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
const { UserProfile } = whoisSchema.parse(JSON.parse(stdout));
|
|
86
|
+
return {
|
|
87
|
+
login: UserProfile.LoginName,
|
|
88
|
+
name: UserProfile.DisplayName || UserProfile.LoginName,
|
|
89
|
+
};
|
|
90
|
+
} catch (error) {
|
|
91
|
+
context.log(`tailscale whois ${address} failed: ${errorMessage(error)}`);
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
return (address: string): Promise<TailnetUser | null> => {
|
|
97
|
+
const now = context.now();
|
|
98
|
+
for (const [cached, { expires }] of cache) {
|
|
99
|
+
if (expires <= now) {
|
|
100
|
+
cache.delete(cached);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const known = cache.get(address);
|
|
104
|
+
if (known) {
|
|
105
|
+
return known.user;
|
|
106
|
+
}
|
|
107
|
+
const user = lookUp(address);
|
|
108
|
+
cache.set(address, { expires: now + whoisCacheMs, user });
|
|
109
|
+
return user;
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
export type Whois = ReturnType<typeof createWhois>;
|
package/src/terminal.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { createInterface } from "node:readline/promises";
|
|
2
|
+
import type { Credentials } from "./protocol";
|
|
3
|
+
|
|
4
|
+
export const ask = async (question: string) => {
|
|
5
|
+
const lines = createInterface({
|
|
6
|
+
input: process.stdin,
|
|
7
|
+
output: process.stdout,
|
|
8
|
+
});
|
|
9
|
+
try {
|
|
10
|
+
return (await lines.question(question)).trim();
|
|
11
|
+
} finally {
|
|
12
|
+
lines.close();
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** Reads a line without echoing it. */
|
|
17
|
+
export const askSecret = (question: string) =>
|
|
18
|
+
new Promise<string>((accept, reject) => {
|
|
19
|
+
if (!process.stdin.isTTY) {
|
|
20
|
+
reject(new Error("Typing a secret needs an interactive terminal."));
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
// Echo goes off before the prompt appears, so nothing typed at it can show.
|
|
24
|
+
process.stdin.setRawMode(true);
|
|
25
|
+
process.stdin.setEncoding("utf8");
|
|
26
|
+
process.stdin.resume();
|
|
27
|
+
process.stdout.write(question);
|
|
28
|
+
let secret = "";
|
|
29
|
+
const finish = () => {
|
|
30
|
+
process.stdin.off("data", read);
|
|
31
|
+
process.stdin.setRawMode(false);
|
|
32
|
+
process.stdin.pause();
|
|
33
|
+
process.stdout.write("\n");
|
|
34
|
+
};
|
|
35
|
+
const read = (text: string) => {
|
|
36
|
+
for (const character of text) {
|
|
37
|
+
if (character === "\r" || character === "\n") {
|
|
38
|
+
finish();
|
|
39
|
+
accept(secret);
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (character === "\u0003") {
|
|
43
|
+
finish();
|
|
44
|
+
reject(new Error("Cancelled."));
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
secret =
|
|
48
|
+
character === "\u007f" ? secret.slice(0, -1) : secret + character;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
process.stdin.on("data", read);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
export const askCredentials = async (): Promise<Credentials> => ({
|
|
55
|
+
username: await ask("Controller username: "),
|
|
56
|
+
password: await askSecret("Controller password: "),
|
|
57
|
+
});
|
package/src/transfer.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { releaseBuckets } from "./protocol";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* How `tsplc deploy` sends a release the agent can build from one it already holds. The release's
|
|
6
|
+
* files fall into buckets by path, and each bucket has a digest; the agent answers which buckets
|
|
7
|
+
* differ from a release it stores and that release's files in them, and the client sends only the
|
|
8
|
+
* files the agent lacks, with the release's other parts named rather than sent. The whole upload
|
|
9
|
+
* is one zstd stream: the release's ST files are thousands of small, similar files.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** A file of a release, at its path in the release. */
|
|
13
|
+
export interface ReleaseContent {
|
|
14
|
+
path: string;
|
|
15
|
+
content: Uint8Array<ArrayBuffer>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The first 16 hex digits of a SHA-256: enough to tell a release's files apart, and short on the wire. */
|
|
19
|
+
export const shortDigest = (data: Uint8Array | string) =>
|
|
20
|
+
createHash("sha256").update(data).digest("hex").slice(0, 16);
|
|
21
|
+
|
|
22
|
+
/** The bucket a release path falls in, the same in every release. */
|
|
23
|
+
export const fileBucket = (path: string) =>
|
|
24
|
+
createHash("sha256").update(path).digest().readUInt8(0) % releaseBuckets;
|
|
25
|
+
|
|
26
|
+
/** Each bucket's digest over the paths and contents of its files, from each file's `shortDigest`. */
|
|
27
|
+
export const bucketDigests = (
|
|
28
|
+
files: Iterable<{ path: string; digest: string }>,
|
|
29
|
+
): string[] => {
|
|
30
|
+
const buckets = Array.from({ length: releaseBuckets }, (): string[] => []);
|
|
31
|
+
for (const { path, digest } of files) {
|
|
32
|
+
buckets[fileBucket(path)]?.push(`${path}\0${digest}`);
|
|
33
|
+
}
|
|
34
|
+
return buckets.map((entries) => shortDigest(entries.sort().join("\n")));
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** A frame's length prefix: an unsigned 32-bit big-endian byte count. */
|
|
38
|
+
const lengthBytes = 4;
|
|
39
|
+
|
|
40
|
+
/** Frames the upload's header and then each file's path and content, and compresses the lot. */
|
|
41
|
+
export const encodeUpload = async (
|
|
42
|
+
header: unknown,
|
|
43
|
+
files: readonly ReleaseContent[],
|
|
44
|
+
): Promise<Uint8Array<ArrayBuffer>> => {
|
|
45
|
+
const encoder = new TextEncoder();
|
|
46
|
+
const frames = [
|
|
47
|
+
encoder.encode(JSON.stringify(header)),
|
|
48
|
+
...files.flatMap(({ path, content }) => [encoder.encode(path), content]),
|
|
49
|
+
];
|
|
50
|
+
const body = new Uint8Array(
|
|
51
|
+
frames.reduce((total, frame) => total + lengthBytes + frame.length, 0),
|
|
52
|
+
);
|
|
53
|
+
const view = new DataView(body.buffer);
|
|
54
|
+
let offset = 0;
|
|
55
|
+
for (const frame of frames) {
|
|
56
|
+
view.setUint32(offset, frame.length);
|
|
57
|
+
body.set(frame, offset + lengthBytes);
|
|
58
|
+
offset += lengthBytes + frame.length;
|
|
59
|
+
}
|
|
60
|
+
return new Uint8Array(await Bun.zstdCompress(body, { level: 12 }));
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** An upload's header, still to be validated, and its files. */
|
|
64
|
+
export const decodeUpload = async (
|
|
65
|
+
compressed: Uint8Array,
|
|
66
|
+
): Promise<{ header: unknown; files: ReleaseContent[] }> => {
|
|
67
|
+
const body = new Uint8Array(await Bun.zstdDecompress(compressed));
|
|
68
|
+
const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
|
|
69
|
+
const frames: Uint8Array<ArrayBuffer>[] = [];
|
|
70
|
+
let offset = 0;
|
|
71
|
+
while (offset < body.length) {
|
|
72
|
+
if (offset + lengthBytes > body.length) {
|
|
73
|
+
throw new Error("The release upload ends inside a frame");
|
|
74
|
+
}
|
|
75
|
+
const end = offset + lengthBytes + view.getUint32(offset);
|
|
76
|
+
if (end > body.length) {
|
|
77
|
+
throw new Error("The release upload ends inside a frame");
|
|
78
|
+
}
|
|
79
|
+
frames.push(body.subarray(offset + lengthBytes, end));
|
|
80
|
+
offset = end;
|
|
81
|
+
}
|
|
82
|
+
const [header, ...rest] = frames;
|
|
83
|
+
if (!header || rest.length % 2 !== 0) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
"The release upload has no header or a file without content",
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
const decoder = new TextDecoder();
|
|
89
|
+
const files = Array.from({ length: rest.length / 2 }, (_, index) => ({
|
|
90
|
+
path: decoder.decode(rest[2 * index]),
|
|
91
|
+
content: rest[2 * index + 1] ?? new Uint8Array(),
|
|
92
|
+
}));
|
|
93
|
+
return { header: JSON.parse(decoder.decode(header)), files };
|
|
94
|
+
};
|
package/src/upgrade.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { AgentControl, Instance } from "./instance";
|
|
3
|
+
|
|
4
|
+
/** A version or dist-tag of @tsplc/agent, which goes into an install command. */
|
|
5
|
+
export const versionSchema = z
|
|
6
|
+
.string()
|
|
7
|
+
.regex(
|
|
8
|
+
/^[0-9A-Za-z][0-9A-Za-z.+-]*$/,
|
|
9
|
+
"Name a version, such as 0.5.0, or a dist-tag, such as latest",
|
|
10
|
+
);
|
|
11
|
+
|
|
12
|
+
/** The package manager whose global install holds the running agent. */
|
|
13
|
+
export type PackageManager = "bun" | "npm";
|
|
14
|
+
|
|
15
|
+
const normalize = (path: string) =>
|
|
16
|
+
path.replaceAll("\\", "/").replace(/\/+$/, "").toLowerCase();
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The package manager whose global install holds the agent package at `packagePath`, such as
|
|
20
|
+
* `C:\Users\plant\.bun\install\global\node_modules\@tsplc\agent`, or null for a project or
|
|
21
|
+
* source checkout, which `upgrade` leaves to whoever installed it. `npmGlobalRoot` is
|
|
22
|
+
* `npm root --global`, or null without npm.
|
|
23
|
+
*/
|
|
24
|
+
export const packageManagerFor = (
|
|
25
|
+
packagePath: string,
|
|
26
|
+
npmGlobalRoot: string | null,
|
|
27
|
+
): PackageManager | null => {
|
|
28
|
+
const path = normalize(packagePath);
|
|
29
|
+
if (path.endsWith("/install/global/node_modules/@tsplc/agent")) {
|
|
30
|
+
return "bun";
|
|
31
|
+
}
|
|
32
|
+
if (
|
|
33
|
+
npmGlobalRoot !== null &&
|
|
34
|
+
path === `${normalize(npmGlobalRoot)}/@tsplc/agent`
|
|
35
|
+
) {
|
|
36
|
+
return "npm";
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** npm with `args` on `platform`, where npm is a batch file on Windows that only cmd runs. */
|
|
42
|
+
export const npmCommand = (platform: NodeJS.Platform, ...args: string[]) =>
|
|
43
|
+
platform === "win32"
|
|
44
|
+
? ["cmd.exe", "/d", "/s", "/c", "npm", ...args]
|
|
45
|
+
: ["npm", ...args];
|
|
46
|
+
|
|
47
|
+
/** The command that installs @tsplc/agent at `version` globally with `manager`. */
|
|
48
|
+
export const installCommand = (
|
|
49
|
+
manager: PackageManager,
|
|
50
|
+
version: string,
|
|
51
|
+
host: { bun: string; platform: NodeJS.Platform },
|
|
52
|
+
) => {
|
|
53
|
+
// The spec reaches cmd on Windows, so it is only ever a version or tag.
|
|
54
|
+
const spec = `@tsplc/agent@${versionSchema.parse(version)}`;
|
|
55
|
+
if (manager === "bun") {
|
|
56
|
+
return [host.bun, "add", "--global", spec];
|
|
57
|
+
}
|
|
58
|
+
return npmCommand(host.platform, "install", "--global", spec);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** What `upgrade` does to the system, so its sequence can be followed without one. */
|
|
62
|
+
export interface UpgradeEffects {
|
|
63
|
+
/** Runs a command on this terminal and returns its exit status. */
|
|
64
|
+
run: (command: string[]) => Promise<number>;
|
|
65
|
+
/** The version of the agent package now installed. */
|
|
66
|
+
installedVersion: () => Promise<string>;
|
|
67
|
+
/** Starts an agent that no service starts again, once `instance` has exited. */
|
|
68
|
+
startAgent: (instance: Instance) => Promise<void>;
|
|
69
|
+
/** Starts the installed service; false when none is installed. */
|
|
70
|
+
startService: () => Promise<boolean>;
|
|
71
|
+
/** Whether an agent of `version` answers within a few minutes. */
|
|
72
|
+
answers: (version: string) => Promise<boolean>;
|
|
73
|
+
print: (line: string) => void;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Installs another version of the agent and runs it, without interrupting a deployment, touching
|
|
78
|
+
* the controller or stopping the line's server. A running agent is held first, which fails while
|
|
79
|
+
* an operation runs or a login is open, then installs, runs the new version's setup (nothing,
|
|
80
|
+
* unless its image recipe changed), and is replaced by the new version, which takes over the
|
|
81
|
+
* line's server and starts CODESYS again with its own code.
|
|
82
|
+
*/
|
|
83
|
+
export const upgradeAgent = async (
|
|
84
|
+
request: {
|
|
85
|
+
version: string;
|
|
86
|
+
install: string[];
|
|
87
|
+
/** The installed version's setup, which builds only images that need it. */
|
|
88
|
+
setup: string[];
|
|
89
|
+
running: { instance: Instance; control: AgentControl } | null;
|
|
90
|
+
/** Where an agent `upgrade` starts writes its output. */
|
|
91
|
+
agentLog: string;
|
|
92
|
+
},
|
|
93
|
+
effects: UpgradeEffects,
|
|
94
|
+
) => {
|
|
95
|
+
const { running } = request;
|
|
96
|
+
if (running) {
|
|
97
|
+
effects.print(
|
|
98
|
+
`Holding tsplc-agent ${running.instance.version} (process ${running.instance.pid}): it takes no deployments or logins until the new version runs`,
|
|
99
|
+
);
|
|
100
|
+
await running.control.hold();
|
|
101
|
+
}
|
|
102
|
+
const installed = await (async () => {
|
|
103
|
+
if ((await effects.run(request.install)) !== 0) {
|
|
104
|
+
throw new Error(
|
|
105
|
+
`Installing @tsplc/agent@${request.version} failed; see the output above`,
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
const version = await effects.installedVersion();
|
|
109
|
+
if (running?.instance.version === version) {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
effects.print(`Installed tsplc-agent ${version}; checking its images`);
|
|
113
|
+
if ((await effects.run(request.setup)) !== 0) {
|
|
114
|
+
throw new Error(
|
|
115
|
+
`tsplc-agent ${version} is installed, but its setup failed; see the output above. Run tsplc-agent upgrade ${version} again once it can`,
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
return version;
|
|
119
|
+
})().catch(async (error: unknown) => {
|
|
120
|
+
await running?.control.releaseHold();
|
|
121
|
+
throw error;
|
|
122
|
+
});
|
|
123
|
+
if (installed === null) {
|
|
124
|
+
await running?.control.releaseHold();
|
|
125
|
+
effects.print(
|
|
126
|
+
`tsplc-agent ${running?.instance.version} is installed and running already`,
|
|
127
|
+
);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
if (!running) {
|
|
131
|
+
if (!(await effects.startService())) {
|
|
132
|
+
effects.print(
|
|
133
|
+
`tsplc-agent ${installed} is installed. No agent was running: start it with tsplc-agent serve, or install the service with tsplc-agent service install`,
|
|
134
|
+
);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
effects.print("Started the tsplc-agent service");
|
|
138
|
+
} else {
|
|
139
|
+
effects.print(
|
|
140
|
+
`Restarting the agent; the line's server keeps running and CODESYS starts again in the background`,
|
|
141
|
+
);
|
|
142
|
+
await running.control.exit({ server: "leave", restart: true });
|
|
143
|
+
if (!running.instance.supervised) {
|
|
144
|
+
await effects.startAgent(running.instance);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (!(await effects.answers(installed))) {
|
|
148
|
+
throw new Error(
|
|
149
|
+
`tsplc-agent ${installed} is installed but doesn't answer; see ${request.agentLog}`,
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
effects.print(`tsplc-agent ${installed} is running`);
|
|
153
|
+
};
|