@tsplc/tmp-agent 0.0.0-stage → 0.6.3
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/releases.ts
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import {
|
|
4
|
+
mkdir,
|
|
5
|
+
mkdtemp,
|
|
6
|
+
readdir,
|
|
7
|
+
readFile,
|
|
8
|
+
rename,
|
|
9
|
+
rm,
|
|
10
|
+
stat,
|
|
11
|
+
writeFile,
|
|
12
|
+
} from "node:fs/promises";
|
|
13
|
+
import {
|
|
14
|
+
dirname,
|
|
15
|
+
isAbsolute,
|
|
16
|
+
join,
|
|
17
|
+
posix,
|
|
18
|
+
relative,
|
|
19
|
+
resolve,
|
|
20
|
+
sep,
|
|
21
|
+
} from "node:path";
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
import { AgentError } from "./errors";
|
|
24
|
+
import {
|
|
25
|
+
type Comparison,
|
|
26
|
+
type DeployOptions,
|
|
27
|
+
deployOptionsSchema,
|
|
28
|
+
type ReleaseManifest,
|
|
29
|
+
type ReleaseUpload,
|
|
30
|
+
releaseManifestSchema,
|
|
31
|
+
releaseUploadSchema,
|
|
32
|
+
releaseUploadType,
|
|
33
|
+
uploadEncoding,
|
|
34
|
+
} from "./protocol";
|
|
35
|
+
import {
|
|
36
|
+
bucketDigests,
|
|
37
|
+
decodeUpload,
|
|
38
|
+
fileBucket,
|
|
39
|
+
type ReleaseContent,
|
|
40
|
+
shortDigest,
|
|
41
|
+
} from "./transfer";
|
|
42
|
+
|
|
43
|
+
/** Uploaded files are named `files/<path in the release>`. */
|
|
44
|
+
const filePrefix = "files/";
|
|
45
|
+
|
|
46
|
+
const releasePath = (name: string) => {
|
|
47
|
+
const path = posix.normalize(name);
|
|
48
|
+
if (posix.isAbsolute(path) || path.startsWith("..") || path.includes("\\")) {
|
|
49
|
+
throw new Error(`Invalid release file name: ${name}`);
|
|
50
|
+
}
|
|
51
|
+
return path;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/** A release to store: its manifest and every file. */
|
|
55
|
+
export interface Upload {
|
|
56
|
+
manifest: ReleaseManifest;
|
|
57
|
+
files: ReleaseContent[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const checkServer = ({ manifest, files }: Upload) => {
|
|
61
|
+
if (manifest.server && !files.some((file) => file.path === manifest.server)) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
`The release names a server ${manifest.server} it doesn't contain`,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
/** An uploaded release, from the multipart form `tsplc deploy` sends an agent that can't compare releases. */
|
|
69
|
+
export const readUpload = async (form: FormData): Promise<Upload> => {
|
|
70
|
+
if (form.get("encoding") !== uploadEncoding) {
|
|
71
|
+
throw new Error(
|
|
72
|
+
"This deployment came from an older tsplc: update tsplc where you deploy from.",
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
const manifest = releaseManifestSchema.parse(
|
|
76
|
+
JSON.parse(z.string().parse(form.get("manifest"))),
|
|
77
|
+
);
|
|
78
|
+
const files = await Promise.all(
|
|
79
|
+
[...form.entries()]
|
|
80
|
+
.filter(([name]) => name.startsWith(filePrefix))
|
|
81
|
+
.map(async ([name, value]) => ({
|
|
82
|
+
path: releasePath(name.slice(filePrefix.length)),
|
|
83
|
+
content: Bun.gunzipSync(await z.instanceof(File).parse(value).bytes()),
|
|
84
|
+
})),
|
|
85
|
+
);
|
|
86
|
+
const upload = { manifest, files };
|
|
87
|
+
checkServer(upload);
|
|
88
|
+
return upload;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** A deployment's options and release, from either form of `POST /deploy`. */
|
|
92
|
+
export interface DeployRequest {
|
|
93
|
+
settings: DeployOptions;
|
|
94
|
+
upload: Upload;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Reads `POST /deploy`: a release upload built on a stored release, or the multipart form of a
|
|
99
|
+
* tsplc from before `POST /releases/compare`.
|
|
100
|
+
*/
|
|
101
|
+
export const readDeployRequest = async (
|
|
102
|
+
releases: ReleaseStore,
|
|
103
|
+
request: Request,
|
|
104
|
+
): Promise<DeployRequest> => {
|
|
105
|
+
const type = request.headers.get("content-type") ?? "";
|
|
106
|
+
if (type.split(";")[0]?.trim() === releaseUploadType) {
|
|
107
|
+
const { header, files } = await decodeUpload(await request.bytes());
|
|
108
|
+
const upload = releaseUploadSchema.parse(header);
|
|
109
|
+
return {
|
|
110
|
+
settings: upload.options,
|
|
111
|
+
upload: await releases.assemble(upload, files),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
if (type.startsWith("multipart/form-data")) {
|
|
115
|
+
const form = await request.formData();
|
|
116
|
+
return {
|
|
117
|
+
settings: deployOptionsSchema.parse(
|
|
118
|
+
JSON.parse(z.string().parse(form.get("options"))),
|
|
119
|
+
),
|
|
120
|
+
upload: await readUpload(form),
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
throw new AgentError(`Unsupported deployment content type ${type}`, 415);
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** A stored release's manifest, which `tsplc deploy` uploads beside its files. */
|
|
127
|
+
export const manifestFile = "manifest.json";
|
|
128
|
+
|
|
129
|
+
/** Whether release `id` is stored, complete, under `releases`. */
|
|
130
|
+
export const isStored = (releases: string, id: string) =>
|
|
131
|
+
existsSync(join(releases, id, manifestFile));
|
|
132
|
+
|
|
133
|
+
/** The ids of the releases stored under `releases`, leaving out uploads still being stored. */
|
|
134
|
+
const storedIds = async (releases: string) =>
|
|
135
|
+
existsSync(releases)
|
|
136
|
+
? (await readdir(releases, { withFileTypes: true }))
|
|
137
|
+
.filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
|
|
138
|
+
.map((entry) => entry.name)
|
|
139
|
+
: [];
|
|
140
|
+
|
|
141
|
+
/** Each file of the release in `directory`: its path in the release, and where it is. */
|
|
142
|
+
async function* releaseFiles(directory: string) {
|
|
143
|
+
for await (const found of new Bun.Glob("**/*").scan({
|
|
144
|
+
cwd: directory,
|
|
145
|
+
dot: true,
|
|
146
|
+
})) {
|
|
147
|
+
yield { path: found.split(sep).join("/"), file: join(directory, found) };
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A release in the releases directory. */
|
|
152
|
+
export interface StoredRelease {
|
|
153
|
+
id: string;
|
|
154
|
+
directory: string;
|
|
155
|
+
manifest: ReleaseManifest;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Stores a release under `releases/<id>`, where the id hashes its contents, so the same
|
|
160
|
+
* upload twice is one release. Each release is complete before it appears.
|
|
161
|
+
*/
|
|
162
|
+
export const saveRelease = async (
|
|
163
|
+
releases: string,
|
|
164
|
+
{ manifest, files }: Upload,
|
|
165
|
+
): Promise<StoredRelease> => {
|
|
166
|
+
const hash = createHash("sha256").update(JSON.stringify(manifest));
|
|
167
|
+
for (const file of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
|
|
168
|
+
hash
|
|
169
|
+
.update(file.path)
|
|
170
|
+
.update(createHash("sha256").update(file.content).digest("hex"));
|
|
171
|
+
}
|
|
172
|
+
const id = hash.digest("hex").slice(0, 16);
|
|
173
|
+
const directory = join(releases, id);
|
|
174
|
+
if (!existsSync(directory)) {
|
|
175
|
+
await mkdir(releases, { recursive: true });
|
|
176
|
+
const staging = await mkdtemp(join(releases, ".upload-"));
|
|
177
|
+
try {
|
|
178
|
+
for (const file of files) {
|
|
179
|
+
await mkdir(dirname(join(staging, file.path)), { recursive: true });
|
|
180
|
+
// Uploads lose their mode; the server must stay executable outside Windows.
|
|
181
|
+
await writeFile(join(staging, file.path), file.content, {
|
|
182
|
+
mode: file.path === manifest.server ? 0o755 : 0o644,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
await writeFile(
|
|
186
|
+
join(staging, manifestFile),
|
|
187
|
+
JSON.stringify(manifest, null, 2),
|
|
188
|
+
);
|
|
189
|
+
await rename(staging, directory);
|
|
190
|
+
} catch (cause) {
|
|
191
|
+
await rm(staging, { recursive: true, force: true });
|
|
192
|
+
throw cause;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return { id, directory, manifest };
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
export const loadRelease = async (
|
|
199
|
+
releases: string,
|
|
200
|
+
id: string,
|
|
201
|
+
): Promise<StoredRelease> => {
|
|
202
|
+
const directory = join(releases, id);
|
|
203
|
+
const manifest = releaseManifestSchema.parse(
|
|
204
|
+
JSON.parse(await readFile(join(directory, manifestFile), "utf8")),
|
|
205
|
+
);
|
|
206
|
+
return { id, directory, manifest };
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
/** The release's server as `Release.server` records it: relative to the releases directory. */
|
|
210
|
+
export const releaseServerPath = (release: StoredRelease) =>
|
|
211
|
+
release.manifest.server && `${release.id}/${release.manifest.server}`;
|
|
212
|
+
|
|
213
|
+
/** The release a `Release.server` path is in, which may be an earlier one than the deployed release. */
|
|
214
|
+
export const serverReleaseId = (serverPath: string) => {
|
|
215
|
+
const slash = serverPath.indexOf("/");
|
|
216
|
+
return slash === -1 ? serverPath : serverPath.slice(0, slash);
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
/** Where the server at `serverPath`, as `Release.server` records it, is stored under `releases`. */
|
|
220
|
+
export const releaseServerFile = (releases: string, serverPath: string) =>
|
|
221
|
+
join(releases, serverPath);
|
|
222
|
+
|
|
223
|
+
/** The stored release under `releases` that `file`, a server `releaseServerFile` named, lies in. */
|
|
224
|
+
export const storedReleaseOf = (releases: string, file: string) => {
|
|
225
|
+
const id = serverReleaseId(relative(releases, file).split(sep).join("/"));
|
|
226
|
+
if (!id) {
|
|
227
|
+
throw new Error(`${file} lies in no release under ${releases}`);
|
|
228
|
+
}
|
|
229
|
+
return loadRelease(releases, id);
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
/** A stored release's files, by path in the release, with their sizes in bytes. */
|
|
233
|
+
export const listReleaseFiles = async (releases: string, id: string) => {
|
|
234
|
+
if (!isStored(releases, id)) {
|
|
235
|
+
throw new AgentError(`The release ${id} is no longer stored`, 404);
|
|
236
|
+
}
|
|
237
|
+
const files: { path: string; size: number }[] = [];
|
|
238
|
+
for await (const { path, file } of releaseFiles(join(releases, id))) {
|
|
239
|
+
files.push({ path, size: (await stat(file)).size });
|
|
240
|
+
}
|
|
241
|
+
return files.sort((left, right) => left.path.localeCompare(right.path));
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
/** One file of a stored release; a path that leaves the release is refused. */
|
|
245
|
+
export const readReleaseFile = async (
|
|
246
|
+
releases: string,
|
|
247
|
+
id: string,
|
|
248
|
+
path: string,
|
|
249
|
+
) => {
|
|
250
|
+
const directory = resolve(releases, id);
|
|
251
|
+
const file = resolve(directory, path);
|
|
252
|
+
const inside = relative(directory, file);
|
|
253
|
+
if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) {
|
|
254
|
+
throw new AgentError(`${path} isn't a path in a release`, 400);
|
|
255
|
+
}
|
|
256
|
+
if (
|
|
257
|
+
!(await stat(file).then(
|
|
258
|
+
(found) => found.isFile(),
|
|
259
|
+
() => false,
|
|
260
|
+
))
|
|
261
|
+
) {
|
|
262
|
+
throw new AgentError(`The release ${id} has no file ${path}`, 404);
|
|
263
|
+
}
|
|
264
|
+
return Bun.file(file);
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
/** Deletes every stored release but the `kept` ones; uploads still being stored are left alone. */
|
|
268
|
+
export const pruneReleases = async (
|
|
269
|
+
releases: string,
|
|
270
|
+
kept: ReadonlySet<string>,
|
|
271
|
+
) => {
|
|
272
|
+
const removed = (await storedIds(releases)).filter((id) => !kept.has(id));
|
|
273
|
+
for (const id of removed) {
|
|
274
|
+
await rm(join(releases, id), { recursive: true, force: true });
|
|
275
|
+
}
|
|
276
|
+
return removed;
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
/** A stored release's files by path, with their digests, and its bucket digests. */
|
|
280
|
+
interface ReleaseIndex {
|
|
281
|
+
files: Map<string, string>;
|
|
282
|
+
buckets: string[];
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Compares uploads with the stored releases and builds releases from them. Stored releases never
|
|
287
|
+
* change, so each one's index is read once.
|
|
288
|
+
*/
|
|
289
|
+
export const createReleaseStore = (releases: string) => {
|
|
290
|
+
const indexes = new Map<string, Promise<ReleaseIndex>>();
|
|
291
|
+
|
|
292
|
+
const readIndex = async (id: string): Promise<ReleaseIndex> => {
|
|
293
|
+
const files = new Map<string, string>();
|
|
294
|
+
for await (const { path, file } of releaseFiles(join(releases, id))) {
|
|
295
|
+
// The release's manifest travels in the upload's header, not as one of its files.
|
|
296
|
+
if (path !== manifestFile) {
|
|
297
|
+
files.set(path, shortDigest(await readFile(file)));
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
const digests = [...files].map(([path, digest]) => ({ path, digest }));
|
|
301
|
+
return { files, buckets: bucketDigests(digests) };
|
|
302
|
+
};
|
|
303
|
+
const index = (id: string) => {
|
|
304
|
+
const known = indexes.get(id);
|
|
305
|
+
if (known) {
|
|
306
|
+
return known;
|
|
307
|
+
}
|
|
308
|
+
const reading = readIndex(id);
|
|
309
|
+
indexes.set(id, reading);
|
|
310
|
+
reading.catch(() => indexes.delete(id));
|
|
311
|
+
return reading;
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
/** The most recently stored release, which a failed deployment of the same program leaves behind. */
|
|
315
|
+
const newest = async () => {
|
|
316
|
+
const stored = await Promise.all(
|
|
317
|
+
(await storedIds(releases)).map(async (id) => ({
|
|
318
|
+
id,
|
|
319
|
+
created: (await stat(join(releases, id))).mtimeMs,
|
|
320
|
+
})),
|
|
321
|
+
);
|
|
322
|
+
return stored.sort((left, right) => right.created - left.created)[0]?.id;
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
return {
|
|
326
|
+
/** The candidate, of the deployed release and the newest stored one, that differs from `buckets` least. */
|
|
327
|
+
compare: async (
|
|
328
|
+
buckets: readonly string[],
|
|
329
|
+
deployed: string | null,
|
|
330
|
+
): Promise<Comparison> => {
|
|
331
|
+
const candidates = [
|
|
332
|
+
...new Set([deployed, await newest()].filter((id) => id != null)),
|
|
333
|
+
].filter((id) => isStored(releases, id));
|
|
334
|
+
const compared = await Promise.all(
|
|
335
|
+
candidates.map(async (id) => {
|
|
336
|
+
const { files, buckets: stored } = await index(id);
|
|
337
|
+
const changed = buckets.flatMap((digest, bucket) =>
|
|
338
|
+
stored[bucket] === digest ? [] : [bucket],
|
|
339
|
+
);
|
|
340
|
+
return { id, files, changed };
|
|
341
|
+
}),
|
|
342
|
+
);
|
|
343
|
+
const [best] = compared.sort(
|
|
344
|
+
(left, right) => left.changed.length - right.changed.length,
|
|
345
|
+
);
|
|
346
|
+
if (!best) {
|
|
347
|
+
return { base: null, changed: [] };
|
|
348
|
+
}
|
|
349
|
+
const changed = new Map<number, Record<string, string>>(
|
|
350
|
+
best.changed.map((bucket) => [bucket, {}]),
|
|
351
|
+
);
|
|
352
|
+
for (const [path, digest] of best.files) {
|
|
353
|
+
const held = changed.get(fileBucket(path));
|
|
354
|
+
if (held) {
|
|
355
|
+
held[path] = digest;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return {
|
|
359
|
+
base: best.id,
|
|
360
|
+
changed: [...changed].map(([bucket, files]) => ({ bucket, files })),
|
|
361
|
+
};
|
|
362
|
+
},
|
|
363
|
+
|
|
364
|
+
/** The release an upload describes, checked against the bucket digests it was sent with. */
|
|
365
|
+
assemble: async (
|
|
366
|
+
{ manifest, base, buckets, remove }: ReleaseUpload,
|
|
367
|
+
uploaded: readonly ReleaseContent[],
|
|
368
|
+
): Promise<Upload> => {
|
|
369
|
+
const files = new Map(
|
|
370
|
+
uploaded.map(({ path, content }) => [releasePath(path), content]),
|
|
371
|
+
);
|
|
372
|
+
if (files.size !== uploaded.length) {
|
|
373
|
+
throw new AgentError("The release upload sends a file twice", 400);
|
|
374
|
+
}
|
|
375
|
+
if (base !== null) {
|
|
376
|
+
if (!isStored(releases, base)) {
|
|
377
|
+
throw new AgentError(
|
|
378
|
+
`The release ${base} this upload builds on is gone; deploy again`,
|
|
379
|
+
409,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
const removed = new Set(remove);
|
|
383
|
+
const reused = [...(await index(base)).files.keys()].filter(
|
|
384
|
+
(path) => !removed.has(path) && !files.has(path),
|
|
385
|
+
);
|
|
386
|
+
for (const path of reused) {
|
|
387
|
+
files.set(
|
|
388
|
+
path,
|
|
389
|
+
new Uint8Array(await readFile(join(releases, base, path))),
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
const assembled = bucketDigests(
|
|
394
|
+
[...files].map(([path, content]) => ({
|
|
395
|
+
path,
|
|
396
|
+
digest: shortDigest(content),
|
|
397
|
+
})),
|
|
398
|
+
);
|
|
399
|
+
if (assembled.some((digest, bucket) => digest !== buckets[bucket])) {
|
|
400
|
+
throw new AgentError(
|
|
401
|
+
"The release upload doesn't match the release it describes; deploy again",
|
|
402
|
+
400,
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
const upload = {
|
|
406
|
+
manifest,
|
|
407
|
+
files: [...files].map(([path, content]) => ({ path, content })),
|
|
408
|
+
};
|
|
409
|
+
checkServer(upload);
|
|
410
|
+
return upload;
|
|
411
|
+
},
|
|
412
|
+
};
|
|
413
|
+
};
|
|
414
|
+
export type ReleaseStore = ReturnType<typeof createReleaseStore>;
|
package/src/restarts.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { type ResetKind, resetLabel } from "@tsplc/build";
|
|
2
|
+
import {
|
|
3
|
+
controllerRestartPath,
|
|
4
|
+
type controllerRestartReplySchema,
|
|
5
|
+
controllerRestartSchema,
|
|
6
|
+
} from "@tsplc/server/plant-agent";
|
|
7
|
+
import type { z } from "zod";
|
|
8
|
+
import { type AuditLog, authorOf } from "./audit";
|
|
9
|
+
import { AgentError, errorMessage } from "./errors";
|
|
10
|
+
import type { Operations } from "./operations";
|
|
11
|
+
import type { Identity } from "./protocol";
|
|
12
|
+
import type { ApiRoute } from "./routes";
|
|
13
|
+
import type { ServerSupervisor } from "./server-process";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Restarting the controller's application, for the dashboard, `tsplc restart` and the deployed
|
|
17
|
+
* server, and restarting the line's server, for the dashboard. Each restart is audited.
|
|
18
|
+
*/
|
|
19
|
+
export const createRestartRoutes = (context: {
|
|
20
|
+
/** Resets the controller's application and starts it again, as the agent's one operation. */
|
|
21
|
+
restartController: (
|
|
22
|
+
reset: ResetKind,
|
|
23
|
+
) => Promise<z.infer<typeof controllerRestartReplySchema>>;
|
|
24
|
+
server: ServerSupervisor;
|
|
25
|
+
operations: Operations;
|
|
26
|
+
audit: AuditLog;
|
|
27
|
+
log: (message: string) => void;
|
|
28
|
+
}): ApiRoute[] => {
|
|
29
|
+
const audited = async <Result>(
|
|
30
|
+
identity: Identity,
|
|
31
|
+
restart: { command: string; action: string },
|
|
32
|
+
run: () => Promise<Result>,
|
|
33
|
+
) => {
|
|
34
|
+
const outcome = await run().then(
|
|
35
|
+
(result): { result: Result } | { failure: unknown } => ({ result }),
|
|
36
|
+
(failure: unknown) => ({ failure }),
|
|
37
|
+
);
|
|
38
|
+
// Refused before it began, such as while another operation runs: nothing happened to record.
|
|
39
|
+
if ("failure" in outcome && outcome.failure instanceof AgentError) {
|
|
40
|
+
throw outcome.failure;
|
|
41
|
+
}
|
|
42
|
+
await context.audit.record({
|
|
43
|
+
by: authorOf(identity),
|
|
44
|
+
command: restart.command,
|
|
45
|
+
values: {},
|
|
46
|
+
previous: null,
|
|
47
|
+
error: "failure" in outcome ? errorMessage(outcome.failure) : null,
|
|
48
|
+
});
|
|
49
|
+
if ("result" in outcome) {
|
|
50
|
+
return outcome.result;
|
|
51
|
+
}
|
|
52
|
+
context.log(`${restart.action} failed: ${errorMessage(outcome.failure)}`);
|
|
53
|
+
throw new AgentError(errorMessage(outcome.failure), 500);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
return [
|
|
57
|
+
{
|
|
58
|
+
method: "POST",
|
|
59
|
+
pattern: controllerRestartPath,
|
|
60
|
+
role: "deployer",
|
|
61
|
+
handle: async (request, { identity }) => {
|
|
62
|
+
const { reset } = controllerRestartSchema.parse(await request.json());
|
|
63
|
+
return Response.json(
|
|
64
|
+
await audited(
|
|
65
|
+
identity,
|
|
66
|
+
{
|
|
67
|
+
command: reset === "warm" ? "restart" : "restart --cold",
|
|
68
|
+
action: "Restarting the controller",
|
|
69
|
+
},
|
|
70
|
+
() => context.restartController(resetLabel(reset)),
|
|
71
|
+
),
|
|
72
|
+
);
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
method: "POST",
|
|
77
|
+
pattern: "/api/server/restart",
|
|
78
|
+
role: "deployer",
|
|
79
|
+
handle: async (_request, { identity }) => {
|
|
80
|
+
const running = context.server.status();
|
|
81
|
+
if (!running) {
|
|
82
|
+
throw new AgentError("The deployed release runs no server", 409);
|
|
83
|
+
}
|
|
84
|
+
await audited(
|
|
85
|
+
identity,
|
|
86
|
+
{ command: "server restart", action: "Restarting the server" },
|
|
87
|
+
() =>
|
|
88
|
+
context.operations.exclusive("a server restart", () =>
|
|
89
|
+
context.server.replace(running.executable),
|
|
90
|
+
),
|
|
91
|
+
);
|
|
92
|
+
return Response.json(context.server.status());
|
|
93
|
+
},
|
|
94
|
+
},
|
|
95
|
+
];
|
|
96
|
+
};
|
package/src/routes.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { AgentError, errorMessage } from "./errors";
|
|
3
|
+
import { allows, type Identity, type Role } from "./protocol";
|
|
4
|
+
|
|
5
|
+
/** One `/api` route: who may call it, and what answers it. */
|
|
6
|
+
export interface ApiRoute {
|
|
7
|
+
method: "GET" | "POST" | "PUT" | "DELETE";
|
|
8
|
+
/**
|
|
9
|
+
* A path with `:name` segments, such as `/api/deployments/:id`. A last segment `*` matches the
|
|
10
|
+
* rest of the path, one segment or more, as param `*`.
|
|
11
|
+
*/
|
|
12
|
+
pattern: string;
|
|
13
|
+
role: Role;
|
|
14
|
+
handle: (
|
|
15
|
+
request: Request,
|
|
16
|
+
context: { identity: Identity; params: Readonly<Record<string, string>> },
|
|
17
|
+
) => Promise<Response>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The route `method` and `pathname` name, with the values of its `:name` segments. */
|
|
21
|
+
const matchRoute = (
|
|
22
|
+
routes: readonly ApiRoute[],
|
|
23
|
+
method: string,
|
|
24
|
+
pathname: string,
|
|
25
|
+
) => {
|
|
26
|
+
const parts = pathname.split("/");
|
|
27
|
+
for (const route of routes) {
|
|
28
|
+
const pattern = route.pattern.split("/");
|
|
29
|
+
const rest = pattern.at(-1) === "*";
|
|
30
|
+
if (
|
|
31
|
+
route.method !== method ||
|
|
32
|
+
(rest ? parts.length < pattern.length : pattern.length !== parts.length)
|
|
33
|
+
) {
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
const params: Record<string, string> = {};
|
|
37
|
+
const matched = pattern.every((segment, index) => {
|
|
38
|
+
const part = parts[index] ?? "";
|
|
39
|
+
if (rest && index === pattern.length - 1) {
|
|
40
|
+
params["*"] = parts.slice(index).map(decodeURIComponent).join("/");
|
|
41
|
+
return part !== "";
|
|
42
|
+
}
|
|
43
|
+
if (segment.startsWith(":")) {
|
|
44
|
+
params[segment.slice(1)] = decodeURIComponent(part);
|
|
45
|
+
return part !== "";
|
|
46
|
+
}
|
|
47
|
+
return segment === part;
|
|
48
|
+
});
|
|
49
|
+
if (matched) {
|
|
50
|
+
return { route, params };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return undefined;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
/** What a request reaches past signing in: who may send it, the role it needs and what answers it. */
|
|
57
|
+
export interface Destination {
|
|
58
|
+
/** A browser's session, this PC or a tailnet member may send it; otherwise only a token. */
|
|
59
|
+
browser: boolean;
|
|
60
|
+
role: Role;
|
|
61
|
+
handle: (identity: Identity) => Promise<Response>;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The route of `routes` that `request` names, as a destination a browser may send it to or not. */
|
|
65
|
+
export const routeDestination = (
|
|
66
|
+
request: Request,
|
|
67
|
+
table: { routes: readonly ApiRoute[]; browser: boolean },
|
|
68
|
+
): Destination | undefined => {
|
|
69
|
+
const matched = matchRoute(
|
|
70
|
+
table.routes,
|
|
71
|
+
request.method,
|
|
72
|
+
new URL(request.url).pathname,
|
|
73
|
+
);
|
|
74
|
+
return (
|
|
75
|
+
matched && {
|
|
76
|
+
browser: table.browser,
|
|
77
|
+
role: matched.route.role,
|
|
78
|
+
handle: (identity) =>
|
|
79
|
+
matched.route.handle(request, { identity, params: matched.params }),
|
|
80
|
+
}
|
|
81
|
+
);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Answers `request` as `identity` at `destination`, if it has one: a refused or invalid request with
|
|
86
|
+
* its status and the agent's message, and anything else that fails, logged, with 500.
|
|
87
|
+
*/
|
|
88
|
+
export const answer = async (
|
|
89
|
+
request: Request,
|
|
90
|
+
destination: Destination | undefined,
|
|
91
|
+
identity: Identity,
|
|
92
|
+
log: (message: string) => void,
|
|
93
|
+
): Promise<Response> => {
|
|
94
|
+
if (!destination) {
|
|
95
|
+
// Only an admin learns that a route doesn't exist.
|
|
96
|
+
return allows(identity.role, "admin")
|
|
97
|
+
? Response.json(
|
|
98
|
+
{
|
|
99
|
+
error: `No route ${request.method} ${new URL(request.url).pathname}`,
|
|
100
|
+
},
|
|
101
|
+
{ status: 404 },
|
|
102
|
+
)
|
|
103
|
+
: Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
104
|
+
}
|
|
105
|
+
if (!allows(identity.role, destination.role)) {
|
|
106
|
+
// The CLI's routes answer a token without the role as if it were none, which its client relies on.
|
|
107
|
+
return destination.browser
|
|
108
|
+
? Response.json(
|
|
109
|
+
{ error: `This needs the ${destination.role} role` },
|
|
110
|
+
{ status: 403 },
|
|
111
|
+
)
|
|
112
|
+
: Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
return await destination.handle(identity);
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (error instanceof AgentError) {
|
|
118
|
+
return Response.json({ error: error.message }, { status: error.status });
|
|
119
|
+
}
|
|
120
|
+
if (error instanceof z.ZodError) {
|
|
121
|
+
return Response.json({ error: z.prettifyError(error) }, { status: 400 });
|
|
122
|
+
}
|
|
123
|
+
log(
|
|
124
|
+
`${request.method} ${request.url} failed: ${error instanceof Error ? error.stack : String(error)}`,
|
|
125
|
+
);
|
|
126
|
+
return Response.json({ error: errorMessage(error) }, { status: 500 });
|
|
127
|
+
}
|
|
128
|
+
};
|