@tsplc/agent 0.4.4 → 0.5.1

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/src/service.ts ADDED
@@ -0,0 +1,206 @@
1
+ import { closeSync, existsSync, openSync } from "node:fs";
2
+ import { appendFile, rename, stat } from "node:fs/promises";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { restartStatus } from "./instance";
5
+
6
+ /** The Task Scheduler task that runs the agent as a service. */
7
+ export const serviceName = "tsplc-agent";
8
+
9
+ /** Set in the environment of a `serve` that `service run` started, which says so in its record. */
10
+ export const supervisedEnv = "TSPLC_AGENT_SUPERVISED";
11
+
12
+ /** An agent log rotates to `<file>.1`, replacing the one before, once it reaches this size. */
13
+ const rotateBytes = 10 * 2 ** 20;
14
+
15
+ /**
16
+ * One argument of a Windows command line, quoted so that a program's C runtime
17
+ * (CommandLineToArgvW) reads it back unchanged: backslashes double only before a quote.
18
+ */
19
+ export const quoteWindowsArgument = (argument: string) => {
20
+ if (argument !== "" && !/[\s"]/.test(argument)) {
21
+ return argument;
22
+ }
23
+ const escaped = argument
24
+ .replace(/(\\*)"/g, '$1$1\\"')
25
+ .replace(/(\\+)$/, "$1$1");
26
+ return `"${escaped}"`;
27
+ };
28
+
29
+ const escapeXml = (text: string) =>
30
+ text
31
+ .replaceAll("&", "&amp;")
32
+ .replaceAll("<", "&lt;")
33
+ .replaceAll(">", "&gt;")
34
+ .replaceAll('"', "&quot;");
35
+
36
+ /**
37
+ * The Task Scheduler definition of the agent's service: `bun script service run <serve…>` as
38
+ * `user`, at boot whether or not anyone logs on, so the line's server runs after a power cut.
39
+ * The password logon keeps the user's Credential Manager, where Bun.secrets keeps the agent's
40
+ * token, readable. `service run` restarts the agent itself; Task Scheduler restarts `service run`
41
+ * if it fails to start. It runs without a time limit, and only one at a time.
42
+ */
43
+ export const taskDefinition = (task: {
44
+ bun: string;
45
+ script: string;
46
+ serve: string[];
47
+ user: string;
48
+ workingDirectory: string;
49
+ }) => {
50
+ const argumentsText = [task.script, "service", "run", ...task.serve]
51
+ .map(quoteWindowsArgument)
52
+ .join(" ");
53
+ return `<?xml version="1.0" encoding="UTF-16"?>
54
+ <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
55
+ <RegistrationInfo>
56
+ <Description>tsPLC plant agent: deploys to the controller and runs the line's server</Description>
57
+ </RegistrationInfo>
58
+ <Triggers>
59
+ <BootTrigger>
60
+ <Enabled>true</Enabled>
61
+ </BootTrigger>
62
+ </Triggers>
63
+ <Principals>
64
+ <Principal id="Author">
65
+ <UserId>${escapeXml(task.user)}</UserId>
66
+ <LogonType>Password</LogonType>
67
+ <RunLevel>LeastPrivilege</RunLevel>
68
+ </Principal>
69
+ </Principals>
70
+ <Settings>
71
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
72
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
73
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
74
+ <AllowHardTerminate>true</AllowHardTerminate>
75
+ <StartWhenAvailable>true</StartWhenAvailable>
76
+ <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
77
+ <IdleSettings>
78
+ <StopOnIdleEnd>false</StopOnIdleEnd>
79
+ <RestartOnIdle>false</RestartOnIdle>
80
+ </IdleSettings>
81
+ <AllowStartOnDemand>true</AllowStartOnDemand>
82
+ <Enabled>true</Enabled>
83
+ <Hidden>false</Hidden>
84
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
85
+ <WakeToRun>false</WakeToRun>
86
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
87
+ <Priority>7</Priority>
88
+ <RestartOnFailure>
89
+ <Interval>PT1M</Interval>
90
+ <Count>999</Count>
91
+ </RestartOnFailure>
92
+ </Settings>
93
+ <Actions Context="Author">
94
+ <Exec>
95
+ <Command>${escapeXml(task.bun)}</Command>
96
+ <Arguments>${escapeXml(argumentsText)}</Arguments>
97
+ <WorkingDirectory>${escapeXml(task.workingDirectory)}</WorkingDirectory>
98
+ </Exec>
99
+ </Actions>
100
+ </Task>
101
+ `;
102
+ };
103
+
104
+ /** A task definition as `schtasks /XML` reads it: UTF-16 with a byte order mark. */
105
+ export const taskFile = (definition: string) =>
106
+ Buffer.concat([
107
+ Buffer.from([0xff, 0xfe]),
108
+ Buffer.from(definition, "utf16le"),
109
+ ]);
110
+
111
+ /** The schtasks commands the service's lifecycle runs, as Task Scheduler names them. */
112
+ export const schtasks = {
113
+ /** Registers `file` as `user`; schtasks asks for the password, which it keeps for boot. */
114
+ create: (file: string, user: string) => [
115
+ "schtasks",
116
+ "/Create",
117
+ "/TN",
118
+ serviceName,
119
+ "/XML",
120
+ file,
121
+ "/RU",
122
+ user,
123
+ "/RP",
124
+ "*",
125
+ "/F",
126
+ ],
127
+ run: () => ["schtasks", "/Run", "/TN", serviceName],
128
+ end: () => ["schtasks", "/End", "/TN", serviceName],
129
+ remove: () => ["schtasks", "/Delete", "/TN", serviceName, "/F"],
130
+ query: () => ["schtasks", "/Query", "/TN", serviceName, "/FO", "LIST", "/V"],
131
+ };
132
+
133
+ /** An agent that ran this long before it failed is started again at once. */
134
+ const steadyMs = 60_000;
135
+
136
+ /** How long `service run` waits before starting an agent that failed again. */
137
+ export const restartDelay = (exits: {
138
+ /** How long the agent that failed ran. */
139
+ ranMs: number;
140
+ /** How many agents in a row, this one included, failed within `steadyMs` of starting. */
141
+ quickExits: number;
142
+ }) => {
143
+ if (exits.ranMs >= steadyMs) {
144
+ return 1000;
145
+ }
146
+ return Math.min(5000 * 2 ** (exits.quickExits - 1), 60_000);
147
+ };
148
+
149
+ /** Appends a timestamped line to the agent log. */
150
+ const logLine = (file: string, message: string) =>
151
+ appendFile(file, `${new Date().toISOString()} ${message}\n`);
152
+
153
+ const rotate = async (file: string) => {
154
+ if (existsSync(file) && (await stat(file)).size >= rotateBytes) {
155
+ await rename(file, `${file}.1`);
156
+ }
157
+ };
158
+
159
+ /**
160
+ * Runs `serve` with `arguments`, writing its output to `log`, and starts it again whenever it
161
+ * exits: at once when it exits to be restarted, as after an upgrade, which re-reads the installed
162
+ * agent; after a growing delay when it fails; never when it exits as asked to stop.
163
+ */
164
+ export const superviseAgent = async (options: {
165
+ command: string[];
166
+ log: string;
167
+ /** Waits between restarts; real time by default. */
168
+ wait?: (milliseconds: number) => Promise<unknown>;
169
+ }) => {
170
+ const wait = options.wait ?? delay;
171
+ let quickExits = 0;
172
+ while (true) {
173
+ await rotate(options.log);
174
+ await logLine(options.log, `Starting ${options.command.join(" ")}`);
175
+ const output = openSync(options.log, "a");
176
+ const started = Date.now();
177
+ const child = (() => {
178
+ try {
179
+ return Bun.spawn(options.command, {
180
+ stdio: ["ignore", output, output],
181
+ env: { ...process.env, [supervisedEnv]: "1" },
182
+ });
183
+ } finally {
184
+ closeSync(output);
185
+ }
186
+ })();
187
+ const status = await child.exited;
188
+ const ranMs = Date.now() - started;
189
+ if (status === 0) {
190
+ await logLine(options.log, "The agent stopped as asked");
191
+ return;
192
+ }
193
+ if (status === restartStatus) {
194
+ quickExits = 0;
195
+ await logLine(options.log, "The agent exited to restart");
196
+ continue;
197
+ }
198
+ quickExits = ranMs < steadyMs ? quickExits + 1 : 0;
199
+ const pause = restartDelay({ ranMs, quickExits });
200
+ await logLine(
201
+ options.log,
202
+ `The agent exited (${status}); starting it again in ${pause / 1000} s`,
203
+ );
204
+ await wait(pause);
205
+ }
206
+ };
package/src/state.ts CHANGED
@@ -34,8 +34,17 @@ export const openState = async (directory: string) => {
34
34
  deployments: join(directory, "deployments.jsonl"),
35
35
  audit: join(directory, "audit.jsonl"),
36
36
  debug: join(directory, "debug"),
37
+ /** The running server's process, for the agent that takes it over. */
38
+ server: join(directory, "server.json"),
39
+ /** The running agent: its process, address and serve arguments. */
40
+ agent: join(directory, "agent.json"),
41
+ logs: join(directory, "logs"),
42
+ /** The server's output. */
43
+ serverLog: join(directory, "logs", "server.log"),
44
+ /** The agent's output when `tsplc-agent service run` or `upgrade` starts it. */
45
+ agentLog: join(directory, "logs", "agent.log"),
37
46
  };
38
- await mkdir(directory, { recursive: true });
47
+ await mkdir(paths.logs, { recursive: true });
39
48
 
40
49
  const target = () => readJsonFile(paths.target, targetSchema);
41
50
  const release = () => readJsonFile(paths.release, releaseSchema);
package/src/upgrade.ts ADDED
@@ -0,0 +1,149 @@
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
+ /** The command that installs @tsplc/agent at `version` globally with `manager`. */
42
+ export const installCommand = (
43
+ manager: PackageManager,
44
+ version: string,
45
+ host: { bun: string; platform: NodeJS.Platform },
46
+ ) => {
47
+ const spec = `@tsplc/agent@${versionSchema.parse(version)}`;
48
+ if (manager === "bun") {
49
+ return [host.bun, "add", "--global", spec];
50
+ }
51
+ // npm is a batch file on Windows, which only cmd runs; the spec is validated above.
52
+ return host.platform === "win32"
53
+ ? ["cmd.exe", "/d", "/s", "/c", "npm", "install", "--global", spec]
54
+ : ["npm", "install", "--global", spec];
55
+ };
56
+
57
+ /** What `upgrade` does to the system, so its sequence can be followed without one. */
58
+ export interface UpgradeEffects {
59
+ /** Runs a command on this terminal and returns its exit status. */
60
+ run: (command: string[]) => Promise<number>;
61
+ /** The version of the agent package now installed. */
62
+ installedVersion: () => Promise<string>;
63
+ /** Starts an agent that no service starts again, once `instance` has exited. */
64
+ startAgent: (instance: Instance) => Promise<void>;
65
+ /** Starts the installed service; false when none is installed. */
66
+ startService: () => Promise<boolean>;
67
+ /** Whether an agent of `version` answers within a few minutes. */
68
+ answers: (version: string) => Promise<boolean>;
69
+ print: (line: string) => void;
70
+ }
71
+
72
+ /**
73
+ * Installs another version of the agent and runs it, without interrupting a deployment, touching
74
+ * the controller or stopping the line's server. A running agent is held first, which fails while
75
+ * an operation runs or a login is open, then installs, runs the new version's setup (nothing,
76
+ * unless its image recipe changed), and is replaced by the new version, which takes over the
77
+ * line's server and starts CODESYS again with its own code.
78
+ */
79
+ export const upgradeAgent = async (
80
+ request: {
81
+ version: string;
82
+ install: string[];
83
+ /** The installed version's setup, which builds only images that need it. */
84
+ setup: string[];
85
+ running: { instance: Instance; control: AgentControl } | null;
86
+ /** Where an agent `upgrade` starts writes its output. */
87
+ agentLog: string;
88
+ },
89
+ effects: UpgradeEffects,
90
+ ) => {
91
+ const { running } = request;
92
+ if (running) {
93
+ effects.print(
94
+ `Holding tsplc-agent ${running.instance.version} (process ${running.instance.pid}): it takes no deployments or logins until the new version runs`,
95
+ );
96
+ await running.control.hold();
97
+ }
98
+ const installed = await (async () => {
99
+ if ((await effects.run(request.install)) !== 0) {
100
+ throw new Error(
101
+ `Installing @tsplc/agent@${request.version} failed; see the output above`,
102
+ );
103
+ }
104
+ const version = await effects.installedVersion();
105
+ if (running?.instance.version === version) {
106
+ return null;
107
+ }
108
+ effects.print(`Installed tsplc-agent ${version}; checking its images`);
109
+ if ((await effects.run(request.setup)) !== 0) {
110
+ throw new Error(
111
+ `tsplc-agent ${version} is installed, but its setup failed; see the output above. Run tsplc-agent upgrade ${version} again once it can`,
112
+ );
113
+ }
114
+ return version;
115
+ })().catch(async (error: unknown) => {
116
+ await running?.control.release();
117
+ throw error;
118
+ });
119
+ if (installed === null) {
120
+ await running?.control.release();
121
+ effects.print(
122
+ `tsplc-agent ${running?.instance.version} is installed and running already`,
123
+ );
124
+ return;
125
+ }
126
+ if (!running) {
127
+ if (!(await effects.startService())) {
128
+ effects.print(
129
+ `tsplc-agent ${installed} is installed. No agent was running: start it with tsplc-agent serve, or install the service with tsplc-agent service install`,
130
+ );
131
+ return;
132
+ }
133
+ effects.print("Started the tsplc-agent service");
134
+ } else {
135
+ effects.print(
136
+ `Restarting the agent; the line's server keeps running and CODESYS starts again in the background`,
137
+ );
138
+ await running.control.exit({ server: "leave", restart: true });
139
+ if (!running.instance.supervised) {
140
+ await effects.startAgent(running.instance);
141
+ }
142
+ }
143
+ if (!(await effects.answers(installed))) {
144
+ throw new Error(
145
+ `tsplc-agent ${installed} is installed but doesn't answer; see ${request.agentLog}`,
146
+ );
147
+ }
148
+ effects.print(`tsplc-agent ${installed} is running`);
149
+ };