@catamorphic/git 0.1.0-alpha.41 → 0.1.0-alpha.43

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.
@@ -0,0 +1,31 @@
1
+ /** The one branch a checkout source advertises, at its commit. */
2
+ export declare const CHECKOUT_BRANCH = "base";
3
+ /** A repository that serves one commit of another, and nothing else. */
4
+ export interface CheckoutSource {
5
+ /** The bare repository `git upload-pack` serves. */
6
+ directory: string;
7
+ /** Remove it. Safe to call again. */
8
+ dispose(): Promise<void>;
9
+ }
10
+ /**
11
+ * Make a repository that serves `commit` of the repository at `repoPath`:
12
+ * the commit with its tree, shallow there, on the branch
13
+ * {@link CHECKOUT_BRANCH}. Nothing is written into `repoPath`.
14
+ */
15
+ export declare function openCheckoutSource(opts: {
16
+ repoPath: string;
17
+ commit: string;
18
+ }): Promise<CheckoutSource>;
19
+ /** What a smart HTTP `info/refs?service=git-upload-pack` answers with. */
20
+ export declare function advertiseCheckout(opts: {
21
+ directory: string;
22
+ signal?: AbortSignal;
23
+ }): AsyncGenerator<Uint8Array>;
24
+ /** What a smart HTTP `git-upload-pack` request answers with. */
25
+ export declare function serveCheckout(opts: {
26
+ directory: string;
27
+ /** The request's body, already decoded when it was compressed. */
28
+ request: AsyncIterable<Uint8Array>;
29
+ signal?: AbortSignal;
30
+ }): AsyncGenerator<Uint8Array>;
31
+ //# sourceMappingURL=workspace-checkout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace-checkout.d.ts","sourceRoot":"","sources":["../src/workspace-checkout.ts"],"names":[],"mappings":"AAwBA,kEAAkE;AAClE,eAAO,MAAM,eAAe,SAAS,CAAC;AAKtC,wEAAwE;AACxE,MAAM,WAAW,cAAc;IAC7B,oDAAoD;IACpD,SAAS,EAAE,MAAM,CAAC;IAClB,qCAAqC;IACrC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CAAC,IAAI,EAAE;IAC7C,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB,GAAG,OAAO,CAAC,cAAc,CAAC,CAsD1B;AAgED,0EAA0E;AAC1E,wBAAuB,iBAAiB,CAAC,IAAI,EAAE;IAC7C,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GAAG,cAAc,CAAC,UAAU,CAAC,CAM7B;AAED,gEAAgE;AAChE,wBAAgB,aAAa,CAAC,IAAI,EAAE;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,kEAAkE;IAClE,OAAO,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,GAAG,cAAc,CAAC,UAAU,CAAC,CAE7B"}
@@ -89,21 +89,42 @@ export declare function moveCheckoutBase(opts: {
89
89
  * the real commits (so `git log`, `diff`, and pushes of new branches work)
90
90
  * without the repository's history before the base. With `tree`, the pack
91
91
  * also holds that tree whole: a session's working tree as last saved (ADR
92
- * 0344), which its sandbox puts back on top of `head`.
92
+ * 0344), which its sandbox puts back on top of `head`. With `holdsBase`
93
+ * the receiver already has the base commit and its tree (it fetched them,
94
+ * ADR 0353), so the pack holds only what the session added: its commits,
95
+ * and the files of the saved tree that differ from the base's. `objects`
96
+ * counts what the pack holds; an empty one need not travel.
93
97
  */
94
98
  export declare function buildSeedPack(opts: {
95
99
  repoPath: string;
96
100
  head: string;
97
101
  base: string;
98
102
  tree?: string;
103
+ holdsBase?: boolean;
99
104
  }): Promise<{
100
105
  pack: Uint8Array;
101
106
  shallow: string[];
107
+ objects: number;
102
108
  }>;
103
109
  /**
104
- * Shell that installs a seed pack uploaded as base64 at `packFile` into the
105
- * repository in the current directory and records `shallow` commits. It
106
- * leaves refs and the working tree to the caller.
110
+ * A seed pack as the files to upload beside each other: base64, in parts
111
+ * named `<name>.000000`, `<name>.000001`, and so on, which
112
+ * {@link seedPackInstallScript} reads back in order. One file per upload
113
+ * keeps every operation small whatever the pack's size, and each part is
114
+ * encoded on its own, so no string grows with the pack either.
115
+ */
116
+ export declare function seedPackParts(opts: {
117
+ pack: Uint8Array;
118
+ name: string;
119
+ }): {
120
+ name: string;
121
+ content: string;
122
+ }[];
123
+ /**
124
+ * Shell that installs a seed pack uploaded as base64 parts
125
+ * (`<packFile>.000000`, ...; see {@link seedPackParts}) into the repository
126
+ * in the current directory and records `shallow` commits. It leaves refs
127
+ * and the working tree to the caller.
107
128
  */
