@tsplc/agent 0.2.17 → 0.2.19
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 +2 -2
- package/dist/cli.js +936 -550
- package/dist/cli.js.map +20 -10
- package/dist/client.js +46 -20
- package/dist/client.js.map +4 -4
- package/dist/index.js +879 -538
- package/dist/index.js.map +18 -9
- package/package.json +50 -49
- package/src/agent.ts +175 -642
- package/src/cli.ts +95 -47
- package/src/client.ts +148 -112
- package/src/codesys.ts +117 -0
- package/src/debugging.ts +134 -0
- package/src/deploy.ts +193 -0
- package/src/discovery.ts +61 -53
- package/src/errors.ts +17 -0
- package/src/index.ts +30 -1
- package/src/login.ts +238 -0
- package/src/logs.ts +36 -26
- package/src/operations.ts +87 -0
- package/src/protocol.ts +108 -69
- package/src/releases.ts +89 -57
- package/src/secrets.ts +118 -0
- package/src/server-process.ts +98 -77
- package/src/state.ts +71 -0
- package/src/terminal.ts +57 -0
package/dist/index.js
CHANGED
|
@@ -1,88 +1,76 @@
|
|
|
1
1
|
// packages/agent/src/agent.ts
|
|
2
|
-
import { execFile } from "node:child_process";
|
|
3
2
|
import { timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { join as join7 } from "node:path";
|
|
4
|
+
import { loginCommandSchema } from "@tsplc/build";
|
|
5
|
+
import { z as z4 } from "zod";
|
|
6
|
+
|
|
7
|
+
// packages/agent/src/debugging.ts
|
|
4
8
|
import { existsSync as existsSync3 } from "node:fs";
|
|
5
|
-
import {
|
|
6
|
-
import { join as join2 } from "node:path";
|
|
7
|
-
import { setTimeout as delay2 } from "node:timers/promises";
|
|
8
|
-
import { promisify } from "node:util";
|
|
9
|
-
import {
|
|
10
|
-
explicitDownload,
|
|
11
|
-
failureReason,
|
|
12
|
-
findControllerLogin,
|
|
13
|
-
gatewayImage,
|
|
14
|
-
loginCommandSchema,
|
|
15
|
-
openControllerLogin,
|
|
16
|
-
resolveConfig,
|
|
17
|
-
startWarmController,
|
|
18
|
-
updateWarmController
|
|
19
|
-
} from "@tsplc/build";
|
|
9
|
+
import { join as join3 } from "node:path";
|
|
20
10
|
import {
|
|
21
11
|
createDebugger,
|
|
22
12
|
createDebugHandler,
|
|
23
13
|
createLoginAdapter,
|
|
24
14
|
loadManifest,
|
|
25
|
-
LoginUnavailable,
|
|
26
|
-
noLogin,
|
|
27
15
|
timelineEntries
|
|
28
16
|
} from "@tsplc/debug";
|
|
29
|
-
import { z as z3 } from "zod";
|
|
30
17
|
|
|
31
|
-
// packages/agent/src/
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
var
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const
|
|
52
|
-
|
|
18
|
+
// packages/agent/src/errors.ts
|
|
19
|
+
class AgentError extends Error {
|
|
20
|
+
status;
|
|
21
|
+
downloadRequired;
|
|
22
|
+
constructor(message, status, { downloadRequired = false } = {}) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.status = status;
|
|
25
|
+
this.downloadRequired = downloadRequired;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
var errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
29
|
+
|
|
30
|
+
// packages/agent/src/logs.ts
|
|
31
|
+
import { existsSync } from "node:fs";
|
|
32
|
+
import { open, readFile, rename, stat } from "node:fs/promises";
|
|
33
|
+
var rotateBytes = 5 * 2 ** 20;
|
|
34
|
+
var appendJsonl = async (file, value) => {
|
|
35
|
+
if (existsSync(file) && (await stat(file)).size >= rotateBytes) {
|
|
36
|
+
await rename(file, `${file}.1`);
|
|
37
|
+
}
|
|
38
|
+
const log = await open(file, "a+");
|
|
39
|
+
try {
|
|
40
|
+
const { size } = await log.stat();
|
|
41
|
+
const last = Buffer.alloc(1);
|
|
42
|
+
if (size) {
|
|
43
|
+
await log.read(last, 0, 1, size - 1);
|
|
44
|
+
}
|
|
45
|
+
const separator = size && last[0] !== 10 ? `
|
|
46
|
+
` : "";
|
|
47
|
+
await log.writeFile(`${separator}${JSON.stringify(value)}
|
|
48
|
+
`);
|
|
49
|
+
} finally {
|
|
50
|
+
await log.close();
|
|
51
|
+
}
|
|
53
52
|
};
|
|
54
|
-
var
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const finish = (open) => {
|
|
58
|
-
clearTimeout(timer);
|
|
59
|
-
socket.destroy();
|
|
60
|
-
resolve(open);
|
|
61
|
-
};
|
|
62
|
-
socket.once("connect", () => finish(true));
|
|
63
|
-
socket.once("error", () => finish(false));
|
|
64
|
-
});
|
|
65
|
-
var resolver = new Resolver({ timeout: 1000, tries: 1 });
|
|
66
|
-
var hostname = (address) => resolver.reverse(address).then((names) => names[0] ?? null, () => null);
|
|
67
|
-
var discoverControllers = async (network, port = runtimePort) => {
|
|
68
|
-
const hosts = subnetHosts(network);
|
|
69
|
-
const found = [];
|
|
70
|
-
for (let start = 0;start < hosts.length; start += probesAtOnce) {
|
|
71
|
-
const batch = hosts.slice(start, start + probesAtOnce);
|
|
72
|
-
const open = await Promise.all(batch.map((host) => accepts(host, port)));
|
|
73
|
-
for (const [index, host] of batch.entries())
|
|
74
|
-
if (open[index])
|
|
75
|
-
found.push({ address: host, port, hostname: await hostname(host) });
|
|
53
|
+
var readJsonl = async (file, schema, limit) => {
|
|
54
|
+
if (!existsSync(file)) {
|
|
55
|
+
return [];
|
|
76
56
|
}
|
|
77
|
-
return
|
|
57
|
+
return (await readFile(file, "utf8")).split(`
|
|
58
|
+
`).filter(Boolean).slice(-limit).flatMap((line) => {
|
|
59
|
+
try {
|
|
60
|
+
return [schema.parse(JSON.parse(line))];
|
|
61
|
+
} catch {
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
});
|
|
78
65
|
};
|
|
79
66
|
|
|
80
67
|
// packages/agent/src/protocol.ts
|
|
81
68
|
import { tsplcConfigSchema } from "@tsplc/config";
|
|
69
|
+
import { tcpPort } from "@tsplc/config/build";
|
|
82
70
|
import { z } from "zod";
|
|
83
71
|
var targetSchema = z.strictObject({
|
|
84
72
|
host: z.string().nonempty(),
|
|
85
|
-
port:
|
|
73
|
+
port: tcpPort
|
|
86
74
|
});
|
|
87
75
|
var networkInterfaceSchema = z.strictObject({
|
|
88
76
|
name: z.string(),
|
|
@@ -94,24 +82,29 @@ var controllerSchema = z.strictObject({
|
|
|
94
82
|
port: z.number().int(),
|
|
95
83
|
hostname: z.string().nullable()
|
|
96
84
|
});
|
|
85
|
+
var discoverSchema = z.strictObject({ name: z.string() });
|
|
97
86
|
var credentialsSchema = z.strictObject({
|
|
98
87
|
username: z.string().nonempty(),
|
|
99
88
|
password: z.string().nonempty()
|
|
100
89
|
});
|
|
101
|
-
var variableSchema = z.strictObject({
|
|
90
|
+
var variableSchema = z.strictObject({
|
|
91
|
+
path: z.string(),
|
|
92
|
+
type: z.string()
|
|
93
|
+
});
|
|
102
94
|
var releaseManifestSchema = z.strictObject({
|
|
103
95
|
config: z.record(z.string(), z.unknown()),
|
|
104
96
|
variables: z.array(variableSchema),
|
|
105
97
|
server: z.string().nonempty().optional(),
|
|
106
98
|
debug: tsplcConfigSchema.shape.debug,
|
|
107
|
-
serverTokenEnv: z.string().nonempty().optional()
|
|
99
|
+
serverTokenEnv: z.string().nonempty().optional(),
|
|
100
|
+
secrets: tsplcConfigSchema.shape.secrets
|
|
108
101
|
});
|
|
109
102
|
var uploadEncoding = "gzip";
|
|
110
103
|
var deployOptionsSchema = z.strictObject({
|
|
111
|
-
credentials: credentialsSchema,
|
|
104
|
+
credentials: credentialsSchema.nullable(),
|
|
112
105
|
download: z.boolean(),
|
|
113
106
|
initializeUser: z.boolean()
|
|
114
|
-
});
|
|
107
|
+
}).refine((options) => options.credentials || !options.initializeUser, "Initializing the controller's user needs the user's credentials.");
|
|
115
108
|
var eventSchema = z.discriminatedUnion("kind", [
|
|
116
109
|
z.strictObject({ kind: z.literal("progress"), message: z.string() }),
|
|
117
110
|
z.strictObject({ kind: z.literal("done"), result: z.unknown() }),
|
|
@@ -121,10 +114,12 @@ var eventSchema = z.discriminatedUnion("kind", [
|
|
|
121
114
|
downloadRequired: z.boolean()
|
|
122
115
|
})
|
|
123
116
|
]);
|
|
117
|
+
var errorSchema = z.object({ error: z.string() });
|
|
118
|
+
var deployOperationSchema = z.enum(["download", "online-change"]);
|
|
124
119
|
var releaseSchema = z.strictObject({
|
|
125
120
|
id: z.string(),
|
|
126
121
|
deployedAt: z.iso.datetime(),
|
|
127
|
-
operation:
|
|
122
|
+
operation: deployOperationSchema,
|
|
128
123
|
controllerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }),
|
|
129
124
|
server: z.string().optional()
|
|
130
125
|
});
|
|
@@ -135,15 +130,24 @@ var statusSchema = z.strictObject({
|
|
|
135
130
|
login: z.union([
|
|
136
131
|
z.strictObject({ state: z.string(), forced: z.array(z.string()) }),
|
|
137
132
|
z.strictObject({ error: z.string() })
|
|
138
|
-
]).nullable()
|
|
133
|
+
]).nullable(),
|
|
134
|
+
credentialsStored: z.boolean()
|
|
139
135
|
});
|
|
140
136
|
var logoutSchema = z.strictObject({ failure: z.string().optional() });
|
|
141
|
-
var clientHeaders = {
|
|
137
|
+
var clientHeaders = {
|
|
138
|
+
user: "x-tsplc-user",
|
|
139
|
+
host: "x-tsplc-host"
|
|
140
|
+
};
|
|
141
|
+
var clientIdentity = (request) => {
|
|
142
|
+
const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
|
|
143
|
+
return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
|
|
144
|
+
};
|
|
142
145
|
var deploymentSchema = z.strictObject({
|
|
143
146
|
at: z.iso.datetime(),
|
|
144
147
|
release: z.string(),
|
|
145
148
|
build: z.string().optional(),
|
|
146
|
-
operation:
|
|
149
|
+
operation: deployOperationSchema,
|
|
150
|
+
credentials: z.enum(["provided", "stored"]).optional(),
|
|
147
151
|
user: z.string().optional(),
|
|
148
152
|
host: z.string().optional()
|
|
149
153
|
});
|
|
@@ -158,69 +162,46 @@ var auditSchema = z.strictObject({
|
|
|
158
162
|
error: z.string().optional()
|
|
159
163
|
});
|
|
160
164
|
|
|
161
|
-
// packages/agent/src/logs.ts
|
|
162
|
-
import { existsSync } from "node:fs";
|
|
163
|
-
import { open, readFile, rename, stat } from "node:fs/promises";
|
|
164
|
-
var rotateBytes = 5 * 2 ** 20;
|
|
165
|
-
var appendJsonl = async (file, value) => {
|
|
166
|
-
if (existsSync(file) && (await stat(file)).size >= rotateBytes)
|
|
167
|
-
await rename(file, `${file}.1`);
|
|
168
|
-
const log = await open(file, "a+");
|
|
169
|
-
try {
|
|
170
|
-
const { size } = await log.stat();
|
|
171
|
-
const last = Buffer.alloc(1);
|
|
172
|
-
if (size)
|
|
173
|
-
await log.read(last, 0, 1, size - 1);
|
|
174
|
-
const separator = size && last[0] !== 10 ? `
|
|
175
|
-
` : "";
|
|
176
|
-
await log.writeFile(`${separator}${JSON.stringify(value)}
|
|
177
|
-
`);
|
|
178
|
-
} finally {
|
|
179
|
-
await log.close();
|
|
180
|
-
}
|
|
181
|
-
};
|
|
182
|
-
var readJsonl = async (file, schema, limit) => {
|
|
183
|
-
if (!existsSync(file))
|
|
184
|
-
return [];
|
|
185
|
-
return (await readFile(file, "utf8")).split(`
|
|
186
|
-
`).filter(Boolean).slice(-limit).flatMap((line) => {
|
|
187
|
-
try {
|
|
188
|
-
return [schema.parse(JSON.parse(line))];
|
|
189
|
-
} catch {
|
|
190
|
-
return [];
|
|
191
|
-
}
|
|
192
|
-
});
|
|
193
|
-
};
|
|
194
|
-
|
|
195
165
|
// packages/agent/src/releases.ts
|
|
196
166
|
import { createHash } from "node:crypto";
|
|
197
167
|
import { existsSync as existsSync2 } from "node:fs";
|
|
198
|
-
import {
|
|
168
|
+
import {
|
|
169
|
+
mkdir,
|
|
170
|
+
mkdtemp,
|
|
171
|
+
readFile as readFile2,
|
|
172
|
+
rename as rename2,
|
|
173
|
+
rm,
|
|
174
|
+
writeFile
|
|
175
|
+
} from "node:fs/promises";
|
|
199
176
|
import { dirname, join, posix } from "node:path";
|
|
200
177
|
import { z as z2 } from "zod";
|
|
201
178
|
var filePrefix = "files/";
|
|
202
179
|
var releasePath = (name) => {
|
|
203
180
|
const path = posix.normalize(name.slice(filePrefix.length));
|
|
204
|
-
if (posix.isAbsolute(path) || path.startsWith("..") || path.includes("\\"))
|
|
181
|
+
if (posix.isAbsolute(path) || path.startsWith("..") || path.includes("\\")) {
|
|
205
182
|
throw new Error(`Invalid release file name: ${name}`);
|
|
183
|
+
}
|
|
206
184
|
return path;
|
|
207
185
|
};
|
|
208
186
|
var readUpload = async (form) => {
|
|
209
|
-
if (form.get("encoding") !== uploadEncoding)
|
|
187
|
+
if (form.get("encoding") !== uploadEncoding) {
|
|
210
188
|
throw new Error("This deployment came from an older tsplc: update tsplc where you deploy from.");
|
|
189
|
+
}
|
|
211
190
|
const manifest = releaseManifestSchema.parse(JSON.parse(z2.string().parse(form.get("manifest"))));
|
|
212
191
|
const files = await Promise.all([...form.entries()].filter(([name]) => name.startsWith(filePrefix)).map(async ([name, value]) => ({
|
|
213
192
|
path: releasePath(name),
|
|
214
193
|
content: Bun.gunzipSync(await z2.instanceof(File).parse(value).bytes())
|
|
215
194
|
})));
|
|
216
|
-
if (manifest.server && !files.some((file) => file.path === manifest.server))
|
|
195
|
+
if (manifest.server && !files.some((file) => file.path === manifest.server)) {
|
|
217
196
|
throw new Error(`The release names a server ${manifest.server} it doesn't contain`);
|
|
197
|
+
}
|
|
218
198
|
return { manifest, files };
|
|
219
199
|
};
|
|
220
200
|
var saveRelease = async (releases, { manifest, files }) => {
|
|
221
201
|
const hash = createHash("sha256").update(JSON.stringify(manifest));
|
|
222
|
-
for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path)))
|
|
202
|
+
for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
|
|
223
203
|
hash.update(file.path).update(createHash("sha256").update(file.content).digest("hex"));
|
|
204
|
+
}
|
|
224
205
|
const id = hash.digest("hex").slice(0, 16);
|
|
225
206
|
const directory = join(releases, id);
|
|
226
207
|
if (!existsSync2(directory)) {
|
|
@@ -248,81 +229,170 @@ var loadRelease = async (releases, id) => {
|
|
|
248
229
|
return { id, directory, manifest };
|
|
249
230
|
};
|
|
250
231
|
|
|
251
|
-
// packages/agent/src/
|
|
252
|
-
import {
|
|
253
|
-
import {
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
var
|
|
257
|
-
var
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
232
|
+
// packages/agent/src/secrets.ts
|
|
233
|
+
import { mkdir as mkdir2, readFile as readFile3, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
|
|
234
|
+
import { dirname as dirname2, join as join2, relative } from "node:path";
|
|
235
|
+
import { secretPlaceholder, secretValue } from "@tsplc/config";
|
|
236
|
+
import { escapeString } from "@tsplc/iec/st";
|
|
237
|
+
var agentService = "tsplc-agent";
|
|
238
|
+
var controllerSecretNames = {
|
|
239
|
+
username: "controller-username",
|
|
240
|
+
password: "controller-password"
|
|
241
|
+
};
|
|
242
|
+
var storedCredentials = async () => {
|
|
243
|
+
const [username, password] = await Promise.all([
|
|
244
|
+
Bun.secrets.get({
|
|
245
|
+
service: agentService,
|
|
246
|
+
name: controllerSecretNames.username
|
|
247
|
+
}),
|
|
248
|
+
Bun.secrets.get({
|
|
249
|
+
service: agentService,
|
|
250
|
+
name: controllerSecretNames.password
|
|
251
|
+
})
|
|
252
|
+
]);
|
|
253
|
+
return username && password ? { username, password } : null;
|
|
254
|
+
};
|
|
255
|
+
var controllerCredentials = async (sent) => {
|
|
256
|
+
const credentials = sent ?? await storedCredentials();
|
|
257
|
+
if (!credentials) {
|
|
258
|
+
throw new AgentError("No controller user is stored on the plant PC: run tsplc-agent secrets set-controller there", 409);
|
|
259
|
+
}
|
|
260
|
+
return credentials;
|
|
261
|
+
};
|
|
262
|
+
var readSecrets = async (secrets) => {
|
|
263
|
+
const values = new Map;
|
|
264
|
+
if (!secrets) {
|
|
265
|
+
return values;
|
|
266
|
+
}
|
|
267
|
+
const { service } = secrets;
|
|
268
|
+
const missing = [];
|
|
269
|
+
for (const name of secrets.names) {
|
|
270
|
+
const value = await Bun.secrets.get({ service, name });
|
|
271
|
+
const valid = secretValue.safeParse(value);
|
|
272
|
+
if (!value) {
|
|
273
|
+
missing.push(name);
|
|
274
|
+
} else if (!valid.success) {
|
|
275
|
+
throw new AgentError(`Secret ${name} in Bun.secrets service ${service} ${valid.error.issues.map((issue) => issue.message).join(" and ")}`, 409);
|
|
276
|
+
} else {
|
|
277
|
+
values.set(name, value);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (missing.length) {
|
|
281
|
+
throw new AgentError(`The plant PC has no ${missing.join(", ")} in Bun.secrets service ${service}: run tsplc-agent secrets set <name> --service ${service} there`, 409);
|
|
282
|
+
}
|
|
283
|
+
return values;
|
|
284
|
+
};
|
|
285
|
+
var releaseVariable = async (manifest, name) => manifest.secrets?.names.includes(name) ? Bun.secrets.get({ service: manifest.secrets.service, name }) : process.env[name];
|
|
286
|
+
var fillSecrets = (st, secrets) => [...secrets].reduce((text, [name, value]) => text.replaceAll(secretPlaceholder(name), () => escapeString(value, "'")), st);
|
|
287
|
+
var withSecrets = async (config, secrets, directory) => {
|
|
288
|
+
await rm2(directory, { recursive: true, force: true });
|
|
289
|
+
for await (const path of new Bun.Glob("**/*").scan({
|
|
290
|
+
cwd: config.sourceDir,
|
|
291
|
+
dot: true
|
|
292
|
+
})) {
|
|
293
|
+
const file = join2(directory, path);
|
|
294
|
+
await mkdir2(dirname2(file), { recursive: true });
|
|
295
|
+
await writeFile2(file, fillSecrets(await readFile3(join2(config.sourceDir, path), "utf8"), secrets));
|
|
296
|
+
}
|
|
297
|
+
return {
|
|
298
|
+
...config,
|
|
299
|
+
sourceDir: directory,
|
|
300
|
+
entry: join2(directory, relative(config.sourceDir, config.entry))
|
|
287
301
|
};
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
302
|
+
};
|
|
303
|
+
|
|
304
|
+
// packages/agent/src/debugging.ts
|
|
305
|
+
var recentEntries = 500;
|
|
306
|
+
var createDebugging = (context) => {
|
|
307
|
+
const { state, log } = context;
|
|
308
|
+
const start = async () => {
|
|
309
|
+
const release = await state.release();
|
|
310
|
+
if (!release) {
|
|
311
|
+
return null;
|
|
292
312
|
}
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
await delay(1000);
|
|
313
|
+
const { directory, manifest: releaseManifest } = await loadRelease(state.paths.releases, release.id);
|
|
314
|
+
const manifestFile = join3(directory, "debug.json");
|
|
315
|
+
if (!existsSync3(manifestFile)) {
|
|
316
|
+
return null;
|
|
298
317
|
}
|
|
299
|
-
|
|
318
|
+
const manifest = await loadManifest(manifestFile);
|
|
319
|
+
const serverToken = releaseManifest.serverTokenEnv && await releaseVariable(releaseManifest, releaseManifest.serverTokenEnv);
|
|
320
|
+
const debug = await createDebugger({
|
|
321
|
+
manifest,
|
|
322
|
+
adapter: createLoginAdapter({
|
|
323
|
+
read: context.readLogin,
|
|
324
|
+
probe: manifest.build.target,
|
|
325
|
+
endpoint: "the agent's login"
|
|
326
|
+
}),
|
|
327
|
+
stateDirectory: state.paths.debug,
|
|
328
|
+
watch: releaseManifest.debug?.watch ?? {},
|
|
329
|
+
...context.serverHealthUrl && serverToken && {
|
|
330
|
+
server: {
|
|
331
|
+
url: new URL(context.serverHealthUrl).origin,
|
|
332
|
+
token: serverToken
|
|
333
|
+
}
|
|
334
|
+
},
|
|
335
|
+
release: {
|
|
336
|
+
id: release.id,
|
|
337
|
+
deployedAt: release.deployedAt,
|
|
338
|
+
operation: release.operation
|
|
339
|
+
},
|
|
340
|
+
timeline: [
|
|
341
|
+
...(await readJsonl(state.paths.deployments, deploymentSchema, recentEntries)).map(({ at, ...deployment }) => timelineEntries.deploy(at, deployment)),
|
|
342
|
+
...(await readJsonl(state.paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) => timelineEntries.audit(at, audit))
|
|
343
|
+
],
|
|
344
|
+
log
|
|
345
|
+
});
|
|
346
|
+
return { debug, handle: createDebugHandler(debug, log) };
|
|
300
347
|
};
|
|
348
|
+
const startOrLog = () => start().catch((error) => {
|
|
349
|
+
log(`Starting the debugger failed: ${errorMessage(error)}`);
|
|
350
|
+
return null;
|
|
351
|
+
});
|
|
352
|
+
let current = startOrLog();
|
|
301
353
|
return {
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
354
|
+
handle: async (request, route) => {
|
|
355
|
+
const debugging = await current;
|
|
356
|
+
if (!debugging) {
|
|
357
|
+
return Response.json({
|
|
358
|
+
error: "The deployed release has no debug manifest, or the debugger failed to start"
|
|
359
|
+
}, { status: 503 });
|
|
360
|
+
}
|
|
361
|
+
return debugging.handle(request, route);
|
|
362
|
+
},
|
|
363
|
+
record: async ({ at, ...audit }) => {
|
|
364
|
+
(await current)?.debug.record(timelineEntries.audit(at, audit));
|
|
365
|
+
},
|
|
366
|
+
restart: () => {
|
|
367
|
+
current = current.then(async (debugging) => {
|
|
368
|
+
await debugging?.debug.close();
|
|
369
|
+
return startOrLog();
|
|
311
370
|
});
|
|
312
|
-
if (started)
|
|
313
|
-
return;
|
|
314
|
-
await stop();
|
|
315
|
-
if (previous)
|
|
316
|
-
start(previous);
|
|
317
|
-
const reason = failure instanceof Error ? failure.message : `it did not start${options.healthUrl ? ` answering ${options.healthUrl}` : ""}`;
|
|
318
|
-
throw new Error(`The new server failed: ${reason}. ${previous ? "The previous one is running again." : ""}`.trim(), { cause: failure });
|
|
319
371
|
},
|
|
320
|
-
|
|
372
|
+
close: async () => {
|
|
373
|
+
await (await current)?.debug.close();
|
|
374
|
+
}
|
|
321
375
|
};
|
|
322
376
|
};
|
|
323
377
|
|
|
324
|
-
// packages/agent/src/
|
|
325
|
-
|
|
378
|
+
// packages/agent/src/deploy.ts
|
|
379
|
+
import { existsSync as existsSync4 } from "node:fs";
|
|
380
|
+
import { readdir, readFile as readFile4, stat as stat2 } from "node:fs/promises";
|
|
381
|
+
import { join as join5 } from "node:path";
|
|
382
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
383
|
+
import {
|
|
384
|
+
findControllerLogin,
|
|
385
|
+
startWarmController,
|
|
386
|
+
updateWarmController
|
|
387
|
+
} from "@tsplc/build";
|
|
388
|
+
import { loadManifest as loadManifest2 } from "@tsplc/debug";
|
|
389
|
+
import { z as z3 } from "zod";
|
|
390
|
+
|
|
391
|
+
// packages/agent/src/codesys.ts
|
|
392
|
+
import { execFile } from "node:child_process";
|
|
393
|
+
import { join as join4 } from "node:path";
|
|
394
|
+
import { promisify } from "node:util";
|
|
395
|
+
import { gatewayImage, resolveConfig } from "@tsplc/build";
|
|
326
396
|
var network = "tsplc-agent";
|
|
327
397
|
var codesysNetwork = "tsplc-agent-codesys";
|
|
328
398
|
var gateway = { host: "tsplc-agent-gateway", port: 1217 };
|
|
@@ -332,55 +402,14 @@ var credentialNames = {
|
|
|
332
402
|
usernameEnv: "TSPLC_DEVICE_USERNAME",
|
|
333
403
|
passwordEnv: "TSPLC_DEVICE_PASSWORD"
|
|
334
404
|
};
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
this.downloadRequired = downloadRequired;
|
|
405
|
+
var docker = async (...args) => {
|
|
406
|
+
const { stdout } = await promisify(execFile)("docker", args);
|
|
407
|
+
return stdout.trim();
|
|
408
|
+
};
|
|
409
|
+
var ensureNetwork = async (name, ...options) => {
|
|
410
|
+
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`)) {
|
|
411
|
+
await docker("network", "create", ...options, name);
|
|
343
412
|
}
|
|
344
|
-
}
|
|
345
|
-
var json = (body, status = 200) => Response.json(body, { status });
|
|
346
|
-
var message = (error) => error instanceof Error ? error.message : String(error);
|
|
347
|
-
var loginStateTimeout = 30000;
|
|
348
|
-
var stoppedAnswering = { error: "The login stopped answering" };
|
|
349
|
-
var recentEntries = 500;
|
|
350
|
-
var clientOf = (request) => {
|
|
351
|
-
const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
|
|
352
|
-
return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
|
|
353
|
-
};
|
|
354
|
-
var auditOf = (command) => {
|
|
355
|
-
switch (command.command) {
|
|
356
|
-
case "write":
|
|
357
|
-
case "force":
|
|
358
|
-
return { command: command.command, values: command.values };
|
|
359
|
-
case "unforce":
|
|
360
|
-
return {
|
|
361
|
-
command: command.restore ? "unforce --restore" : "unforce",
|
|
362
|
-
values: Object.fromEntries(command.expressions.map((expression) => [expression, ""]))
|
|
363
|
-
};
|
|
364
|
-
case "start":
|
|
365
|
-
case "stop":
|
|
366
|
-
return { command: command.command, values: {} };
|
|
367
|
-
case "reset":
|
|
368
|
-
return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
|
|
369
|
-
case "state":
|
|
370
|
-
case "read":
|
|
371
|
-
return;
|
|
372
|
-
}
|
|
373
|
-
};
|
|
374
|
-
var matches = (presented, token) => {
|
|
375
|
-
const actual = Buffer.from(presented);
|
|
376
|
-
const expected = Buffer.from(token);
|
|
377
|
-
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
378
|
-
};
|
|
379
|
-
var readJson = async (path, schema) => existsSync3(path) ? schema.parse(JSON.parse(await readFile3(path, "utf8"))) : null;
|
|
380
|
-
var docker = (...args) => execute("docker", args).then(({ stdout }) => stdout.trim());
|
|
381
|
-
var ensureNetwork = async (name, ...options) => {
|
|
382
|
-
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`))
|
|
383
|
-
await docker("network", "create", ...options, name);
|
|
384
413
|
};
|
|
385
414
|
var ensureGateway = async () => {
|
|
386
415
|
await ensureNetwork(network);
|
|
@@ -390,8 +419,9 @@ var ensureGateway = async () => {
|
|
|
390
419
|
await docker("run", "--detach", "--restart", "unless-stopped", "--platform", "linux/amd64", "--network", network, "--name", gateway.host, gatewayImage);
|
|
391
420
|
}
|
|
392
421
|
const networks = await docker("inspect", "--format", "{{json .NetworkSettings.Networks}}", gateway.host);
|
|
393
|
-
if (!(codesysNetwork in JSON.parse(networks)))
|
|
422
|
+
if (!(codesysNetwork in JSON.parse(networks))) {
|
|
394
423
|
await docker("network", "connect", codesysNetwork, gateway.host);
|
|
424
|
+
}
|
|
395
425
|
};
|
|
396
426
|
var withCredentials = async (credentials, run) => {
|
|
397
427
|
process.env[credentialNames.usernameEnv] = credentials.username;
|
|
@@ -403,28 +433,45 @@ var withCredentials = async (credentials, run) => {
|
|
|
403
433
|
delete process.env[credentialNames.passwordEnv];
|
|
404
434
|
}
|
|
405
435
|
};
|
|
436
|
+
var controllerConfig = (release, target, controllerDirectory) => ({
|
|
437
|
+
...resolveConfig({
|
|
438
|
+
...release.manifest.config,
|
|
439
|
+
online: {
|
|
440
|
+
network: codesysNetwork,
|
|
441
|
+
gateway,
|
|
442
|
+
device: target,
|
|
443
|
+
credentials: credentialNames
|
|
444
|
+
}
|
|
445
|
+
}, join4(release.directory, "manifest.json")),
|
|
446
|
+
outDir: controllerDirectory
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
// packages/agent/src/deploy.ts
|
|
406
450
|
var followProgress = (controller, emit) => {
|
|
407
|
-
const jobs =
|
|
451
|
+
const jobs = join5(controller, ".codesys/controller/jobs");
|
|
408
452
|
const since = Date.now();
|
|
409
453
|
let following = true;
|
|
410
454
|
const done = (async () => {
|
|
411
455
|
let log;
|
|
412
456
|
let offset = 0;
|
|
413
457
|
while (following) {
|
|
414
|
-
await
|
|
415
|
-
if (!log &&
|
|
458
|
+
await delay(2000);
|
|
459
|
+
if (!log && existsSync4(jobs)) {
|
|
416
460
|
for (const job of await readdir(jobs)) {
|
|
417
|
-
const path =
|
|
418
|
-
if (
|
|
461
|
+
const path = join5(jobs, job, ".codesys/controller/progress.log");
|
|
462
|
+
if (existsSync4(path) && (await stat2(path)).mtimeMs >= since) {
|
|
419
463
|
log = path;
|
|
464
|
+
}
|
|
420
465
|
}
|
|
421
466
|
}
|
|
422
|
-
if (!log)
|
|
467
|
+
if (!log) {
|
|
423
468
|
continue;
|
|
424
|
-
|
|
469
|
+
}
|
|
470
|
+
const text = await readFile4(log, "utf8");
|
|
425
471
|
for (const line of text.slice(offset).split(`
|
|
426
|
-
`).filter(Boolean))
|
|
472
|
+
`).filter(Boolean)) {
|
|
427
473
|
emit({ kind: "progress", message: line.replace(/^\S+Z /, "") });
|
|
474
|
+
}
|
|
428
475
|
offset = text.length;
|
|
429
476
|
}
|
|
430
477
|
})();
|
|
@@ -433,58 +480,176 @@ var followProgress = (controller, emit) => {
|
|
|
433
480
|
await done;
|
|
434
481
|
};
|
|
435
482
|
};
|
|
436
|
-
var
|
|
437
|
-
const
|
|
438
|
-
releases: join2(options.state, "releases"),
|
|
439
|
-
controller: join2(options.state, "controller"),
|
|
440
|
-
release: join2(options.state, "release.json"),
|
|
441
|
-
target: join2(options.state, "target.json"),
|
|
442
|
-
deployments: join2(options.state, "deployments.jsonl"),
|
|
443
|
-
audit: join2(options.state, "audit.jsonl"),
|
|
444
|
-
debug: join2(options.state, "debug")
|
|
445
|
-
};
|
|
446
|
-
await mkdir2(options.state, { recursive: true });
|
|
447
|
-
const server = createServerSupervisor({ healthUrl: options.serverHealthUrl, log: options.log });
|
|
448
|
-
const deployed = await readJson(paths.release, releaseSchema);
|
|
449
|
-
if (deployed?.server)
|
|
450
|
-
server.start(join2(paths.releases, deployed.server));
|
|
451
|
-
let busy;
|
|
452
|
-
const requireTarget = async () => {
|
|
453
|
-
const target = await readJson(paths.target, targetSchema);
|
|
454
|
-
if (!target)
|
|
455
|
-
throw new AgentError("Select the controller first: tsplc target", 409);
|
|
456
|
-
return target;
|
|
457
|
-
};
|
|
458
|
-
const controllerConfig = (release, target) => ({
|
|
459
|
-
...resolveConfig({
|
|
460
|
-
...release.manifest.config,
|
|
461
|
-
online: { network: codesysNetwork, gateway, device: target, credentials: credentialNames }
|
|
462
|
-
}, join2(release.directory, "manifest.json")),
|
|
463
|
-
outDir: paths.controller
|
|
464
|
-
});
|
|
465
|
-
const currentRelease = async () => {
|
|
466
|
-
const release = await readJson(paths.release, releaseSchema);
|
|
467
|
-
if (!release)
|
|
468
|
-
throw new AgentError("Nothing has been deployed yet: tsplc deploy", 409);
|
|
469
|
-
return loadRelease(paths.releases, release.id);
|
|
470
|
-
};
|
|
483
|
+
var createDeployments = (context) => {
|
|
484
|
+
const { state, server } = context;
|
|
471
485
|
const warming = (async () => {
|
|
472
|
-
const
|
|
473
|
-
|
|
486
|
+
const deployed = await state.release();
|
|
487
|
+
const target = await state.target();
|
|
488
|
+
if (!deployed || !target) {
|
|
474
489
|
return;
|
|
490
|
+
}
|
|
475
491
|
await ensureGateway();
|
|
476
|
-
const release = await loadRelease(paths.releases, deployed.id);
|
|
477
|
-
await startWarmController(controllerConfig(release, target), deployContainer);
|
|
492
|
+
const release = await loadRelease(state.paths.releases, deployed.id);
|
|
493
|
+
await startWarmController(controllerConfig(release, target, state.paths.controller), deployContainer);
|
|
478
494
|
})().catch((error) => {
|
|
479
|
-
|
|
495
|
+
context.log(`Starting CODESYS failed: ${errorMessage(error)}`);
|
|
480
496
|
});
|
|
481
|
-
|
|
497
|
+
return {
|
|
498
|
+
deploy: async (form, client) => {
|
|
499
|
+
const settings = deployOptionsSchema.parse(JSON.parse(z3.string().parse(form.get("options"))));
|
|
500
|
+
const upload = await readUpload(form);
|
|
501
|
+
const target = await state.requireTarget();
|
|
502
|
+
if (await findControllerLogin(loginContainer)) {
|
|
503
|
+
throw new AgentError("A login is open; log out before deploying: tsplc logout", 409);
|
|
504
|
+
}
|
|
505
|
+
const credentials = await controllerCredentials(settings.credentials);
|
|
506
|
+
const secrets = await readSecrets(upload.manifest.secrets);
|
|
507
|
+
return context.operations.stream("a deployment", async (emit) => {
|
|
508
|
+
const release = await saveRelease(state.paths.releases, upload);
|
|
509
|
+
if (!settings.download && !existsSync4(join5(state.paths.controller, ".codesys/controller/current.json"))) {
|
|
510
|
+
throw new AgentError("The controller has no application downloaded by this agent; only a full download can deploy", 409, { downloadRequired: true });
|
|
511
|
+
}
|
|
512
|
+
const config = await withSecrets(controllerConfig(release, target, state.paths.controller), secrets, state.paths.sources);
|
|
513
|
+
const previous = await state.release();
|
|
514
|
+
const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
|
|
515
|
+
if (serverPath) {
|
|
516
|
+
emit({ kind: "progress", message: "Starting the new server" });
|
|
517
|
+
await server.replace(join5(state.paths.releases, serverPath));
|
|
518
|
+
}
|
|
519
|
+
const kind = settings.download ? "download" : "online-change";
|
|
520
|
+
emit({ kind: "progress", message: `Starting the ${kind}` });
|
|
521
|
+
await ensureGateway();
|
|
522
|
+
await warming;
|
|
523
|
+
const stopFollowing = followProgress(state.paths.controller, emit);
|
|
524
|
+
const receipt = await updateWarmController(config, deployContainer, kind, { initializeUser: settings.initializeUser, credentials }).catch(async (failure) => {
|
|
525
|
+
if (serverPath) {
|
|
526
|
+
emit({
|
|
527
|
+
kind: "progress",
|
|
528
|
+
message: "Restoring the previous server"
|
|
529
|
+
});
|
|
530
|
+
await (previous?.server ? server.replace(join5(state.paths.releases, previous.server)) : server.stop());
|
|
531
|
+
}
|
|
532
|
+
throw failure;
|
|
533
|
+
}).finally(stopFollowing);
|
|
534
|
+
const deployed = {
|
|
535
|
+
id: release.id,
|
|
536
|
+
deployedAt: new Date().toISOString(),
|
|
537
|
+
operation: kind,
|
|
538
|
+
controllerIds: receipt.controllerIds,
|
|
539
|
+
server: serverPath ?? previous?.server
|
|
540
|
+
};
|
|
541
|
+
await state.setRelease(deployed);
|
|
542
|
+
const debugManifest = join5(release.directory, "debug.json");
|
|
543
|
+
const deployment = {
|
|
544
|
+
at: deployed.deployedAt,
|
|
545
|
+
release: release.id,
|
|
546
|
+
...existsSync4(debugManifest) && {
|
|
547
|
+
build: (await loadManifest2(debugManifest)).build.id
|
|
548
|
+
},
|
|
549
|
+
operation: kind,
|
|
550
|
+
credentials: settings.credentials ? "provided" : "stored",
|
|
551
|
+
...client
|
|
552
|
+
};
|
|
553
|
+
await appendJsonl(state.paths.deployments, deployment);
|
|
554
|
+
context.debugging.restart();
|
|
555
|
+
return deployed;
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
};
|
|
560
|
+
|
|
561
|
+
// packages/agent/src/discovery.ts
|
|
562
|
+
import { Resolver } from "node:dns/promises";
|
|
563
|
+
import { createConnection } from "node:net";
|
|
564
|
+
import { networkInterfaces as osInterfaces } from "node:os";
|
|
565
|
+
var runtimePort = 11740;
|
|
566
|
+
var largestPrefix = 22;
|
|
567
|
+
var probeTimeoutMs = 500;
|
|
568
|
+
var probesAtOnce = 128;
|
|
569
|
+
var networkInterfaces = () => Object.entries(osInterfaces()).flatMap(([name, addresses]) => (addresses ?? []).filter((address) => address.family === "IPv4" && !address.internal).map((address) => ({
|
|
570
|
+
name,
|
|
571
|
+
address: address.address,
|
|
572
|
+
prefixLength: address.netmask.split(".").reduce((bits, octet) => bits + Number(octet).toString(2).replaceAll("0", "").length, 0)
|
|
573
|
+
})));
|
|
574
|
+
var toNumber = (address) => address.split(".").reduce((value, octet) => value * 256 + Number(octet), 0);
|
|
575
|
+
var toAddress = (value) => [24, 16, 8, 0].map((shift) => Math.floor(value / 2 ** shift) % 256).join(".");
|
|
576
|
+
var subnetHosts = ({ address, prefixLength }) => {
|
|
577
|
+
if (prefixLength < largestPrefix) {
|
|
578
|
+
throw new Error(`The /${prefixLength} network is too large to scan; the limit is /${largestPrefix}.`);
|
|
579
|
+
}
|
|
580
|
+
const size = 2 ** (32 - prefixLength);
|
|
581
|
+
const network = toNumber(address) - toNumber(address) % size;
|
|
582
|
+
const hosts = size <= 2 ? Array.from({ length: size }, (_, index) => network + index) : Array.from({ length: size - 2 }, (_, index) => network + index + 1);
|
|
583
|
+
return hosts.map(toAddress).filter((host) => host !== address);
|
|
584
|
+
};
|
|
585
|
+
var accepts = (host, port) => new Promise((resolve) => {
|
|
586
|
+
const socket = createConnection({ host, port });
|
|
587
|
+
const timer = setTimeout(() => finish(false), probeTimeoutMs);
|
|
588
|
+
const finish = (open) => {
|
|
589
|
+
clearTimeout(timer);
|
|
590
|
+
socket.destroy();
|
|
591
|
+
resolve(open);
|
|
592
|
+
};
|
|
593
|
+
socket.once("connect", () => finish(true));
|
|
594
|
+
socket.once("error", () => finish(false));
|
|
595
|
+
});
|
|
596
|
+
var resolver = new Resolver({ timeout: 1000, tries: 1 });
|
|
597
|
+
var hostname = (address) => resolver.reverse(address).then((names) => names[0] ?? null, () => null);
|
|
598
|
+
var discoverControllers = async (network, port = runtimePort) => {
|
|
599
|
+
const hosts = subnetHosts(network);
|
|
600
|
+
const found = [];
|
|
601
|
+
for (let start = 0;start < hosts.length; start += probesAtOnce) {
|
|
602
|
+
const batch = hosts.slice(start, start + probesAtOnce);
|
|
603
|
+
const open = await Promise.all(batch.map((host) => accepts(host, port)));
|
|
604
|
+
for (const [index, host] of batch.entries()) {
|
|
605
|
+
if (open[index]) {
|
|
606
|
+
found.push({ address: host, port, hostname: await hostname(host) });
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
return found;
|
|
611
|
+
};
|
|
612
|
+
|
|
613
|
+
// packages/agent/src/login.ts
|
|
614
|
+
import { setTimeout as delay2 } from "node:timers/promises";
|
|
615
|
+
import {
|
|
616
|
+
failureReason,
|
|
617
|
+
findControllerLogin as findControllerLogin2,
|
|
618
|
+
openControllerLogin
|
|
619
|
+
} from "@tsplc/build";
|
|
620
|
+
import { LoginUnavailable, noLogin } from "@tsplc/debug";
|
|
621
|
+
var loginStateTimeout = 30000;
|
|
622
|
+
var stoppedAnswering = { error: "The login stopped answering" };
|
|
623
|
+
var auditOf = (command) => {
|
|
624
|
+
switch (command.command) {
|
|
625
|
+
case "write":
|
|
626
|
+
case "force":
|
|
627
|
+
return { command: command.command, values: command.values };
|
|
628
|
+
case "unforce":
|
|
629
|
+
return {
|
|
630
|
+
command: command.restore ? "unforce --restore" : "unforce",
|
|
631
|
+
values: Object.fromEntries(command.expressions.map((expression) => [expression, ""]))
|
|
632
|
+
};
|
|
633
|
+
case "start":
|
|
634
|
+
case "stop":
|
|
635
|
+
return { command: command.command, values: {} };
|
|
636
|
+
case "reset":
|
|
637
|
+
return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
|
|
638
|
+
case "state":
|
|
639
|
+
case "read":
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
var createLogin = (context) => {
|
|
644
|
+
const { state, operations } = context;
|
|
645
|
+
let generation = 0;
|
|
482
646
|
let commands = Promise.resolve();
|
|
483
647
|
const enqueue = (run) => {
|
|
484
|
-
const
|
|
648
|
+
const queuedIn = generation;
|
|
485
649
|
const sent = commands.then(() => {
|
|
486
|
-
if (
|
|
650
|
+
if (queuedIn !== generation) {
|
|
487
651
|
throw new AgentError("The login was closed", 409);
|
|
652
|
+
}
|
|
488
653
|
return run();
|
|
489
654
|
});
|
|
490
655
|
commands = sent.catch(() => {
|
|
@@ -492,321 +657,497 @@ var createAgent = async (options) => {
|
|
|
492
657
|
});
|
|
493
658
|
return sent;
|
|
494
659
|
};
|
|
495
|
-
const send = (login,
|
|
496
|
-
const
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
if (!
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
throw new Error("The login answered a read without values");
|
|
509
|
-
return result.values;
|
|
510
|
-
};
|
|
511
|
-
const startDebugger = async () => {
|
|
512
|
-
const release = await readJson(paths.release, releaseSchema);
|
|
513
|
-
if (!release)
|
|
514
|
-
return null;
|
|
515
|
-
const { directory, manifest: releaseManifest } = await loadRelease(paths.releases, release.id);
|
|
516
|
-
const manifestFile = join2(directory, "debug.json");
|
|
517
|
-
if (!existsSync3(manifestFile))
|
|
518
|
-
return null;
|
|
519
|
-
const manifest = await loadManifest(manifestFile);
|
|
520
|
-
const serverToken = releaseManifest.serverTokenEnv && process.env[releaseManifest.serverTokenEnv];
|
|
521
|
-
const debug = await createDebugger({
|
|
522
|
-
manifest,
|
|
523
|
-
adapter: createLoginAdapter({
|
|
524
|
-
read: readLogin,
|
|
525
|
-
probe: manifest.build.target,
|
|
526
|
-
endpoint: "the agent's login"
|
|
527
|
-
}),
|
|
528
|
-
stateDirectory: paths.debug,
|
|
529
|
-
watch: releaseManifest.debug?.watch ?? {},
|
|
530
|
-
...options.serverHealthUrl && serverToken && {
|
|
531
|
-
server: { url: new URL(options.serverHealthUrl).origin, token: serverToken }
|
|
532
|
-
},
|
|
533
|
-
release: { id: release.id, deployedAt: release.deployedAt, operation: release.operation },
|
|
534
|
-
timeline: [
|
|
535
|
-
...(await readJsonl(paths.deployments, deploymentSchema, recentEntries)).map(({ at, ...deployment }) => timelineEntries.deploy(at, deployment)),
|
|
536
|
-
...(await readJsonl(paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) => timelineEntries.audit(at, audit))
|
|
537
|
-
],
|
|
538
|
-
log: options.log
|
|
539
|
-
});
|
|
540
|
-
return { debug, handle: createDebugHandler(debug, options.log) };
|
|
541
|
-
};
|
|
542
|
-
const debuggerFailed = (error) => {
|
|
543
|
-
options.log(`Starting the debugger failed: ${message(error)}`);
|
|
544
|
-
return null;
|
|
545
|
-
};
|
|
546
|
-
let debugging = startDebugger().catch(debuggerFailed);
|
|
547
|
-
const restartDebugger = () => {
|
|
548
|
-
debugging = debugging.then(async (current) => {
|
|
549
|
-
await current?.debug.close();
|
|
550
|
-
return startDebugger().catch(debuggerFailed);
|
|
551
|
-
});
|
|
660
|
+
const send = (login, command) => enqueue(() => login.send(command));
|
|
661
|
+
const requireLogin = async () => {
|
|
662
|
+
operations.requireIdle();
|
|
663
|
+
const lookedUpIn = generation;
|
|
664
|
+
const login = await findControllerLogin2(loginContainer);
|
|
665
|
+
if (lookedUpIn !== generation) {
|
|
666
|
+
throw new AgentError("The login was closed", 409);
|
|
667
|
+
}
|
|
668
|
+
operations.requireIdle();
|
|
669
|
+
if (!login) {
|
|
670
|
+
throw new AgentError("No login is open: tsplc login", 409);
|
|
671
|
+
}
|
|
672
|
+
return login;
|
|
552
673
|
};
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
674
|
+
return {
|
|
675
|
+
read: async ([first, ...rest]) => {
|
|
676
|
+
const busy = operations.busy();
|
|
677
|
+
if (busy === "a login") {
|
|
678
|
+
throw new LoginUnavailable("The engineering login is opening", {
|
|
679
|
+
state: "connecting"
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
if (busy) {
|
|
683
|
+
throw new LoginUnavailable(`Live values pause during ${busy}`);
|
|
684
|
+
}
|
|
685
|
+
const login = await findControllerLogin2(loginContainer);
|
|
686
|
+
if (!login) {
|
|
687
|
+
throw new LoginUnavailable(noLogin);
|
|
688
|
+
}
|
|
689
|
+
if (!first) {
|
|
690
|
+
return {};
|
|
691
|
+
}
|
|
692
|
+
const result = await send(login, {
|
|
693
|
+
command: "read",
|
|
694
|
+
expressions: [first, ...rest]
|
|
695
|
+
});
|
|
696
|
+
if (!("values" in result)) {
|
|
697
|
+
throw new Error("The login answered a read without values");
|
|
698
|
+
}
|
|
699
|
+
return result.values;
|
|
700
|
+
},
|
|
701
|
+
open: async (sent) => {
|
|
702
|
+
const credentials = await controllerCredentials(sent);
|
|
703
|
+
context.log(`Opening a login with the ${sent ? "provided" : "stored"} controller user`);
|
|
704
|
+
const config = controllerConfig(await state.requireRelease(), await state.requireTarget(), state.paths.controller);
|
|
705
|
+
return operations.stream("a login", async (emit) => {
|
|
706
|
+
if (await findControllerLogin2(loginContainer)) {
|
|
707
|
+
throw new AgentError("A login is already open", 409);
|
|
708
|
+
}
|
|
709
|
+
emit({
|
|
710
|
+
kind: "progress",
|
|
711
|
+
message: "Logging in; CODESYS takes minutes to start"
|
|
712
|
+
});
|
|
713
|
+
await ensureGateway();
|
|
714
|
+
const login = await withCredentials(credentials, () => openControllerLogin(config, loginContainer));
|
|
715
|
+
return send(login, { command: "state" });
|
|
716
|
+
});
|
|
717
|
+
},
|
|
718
|
+
command: async (command, client) => {
|
|
719
|
+
const login = await requireLogin();
|
|
720
|
+
const change = auditOf(command);
|
|
721
|
+
if (!change) {
|
|
722
|
+
return send(login, command);
|
|
723
|
+
}
|
|
724
|
+
return enqueue(async () => {
|
|
725
|
+
const [first, ...rest] = Object.keys(change.values);
|
|
726
|
+
const previous = first ? await login.send({ command: "read", expressions: [first, ...rest] }).then((result) => ("values" in result) ? result.values : undefined).catch(() => {
|
|
727
|
+
return;
|
|
728
|
+
}) : undefined;
|
|
729
|
+
const audit = async (error) => {
|
|
730
|
+
const entry = {
|
|
731
|
+
at: new Date().toISOString(),
|
|
732
|
+
...change,
|
|
733
|
+
...previous && { previous },
|
|
734
|
+
...client,
|
|
735
|
+
release: (await state.release())?.id,
|
|
736
|
+
...error !== undefined && { error: errorMessage(error) }
|
|
737
|
+
};
|
|
738
|
+
await appendJsonl(state.paths.audit, entry);
|
|
739
|
+
await context.onAudit(entry);
|
|
564
740
|
};
|
|
565
|
-
const emit = (event) => write(`${JSON.stringify(event)}
|
|
566
|
-
`);
|
|
567
|
-
const heartbeat = setInterval(() => write(`
|
|
568
|
-
`), 15000);
|
|
569
741
|
try {
|
|
570
|
-
|
|
742
|
+
const result = await login.send(command);
|
|
743
|
+
await audit();
|
|
744
|
+
return result;
|
|
571
745
|
} catch (error) {
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
kind: "error",
|
|
575
|
-
message: error instanceof Error ? error.message : String(error),
|
|
576
|
-
downloadRequired: error instanceof AgentError && error.downloadRequired || error instanceof Error && error.message.includes(explicitDownload)
|
|
577
|
-
});
|
|
578
|
-
} finally {
|
|
579
|
-
clearInterval(heartbeat);
|
|
580
|
-
busy = undefined;
|
|
581
|
-
if (listening)
|
|
582
|
-
controller.close();
|
|
746
|
+
await audit(error);
|
|
747
|
+
throw error;
|
|
583
748
|
}
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
|
|
749
|
+
});
|
|
750
|
+
},
|
|
751
|
+
status: async () => {
|
|
752
|
+
const login = await findControllerLogin2(loginContainer);
|
|
753
|
+
if (!login) {
|
|
754
|
+
return null;
|
|
755
|
+
}
|
|
756
|
+
if (!await login.ready()) {
|
|
757
|
+
return operations.busy() === "a login" ? null : stoppedAnswering;
|
|
587
758
|
}
|
|
588
|
-
|
|
759
|
+
try {
|
|
760
|
+
const loginState = await Promise.race([
|
|
761
|
+
send(login, { command: "state" }),
|
|
762
|
+
delay2(loginStateTimeout, null)
|
|
763
|
+
]);
|
|
764
|
+
if (!loginState) {
|
|
765
|
+
return stoppedAnswering;
|
|
766
|
+
}
|
|
767
|
+
return "state" in loginState ? loginState : null;
|
|
768
|
+
} catch (error) {
|
|
769
|
+
return { error: failureReason(error) };
|
|
770
|
+
}
|
|
771
|
+
},
|
|
772
|
+
logout: async () => {
|
|
773
|
+
const login = await requireLogin();
|
|
774
|
+
return operations.exclusive("a logout", async () => {
|
|
775
|
+
generation++;
|
|
776
|
+
const failure = await login.close();
|
|
777
|
+
commands = Promise.resolve();
|
|
778
|
+
if (failure) {
|
|
779
|
+
context.log(`The login couldn't log out (${failure}); its container was removed`);
|
|
780
|
+
}
|
|
781
|
+
return failure ? { failure } : {};
|
|
782
|
+
});
|
|
783
|
+
}
|
|
589
784
|
};
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
// packages/agent/src/operations.ts
|
|
788
|
+
import { explicitDownload } from "@tsplc/build";
|
|
789
|
+
var createOperations = (log) => {
|
|
790
|
+
let busy;
|
|
791
|
+
const requireIdle = () => {
|
|
792
|
+
if (busy) {
|
|
793
|
+
throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
return {
|
|
797
|
+
busy: () => busy,
|
|
798
|
+
requireIdle,
|
|
799
|
+
exclusive: async (operation, run) => {
|
|
800
|
+
requireIdle();
|
|
801
|
+
busy = operation;
|
|
802
|
+
try {
|
|
803
|
+
return await run();
|
|
804
|
+
} finally {
|
|
805
|
+
busy = undefined;
|
|
806
|
+
}
|
|
807
|
+
},
|
|
808
|
+
stream: (operation, run) => {
|
|
809
|
+
requireIdle();
|
|
810
|
+
busy = operation;
|
|
811
|
+
const encoder = new TextEncoder;
|
|
812
|
+
let listening = true;
|
|
813
|
+
return new Response(new ReadableStream({
|
|
814
|
+
start: async (controller) => {
|
|
815
|
+
const write = (text) => {
|
|
816
|
+
if (listening) {
|
|
817
|
+
controller.enqueue(encoder.encode(text));
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
const emit = (event) => write(`${JSON.stringify(event)}
|
|
821
|
+
`);
|
|
822
|
+
const heartbeat = setInterval(() => write(`
|
|
823
|
+
`), 15000);
|
|
824
|
+
try {
|
|
825
|
+
emit({ kind: "done", result: await run(emit) });
|
|
826
|
+
} catch (error) {
|
|
827
|
+
log(`${operation} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
828
|
+
emit({
|
|
829
|
+
kind: "error",
|
|
830
|
+
message: errorMessage(error),
|
|
831
|
+
downloadRequired: error instanceof AgentError && error.downloadRequired || error instanceof Error && error.message.includes(explicitDownload)
|
|
832
|
+
});
|
|
833
|
+
} finally {
|
|
834
|
+
clearInterval(heartbeat);
|
|
835
|
+
busy = undefined;
|
|
836
|
+
if (listening) {
|
|
837
|
+
controller.close();
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
},
|
|
841
|
+
cancel: () => {
|
|
842
|
+
listening = false;
|
|
619
843
|
}
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
const deployedRelease = {
|
|
623
|
-
id: release.id,
|
|
624
|
-
deployedAt: new Date().toISOString(),
|
|
625
|
-
operation: kind,
|
|
626
|
-
controllerIds: receipt.controllerIds,
|
|
627
|
-
server: serverPath ?? previous?.server
|
|
628
|
-
};
|
|
629
|
-
await writeFile2(paths.release, JSON.stringify(deployedRelease, null, 2));
|
|
630
|
-
const debugManifest = join2(release.directory, "debug.json");
|
|
631
|
-
const deployment = {
|
|
632
|
-
at: deployedRelease.deployedAt,
|
|
633
|
-
release: release.id,
|
|
634
|
-
...existsSync3(debugManifest) && { build: (await loadManifest(debugManifest)).build.id },
|
|
635
|
-
operation: kind,
|
|
636
|
-
...client
|
|
637
|
-
};
|
|
638
|
-
await appendJsonl(paths.deployments, deployment);
|
|
639
|
-
restartDebugger();
|
|
640
|
-
return deployedRelease;
|
|
641
|
-
});
|
|
844
|
+
}), { headers: { "Content-Type": "application/x-ndjson" } });
|
|
845
|
+
}
|
|
642
846
|
};
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
847
|
+
};
|
|
848
|
+
|
|
849
|
+
// packages/agent/src/server-process.ts
|
|
850
|
+
import { dirname as dirname3 } from "node:path";
|
|
851
|
+
import { setTimeout as delay3 } from "node:timers/promises";
|
|
852
|
+
var healthyWithinMs = 60000;
|
|
853
|
+
var settleMs = 5000;
|
|
854
|
+
var restartDelayMs = 2000;
|
|
855
|
+
var createServerSupervisor = (options) => {
|
|
856
|
+
let current;
|
|
857
|
+
const spawn = (executable) => {
|
|
858
|
+
const command = executable.endsWith(".js") ? [process.execPath, executable] : [executable];
|
|
859
|
+
const child = Bun.spawn(command, {
|
|
860
|
+
cwd: dirname3(executable),
|
|
861
|
+
stdio: ["ignore", "inherit", "inherit"],
|
|
862
|
+
onExit: (_, code) => {
|
|
863
|
+
if (current?.process !== child) {
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
options.log(`Server exited (${code}); restarting it in ${restartDelayMs / 1000} s`);
|
|
867
|
+
delay3(restartDelayMs).then(() => {
|
|
868
|
+
if (current?.process === child) {
|
|
869
|
+
current = { executable, process: spawn(executable) };
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
}
|
|
653
873
|
});
|
|
874
|
+
return child;
|
|
654
875
|
};
|
|
655
|
-
const
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
if (
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
876
|
+
const start = (executable) => {
|
|
877
|
+
current = { executable, process: spawn(executable) };
|
|
878
|
+
return current.process;
|
|
879
|
+
};
|
|
880
|
+
const stop = async () => {
|
|
881
|
+
const running = current;
|
|
882
|
+
current = undefined;
|
|
883
|
+
if (!running) {
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
running.process.kill();
|
|
887
|
+
await running.process.exited;
|
|
888
|
+
};
|
|
889
|
+
const healthy = async (child) => {
|
|
890
|
+
if (!options.healthUrl) {
|
|
891
|
+
await delay3(settleMs);
|
|
892
|
+
return child.exitCode === null;
|
|
893
|
+
}
|
|
894
|
+
const deadline = Date.now() + healthyWithinMs;
|
|
895
|
+
while (Date.now() < deadline && child.exitCode === null) {
|
|
896
|
+
if (await fetch(options.healthUrl).then((response) => response.ok, () => false)) {
|
|
897
|
+
return true;
|
|
898
|
+
}
|
|
899
|
+
await delay3(1000);
|
|
900
|
+
}
|
|
901
|
+
return false;
|
|
667
902
|
};
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
const
|
|
903
|
+
return {
|
|
904
|
+
start,
|
|
905
|
+
stop,
|
|
906
|
+
replace: async (executable) => {
|
|
907
|
+
const previous = current?.executable;
|
|
908
|
+
await stop();
|
|
909
|
+
let failure;
|
|
910
|
+
const started = await (async () => healthy(start(executable)))().catch((error) => {
|
|
911
|
+
failure = error;
|
|
912
|
+
return false;
|
|
913
|
+
});
|
|
914
|
+
if (started) {
|
|
676
915
|
return;
|
|
677
|
-
}) : undefined;
|
|
678
|
-
const audit = async (error) => {
|
|
679
|
-
const entry = {
|
|
680
|
-
at: new Date().toISOString(),
|
|
681
|
-
...change,
|
|
682
|
-
...previous && { previous },
|
|
683
|
-
...client,
|
|
684
|
-
release: (await readJson(paths.release, releaseSchema))?.id,
|
|
685
|
-
...error !== undefined && { error: message(error) }
|
|
686
|
-
};
|
|
687
|
-
await appendJsonl(paths.audit, entry);
|
|
688
|
-
const { at, ...details } = entry;
|
|
689
|
-
(await debugging)?.debug.record(timelineEntries.audit(at, details));
|
|
690
|
-
};
|
|
691
|
-
try {
|
|
692
|
-
const result = await login.send(loginCommand);
|
|
693
|
-
await audit();
|
|
694
|
-
return result;
|
|
695
|
-
} catch (error) {
|
|
696
|
-
await audit(error);
|
|
697
|
-
throw error;
|
|
698
916
|
}
|
|
699
|
-
|
|
917
|
+
await stop();
|
|
918
|
+
if (previous) {
|
|
919
|
+
start(previous);
|
|
920
|
+
}
|
|
921
|
+
const reason = failure instanceof Error ? failure.message : `it did not start${options.healthUrl ? ` answering ${options.healthUrl}` : ""}`;
|
|
922
|
+
throw new Error(`The new server failed: ${reason}. ${previous ? "The previous one is running again." : ""}`.trim(), { cause: failure });
|
|
923
|
+
},
|
|
924
|
+
status: () => current && {
|
|
925
|
+
executable: current.executable,
|
|
926
|
+
running: current.process.exitCode === null
|
|
927
|
+
}
|
|
700
928
|
};
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
929
|
+
};
|
|
930
|
+
|
|
931
|
+
// packages/agent/src/state.ts
|
|
932
|
+
import { existsSync as existsSync5 } from "node:fs";
|
|
933
|
+
import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile3 } from "node:fs/promises";
|
|
934
|
+
import { join as join6 } from "node:path";
|
|
935
|
+
var readJsonFile = async (path, schema) => existsSync5(path) ? schema.parse(JSON.parse(await readFile5(path, "utf8"))) : null;
|
|
936
|
+
var writeJsonFile = (path, value) => writeFile3(path, JSON.stringify(value, null, 2));
|
|
937
|
+
var openState = async (directory) => {
|
|
938
|
+
const paths = {
|
|
939
|
+
releases: join6(directory, "releases"),
|
|
940
|
+
controller: join6(directory, "controller"),
|
|
941
|
+
sources: join6(directory, "sources"),
|
|
942
|
+
release: join6(directory, "release.json"),
|
|
943
|
+
target: join6(directory, "target.json"),
|
|
944
|
+
deployments: join6(directory, "deployments.jsonl"),
|
|
945
|
+
audit: join6(directory, "audit.jsonl"),
|
|
946
|
+
debug: join6(directory, "debug")
|
|
947
|
+
};
|
|
948
|
+
await mkdir3(directory, { recursive: true });
|
|
949
|
+
const target = () => readJsonFile(paths.target, targetSchema);
|
|
950
|
+
const release = () => readJsonFile(paths.release, releaseSchema);
|
|
951
|
+
return {
|
|
952
|
+
paths,
|
|
953
|
+
target,
|
|
954
|
+
setTarget: (selected) => writeJsonFile(paths.target, selected),
|
|
955
|
+
requireTarget: async () => {
|
|
956
|
+
const selected = await target();
|
|
957
|
+
if (!selected) {
|
|
958
|
+
throw new AgentError("Select the controller first: tsplc target", 409);
|
|
959
|
+
}
|
|
960
|
+
return selected;
|
|
961
|
+
},
|
|
962
|
+
release,
|
|
963
|
+
setRelease: (deployed) => writeJsonFile(paths.release, deployed),
|
|
964
|
+
requireRelease: async () => {
|
|
965
|
+
const deployed = await release();
|
|
966
|
+
if (!deployed) {
|
|
967
|
+
throw new AgentError("Nothing has been deployed yet: tsplc deploy", 409);
|
|
968
|
+
}
|
|
969
|
+
return loadRelease(paths.releases, deployed.id);
|
|
717
970
|
}
|
|
718
971
|
};
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
972
|
+
};
|
|
973
|
+
|
|
974
|
+
// packages/agent/src/agent.ts
|
|
975
|
+
var matches = (presented, token) => {
|
|
976
|
+
const actual = Buffer.from(presented);
|
|
977
|
+
const expected = Buffer.from(token);
|
|
978
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
979
|
+
};
|
|
980
|
+
var createAgent = async (options) => {
|
|
981
|
+
const { log } = options;
|
|
982
|
+
const state = await openState(options.state);
|
|
983
|
+
const server = createServerSupervisor({
|
|
984
|
+
healthUrl: options.serverHealthUrl,
|
|
985
|
+
log
|
|
986
|
+
});
|
|
987
|
+
const deployed = await state.release();
|
|
988
|
+
if (deployed?.server) {
|
|
989
|
+
server.start(join7(state.paths.releases, deployed.server));
|
|
990
|
+
}
|
|
991
|
+
const operations = createOperations(log);
|
|
992
|
+
const login = createLogin({
|
|
993
|
+
state,
|
|
994
|
+
operations,
|
|
995
|
+
onAudit: (entry) => debugging.record(entry),
|
|
996
|
+
log
|
|
997
|
+
});
|
|
998
|
+
const debugging = createDebugging({
|
|
999
|
+
state,
|
|
1000
|
+
readLogin: login.read,
|
|
1001
|
+
serverHealthUrl: options.serverHealthUrl,
|
|
1002
|
+
log
|
|
1003
|
+
});
|
|
1004
|
+
const deployments = createDeployments({
|
|
1005
|
+
state,
|
|
1006
|
+
operations,
|
|
1007
|
+
server,
|
|
1008
|
+
debugging,
|
|
1009
|
+
log
|
|
724
1010
|
});
|
|
725
1011
|
const route = async (request) => {
|
|
726
1012
|
const { pathname } = new URL(request.url);
|
|
727
1013
|
const key = `${request.method} ${pathname}`;
|
|
728
1014
|
switch (key) {
|
|
729
|
-
case "GET /status":
|
|
730
|
-
|
|
1015
|
+
case "GET /status": {
|
|
1016
|
+
const status = {
|
|
1017
|
+
target: await state.target(),
|
|
1018
|
+
release: await state.release(),
|
|
1019
|
+
server: server.status() ?? null,
|
|
1020
|
+
login: await login.status(),
|
|
1021
|
+
credentialsStored: await storedCredentials() !== null
|
|
1022
|
+
};
|
|
1023
|
+
return Response.json(status);
|
|
1024
|
+
}
|
|
731
1025
|
case "GET /interfaces":
|
|
732
|
-
return json(networkInterfaces());
|
|
1026
|
+
return Response.json(networkInterfaces());
|
|
733
1027
|
case "POST /discover": {
|
|
734
|
-
const { name } =
|
|
1028
|
+
const { name } = discoverSchema.parse(await request.json());
|
|
735
1029
|
const selected = networkInterfaces().find((network) => network.name === name);
|
|
736
|
-
if (!selected)
|
|
1030
|
+
if (!selected) {
|
|
737
1031
|
throw new AgentError(`No IPv4 interface named ${name}`, 404);
|
|
738
|
-
|
|
1032
|
+
}
|
|
1033
|
+
return Response.json(await discoverControllers(selected));
|
|
739
1034
|
}
|
|
740
1035
|
case "PUT /target": {
|
|
741
1036
|
const target = targetSchema.parse(await request.json());
|
|
742
|
-
await
|
|
743
|
-
return json(target);
|
|
1037
|
+
await state.setTarget(target);
|
|
1038
|
+
return Response.json(target);
|
|
744
1039
|
}
|
|
745
1040
|
case "GET /variables":
|
|
746
|
-
return json((await
|
|
1041
|
+
return Response.json((await state.requireRelease()).manifest.variables);
|
|
747
1042
|
case "POST /deploy":
|
|
748
|
-
return deploy(await request.formData(),
|
|
1043
|
+
return deployments.deploy(await request.formData(), clientIdentity(request));
|
|
749
1044
|
case "POST /login":
|
|
750
|
-
return
|
|
1045
|
+
return login.open(credentialsSchema.nullable().parse(await request.json()));
|
|
751
1046
|
case "POST /login/command":
|
|
752
|
-
return json(await command(loginCommandSchema.parse(await request.json()),
|
|
753
|
-
case "DELETE /login":
|
|
754
|
-
|
|
755
|
-
busy = "a logout";
|
|
756
|
-
loginGeneration++;
|
|
757
|
-
try {
|
|
758
|
-
const failure = await login.close();
|
|
759
|
-
commands = Promise.resolve();
|
|
760
|
-
if (failure)
|
|
761
|
-
options.log(`The login couldn't log out (${failure}); its container was removed`);
|
|
762
|
-
return json(failure ? { failure } : {});
|
|
763
|
-
} finally {
|
|
764
|
-
busy = undefined;
|
|
765
|
-
}
|
|
766
|
-
}
|
|
1047
|
+
return Response.json(await login.command(loginCommandSchema.parse(await request.json()), clientIdentity(request)));
|
|
1048
|
+
case "DELETE /login":
|
|
1049
|
+
return Response.json(await login.logout());
|
|
767
1050
|
default:
|
|
768
|
-
return json({ error: `No route ${key}` }, 404);
|
|
1051
|
+
return Response.json({ error: `No route ${key}` }, { status: 404 });
|
|
769
1052
|
}
|
|
770
1053
|
};
|
|
771
|
-
const debugRoute = async (request, route) => {
|
|
772
|
-
const current = await debugging;
|
|
773
|
-
if (!current)
|
|
774
|
-
return json({ error: "The deployed release has no debug manifest, or the debugger failed to start" }, 503);
|
|
775
|
-
return current.handle(request, route);
|
|
776
|
-
};
|
|
777
1054
|
return {
|
|
778
1055
|
fetch: async (request) => {
|
|
779
1056
|
const { pathname, search, searchParams } = new URL(request.url);
|
|
780
1057
|
const debugPath = pathname.startsWith("/debug/");
|
|
781
|
-
if (pathname === "/debug")
|
|
782
|
-
return new Response(null, {
|
|
783
|
-
|
|
784
|
-
|
|
1058
|
+
if (pathname === "/debug") {
|
|
1059
|
+
return new Response(null, {
|
|
1060
|
+
status: 308,
|
|
1061
|
+
headers: { Location: `/debug/${search}` }
|
|
1062
|
+
});
|
|
1063
|
+
}
|
|
1064
|
+
if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js")) {
|
|
1065
|
+
return debugging.handle(request, pathname.slice("/debug".length));
|
|
1066
|
+
}
|
|
785
1067
|
const presented = /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ?? (debugPath ? searchParams.get("token") : null) ?? "";
|
|
786
1068
|
const full = matches(presented, options.token);
|
|
787
1069
|
const read = options.readToken !== undefined && matches(presented, options.readToken) && (debugPath || request.method === "GET" && pathname === "/status");
|
|
788
|
-
if (!full && !read)
|
|
789
|
-
return json({ error: "Unauthorized" }, 401);
|
|
1070
|
+
if (!full && !read) {
|
|
1071
|
+
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
1072
|
+
}
|
|
790
1073
|
try {
|
|
791
|
-
if (debugPath)
|
|
792
|
-
return await
|
|
1074
|
+
if (debugPath) {
|
|
1075
|
+
return await debugging.handle(request, pathname.slice("/debug".length));
|
|
1076
|
+
}
|
|
793
1077
|
return await route(request);
|
|
794
1078
|
} catch (error) {
|
|
795
|
-
if (error instanceof AgentError)
|
|
796
|
-
return json({ error: error.message }, error.status);
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
1079
|
+
if (error instanceof AgentError) {
|
|
1080
|
+
return Response.json({ error: error.message }, { status: error.status });
|
|
1081
|
+
}
|
|
1082
|
+
if (error instanceof z4.ZodError) {
|
|
1083
|
+
return Response.json({ error: z4.prettifyError(error) }, { status: 400 });
|
|
1084
|
+
}
|
|
1085
|
+
log(`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
1086
|
+
return Response.json({ error: errorMessage(error) }, { status: 500 });
|
|
801
1087
|
}
|
|
802
1088
|
},
|
|
803
1089
|
stop: async () => {
|
|
804
|
-
await
|
|
1090
|
+
await debugging.close();
|
|
805
1091
|
await server.stop();
|
|
806
1092
|
}
|
|
807
1093
|
};
|
|
808
1094
|
};
|
|
1095
|
+
// packages/agent/src/terminal.ts
|
|
1096
|
+
import { createInterface } from "node:readline/promises";
|
|
1097
|
+
var ask = async (question) => {
|
|
1098
|
+
const lines = createInterface({
|
|
1099
|
+
input: process.stdin,
|
|
1100
|
+
output: process.stdout
|
|
1101
|
+
});
|
|
1102
|
+
try {
|
|
1103
|
+
return (await lines.question(question)).trim();
|
|
1104
|
+
} finally {
|
|
1105
|
+
lines.close();
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
var askSecret = (question) => new Promise((accept, reject) => {
|
|
1109
|
+
if (!process.stdin.isTTY) {
|
|
1110
|
+
reject(new Error("Typing a secret needs an interactive terminal."));
|
|
1111
|
+
return;
|
|
1112
|
+
}
|
|
1113
|
+
process.stdin.setRawMode(true);
|
|
1114
|
+
process.stdin.setEncoding("utf8");
|
|
1115
|
+
process.stdin.resume();
|
|
1116
|
+
process.stdout.write(question);
|
|
1117
|
+
let secret = "";
|
|
1118
|
+
const finish = () => {
|
|
1119
|
+
process.stdin.off("data", read);
|
|
1120
|
+
process.stdin.setRawMode(false);
|
|
1121
|
+
process.stdin.pause();
|
|
1122
|
+
process.stdout.write(`
|
|
1123
|
+
`);
|
|
1124
|
+
};
|
|
1125
|
+
const read = (text) => {
|
|
1126
|
+
for (const character of text) {
|
|
1127
|
+
if (character === "\r" || character === `
|
|
1128
|
+
`) {
|
|
1129
|
+
finish();
|
|
1130
|
+
accept(secret);
|
|
1131
|
+
return;
|
|
1132
|
+
}
|
|
1133
|
+
if (character === "\x03") {
|
|
1134
|
+
finish();
|
|
1135
|
+
reject(new Error("Cancelled."));
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
secret = character === "" ? secret.slice(0, -1) : secret + character;
|
|
1139
|
+
}
|
|
1140
|
+
};
|
|
1141
|
+
process.stdin.on("data", read);
|
|
1142
|
+
});
|
|
1143
|
+
var askCredentials = async () => ({
|
|
1144
|
+
username: await ask("Controller username: "),
|
|
1145
|
+
password: await askSecret("Controller password: ")
|
|
1146
|
+
});
|
|
809
1147
|
export {
|
|
1148
|
+
ask,
|
|
1149
|
+
askCredentials,
|
|
1150
|
+
askSecret,
|
|
810
1151
|
auditSchema,
|
|
811
1152
|
clientHeaders,
|
|
812
1153
|
controllerSchema,
|
|
@@ -825,5 +1166,5 @@ export {
|
|
|
825
1166
|
variableSchema
|
|
826
1167
|
};
|
|
827
1168
|
|
|
828
|
-
//# debugId=
|
|
1169
|
+
//# debugId=F9096C79802F487164756E2164756E21
|
|
829
1170
|
//# sourceMappingURL=index.js.map
|