@catamorphic/git 0.0.0-stage → 0.1.0-alpha.30

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.
Files changed (79) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/dist/checkout-remote-backend.d.ts +12 -0
  4. package/dist/checkout-remote-backend.d.ts.map +1 -0
  5. package/dist/file-reads.d.ts +15 -0
  6. package/dist/file-reads.d.ts.map +1 -0
  7. package/dist/fs-backend.d.ts +30 -0
  8. package/dist/fs-backend.d.ts.map +1 -0
  9. package/dist/fs-remote-backend.d.ts +47 -0
  10. package/dist/fs-remote-backend.d.ts.map +1 -0
  11. package/dist/git-object-codec.d.ts +31 -0
  12. package/dist/git-object-codec.d.ts.map +1 -0
  13. package/dist/git-sync.d.ts +61 -0
  14. package/dist/git-sync.d.ts.map +1 -0
  15. package/dist/in-memory-object-store.d.ts +23 -0
  16. package/dist/in-memory-object-store.d.ts.map +1 -0
  17. package/dist/index.d.ts +24 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +4746 -0
  20. package/dist/index.js.map +32 -0
  21. package/dist/migrate-workflow.d.ts +12 -0
  22. package/dist/migrate-workflow.d.ts.map +1 -0
  23. package/dist/native-git.d.ts +25 -0
  24. package/dist/native-git.d.ts.map +1 -0
  25. package/dist/native-project-repo.d.ts +57 -0
  26. package/dist/native-project-repo.d.ts.map +1 -0
  27. package/dist/network-sync.d.ts +58 -0
  28. package/dist/network-sync.d.ts.map +1 -0
  29. package/dist/network.d.ts +81 -0
  30. package/dist/network.d.ts.map +1 -0
  31. package/dist/object-remote-backend.d.ts +95 -0
  32. package/dist/object-remote-backend.d.ts.map +1 -0
  33. package/dist/object-store.d.ts +42 -0
  34. package/dist/object-store.d.ts.map +1 -0
  35. package/dist/origin-draft.d.ts +264 -0
  36. package/dist/origin-draft.d.ts.map +1 -0
  37. package/dist/origin-objects.d.ts +201 -0
  38. package/dist/origin-objects.d.ts.map +1 -0
  39. package/dist/personal-files.d.ts +6 -0
  40. package/dist/personal-files.d.ts.map +1 -0
  41. package/dist/project-manager.d.ts +214 -0
  42. package/dist/project-manager.d.ts.map +1 -0
  43. package/dist/project-repo.d.ts +79 -0
  44. package/dist/project-repo.d.ts.map +1 -0
  45. package/dist/ref-moved-error.d.ts +13 -0
  46. package/dist/ref-moved-error.d.ts.map +1 -0
  47. package/dist/ref-names.d.ts +18 -0
  48. package/dist/ref-names.d.ts.map +1 -0
  49. package/dist/types.d.ts +276 -0
  50. package/dist/types.d.ts.map +1 -0
  51. package/dist/workspace-mirror.d.ts +110 -0
  52. package/dist/workspace-mirror.d.ts.map +1 -0
  53. package/package.json +53 -4
  54. package/src/checkout-remote-backend.ts +154 -0
  55. package/src/diff3.d.ts +16 -0
  56. package/src/file-reads.ts +53 -0
  57. package/src/fs-backend.ts +206 -0
  58. package/src/fs-remote-backend.ts +252 -0
  59. package/src/git-object-codec.ts +87 -0
  60. package/src/git-sync.ts +539 -0
  61. package/src/in-memory-object-store.ts +60 -0
  62. package/src/index.ts +110 -0
  63. package/src/migrate-workflow.ts +30 -0
  64. package/src/native-git.ts +177 -0
  65. package/src/native-project-repo.ts +515 -0
  66. package/src/network-sync.ts +239 -0
  67. package/src/network.ts +269 -0
  68. package/src/object-remote-backend.ts +366 -0
  69. package/src/object-store.ts +41 -0
  70. package/src/origin-draft.ts +1033 -0
  71. package/src/origin-objects.ts +906 -0
  72. package/src/personal-files.ts +57 -0
  73. package/src/project-manager.ts +743 -0
  74. package/src/project-repo.ts +800 -0
  75. package/src/ref-moved-error.ts +18 -0
  76. package/src/ref-names.ts +47 -0
  77. package/src/types.ts +289 -0
  78. package/src/workspace-mirror.ts +400 -0
  79. package/README.md +0 -3
