@tsplc/agent 0.2.21 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/releases.ts CHANGED
@@ -3,32 +3,62 @@ import { existsSync } from "node:fs";
3
3
  import {
4
4
  mkdir,
5
5
  mkdtemp,
6
+ readdir,
6
7
  readFile,
7
8
  rename,
8
9
  rm,
10
+ stat,
9
11
  writeFile,
10
12
  } from "node:fs/promises";
11
- import { dirname, join, posix } from "node:path";
13
+ import { dirname, join, posix, sep } from "node:path";
12
14
  import { z } from "zod";
15
+ import { AgentError } from "./errors";
13
16
  import {
17
+ type Comparison,
18
+ type DeployOptions,
19
+ deployOptionsSchema,
14
20
  type ReleaseManifest,
21
+ type ReleaseUpload,
15
22
  releaseManifestSchema,
23
+ releaseUploadSchema,
24
+ releaseUploadType,
16
25
  uploadEncoding,
17
26
  } from "./protocol";
27
+ import {
28
+ bucketDigests,
29
+ decodeUpload,
30
+ fileBucket,
31
+ type ReleaseContent,
32
+ shortDigest,
33
+ } from "./transfer";
18
34
 
19
35
  /** Uploaded files are named `files/<path in the release>`. */
20
36
  const filePrefix = "files/";
21
37
 
22
38
  const releasePath = (name: string) => {
23
- const path = posix.normalize(name.slice(filePrefix.length));
39
+ const path = posix.normalize(name);
24
40
  if (posix.isAbsolute(path) || path.startsWith("..") || path.includes("\\")) {
25
41
  throw new Error(`Invalid release file name: ${name}`);
26
42
  }
27
43
  return path;
28
44
  };
29
45
 