108
129
  export declare function seedPackInstallScript(opts: {
109
130
  packFile: string;
@@ -1 +1 @@
1
- {"version":3,"file":"workspace-mirror.d.ts","sourceRoot":"","sources":["../src/workspace-mirror.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;CAChB;AAID;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAsBvD;AAED,8DAA8D;AAC9D,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAE/C;AAuCD;;;;;;GAMG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE;IAC1C,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,CAAC,EAAE,cAAc,CAAC;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;CACb,GAAG,OAAO,CAAC;IAAE,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CA4C9B;AAED,gEAAgE;AAChE,wBAAsB,cAAc,CAAC,IAAI,EAAE;IACzC,UAAU,EAAE,MAAM,CAAC;IACnB,GAAG,EAAE,MAAM,CAAC;CACb,GAAG,OAAO,CAAC,IAAI,CAAC,CAUhB;AA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U,CAAC;IAAC,OAAO,EAAE,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAiDpE;AAqBD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE;IAClC,IAAI,EAAE,UAAU,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,EAAE,CAetC;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CAC5B,GAAG,MAAM,CAmBT;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@catamorphic/git",
3
- "version": "0.1.0-alpha.41",
3
+ "version": "0.1.0-alpha.43",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -23,7 +23,7 @@
23
23
  ]
24
24
  },
25
25
  "dependencies": {
26
- "@catamorphic/workflow": "0.1.0-alpha.41",
26
+ "@catamorphic/workflow": "0.1.0-alpha.43",
27
27
  "diff3": "0.0.4",
28
28
  "ignore": "^7.0.14",
29
29
  "isomorphic-git": "^1.44.12"
package/src/index.ts CHANGED
@@ -104,6 +104,13 @@ export type {
104
104
  RepoStatus,
105
105
  StorageBackend,
106
106
  } from "./types.js";
107
+ export {
108
+ advertiseCheckout,
109
+ CHECKOUT_BRANCH,
110
+ type CheckoutSource,
111
+ openCheckoutSource,
112
+ serveCheckout,
113
+ } from "./workspace-checkout.js";
107
114
  export {
108
115
  type BaseMoveOutcome,
109
116
  buildSeedPack,
@@ -114,6 +121,7 @@ export {
114
121
  moveCheckoutBase,
115
122
  parseWorkspaceRef,
116
123
  seedPackInstallScript,
124
+ seedPackParts,
117
125
  shellQuote,
118
126
  unpinMirrorRef,
119
127
  type WorkspaceBase,
@@ -0,0 +1,185 @@
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { nativeGit } from "./native-git.js";
6
+
7
+ /*
8
+ * A workspace's base as a Git remote (ADR 0353). A sandbox fetches the
9
+ * commit it stands on with Git's own protocol instead of being handed a
10
+ * pack: the transfer streams, a receiver that already holds some of it
11
+ * (an image, a cache, an earlier base) is sent the rest, and how much
12
+ * arrives (shallow, without blobs, a sparse cone) is the fetching
13
+ * command's to say.
14
+ *
15
+ * The remote is a repository of its own, made for one request and thrown
16
+ * away: it borrows the objects of the copy that holds the commit, ends
17
+ * history at that commit, and advertises one branch at it. Over smart HTTP
18
+ * `git upload-pack` serves a want only when it is reachable from what is
19
+ * advertised, so the commit, its tree and its files can be fetched and
20
+ * nothing else the copy holds, whatever object id a caller names.
21
+ */
22
+
23
+ const COMMIT = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
24
+
25
+ /** The one branch a checkout source advertises, at its commit. */
26
+ export const CHECKOUT_BRANCH = "base";
27
+
28
+ /** How long one `git upload-pack` may run. */
29
+ const UPLOAD_PACK_TIMEOUT_MS = 30 * 60_000;
30
+
31
+ /** A repository that serves one commit of another, and nothing else. */
32
+ export interface CheckoutSource {
33
+ /** The bare repository `git upload-pack` serves. */
34
+ directory: string;
35
+ /** Remove it. Safe to call again. */
36
+ dispose(): Promise<void>;
37
+ }
38
+
39
+ /**
40
+ * Make a repository that serves `commit` of the repository at `repoPath`:
41
+ * the commit with its tree, shallow there, on the branch
42
+ * {@link CHECKOUT_BRANCH}. Nothing is written into `repoPath`.
43
+ */
44
+ export async function openCheckoutSource(opts: {
45
+ repoPath: string;
46
+ commit: string;
47
+ }): Promise<CheckoutSource> {
48
+ if (!COMMIT.test(opts.commit))
49
+ throw new Error("A checkout source names a full commit id");
50
+ const objects = path.resolve(
51
+ opts.repoPath,
52
+ (
53
+ await nativeGit(opts.repoPath, ["rev-parse", "--git-path", "objects"])
54
+ ).trim(),
55
+ );
56
+ if (/[\n"]/.test(objects))
57
+ throw new Error("The repository's path cannot be served from");
58
+ // The commit must be there whole before anything is advertised.
59
+ await nativeGit(opts.repoPath, ["cat-file", "-e", `${opts.commit}^{commit}`]);
60
+ const directory = await fs.mkdtemp(path.join(tmpdir(), "work-checkout-"));
61
+ const dispose = () => fs.rm(directory, { recursive: true, force: true });
62
+ try {
63
+ await nativeGit(directory, [
64
+ "init",
65
+ "--bare",
66
+ "--quiet",
67
+ ...(opts.commit.length === 64 ? ["--object-format=sha256"] : []),
68
+ ]);
69
+ await fs.writeFile(
70
+ path.join(directory, "objects", "info", "alternates"),
71
+ `${objects}\n`,
72
+ );
73
+ // History ends here: nothing before the commit is reachable, so none
74
+ // of it is served.
75
+ await fs.writeFile(path.join(directory, "shallow"), `${opts.commit}\n`);
76
+ await nativeGit(directory, [
77
+ "update-ref",
78
+ `refs/heads/${CHECKOUT_BRANCH}`,
79
+ opts.commit,
80
+ ]);
81
+ await nativeGit(directory, [
82
+ "symbolic-ref",
83
+ "HEAD",
84
+ `refs/heads/${CHECKOUT_BRANCH}`,
85
+ ]);
86
+ // A fetching command may leave blobs or trees out (`--filter`), and
87
+ // ask for one later by its id: served when it is reachable from the
88
+ // branch, which is all that "reachable" can mean in a repository
89
+ // whose history ends at it.
90
+ await nativeGit(directory, ["config", "uploadpack.allowFilter", "true"]);
91
+ await nativeGit(directory, [
92
+ "config",
93
+ "uploadpack.allowReachableSHA1InWant",
94
+ "true",
95
+ ]);
96
+ return { directory, dispose };
97
+ } catch (error) {
98
+ await dispose();
99
+ throw error;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Run `git upload-pack` on a checkout source and stream what it writes.
105
+ * Protocol version 0 always: there the server checks that every want is
106
+ * reachable from what it advertised, which version 2 does not. A request
107
+ * the server refuses ends with Git's own error line for the client.
108
+ */
109
+ async function* uploadPack(opts: {
110
+ directory: string;
111
+ args: readonly string[];
112
+ request?: AsyncIterable<Uint8Array>;
113
+ signal?: AbortSignal;
114
+ }): AsyncGenerator<Uint8Array> {
115
+ const { GIT_PROTOCOL: _version, ...env } = process.env;
116
+ const child = spawn(
117
+ "git",
118
+ ["upload-pack", "--stateless-rpc", ...opts.args, opts.directory],
119
+ {
120
+ env: { ...env, GIT_OPTIONAL_LOCKS: "0" },
121
+ stdio: ["pipe", "pipe", "ignore"],
122
+ },
123
+ );
124
+ const stop = () => {
125
+ if (child.exitCode === null && child.signalCode === null)
126
+ child.kill("SIGKILL");
127
+ };
128
+ const timer = setTimeout(stop, UPLOAD_PACK_TIMEOUT_MS);
129
+ timer.unref?.();
130
+ opts.signal?.addEventListener("abort", stop, { once: true });
131
+ const spawned = new Promise<void>((resolve, reject) => {
132
+ child.once("spawn", () => resolve());
133
+ child.once("error", reject);
134
+ });
135
+ // The request is written beside the read: a large negotiation fills
136
+ // both pipes at once.
137
+ const written = (async () => {
138
+ try {
139
+ if (opts.request)
140
+ for await (const chunk of opts.request) {
141
+ if (!child.stdin.write(chunk))
142
+ await new Promise<void>((resolve) =>
143
+ child.stdin.once("drain", () => resolve()),
144
+ );
145
+ }
146
+ } catch {
147
+ // A request that ends early ends the answer: Git says why.
148
+ } finally {
149
+ child.stdin.end();
150
+ }
151
+ })();
152
+ child.stdin.on("error", () => {});
153
+ try {
154
+ await spawned;
155
+ for await (const chunk of child.stdout)
156
+ if (chunk instanceof Uint8Array) yield chunk;
157
+ await written;
158
+ } finally {
159
+ clearTimeout(timer);
160
+ opts.signal?.removeEventListener("abort", stop);
161
+ stop();
162
+ }
163
+ }
164
+
165
+ /** What a smart HTTP `info/refs?service=git-upload-pack` answers with. */
166
+ export async function* advertiseCheckout(opts: {
167
+ directory: string;
168
+ signal?: AbortSignal;
169
+ }): AsyncGenerator<Uint8Array> {
170
+ const service = "# service=git-upload-pack\n";
171
+ yield new TextEncoder().encode(
172
+ `${(service.length + 4).toString(16).padStart(4, "0")}${service}0000`,
173
+ );
174
+ yield* uploadPack({ ...opts, args: ["--advertise-refs"] });
175
+ }
176
+
177
+ /** What a smart HTTP `git-upload-pack` request answers with. */
178
+ export function serveCheckout(opts: {
179
+ directory: string;
180
+ /** The request's body, already decoded when it was compressed. */
181
+ request: AsyncIterable<Uint8Array>;
182
+ signal?: AbortSignal;
183
+ }): AsyncGenerator<Uint8Array> {
184
+ return uploadPack({ ...opts, args: [] });
185
+ }
@@ -279,14 +279,19 @@ export async function moveCheckoutBase(opts: {
279
279
  * the real commits (so `git log`, `diff`, and pushes of new branches work)
280
280
  * without the repository's history before the base. With `tree`, the pack
281
281
  * also holds that tree whole: a session's working tree as last saved (ADR
282
- * 0344), which its sandbox puts back on top of `head`.
282
+ * 0344), which its sandbox puts back on top of `head`. With `holdsBase`
283
+ * the receiver already has the base commit and its tree (it fetched them,
284
+ * ADR 0353), so the pack holds only what the session added: its commits,
285
+ * and the files of the saved tree that differ from the base's. `objects`
286
+ * counts what the pack holds; an empty one need not travel.
283
287
  */
284
288
  export async function buildSeedPack(opts: {
285
289
  repoPath: string;
286
290
  head: string;
287
291
  base: string;
288
292
  tree?: string;
289
- }): Promise<{ pack: Uint8Array; shallow: string[] }> {
293
+ holdsBase?: boolean;
294
+ }): Promise<{ pack: Uint8Array; shallow: string[]; objects: number }> {
290
295
  for (const id of [opts.head, opts.base, ...(opts.tree ? [opts.tree] : [])])
291
296
  if (!COMMIT.test(id)) throw new Error("A seed pack names full object ids");
292
297
  const objects = path.resolve(
@@ -313,22 +318,81 @@ export async function buildSeedPack(opts: {
313
318
  `${objects}\n`,
314
319
  );
315
320
  await fs.writeFile(path.join(directory, "shallow"), `${opts.base}\n`);
321
+ // The base's tree is left out by name as well as its commit: a walk
322
+ // that finds no commit to send (a head still on its base) never
323
+ // reaches the base's tree to leave it out, and would send the saved
324
+ // tree whole.
325
+ const held = opts.holdsBase
326
+ ? [
327
+ `^${opts.base}`,
328
+ `^${(await nativeGit(directory, ["rev-parse", "--verify", `${opts.base}^{tree}`])).trim()}`,
329
+ ]
330
+ : [opts.base];
316
331
  const pack = await gitOutput({
317
332
  cwd: directory,
318
333
  args: ["pack-objects", "--revs", "--stdout", "--quiet"],
319
- // The base itself too: a head that left it still needs it as its ref.
320
- input: `${[opts.head, opts.base, ...(opts.tree ? [opts.tree] : [])].join("\n")}\n`,
334
+ // The base itself too: a head that left it still needs it as its
335
+ // ref. Left out, with everything it reaches, when the receiver
336
+ // holds it.
337
+ input: `${[...held, opts.head, ...(opts.tree ? [opts.tree] : [])].join("\n")}\n`,
321
338
  });
322
- return { pack, shallow: [opts.base] };
339
+ return { pack, shallow: [opts.base], objects: packObjectCount(pack) };
323
340
  } finally {
324
341
  await fs.rm(directory, { recursive: true, force: true });
325
342
  }
326
343
  }
327
344
 
345
+ /** How many objects a packfile says it holds (its header's count). */
346
+ function packObjectCount(pack: Uint8Array): number {
347
+ if (pack.byteLength < 12) return 0;
348
+ return new DataView(pack.buffer, pack.byteOffset, pack.byteLength).getUint32(
349
+ 8,
350
+ );
351
+ }
352
+
353
+ /**
354
+ * The bytes of a seed pack one uploaded part holds: a multiple of three,
355
+ * so every part is whole base64 groups and the parts decode joined, and
356
+ * small enough that a part's operation stays far under what a queue row
357
+ * can carry (4 MiB of text).
358
+ */
359
+ const SEED_PART_BYTES = 3 * 1024 * 1024;
360
+
361
+ /** Digits in a part's number: parts sort by name whatever their count. */
362
+ const SEED_PART_DIGITS = 6;
363
+
364
+ /**
365
+ * A seed pack as the files to upload beside each other: base64, in parts
366
+ * named `<name>.000000`, `<name>.000001`, and so on, which
367
+ * {@link seedPackInstallScript} reads back in order. One file per upload
368
+ * keeps every operation small whatever the pack's size, and each part is
369
+ * encoded on its own, so no string grows with the pack either.
370
+ */
371
+ export function seedPackParts(opts: {
372
+ pack: Uint8Array;
373
+ name: string;
374
+ }): { name: string; content: string }[] {
375
+ const bytes = Buffer.from(
376
+ opts.pack.buffer,
377
+ opts.pack.byteOffset,
378
+ opts.pack.byteLength,
379
+ );
380
+ const parts: { name: string; content: string }[] = [];
381
+ for (let start = 0; start < bytes.byteLength; start += SEED_PART_BYTES)
382
+ parts.push({
383
+ name: `${opts.name}.${String(parts.length).padStart(SEED_PART_DIGITS, "0")}`,
384
+ content: bytes
385
+ .subarray(start, start + SEED_PART_BYTES)
386
+ .toString("base64"),
387
+ });
388
+ return parts;
389
+ }
390
+
328
391
  /**
329
- * Shell that installs a seed pack uploaded as base64 at `packFile` into the
330
- * repository in the current directory and records `shallow` commits. It
331
- * leaves refs and the working tree to the caller.
392
+ * Shell that installs a seed pack uploaded as base64 parts
393
+ * (`<packFile>.000000`, ...; see {@link seedPackParts}) into the repository
394
+ * in the current directory and records `shallow` commits. It leaves refs
395
+ * and the working tree to the caller.
332
396
  */
333
397
  export function seedPackInstallScript(opts: {
334
398
  packFile: string;
@@ -338,9 +402,12 @@ export function seedPackInstallScript(opts: {
338
402
  if (!COMMIT.test(commit)) throw new Error("Invalid shallow commit");
339
403
  }
340
404
  const gitDir = `"$(git rev-parse --git-dir)"`;
405
+ const parts = `${shellQuote(opts.packFile)}.${"[0-9]".repeat(SEED_PART_DIGITS)}`;
341
406
  return [
342
- `base64 -d < ${shellQuote(opts.packFile)} | git index-pack --stdin --fix-thin >/dev/null`,
343
- `rm -f ${shellQuote(opts.packFile)}`,
407
+ // Parts sort by name, and each is whole base64 groups, so they decode
408
+ // as one stream.
409
+ `cat ${parts} | base64 -d | git index-pack --stdin --fix-thin >/dev/null`,
410
+ `rm -f ${parts}`,
344
411
  ...(opts.shallow.length > 0
345
412
  ? [
346
413
  `touch ${gitDir}/shallow`,