@@ -0,0 +1,366 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ type GitObjectType,
4
+ parseCommit,
5
+ unwrapObject,
6
+ wrapObject,
7
+ } from "./git-object-codec.js";
8
+ import { type ObjectStore, PreconditionFailedError } from "./object-store.js";
9
+ import { RefMovedError } from "./ref-moved-error.js";
10
+ import { InvalidRefNameError, isValidRefName } from "./ref-names.js";
11
+ import type {
12
+ CommitInfo,
13
+ DraftSupport,
14
+ OriginRepo,
15
+ RemoteBackend,
16
+ } from "./types.js";
17
+
18
+ const UUID_RE =
19
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
20
+
21
+ function assertUuid(value: string): void {
22
+ if (!UUID_RE.test(value)) {
23
+ throw new Error(`Invalid UUID: ${value}`);
24
+ }
25
+ }
26
+
27
+ const SHA_RE = /^[0-9a-f]{40}$/;
28
+ const REF_RE = /^refs\/[A-Za-z0-9._/-]+$/;
29
+
30
+ function assertRefName(ref: string): void {
31
+ if (!REF_RE.test(ref) || !isValidRefName(ref))
32
+ throw new InvalidRefNameError(ref);
33
+ }
34
+
35
+ /**
36
+ * Check that a store enforces the preconditions drafts rely on: a put with
37
+ * `ifNoneMatch` on an existing key, and deletes with a stale or the current
38
+ * `ifMatch`. Returns why it does not, or null when it does. The probe key
39
+ * is removed afterwards.
40
+ */
41
+ export async function probeConditionalWrites(input: {
42
+ store: ObjectStore;
43
+ key: string;
44
+ }): Promise<string | null> {
45
+ const { store, key } = input;
46
+ const refused = async (write: () => Promise<void>) =>
47
+ write().then(
48
+ () => false,
49
+ (error: unknown) => {
50
+ if (error instanceof PreconditionFailedError) return true;
51
+ throw error;
52
+ },
53
+ );
54
+ try {
55
+ // A stale ETag the store itself issued: the one before an overwrite.
56
+ await store.put(key, new TextEncoder().encode(`probe ${randomUUID()}`));
57
+ const stale = await store.get(key);
58
+ await store.put(key, new TextEncoder().encode(`probe ${randomUUID()}`));
59
+ const entry = await store.get(key);
60
+ if (!stale || !entry) return "the store did not keep a written object";
61
+ if (stale.etag === entry.etag)
62
+ return "the store kept an object's ETag when its content changed";
63
+ if (
64
+ !(await refused(() =>
65
+ store.put(key, new TextEncoder().encode("again"), {
66
+ ifNoneMatch: "*",
67
+ }),
68
+ ))
69
+ )
70
+ return "the store ignores If-None-Match on writes";
71
+ if (
72
+ !(await refused(() => store.delete(key, { ifMatch: stale.etag }))) ||
73
+ !(await store.has(key))
74
+ )
75
+ return "the store ignores If-Match on deletes, so a draft could be deleted after another replica moved it";
76
+ await store.delete(key, { ifMatch: entry.etag });
77
+ if (await store.has(key))
78
+ return "the store did not delete an object whose ETag matched";
79
+ return null;
80
+ } finally {
81
+ await store.delete(key).catch(() => {});
82
+ }
83
+ }
84
+
85
+ export interface ObjectRemoteBackendOpts {
86
+ store: ObjectStore;
87
+ /**
88
+ * Key prefix so multiple catamorphic environments can share a bucket.
89
+ * Project layout: `<keyPrefix><tenantId>/<projectId>/{repo.json,objects/,refs/}`.
90
+ */
91
+ keyPrefix?: string;
92
+ }
93
+
94
+ /**
95
+ * `RemoteBackend` storing each project's canonical bare repository directly
96
+ * in a host-injected object store. S3 and Postgres backends share the same
97
+ * immutable objects and conditional ref updates, without a local origin mirror.
98
+ *
99
+ * Git objects are immutable and content-addressed, so they map cleanly onto
100
+ * object storage; ref updates use conditional PUTs (`If-Match` /
101
+ * `If-None-Match`) for the compare-and-swap semantics `OriginRepo.updateRef`
102
+ * requires. Buckets don't speak the git protocol, so `getCloneSource` is not
103
+ * implemented and sandboxes receive file uploads (same as `FsRemoteBackend`).
104
+ * See docs/decisions/0012.
105
+ */
106
+ export class ObjectRemoteBackend implements RemoteBackend {
107
+ private readonly store: ObjectStore;
108
+ private readonly keyPrefix: string;
109
+ private draftCheck: Promise<DraftSupport> | undefined;
110
+
111
+ constructor(opts: ObjectRemoteBackendOpts) {
112
+ this.store = opts.store;
113
+ this.keyPrefix = opts.keyPrefix ?? "";
114
+ }
115
+
116
+ private basePath(tenantId: string, projectId: string): string {
117
+ assertUuid(tenantId);
118
+ assertUuid(projectId);
119
+ return `${this.keyPrefix}${tenantId}/${projectId}`;
120
+ }
121
+
122
+ private markerKey(tenantId: string, projectId: string): string {
123
+ return `${this.basePath(tenantId, projectId)}/repo.json`;
124
+ }
125
+
126
+ async initRemote(tenantId: string, projectId: string): Promise<void> {
127
+ const marker = new TextEncoder().encode(
128
+ JSON.stringify({ createdAt: new Date().toISOString() }),
129
+ );
130
+ try {
131
+ await this.store.put(this.markerKey(tenantId, projectId), marker, {
132
+ ifNoneMatch: "*",
133
+ });
134
+ } catch (err) {
135
+ // Already initialized — init is idempotent.
136
+ if (!(err instanceof PreconditionFailedError)) throw err;
137
+ }
138
+ }
139
+
140
+ async deleteRemote(tenantId: string, projectId: string): Promise<void> {
141
+ await this.store.deletePrefix(`${this.basePath(tenantId, projectId)}/`);
142
+ }
143
+
144
+ async exists(tenantId: string, projectId: string): Promise<boolean> {
145
+ return this.store.has(this.markerKey(tenantId, projectId));
146
+ }
147
+
148
+ /**
149
+ * Drafts need conditional puts and deletes that the store really
150
+ * enforces (ADR 0191). Some S3-compatible stores ignore `If-Match` on
151
+ * DeleteObject, so the store is probed once per process before any draft
152
+ * is written, and drafts are refused on a store that fails.
153
+ */
154
+ draftSupport(): Promise<DraftSupport> {
155
+ this.draftCheck ??= probeConditionalWrites({
156
+ store: this.store,
157
+ key: `${this.keyPrefix}conformance/${randomUUID()}`,
158
+ }).then(
159
+ (failure): DraftSupport =>
160
+ failure ? { supported: false, reason: failure } : { supported: true },
161
+ (error: unknown) => {
162
+ // A probe that could not run (a transient store error) is not an
163
+ // answer: the next call probes again.
164
+ this.draftCheck = undefined;
165
+ throw error;
166
+ },
167
+ );
168
+ return this.draftCheck;
169
+ }
170
+
171
+ async withOrigin<T>(
172
+ tenantId: string,
173
+ projectId: string,
174
+ fn: (origin: OriginRepo) => Promise<T>,
175
+ ): Promise<T> {
176
+ return fn(
177
+ new ObjectOriginRepo({
178
+ store: this.store,
179
+ basePath: this.basePath(tenantId, projectId),
180
+ }),
181
+ );
182
+ }
183
+ }
184
+
185
+ /**
186
+ * `OriginRepo` over a key prefix in an object store:
187
+ * - `objects/<sha>` — wrapped git objects (`<type> <len>\0<content>`), so
188
+ * `sha1(body) == key` and every object is self-verifying.
189
+ * - `refs/heads/<branch>` — the 40-char commit SHA as the body.
190
+ */
191
+ export class ObjectOriginRepo implements OriginRepo {
192
+ private readonly store: ObjectStore;
193
+ private readonly basePath: string;
194
+ /** Synthetic identifier — this origin has no on-disk git directory. */
195
+ readonly gitdir: string;
196
+
197
+ constructor(opts: { store: ObjectStore; basePath: string }) {
198
+ this.store = opts.store;
199
+ this.basePath = opts.basePath;
200
+ this.gitdir = `objectstore://${opts.basePath}`;
201
+ }
202
+
203
+ private refKey(ref: string): string {
204
+ assertRefName(ref);
205
+ return `${this.basePath}/${ref}`;
206
+ }
207
+
208
+ private objectKey(sha: string): string {
209
+ if (!SHA_RE.test(sha)) {
210
+ throw new Error(`Invalid object sha: ${sha}`);
211
+ }
212
+ return `${this.basePath}/objects/${sha}`;
213
+ }
214
+
215
+ async resolveRef(ref: string): Promise<string | null> {
216
+ const entry = await this.store.get(this.refKey(ref));
217
+ if (!entry) return null;
218
+ const sha = new TextDecoder().decode(entry.data).trim();
219
+ return SHA_RE.test(sha) ? sha : null;
220
+ }
221
+
222
+ async listRefs(prefix: string): Promise<{ ref: string; sha: string }[]> {
223
+ const normalized = prefix.endsWith("/") ? prefix : `${prefix}/`;
224
+ assertRefName(normalized.slice(0, -1));
225
+ const keys = await this.store.list(`${this.basePath}/${normalized}`);
226
+ const entries = await Promise.all(
227
+ keys.map(async (key) => {
228
+ const ref = key.slice(this.basePath.length + 1);
229
+ const sha = await this.resolveRef(ref);
230
+ return sha ? { ref, sha } : null;
231
+ }),
232
+ );
233
+ return entries.filter((entry) => entry !== null);
234
+ }
235
+
236
+ async updateRef(opts: {
237
+ ref: string;
238
+ sha: string;
239
+ expected?: string | null;
240
+ }): Promise<void> {
241
+ const key = this.refKey(opts.ref);
242
+ const body = new TextEncoder().encode(opts.sha);
243
+
244
+ if (opts.expected === undefined) {
245
+ await this.store.put(key, body);
246
+ return;
247
+ }
248
+
249
+ const expected = opts.expected;
250
+ const moved = async (): Promise<never> => {
251
+ throw new RefMovedError({
252
+ ref: opts.ref,
253
+ expected,
254
+ actual: await this.resolveRef(opts.ref),
255
+ });
256
+ };
257
+
258
+ if (opts.expected === null) {
259
+ try {
260
+ await this.store.put(key, body, { ifNoneMatch: "*" });
261
+ } catch (err) {
262
+ if (err instanceof PreconditionFailedError) await moved();
263
+ throw err;
264
+ }
265
+ return;
266
+ }
267
+
268
+ const currentEntry = await this.store.get(key);
269
+ const currentSha = currentEntry
270
+ ? new TextDecoder().decode(currentEntry.data).trim()
271
+ : null;
272
+ if (!currentEntry || currentSha !== opts.expected) {
273
+ await moved();
274
+ return;
275
+ }
276
+ try {
277
+ await this.store.put(key, body, { ifMatch: currentEntry.etag });
278
+ } catch (err) {
279
+ if (err instanceof PreconditionFailedError) await moved();
280
+ throw err;
281
+ }
282
+ }
283
+
284
+ async deleteRef(input: { ref: string; expected?: string }): Promise<void> {
285
+ const key = this.refKey(input.ref);
286
+ if (input.expected === undefined) {
287
+ await this.store.delete(key);
288
+ return;
289
+ }
290
+ const entry = await this.store.get(key);
291
+ const actual = entry ? new TextDecoder().decode(entry.data).trim() : null;
292
+ const moved = () =>
293
+ new RefMovedError({
294
+ ref: input.ref,
295
+ expected: input.expected ?? null,
296
+ actual,
297
+ });
298
+ if (!entry || actual !== input.expected) throw moved();
299
+ try {
300
+ await this.store.delete(key, { ifMatch: entry.etag });
301
+ } catch (err) {
302
+ if (err instanceof PreconditionFailedError) throw moved();
303
+ throw err;
304
+ }
305
+ }
306
+
307
+ async hasObject(sha: string): Promise<boolean> {
308
+ return this.store.has(this.objectKey(sha));
309
+ }
310
+
311
+ async readObject(sha: string): Promise<{
312
+ type: GitObjectType;
313
+ data: Uint8Array;
314
+ }> {
315
+ const entry = await this.store.get(this.objectKey(sha));
316
+ if (!entry) {
317
+ throw new Error(`Object not found: ${sha}`);
318
+ }
319
+ return unwrapObject(entry.data);
320
+ }
321
+
322
+ async writeObject(opts: {
323
+ type: GitObjectType;
324
+ data: Uint8Array;
325
+ }): Promise<string> {
326
+ const { wrapped, sha } = wrapObject(opts);
327
+ // Objects are immutable and content-addressed; skip the PUT when the
328
+ // object is already stored, otherwise write unconditionally (an
329
+ // overwrite is byte-identical by construction).
330
+ if (!(await this.hasObject(sha))) {
331
+ await this.store.put(this.objectKey(sha), wrapped);
332
+ }
333
+ return sha;
334
+ }
335
+
336
+ async log(ref: string, maxCount = 50): Promise<CommitInfo[]> {
337
+ const tip = await this.resolveRef(ref);
338
+ if (!tip) return [];
339
+
340
+ const commits: CommitInfo[] = [];
341
+ const seen = new Set<string>();
342
+ const queue: string[] = [tip];
343
+
344
+ while (queue.length > 0 && commits.length < maxCount) {
345
+ const sha = queue.shift();
346
+ if (!sha || seen.has(sha)) continue;
347
+ seen.add(sha);
348
+
349
+ const entry = await this.store.get(this.objectKey(sha));
350
+ if (!entry) break;
351
+ const obj = unwrapObject(entry.data);
352
+ if (obj.type !== "commit") break;
353
+
354
+ const commit = parseCommit(obj.data);
355
+ commits.push({
356
+ sha,
357
+ message: commit.message,
358
+ author: { name: commit.author.name, email: commit.author.email },
359
+ timestamp: commit.author.timestamp,
360
+ });
361
+ queue.push(...commit.parents);
362
+ }
363
+
364
+ return commits.sort((a, b) => b.timestamp - a.timestamp);
365
+ }
366
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Minimal object-storage contract the git origin needs. `S3ObjectStore` is
3
+ * the production implementation; `InMemoryObjectStore` backs unit tests.
4
+ *
5
+ * Semantics implementations must honor:
6
+ * - `put` with `ifNoneMatch: "*"` fails with {@link PreconditionFailedError}
7
+ * when the key already exists.
8
+ * - `put` and `delete` with `ifMatch` fail with
9
+ * {@link PreconditionFailedError} when the key is missing or its ETag
10
+ * differs. ETags are opaque — callers only pass
11
+ * back values previously returned by `get`.
12
+ */
13
+ export interface ObjectStore {
14
+ /** Read an object, or null when the key does not exist. */
15
+ get(key: string): Promise<{ data: Uint8Array; etag: string } | null>;
16
+ /** Whether the key exists (no body transfer). */
17
+ has(key: string): Promise<boolean>;
18
+ put(
19
+ key: string,
20
+ data: Uint8Array,
21
+ opts?: { ifMatch?: string; ifNoneMatch?: "*" },
22
+ ): Promise<void>;
23
+ /** List full keys under a prefix. */
24
+ list(prefix: string): Promise<string[]>;
25
+ /**
26
+ * Delete exactly one key; a missing key is a no-op. With `ifMatch`, fails
27
+ * with {@link PreconditionFailedError} when the key is missing or its ETag
28
+ * differs.
29
+ */
30
+ delete(key: string, opts?: { ifMatch?: string }): Promise<void>;
31
+ /** Delete every object under a prefix. */
32
+ deletePrefix(prefix: string): Promise<void>;
33
+ }
34
+
35
+ /** A conditional `put` lost the race (HTTP 412 on S3-compatible stores). */
36
+ export class PreconditionFailedError extends Error {
37
+ constructor(key: string) {
38
+ super(`Conditional write failed for '${key}'`);
39
+ this.name = "PreconditionFailedError";
40
+ }
41
+ }