@catamorphic/git 0.1.0-alpha.42 → 0.1.0-alpha.44
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/dist/checkout-remote-backend.d.ts.map +1 -1
- package/dist/fs-backend.d.ts +8 -0
- package/dist/fs-backend.d.ts.map +1 -1
- package/dist/fs-remote-backend.d.ts +43 -9
- package/dist/fs-remote-backend.d.ts.map +1 -1
- package/dist/git-objects.d.ts +77 -0
- package/dist/git-objects.d.ts.map +1 -0
- package/dist/git-sync.d.ts +16 -17
- package/dist/git-sync.d.ts.map +1 -1
- package/dist/index.d.ts +6 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3912 -3059
- package/dist/index.js.map +23 -21
- package/dist/native-git.d.ts +114 -2
- package/dist/native-git.d.ts.map +1 -1
- package/dist/native-project-repo.d.ts +40 -5
- package/dist/native-project-repo.d.ts.map +1 -1
- package/dist/network-sync.d.ts.map +1 -1
- package/dist/network.d.ts +14 -9
- package/dist/network.d.ts.map +1 -1
- package/dist/object-origin-cache.d.ts +86 -0
- package/dist/object-origin-cache.d.ts.map +1 -0
- package/dist/object-remote-backend.d.ts +64 -10
- package/dist/object-remote-backend.d.ts.map +1 -1
- package/dist/origin-draft.d.ts.map +1 -1
- package/dist/origin-objects.d.ts +7 -2
- package/dist/origin-objects.d.ts.map +1 -1
- package/dist/project-manager.d.ts +22 -0
- package/dist/project-manager.d.ts.map +1 -1
- package/dist/project-paths.d.ts +20 -0
- package/dist/project-paths.d.ts.map +1 -0
- package/dist/ref-names.d.ts +35 -0
- package/dist/ref-names.d.ts.map +1 -1
- package/dist/types.d.ts +37 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/workspace-checkout.d.ts +31 -0
- package/dist/workspace-checkout.d.ts.map +1 -0
- package/dist/workspace-mirror.d.ts +38 -5
- package/dist/workspace-mirror.d.ts.map +1 -1
- package/dist/workspace-save.d.ts +27 -2
- package/dist/workspace-save.d.ts.map +1 -1
- package/package.json +4 -4
- package/src/checkout-remote-backend.ts +77 -29
- package/src/fs-backend.ts +69 -7
- package/src/fs-remote-backend.ts +255 -133
- package/src/git-objects.ts +363 -0
- package/src/git-sync.ts +124 -453
- package/src/index.ts +17 -7
- package/src/native-git.ts +566 -25
- package/src/native-project-repo.ts +318 -99
- package/src/network-sync.ts +43 -35
- package/src/network.ts +177 -153
- package/src/object-origin-cache.ts +689 -0
- package/src/object-remote-backend.ts +277 -20
- package/src/origin-draft.ts +22 -15
- package/src/origin-objects.ts +21 -5
- package/src/project-manager.ts +261 -73
- package/src/project-paths.ts +142 -0
- package/src/ref-names.ts +56 -0
- package/src/types.ts +38 -4
- package/src/workspace-checkout.ts +192 -0
- package/src/workspace-mirror.ts +276 -68
- package/src/workspace-save.ts +99 -30
- package/dist/project-repo.d.ts +0 -81
- package/dist/project-repo.d.ts.map +0 -1
- package/src/project-repo.ts +0 -821
|
@@ -0,0 +1,689 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import {
|
|
5
|
+
type GitObjectType,
|
|
6
|
+
parseCommit,
|
|
7
|
+
unwrapObject,
|
|
8
|
+
} from "./git-object-codec.js";
|
|
9
|
+
import {
|
|
10
|
+
closeObjectReaders,
|
|
11
|
+
type ObjectAnswer,
|
|
12
|
+
objectContent,
|
|
13
|
+
objectHeader,
|
|
14
|
+
writeWrappedObject,
|
|
15
|
+
} from "./git-objects.js";
|
|
16
|
+
import {
|
|
17
|
+
gitErrorText,
|
|
18
|
+
initManagedRepository,
|
|
19
|
+
nativeGit,
|
|
20
|
+
nativeGitStream,
|
|
21
|
+
TRANSFER_TIMEOUT_MS,
|
|
22
|
+
} from "./native-git.js";
|
|
23
|
+
import type { ObjectStore } from "./object-store.js";
|
|
24
|
+
import { mapLimit, parseTree } from "./origin-objects.js";
|
|
25
|
+
|
|
26
|
+
/** Bytes of a pack one stored part holds. */
|
|
27
|
+
export const PACK_PART_BYTES = 8 * 1024 * 1024;
|
|
28
|
+
|
|
29
|
+
/** Parts of one pack written or read at once. */
|
|
30
|
+
const PART_CONCURRENCY = 4;
|
|
31
|
+
|
|
32
|
+
/** Single objects read from the store at once. */
|
|
33
|
+
const OBJECT_CONCURRENCY = 16;
|
|
34
|
+
|
|
35
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
36
|
+
/**
|
|
37
|
+
* A stored pack's id: when its upload began (milliseconds, base 36), then
|
|
38
|
+
* a random part. The time tells an upload still under way from one that a
|
|
39
|
+
* stopped process left behind.
|
|
40
|
+
*/
|
|
41
|
+
const PACK_ID =
|
|
42
|
+
/^([0-9a-z]{7,11})-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* How long parts with no description, or scratch on disk, are left alone:
|
|
46
|
+
* longer than any upload or download may run, so what is removed belongs
|
|
47
|
+
* to nothing that is still working.
|
|
48
|
+
*/
|
|
49
|
+
const ABANDONED_AFTER_MS = 2 * TRANSFER_TIMEOUT_MS;
|
|
50
|
+
|
|
51
|
+
/** Cache folders this process has already cleared of leftovers. */
|
|
52
|
+
const swept = new Set<string>();
|
|
53
|
+
/** Origins whose abandoned parts this process has already removed. */
|
|
54
|
+
const sweptStores = new WeakMap<ObjectStore, Set<string>>();
|
|
55
|
+
const OBJECT_ID = /^[0-9a-f]{40}$/;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* What a stored pack is: how many parts hold it, its size, and the commits
|
|
59
|
+
* whose histories it was built on top of. A pack holds what its tip reaches
|
|
60
|
+
* and those commits do not, so it is whole once they are.
|
|
61
|
+
*/
|
|
62
|
+
interface PackManifest {
|
|
63
|
+
version: 1;
|
|
64
|
+
parts: number;
|
|
65
|
+
bytes: number;
|
|
66
|
+
bases: string[];
|
|
67
|
+
/** The commit the pack was built for. */
|
|
68
|
+
tip?: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function parseManifest(data: Uint8Array): PackManifest {
|
|
72
|
+
const value: unknown = JSON.parse(new TextDecoder().decode(data));
|
|
73
|
+
if (!value || typeof value !== "object")
|
|
74
|
+
throw new Error("A stored pack's description is not readable");
|
|
75
|
+
const parts = "parts" in value ? value.parts : undefined;
|
|
76
|
+
const bytes = "bytes" in value ? value.bytes : undefined;
|
|
77
|
+
const bases = "bases" in value ? value.bases : undefined;
|
|
78
|
+
const tip = "tip" in value ? value.tip : undefined;
|
|
79
|
+
if (
|
|
80
|
+
typeof parts !== "number" ||
|
|
81
|
+
!Number.isSafeInteger(parts) ||
|
|
82
|
+
parts < 1 ||
|
|
83
|
+
typeof bytes !== "number" ||
|
|
84
|
+
!Array.isArray(bases)
|
|
85
|
+
)
|
|
86
|
+
throw new Error("A stored pack's description is not readable");
|
|
87
|
+
return {
|
|
88
|
+
version: 1,
|
|
89
|
+
parts,
|
|
90
|
+
bytes,
|
|
91
|
+
bases: bases.filter(
|
|
92
|
+
(base): base is string =>
|
|
93
|
+
typeof base === "string" && OBJECT_ID.test(base),
|
|
94
|
+
),
|
|
95
|
+
...(typeof tip === "string" && OBJECT_ID.test(tip) ? { tip } : {}),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** What an object names: the objects a reader must also hold to use it. */
|
|
100
|
+
function referencedObjects(object: {
|
|
101
|
+
type: GitObjectType;
|
|
102
|
+
data: Uint8Array;
|
|
103
|
+
}): string[] {
|
|
104
|
+
if (object.type === "commit") {
|
|
105
|
+
const commit = parseCommit(object.data);
|
|
106
|
+
return [commit.tree, ...commit.parents].filter((oid) =>
|
|
107
|
+
OBJECT_ID.test(oid),
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
if (object.type === "tree")
|
|
111
|
+
return parseTree(object.data)
|
|
112
|
+
.filter((entry) => entry.mode !== "160000")
|
|
113
|
+
.map((entry) => entry.oid);
|
|
114
|
+
if (object.type === "tag") {
|
|
115
|
+
const target = /^object ([0-9a-f]{40})$/m.exec(
|
|
116
|
+
new TextDecoder().decode(object.data),
|
|
117
|
+
)?.[1];
|
|
118
|
+
return target ? [target] : [];
|
|
119
|
+
}
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** One piece of work per cache folder at a time, in this process. */
|
|
124
|
+
const cacheLocks = new Map<string, Promise<unknown>>();
|
|
125
|
+
|
|
126
|
+
async function withCacheLock<T>(
|
|
127
|
+
directory: string,
|
|
128
|
+
work: () => Promise<T>,
|
|
129
|
+
): Promise<T> {
|
|
130
|
+
const previous = cacheLocks.get(directory) ?? Promise.resolve();
|
|
131
|
+
const next = previous.then(work, work);
|
|
132
|
+
const settled = next.then(
|
|
133
|
+
() => undefined,
|
|
134
|
+
() => undefined,
|
|
135
|
+
);
|
|
136
|
+
cacheLocks.set(directory, settled);
|
|
137
|
+
try {
|
|
138
|
+
return await next;
|
|
139
|
+
} finally {
|
|
140
|
+
if (cacheLocks.get(directory) === settled) cacheLocks.delete(directory);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* This machine's copy of the packs an object-store origin keeps (ADR 0356):
|
|
146
|
+
* a bare repository Git reads them from, and that copies on this machine
|
|
147
|
+
* borrow from. It is a cache. Everything in it came from the store, and the
|
|
148
|
+
* store refills it; what it holds is always whole, so an object found here
|
|
149
|
+
* can be used with everything it reaches.
|
|
150
|
+
*
|
|
151
|
+
* The store keeps an origin's objects two ways: single objects under
|
|
152
|
+
* `objects/<id>` (what drafts and small saves write), and packs under
|
|
153
|
+
* `packs/<pack>.json` with their bytes in `pack-parts/<pack>/<number>`
|
|
154
|
+
* (what a large history arrives as).
|
|
155
|
+
*/
|
|
156
|
+
export class ObjectOriginCache {
|
|
157
|
+
private readonly store: ObjectStore;
|
|
158
|
+
private readonly basePath: string;
|
|
159
|
+
private readonly locate: () => Promise<string>;
|
|
160
|
+
|
|
161
|
+
constructor(opts: {
|
|
162
|
+
store: ObjectStore;
|
|
163
|
+
basePath: string;
|
|
164
|
+
/** The folder on this machine that holds this origin's cache. */
|
|
165
|
+
directory: () => Promise<string>;
|
|
166
|
+
}) {
|
|
167
|
+
this.store = opts.store;
|
|
168
|
+
this.basePath = opts.basePath;
|
|
169
|
+
this.locate = opts.directory;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
objectKey(sha: string): string {
|
|
173
|
+
if (!OBJECT_ID.test(sha)) throw new Error(`Invalid object sha: ${sha}`);
|
|
174
|
+
return `${this.basePath}/objects/${sha}`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
private manifestKey(id: string): string {
|
|
178
|
+
return `${this.basePath}/packs/${id}.json`;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
private partKey(id: string, part: number): string {
|
|
182
|
+
return `${this.basePath}/pack-parts/${id}/${String(part).padStart(6, "0")}`;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The folder copies borrow from; made when missing. */
|
|
186
|
+
async objects(): Promise<string> {
|
|
187
|
+
const directory = await this.ensure();
|
|
188
|
+
return path.join(await fs.realpath(directory), "objects");
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async directory(): Promise<string> {
|
|
192
|
+
return this.ensure();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The cache's repository, named by the folder's `current`, or null. */
|
|
196
|
+
private async exists(): Promise<string | null> {
|
|
197
|
+
const folder = await this.locate();
|
|
198
|
+
const generation = (
|
|
199
|
+
await fs.readFile(path.join(folder, "current"), "utf8").catch(() => "")
|
|
200
|
+
).trim();
|
|
201
|
+
if (!UUID.test(generation)) return null;
|
|
202
|
+
const directory = path.join(folder, `${generation}.git`);
|
|
203
|
+
return fs.access(path.join(directory, "HEAD")).then(
|
|
204
|
+
() => directory,
|
|
205
|
+
() => null,
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private async ensure(): Promise<string> {
|
|
210
|
+
const existing = await this.exists();
|
|
211
|
+
if (existing) return existing;
|
|
212
|
+
const folder = await this.locate();
|
|
213
|
+
return withCacheLock(`${folder}\0create`, async () => {
|
|
214
|
+
const made = await this.exists();
|
|
215
|
+
if (made) return made;
|
|
216
|
+
// A cache made again is a new folder, never the old one refilled: a
|
|
217
|
+
// copy that borrowed from the one before finds it gone and is
|
|
218
|
+
// rebuilt, instead of reading from a cache that no longer holds
|
|
219
|
+
// what it lent.
|
|
220
|
+
const generation = randomUUID();
|
|
221
|
+
const directory = path.join(folder, `${generation}.git`);
|
|
222
|
+
await initManagedRepository({ path: directory, bare: true });
|
|
223
|
+
const staged = path.join(folder, `current-${generation}`);
|
|
224
|
+
await fs.writeFile(staged, `${generation}\n`);
|
|
225
|
+
await fs.rename(staged, path.join(folder, "current"));
|
|
226
|
+
for (const name of await fs.readdir(folder)) {
|
|
227
|
+
if (!name.endsWith(".git") || name === `${generation}.git`) continue;
|
|
228
|
+
closeObjectReaders(path.join(folder, name));
|
|
229
|
+
await fs.rm(path.join(folder, name), { recursive: true, force: true });
|
|
230
|
+
}
|
|
231
|
+
return directory;
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** An object held here, with its content, or null. Never asks the store. */
|
|
236
|
+
async read(sha: string, maxBytes?: number): Promise<ObjectAnswer | null> {
|
|
237
|
+
const directory = await this.exists();
|
|
238
|
+
return directory
|
|
239
|
+
? objectContent({
|
|
240
|
+
gitdir: directory,
|
|
241
|
+
name: sha,
|
|
242
|
+
...(maxBytes !== undefined ? { maxBytes } : {}),
|
|
243
|
+
})
|
|
244
|
+
: null;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Whether an object is held here. Never asks the store. */
|
|
248
|
+
async has(sha: string): Promise<boolean> {
|
|
249
|
+
const directory = await this.exists();
|
|
250
|
+
return directory
|
|
251
|
+
? (await objectHeader({ gitdir: directory, name: sha })) !== null
|
|
252
|
+
: false;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Remove the cache; the store refills it. */
|
|
256
|
+
async remove(): Promise<void> {
|
|
257
|
+
const directory = await this.exists();
|
|
258
|
+
if (directory) closeObjectReaders(directory);
|
|
259
|
+
await fs.rm(await this.locate(), { recursive: true, force: true });
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Bring every pack the store keeps that this machine lacks. Returns
|
|
264
|
+
* whether any arrived. A store without packs is never given a cache.
|
|
265
|
+
*/
|
|
266
|
+
async refreshPacks(): Promise<boolean> {
|
|
267
|
+
const pending = await this.missingPacks(new Set());
|
|
268
|
+
if (pending.length === 0) return false;
|
|
269
|
+
const directory = await this.ensure();
|
|
270
|
+
return withCacheLock(directory, () =>
|
|
271
|
+
this.installMissing({ directory, installing: new Set() }),
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Make `commit` and everything it reaches readable here. */
|
|
276
|
+
async materialize(commit: string): Promise<void> {
|
|
277
|
+
// The first time this process works in the cache, what a stopped one
|
|
278
|
+
// left behind goes first.
|
|
279
|
+
const present = await this.exists();
|
|
280
|
+
if (present) await this.sweepScratch(present);
|
|
281
|
+
if (await this.has(commit)) return;
|
|
282
|
+
const directory = await this.ensure();
|
|
283
|
+
await withCacheLock(directory, async () => {
|
|
284
|
+
await this.materializeLocked({
|
|
285
|
+
directory,
|
|
286
|
+
commit,
|
|
287
|
+
installing: new Set(),
|
|
288
|
+
});
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Remove what a stopped process left in the cache, once per process:
|
|
294
|
+
* scratch folders of a transfer that never finished, and the temporary
|
|
295
|
+
* packs of a Git that was killed while indexing. Only what has not been
|
|
296
|
+
* touched for longer than any transfer runs, so nothing in use goes.
|
|
297
|
+
*/
|
|
298
|
+
private async sweepScratch(directory: string): Promise<void> {
|
|
299
|
+
if (swept.has(directory)) return;
|
|
300
|
+
swept.add(directory);
|
|
301
|
+
const stale = async (file: string) => {
|
|
302
|
+
const stat = await fs.stat(file).catch(() => null);
|
|
303
|
+
return stat !== null && Date.now() - stat.mtimeMs > ABANDONED_AFTER_MS;
|
|
304
|
+
};
|
|
305
|
+
for (const name of await fs.readdir(directory).catch(() => [])) {
|
|
306
|
+
if (!/^(incoming|outgoing)-/.test(name)) continue;
|
|
307
|
+
const scratch = path.join(directory, name);
|
|
308
|
+
if (await stale(scratch))
|
|
309
|
+
await fs.rm(scratch, { recursive: true, force: true }).catch(() => {});
|
|
310
|
+
}
|
|
311
|
+
const packs = path.join(directory, "objects", "pack");
|
|
312
|
+
for (const name of await fs.readdir(packs).catch(() => [])) {
|
|
313
|
+
if (!/^(tmp_|\.tmp-)/.test(name)) continue;
|
|
314
|
+
const leftover = path.join(packs, name);
|
|
315
|
+
if (await stale(leftover))
|
|
316
|
+
await fs.rm(leftover, { recursive: true, force: true }).catch(() => {});
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Remove from the store the parts of uploads that never got their
|
|
322
|
+
* description, once per process: a pack is listed only by it, so parts
|
|
323
|
+
* without one are read by nothing. An upload still under way is told by
|
|
324
|
+
* the time in its id and left alone.
|
|
325
|
+
*/
|
|
326
|
+
private async sweepAbandonedParts(): Promise<void> {
|
|
327
|
+
const done = sweptStores.get(this.store) ?? new Set<string>();
|
|
328
|
+
sweptStores.set(this.store, done);
|
|
329
|
+
if (done.has(this.basePath)) return;
|
|
330
|
+
done.add(this.basePath);
|
|
331
|
+
const prefix = `${this.basePath}/pack-parts/`;
|
|
332
|
+
const ids = new Set(
|
|
333
|
+
(await this.store.list(prefix)).map(
|
|
334
|
+
(key) => key.slice(prefix.length).split("/")[0] ?? "",
|
|
335
|
+
),
|
|
336
|
+
);
|
|
337
|
+
for (const id of ids) {
|
|
338
|
+
const began = Number.parseInt(PACK_ID.exec(id)?.[1] ?? "", 36);
|
|
339
|
+
// An id that names no time is from no upload this code makes.
|
|
340
|
+
if (Number.isFinite(began) && Date.now() - began < ABANDONED_AFTER_MS)
|
|
341
|
+
continue;
|
|
342
|
+
if (await this.store.has(this.manifestKey(id))) continue;
|
|
343
|
+
await this.store.deletePrefix(`${prefix}${id}/`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* The stored packs this cache holds. A pack counts only while its file
|
|
349
|
+
* is still there: its mark alone says it once arrived, and a pack that
|
|
350
|
+
* went missing since is brought again.
|
|
351
|
+
*/
|
|
352
|
+
private async installedPacks(directory: string): Promise<Set<string>> {
|
|
353
|
+
const marks = path.join(directory, "work-packs");
|
|
354
|
+
const held = new Set<string>();
|
|
355
|
+
for (const id of await fs.readdir(marks).catch(() => [])) {
|
|
356
|
+
const name = (
|
|
357
|
+
await fs.readFile(path.join(marks, id), "utf8").catch(() => "")
|
|
358
|
+
).trim();
|
|
359
|
+
const present =
|
|
360
|
+
/^pack-[0-9a-f]{40,64}$/.test(name) &&
|
|
361
|
+
(await fs
|
|
362
|
+
.access(path.join(directory, "objects", "pack", `${name}.pack`))
|
|
363
|
+
.then(
|
|
364
|
+
() => true,
|
|
365
|
+
() => false,
|
|
366
|
+
)) &&
|
|
367
|
+
(await fs
|
|
368
|
+
.access(path.join(directory, "objects", "pack", `${name}.idx`))
|
|
369
|
+
.then(
|
|
370
|
+
() => true,
|
|
371
|
+
() => false,
|
|
372
|
+
));
|
|
373
|
+
if (present) held.add(id);
|
|
374
|
+
}
|
|
375
|
+
return held;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
private async missingPacks(installing: ReadonlySet<string>) {
|
|
379
|
+
const keys = await this.store.list(`${this.basePath}/packs/`);
|
|
380
|
+
const ids = keys.flatMap((key) => {
|
|
381
|
+
const name = key.slice(`${this.basePath}/packs/`.length);
|
|
382
|
+
const id = name.endsWith(".json") ? name.slice(0, -5) : "";
|
|
383
|
+
return PACK_ID.test(id) ? [id] : [];
|
|
384
|
+
});
|
|
385
|
+
if (ids.length === 0) return [];
|
|
386
|
+
const directory = await this.exists();
|
|
387
|
+
const installed = directory
|
|
388
|
+
? await this.installedPacks(directory)
|
|
389
|
+
: new Set<string>();
|
|
390
|
+
return ids.filter((id) => !installed.has(id) && !installing.has(id));
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
private async installMissing(input: {
|
|
394
|
+
directory: string;
|
|
395
|
+
installing: Set<string>;
|
|
396
|
+
}): Promise<boolean> {
|
|
397
|
+
const { directory, installing } = input;
|
|
398
|
+
const pending = await this.missingPacks(installing);
|
|
399
|
+
for (const id of pending) {
|
|
400
|
+
installing.add(id);
|
|
401
|
+
const entry = await this.store.get(this.manifestKey(id));
|
|
402
|
+
// A manifest is written last and never removed while its origin lives.
|
|
403
|
+
if (!entry) continue;
|
|
404
|
+
const manifest = parseManifest(entry.data);
|
|
405
|
+
// A pack is whole once the histories it was built on are: they come
|
|
406
|
+
// first, so nothing here is ever found without what it reaches.
|
|
407
|
+
for (const base of manifest.bases)
|
|
408
|
+
await this.materializeLocked({ directory, commit: base, installing });
|
|
409
|
+
const store = this.store;
|
|
410
|
+
const partKey = (part: number) => this.partKey(id, part);
|
|
411
|
+
async function* parts(): AsyncGenerator<Uint8Array> {
|
|
412
|
+
for (let part = 0; part < manifest.parts; part++) {
|
|
413
|
+
const stored = await store.get(partKey(part));
|
|
414
|
+
if (!stored)
|
|
415
|
+
throw new Error(
|
|
416
|
+
`The project's origin store has lost part ${part + 1} of ${manifest.parts} of a pack`,
|
|
417
|
+
);
|
|
418
|
+
yield stored.data;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
const printed: string[] = [];
|
|
422
|
+
const decoder = new TextDecoder();
|
|
423
|
+
await nativeGitStream({
|
|
424
|
+
cwd: directory,
|
|
425
|
+
args: ["index-pack", "--stdin"],
|
|
426
|
+
input: parts(),
|
|
427
|
+
onOutput: (chunk) => {
|
|
428
|
+
printed.push(decoder.decode(chunk, { stream: true }));
|
|
429
|
+
},
|
|
430
|
+
}).catch((error: unknown) => {
|
|
431
|
+
throw new Error(
|
|
432
|
+
`Could not read a pack from the project's origin store: ${gitErrorText(error)}`,
|
|
433
|
+
);
|
|
434
|
+
});
|
|
435
|
+
// Git names the pack it wrote: `pack` or `keep`, then its hash.
|
|
436
|
+
const hash = /^(?:pack|keep)\t([0-9a-f]{40,64})$/m.exec(
|
|
437
|
+
printed.join(""),
|
|
438
|
+
)?.[1];
|
|
439
|
+
if (!hash) throw new Error("Git did not say which pack it indexed");
|
|
440
|
+
await this.markInstalled({
|
|
441
|
+
directory,
|
|
442
|
+
id,
|
|
443
|
+
pack: `pack-${hash}`,
|
|
444
|
+
tip: manifest.tip,
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
return pending.length > 0;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
private async markInstalled(input: {
|
|
451
|
+
directory: string;
|
|
452
|
+
id: string;
|
|
453
|
+
/** The pack's file name here, without its extension. */
|
|
454
|
+
pack: string;
|
|
455
|
+
tip?: string;
|
|
456
|
+
}): Promise<void> {
|
|
457
|
+
// A ref at the history a pack brought: a repository that borrows from
|
|
458
|
+
// this cache then tells a remote it already has it, and is sent only
|
|
459
|
+
// what is new.
|
|
460
|
+
if (input.tip)
|
|
461
|
+
await nativeGit(input.directory, [
|
|
462
|
+
"update-ref",
|
|
463
|
+
`refs/work/packs/${input.id}`,
|
|
464
|
+
input.tip,
|
|
465
|
+
]).catch(() => "");
|
|
466
|
+
const folder = path.join(input.directory, "work-packs");
|
|
467
|
+
await fs.mkdir(folder, { recursive: true });
|
|
468
|
+
await fs.writeFile(path.join(folder, input.id), `${input.pack}\n`);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
private async materializeLocked(input: {
|
|
472
|
+
directory: string;
|
|
473
|
+
commit: string;
|
|
474
|
+
installing: Set<string>;
|
|
475
|
+
}): Promise<void> {
|
|
476
|
+
const { directory, commit } = input;
|
|
477
|
+
const held = async (oid: string) =>
|
|
478
|
+
(await objectHeader({ gitdir: directory, name: oid })) !== null;
|
|
479
|
+
if (await held(commit)) return;
|
|
480
|
+
const scratch = await fs.mkdtemp(path.join(directory, "incoming-"));
|
|
481
|
+
try {
|
|
482
|
+
await initManagedRepository({ path: scratch, bare: true });
|
|
483
|
+
const objects = path.join(scratch, "objects");
|
|
484
|
+
const fetched: string[] = [];
|
|
485
|
+
const seen = new Set<string>([commit]);
|
|
486
|
+
let refreshed: Promise<boolean> | undefined;
|
|
487
|
+
let frontier = [commit];
|
|
488
|
+
while (frontier.length > 0) {
|
|
489
|
+
const found = await mapLimit(
|
|
490
|
+
frontier,
|
|
491
|
+
OBJECT_CONCURRENCY,
|
|
492
|
+
async (oid) => {
|
|
493
|
+
if (await held(oid)) return [];
|
|
494
|
+
const stored = await this.store.get(this.objectKey(oid));
|
|
495
|
+
if (!stored) {
|
|
496
|
+
// Not a single object: it is in a pack this machine lacks.
|
|
497
|
+
refreshed ??= this.installMissing({
|
|
498
|
+
directory,
|
|
499
|
+
installing: input.installing,
|
|
500
|
+
});
|
|
501
|
+
await refreshed;
|
|
502
|
+
if (await held(oid)) return [];
|
|
503
|
+
throw new Error(
|
|
504
|
+
`The project's origin store is missing object ${oid}, which ${commit.slice(0, 12)} needs`,
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
if (createHash("sha1").update(stored.data).digest("hex") !== oid)
|
|
508
|
+
throw new Error(
|
|
509
|
+
`The project's origin store returned different content for object ${oid}`,
|
|
510
|
+
);
|
|
511
|
+
await writeWrappedObject({
|
|
512
|
+
objects,
|
|
513
|
+
sha: oid,
|
|
514
|
+
wrapped: stored.data,
|
|
515
|
+
});
|
|
516
|
+
fetched.push(oid);
|
|
517
|
+
return referencedObjects(unwrapObject(stored.data));
|
|
518
|
+
},
|
|
519
|
+
);
|
|
520
|
+
frontier = [];
|
|
521
|
+
for (const oid of found.flat()) {
|
|
522
|
+
if (seen.has(oid)) continue;
|
|
523
|
+
seen.add(oid);
|
|
524
|
+
frontier.push(oid);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (fetched.length === 0) return;
|
|
528
|
+
// One pack, placed whole: an object is never here without what it
|
|
529
|
+
// reaches, whatever stops this part way.
|
|
530
|
+
const pack = await writePack({
|
|
531
|
+
repoPath: scratch,
|
|
532
|
+
args: [],
|
|
533
|
+
input: `${fetched.join("\n")}\n`,
|
|
534
|
+
into: scratch,
|
|
535
|
+
});
|
|
536
|
+
await placePack({ directory, pack });
|
|
537
|
+
} finally {
|
|
538
|
+
await fs.rm(scratch, { recursive: true, force: true });
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Store what `commit` reaches beyond `bases` as one pack, built by Git in
|
|
544
|
+
* the repository at `repoPath` and written in parts, so neither side
|
|
545
|
+
* ever holds it in memory. The pack is kept here too.
|
|
546
|
+
*/
|
|
547
|
+
async uploadPack(input: {
|
|
548
|
+
repoPath: string;
|
|
549
|
+
commit: string;
|
|
550
|
+
bases: readonly string[];
|
|
551
|
+
}): Promise<{ bytes: number }> {
|
|
552
|
+
const directory = await this.ensure();
|
|
553
|
+
await this.sweepScratch(directory);
|
|
554
|
+
await this.sweepAbandonedParts().catch(() => {});
|
|
555
|
+
const scratch = await fs.mkdtemp(path.join(directory, "outgoing-"));
|
|
556
|
+
const id = `${Date.now().toString(36)}-${randomUUID()}`;
|
|
557
|
+
try {
|
|
558
|
+
const pack = await writePack({
|
|
559
|
+
repoPath: input.repoPath,
|
|
560
|
+
args: ["--revs", "--delta-base-offset"],
|
|
561
|
+
input: `${[input.commit, ...input.bases.map((base) => `^${base}`)].join("\n")}\n`,
|
|
562
|
+
into: scratch,
|
|
563
|
+
});
|
|
564
|
+
const { size } = await fs.stat(pack.pack);
|
|
565
|
+
const parts = Math.max(1, Math.ceil(size / PACK_PART_BYTES));
|
|
566
|
+
const handle = await fs.open(pack.pack, "r");
|
|
567
|
+
try {
|
|
568
|
+
await mapLimit(
|
|
569
|
+
Array.from({ length: parts }, (_, part) => part),
|
|
570
|
+
PART_CONCURRENCY,
|
|
571
|
+
async (part) => {
|
|
572
|
+
const start = part * PACK_PART_BYTES;
|
|
573
|
+
const length = Math.min(PACK_PART_BYTES, size - start);
|
|
574
|
+
const buffer = new Uint8Array(length);
|
|
575
|
+
let read = 0;
|
|
576
|
+
while (read < length) {
|
|
577
|
+
const chunk = await handle.read(
|
|
578
|
+
buffer,
|
|
579
|
+
read,
|
|
580
|
+
length - read,
|
|
581
|
+
start + read,
|
|
582
|
+
);
|
|
583
|
+
if (chunk.bytesRead === 0)
|
|
584
|
+
throw new Error("The pack ended before its size");
|
|
585
|
+
read += chunk.bytesRead;
|
|
586
|
+
}
|
|
587
|
+
await this.store.put(this.partKey(id, part), buffer);
|
|
588
|
+
},
|
|
589
|
+
);
|
|
590
|
+
} finally {
|
|
591
|
+
await handle.close();
|
|
592
|
+
}
|
|
593
|
+
// The description is written last: a pack is listed only when whole.
|
|
594
|
+
const manifest: PackManifest = {
|
|
595
|
+
version: 1,
|
|
596
|
+
parts,
|
|
597
|
+
bytes: size,
|
|
598
|
+
bases: [...input.bases],
|
|
599
|
+
tip: input.commit,
|
|
600
|
+
};
|
|
601
|
+
await this.store.put(
|
|
602
|
+
this.manifestKey(id),
|
|
603
|
+
new TextEncoder().encode(JSON.stringify(manifest)),
|
|
604
|
+
);
|
|
605
|
+
await withCacheLock(directory, async () => {
|
|
606
|
+
const installing = new Set([id]);
|
|
607
|
+
for (const base of input.bases)
|
|
608
|
+
await this.materializeLocked({ directory, commit: base, installing });
|
|
609
|
+
await placePack({ directory, pack });
|
|
610
|
+
await this.markInstalled({
|
|
611
|
+
directory,
|
|
612
|
+
id,
|
|
613
|
+
pack: path.basename(pack.pack, ".pack"),
|
|
614
|
+
tip: input.commit,
|
|
615
|
+
});
|
|
616
|
+
});
|
|
617
|
+
return { bytes: size };
|
|
618
|
+
} catch (error) {
|
|
619
|
+
// Parts no description names are never read; remove what was written.
|
|
620
|
+
await this.store
|
|
621
|
+
.has(this.manifestKey(id))
|
|
622
|
+
.then((listed) =>
|
|
623
|
+
listed
|
|
624
|
+
? undefined
|
|
625
|
+
: this.store.deletePrefix(`${this.basePath}/pack-parts/${id}/`),
|
|
626
|
+
)
|
|
627
|
+
.catch(() => {});
|
|
628
|
+
throw error;
|
|
629
|
+
} finally {
|
|
630
|
+
await fs.rm(scratch, { recursive: true, force: true });
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
interface WrittenPack {
|
|
636
|
+
pack: string;
|
|
637
|
+
index: string;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** Have Git write a pack and its index into `into`; returns their paths. */
|
|
641
|
+
async function writePack(input: {
|
|
642
|
+
repoPath: string;
|
|
643
|
+
args: readonly string[];
|
|
644
|
+
/** What `git pack-objects` reads: revisions, or object ids. */
|
|
645
|
+
input: string;
|
|
646
|
+
into: string;
|
|
647
|
+
}): Promise<WrittenPack> {
|
|
648
|
+
const printed: string[] = [];
|
|
649
|
+
const decoder = new TextDecoder();
|
|
650
|
+
await nativeGitStream({
|
|
651
|
+
cwd: input.repoPath,
|
|
652
|
+
args: [
|
|
653
|
+
"pack-objects",
|
|
654
|
+
"--quiet",
|
|
655
|
+
...input.args,
|
|
656
|
+
path.join(input.into, "pack"),
|
|
657
|
+
],
|
|
658
|
+
input: input.input,
|
|
659
|
+
onOutput: (chunk) => {
|
|
660
|
+
printed.push(decoder.decode(chunk, { stream: true }));
|
|
661
|
+
},
|
|
662
|
+
}).catch((error: unknown) => {
|
|
663
|
+
throw new Error(`Git could not pack the history: ${gitErrorText(error)}`);
|
|
664
|
+
});
|
|
665
|
+
const name = printed.join("").trim();
|
|
666
|
+
if (!/^[0-9a-f]{40,64}$/.test(name))
|
|
667
|
+
throw new Error("Git did not say which pack it wrote");
|
|
668
|
+
return {
|
|
669
|
+
pack: path.join(input.into, `pack-${name}.pack`),
|
|
670
|
+
index: path.join(input.into, `pack-${name}.idx`),
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/** Move a written pack into a repository; its index last, which lists it. */
|
|
675
|
+
async function placePack(input: {
|
|
676
|
+
directory: string;
|
|
677
|
+
pack: WrittenPack;
|
|
678
|
+
}): Promise<void> {
|
|
679
|
+
const folder = path.join(input.directory, "objects", "pack");
|
|
680
|
+
await fs.mkdir(folder, { recursive: true });
|
|
681
|
+
await fs.rename(
|
|
682
|
+
input.pack.pack,
|
|
683
|
+
path.join(folder, path.basename(input.pack.pack)),
|
|
684
|
+
);
|
|
685
|
+
await fs.rename(
|
|
686
|
+
input.pack.index,
|
|
687
|
+
path.join(folder, path.basename(input.pack.index)),
|
|
688
|
+
);
|
|
689
|
+
}
|