30
- /** An uploaded release, from `tsplc deploy`'s form. */
31
- export const readUpload = async (form: FormData) => {
46
+ /** A release to store: its manifest and every file. */
47
+ export interface Upload {
48
+ manifest: ReleaseManifest;
49
+ files: ReleaseContent[];
50
+ }
51
+
52
+ const checkServer = ({ manifest, files }: Upload) => {
53
+ if (manifest.server && !files.some((file) => file.path === manifest.server)) {
54
+ throw new Error(
55
+ `The release names a server ${manifest.server} it doesn't contain`,
56
+ );
57
+ }
58
+ };
59
+
60
+ /** An uploaded release, from the multipart form `tsplc deploy` sends an agent that can't compare releases. */
61
+ export const readUpload = async (form: FormData): Promise<Upload> => {
32
62
  if (form.get("encoding") !== uploadEncoding) {
33
63
  throw new Error(
34
64
  "This deployment came from an older tsplc: update tsplc where you deploy from.",
@@ -41,18 +71,49 @@ export const readUpload = async (form: FormData) => {
41
71
  [...form.entries()]
42
72
  .filter(([name]) => name.startsWith(filePrefix))
43
73
  .map(async ([name, value]) => ({
44
- path: releasePath(name),
74
+ path: releasePath(name.slice(filePrefix.length)),
45
75
  content: Bun.gunzipSync(await z.instanceof(File).parse(value).bytes()),
46
76
  })),
47
77
  );
48
- if (manifest.server && !files.some((file) => file.path === manifest.server)) {
49
- throw new Error(
50
- `The release names a server ${manifest.server} it doesn't contain`,
51
- );
78
+ const upload = { manifest, files };
79
+ checkServer(upload);
80
+ return upload;
81
+ };
82
+
83
+ /** A deployment's options and release, from either form of `POST /deploy`. */
84
+ export interface DeployRequest {
85
+ settings: DeployOptions;
86
+ upload: Upload;
87
+ }
88
+
89
+ /**
90
+ * Reads `POST /deploy`: a release upload built on a stored release, or the multipart form of a
91
+ * tsplc from before `POST /releases/compare`.
92
+ */
93
+ export const readDeployRequest = async (
94
+ releases: ReleaseStore,
95
+ request: Request,
96
+ ): Promise<DeployRequest> => {
97
+ const type = request.headers.get("content-type") ?? "";
98
+ if (type.split(";")[0]?.trim() === releaseUploadType) {
99
+ const { header, files } = await decodeUpload(await request.bytes());
100
+ const upload = releaseUploadSchema.parse(header);
101
+ return {
102
+ settings: upload.options,
103
+ upload: await releases.assemble(upload, files),
104
+ };
52
105
  }
53
- return { manifest, files };
106
+ if (type.startsWith("multipart/form-data")) {
107
+ const form = await request.formData();
108
+ return {
109
+ settings: deployOptionsSchema.parse(
110
+ JSON.parse(z.string().parse(form.get("options"))),
111
+ ),
112
+ upload: await readUpload(form),
113
+ };
114
+ }
115
+ throw new AgentError(`Unsupported deployment content type ${type}`, 415);
54
116
  };
55
- export type Upload = Awaited<ReturnType<typeof readUpload>>;
56
117
 
57
118
  /** A release in the releases directory. */
58
119
  export interface StoredRelease {
@@ -111,3 +172,150 @@ export const loadRelease = async (
111
172
  );
112
173
  return { id, directory, manifest };
113
174
  };
175
+
176
+ /** A stored release's files by path, with their digests, and its bucket digests. */
177
+ interface ReleaseIndex {
178
+ files: Map<string, string>;
179
+ buckets: string[];
180
+ }
181
+
182
+ /**
183
+ * Compares uploads with the stored releases and builds releases from them. Stored releases never
184
+ * change, so each one's index is read once.
185
+ */
186
+ export const createReleaseStore = (releases: string) => {
187
+ const indexes = new Map<string, Promise<ReleaseIndex>>();
188
+
189
+ const readIndex = async (id: string): Promise<ReleaseIndex> => {
190
+ const directory = join(releases, id);
191
+ const files = new Map<string, string>();
192
+ for await (const found of new Bun.Glob("**/*").scan({
193
+ cwd: directory,
194
+ dot: true,
195
+ })) {
196
+ const path = found.split(sep).join("/");
197
+ // The release's manifest travels in the upload's header, not as one of its files.
198
+ if (path !== "manifest.json") {
199
+ files.set(path, shortDigest(await readFile(join(directory, found))));
200
+ }
201
+ }
202
+ const digests = [...files].map(([path, digest]) => ({ path, digest }));
203
+ return { files, buckets: bucketDigests(digests) };
204
+ };
205
+ const index = (id: string) => {
206
+ const known = indexes.get(id);
207
+ if (known) {
208
+ return known;
209
+ }
210
+ const reading = readIndex(id);
211
+ indexes.set(id, reading);
212
+ reading.catch(() => indexes.delete(id));
213
+ return reading;
214
+ };
215
+
216
+ /** The most recently stored release, which a failed deployment of the same program leaves behind. */
217
+ const newest = async () => {
218
+ if (!existsSync(releases)) {
219
+ return undefined;
220
+ }
221
+ const stored = await Promise.all(
222
+ (await readdir(releases, { withFileTypes: true }))
223
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
224
+ .map(async ({ name }) => ({
225
+ name,
226
+ created: (await stat(join(releases, name))).mtimeMs,
227
+ })),
228
+ );
229
+ return stored.sort((left, right) => right.created - left.created)[0]?.name;
230
+ };
231
+
232
+ return {
233
+ /** The candidate, of the deployed release and the newest stored one, that differs from `buckets` least. */
234
+ compare: async (
235
+ buckets: readonly string[],
236
+ deployed: string | null,
237
+ ): Promise<Comparison> => {
238
+ const candidates = [
239
+ ...new Set([deployed, await newest()].filter((id) => id != null)),
240
+ ].filter((id) => existsSync(join(releases, id, "manifest.json")));
241
+ const compared = await Promise.all(
242
+ candidates.map(async (id) => {
243
+ const { files, buckets: stored } = await index(id);
244
+ const changed = buckets.flatMap((digest, bucket) =>
245
+ stored[bucket] === digest ? [] : [bucket],
246
+ );
247
+ return { id, files, changed };
248
+ }),
249
+ );
250
+ const [best] = compared.sort(
251
+ (left, right) => left.changed.length - right.changed.length,
252
+ );
253
+ if (!best) {
254
+ return { base: null, changed: [] };
255
+ }
256
+ const changed = new Map<number, Record<string, string>>(
257
+ best.changed.map((bucket) => [bucket, {}]),
258
+ );
259
+ for (const [path, digest] of best.files) {
260
+ const held = changed.get(fileBucket(path));
261
+ if (held) {
262
+ held[path] = digest;
263
+ }
264
+ }
265
+ return {
266
+ base: best.id,
267
+ changed: [...changed].map(([bucket, files]) => ({ bucket, files })),
268
+ };
269
+ },
270
+
271
+ /** The release an upload describes, checked against the bucket digests it was sent with. */
272
+ assemble: async (
273
+ { manifest, base, buckets, remove }: ReleaseUpload,
274
+ uploaded: readonly ReleaseContent[],
275
+ ): Promise<Upload> => {
276
+ const files = new Map(
277
+ uploaded.map(({ path, content }) => [releasePath(path), content]),
278
+ );
279
+ if (files.size !== uploaded.length) {
280
+ throw new AgentError("The release upload sends a file twice", 400);
281
+ }
282
+ if (base !== null) {
283
+ if (!existsSync(join(releases, base, "manifest.json"))) {
284
+ throw new AgentError(
285
+ `The release ${base} this upload builds on is gone; deploy again`,
286
+ 409,
287
+ );
288
+ }
289
+ const removed = new Set(remove);
290
+ const reused = [...(await index(base)).files.keys()].filter(
291
+ (path) => !removed.has(path) && !files.has(path),
292
+ );
293
+ for (const path of reused) {
294
+ files.set(
295
+ path,
296
+ new Uint8Array(await readFile(join(releases, base, path))),
297
+ );
298
+ }
299
+ }
300
+ const assembled = bucketDigests(
301
+ [...files].map(([path, content]) => ({
302
+ path,
303
+ digest: shortDigest(content),
304
+ })),
305
+ );
306
+ if (assembled.some((digest, bucket) => digest !== buckets[bucket])) {
307
+ throw new AgentError(
308
+ "The release upload doesn't match the release it describes; deploy again",
309
+ 400,
310
+ );
311
+ }
312
+ const upload = {
313
+ manifest,
314
+ files: [...files].map(([path, content]) => ({ path, content })),
315
+ };
316
+ checkServer(upload);
317
+ return upload;
318
+ },
319
+ };
320
+ };
321
+ export type ReleaseStore = ReturnType<typeof createReleaseStore>;
package/src/secrets.ts CHANGED
@@ -79,14 +79,15 @@ export const readSecrets = async (secrets: ReleaseManifest["secrets"]) => {
79
79
  return values;
80
80
  };
81
81
 
82
- /** Variable `name` for the agent's own use: from Bun.secrets when the release names it as a secret, otherwise the agent's environment. */
82
+ /** Variable `name` for the agent's own use: from Bun.secrets when the release names it as a secret, otherwise `environment`. */
83
83
  export const releaseVariable = async (
84
84
  manifest: ReleaseManifest,
85
85
  name: string,
86
+ environment: Readonly<Record<string, string | undefined>>,
86
87
  ) =>
87
88
  manifest.secrets?.names.includes(name)
88
89
  ? Bun.secrets.get({ service: manifest.secrets.service, name })
89
- : process.env[name];
90
+ : environment[name];
90
91
 
91
92
  /** Structured Text with each secret's placeholder replaced by its value, inside the STRING literal that holds it. */
92
93
  const fillSecrets = (st: string, secrets: ReadonlyMap<string, string>) =>
@@ -1,6 +1,6 @@
1
- import type { Subprocess } from "bun";
2
1
  import { dirname } from "node:path";
3
2
  import { setTimeout as delay } from "node:timers/promises";
3
+ import type { Subprocess } from "bun";
4
4
 
5
5
  const healthyWithinMs = 60_000;
6
6
  /** Without a health URL, a server that stays up this long counts as started. */
@@ -0,0 +1,94 @@
1
+ import { createHash } from "node:crypto";
2
+ import { releaseBuckets } from "./protocol";
3
+
4
+ /**
5
+ * How `tsplc deploy` sends a release the agent can build from one it already holds. The release's
6
+ * files fall into buckets by path, and each bucket has a digest; the agent answers which buckets
7
+ * differ from a release it stores and that release's files in them, and the client sends only the
8
+ * files the agent lacks, with the release's other parts named rather than sent. The whole upload
9
+ * is one zstd stream: the release's ST files are thousands of small, similar files.
10
+ */
11
+
12
+ /** A file of a release, at its path in the release. */
13
+ export interface ReleaseContent {
14
+ path: string;
15
+ content: Uint8Array<ArrayBuffer>;
16
+ }
17
+
18
+ /** The first 16 hex digits of a SHA-256: enough to tell a release's files apart, and short on the wire. */
19
+ export const shortDigest = (data: Uint8Array | string) =>
20
+ createHash("sha256").update(data).digest("hex").slice(0, 16);
21
+
22
+ /** The bucket a release path falls in, the same in every release. */
23
+ export const fileBucket = (path: string) =>
24
+ createHash("sha256").update(path).digest().readUInt8(0) % releaseBuckets;
25
+
26
+ /** Each bucket's digest over the paths and contents of its files, from each file's `shortDigest`. */
27
+ export const bucketDigests = (
28
+ files: Iterable<{ path: string; digest: string }>,
29
+ ): string[] => {
30
+ const buckets = Array.from({ length: releaseBuckets }, (): string[] => []);
31
+ for (const { path, digest } of files) {
32
+ buckets[fileBucket(path)]?.push(`${path}\0${digest}`);
33
+ }
34
+ return buckets.map((entries) => shortDigest(entries.sort().join("\n")));
35
+ };
36
+
37
+ /** A frame's length prefix: an unsigned 32-bit big-endian byte count. */
38
+ const lengthBytes = 4;
39
+
40
+ /** Frames the upload's header and then each file's path and content, and compresses the lot. */
41
+ export const encodeUpload = async (
42
+ header: unknown,
43
+ files: readonly ReleaseContent[],
44
+ ): Promise<Uint8Array<ArrayBuffer>> => {
45
+ const encoder = new TextEncoder();
46
+ const frames = [
47
+ encoder.encode(JSON.stringify(header)),
48
+ ...files.flatMap(({ path, content }) => [encoder.encode(path), content]),
49
+ ];
50
+ const body = new Uint8Array(
51
+ frames.reduce((total, frame) => total + lengthBytes + frame.length, 0),
52
+ );
53
+ const view = new DataView(body.buffer);
54
+ let offset = 0;
55
+ for (const frame of frames) {
56
+ view.setUint32(offset, frame.length);
57
+ body.set(frame, offset + lengthBytes);
58
+ offset += lengthBytes + frame.length;
59
+ }
60
+ return new Uint8Array(await Bun.zstdCompress(body, { level: 12 }));
61
+ };
62
+
63
+ /** An upload's header, still to be validated, and its files. */
64
+ export const decodeUpload = async (
65
+ compressed: Uint8Array,
66
+ ): Promise<{ header: unknown; files: ReleaseContent[] }> => {
67
+ const body = new Uint8Array(await Bun.zstdDecompress(compressed));
68
+ const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
69
+ const frames: Uint8Array<ArrayBuffer>[] = [];
70
+ let offset = 0;
71
+ while (offset < body.length) {
72
+ if (offset + lengthBytes > body.length) {
73
+ throw new Error("The release upload ends inside a frame");
74
+ }
75
+ const end = offset + lengthBytes + view.getUint32(offset);
76
+ if (end > body.length) {
77
+ throw new Error("The release upload ends inside a frame");
78
+ }
79
+ frames.push(body.subarray(offset + lengthBytes, end));
80
+ offset = end;
81
+ }
82
+ const [header, ...rest] = frames;
83
+ if (!header || rest.length % 2 !== 0) {
84
+ throw new Error(
85
+ "The release upload has no header or a file without content",
86
+ );
87
+ }
88
+ const decoder = new TextDecoder();
89
+ const files = Array.from({ length: rest.length / 2 }, (_, index) => ({
90
+ path: decoder.decode(rest[2 * index]),
91
+ content: rest[2 * index + 1] ?? new Uint8Array(),
92
+ }));
93
+ return { header: JSON.parse(decoder.decode(header)), files };
94
+ };