@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.
Files changed (66) hide show
  1. package/dist/checkout-remote-backend.d.ts.map +1 -1
  2. package/dist/fs-backend.d.ts +8 -0
  3. package/dist/fs-backend.d.ts.map +1 -1
  4. package/dist/fs-remote-backend.d.ts +43 -9
  5. package/dist/fs-remote-backend.d.ts.map +1 -1
  6. package/dist/git-objects.d.ts +77 -0
  7. package/dist/git-objects.d.ts.map +1 -0
  8. package/dist/git-sync.d.ts +16 -17
  9. package/dist/git-sync.d.ts.map +1 -1
  10. package/dist/index.d.ts +6 -5
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3912 -3059
  13. package/dist/index.js.map +23 -21
  14. package/dist/native-git.d.ts +114 -2
  15. package/dist/native-git.d.ts.map +1 -1
  16. package/dist/native-project-repo.d.ts +40 -5
  17. package/dist/native-project-repo.d.ts.map +1 -1
  18. package/dist/network-sync.d.ts.map +1 -1
  19. package/dist/network.d.ts +14 -9
  20. package/dist/network.d.ts.map +1 -1
  21. package/dist/object-origin-cache.d.ts +86 -0
  22. package/dist/object-origin-cache.d.ts.map +1 -0
  23. package/dist/object-remote-backend.d.ts +64 -10
  24. package/dist/object-remote-backend.d.ts.map +1 -1
  25. package/dist/origin-draft.d.ts.map +1 -1
  26. package/dist/origin-objects.d.ts +7 -2
  27. package/dist/origin-objects.d.ts.map +1 -1
  28. package/dist/project-manager.d.ts +22 -0
  29. package/dist/project-manager.d.ts.map +1 -1
  30. package/dist/project-paths.d.ts +20 -0
  31. package/dist/project-paths.d.ts.map +1 -0
  32. package/dist/ref-names.d.ts +35 -0
  33. package/dist/ref-names.d.ts.map +1 -1
  34. package/dist/types.d.ts +37 -4
  35. package/dist/types.d.ts.map +1 -1
  36. package/dist/workspace-checkout.d.ts +31 -0
  37. package/dist/workspace-checkout.d.ts.map +1 -0
  38. package/dist/workspace-mirror.d.ts +38 -5
  39. package/dist/workspace-mirror.d.ts.map +1 -1
  40. package/dist/workspace-save.d.ts +27 -2
  41. package/dist/workspace-save.d.ts.map +1 -1
  42. package/package.json +4 -4
  43. package/src/checkout-remote-backend.ts +77 -29
  44. package/src/fs-backend.ts +69 -7
  45. package/src/fs-remote-backend.ts +255 -133
  46. package/src/git-objects.ts +363 -0
  47. package/src/git-sync.ts +124 -453
  48. package/src/index.ts +17 -7
  49. package/src/native-git.ts +566 -25
  50. package/src/native-project-repo.ts +318 -99
  51. package/src/network-sync.ts +43 -35
  52. package/src/network.ts +177 -153
  53. package/src/object-origin-cache.ts +689 -0
  54. package/src/object-remote-backend.ts +277 -20
  55. package/src/origin-draft.ts +22 -15
  56. package/src/origin-objects.ts +21 -5
  57. package/src/project-manager.ts +261 -73
  58. package/src/project-paths.ts +142 -0
  59. package/src/ref-names.ts +56 -0
  60. package/src/types.ts +38 -4
  61. package/src/workspace-checkout.ts +192 -0
  62. package/src/workspace-mirror.ts +276 -68
  63. package/src/workspace-save.ts +99 -30
  64. package/dist/project-repo.d.ts +0 -81
  65. package/dist/project-repo.d.ts.map +0 -1
  66. package/src/project-repo.ts +0 -821
@@ -1,11 +1,27 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import path from "node:path";
3
+ import { getTracer, withSpan } from "@catamorphic/otel";
2
4
  import {
3
5
  type GitObjectType,
4
6
  parseCommit,
5
7
  unwrapObject,
6
8
  wrapObject,
7
9
  } from "./git-object-codec.js";
10
+ import {
11
+ OBJECT_MAX_BYTES,
12
+ ObjectTooLargeError,
13
+ openObjectReader,
14
+ } from "./git-objects.js";
15
+ import {
16
+ borrowObjects,
17
+ gitErrorText,
18
+ nativeGit,
19
+ nativeGitLines,
20
+ TRANSFER_TIMEOUT_MS,
21
+ } from "./native-git.js";
22
+ import { ObjectOriginCache } from "./object-origin-cache.js";
8
23
  import { type ObjectStore, PreconditionFailedError } from "./object-store.js";
24
+ import { mapLimit } from "./origin-objects.js";
9
25
  import { RefMovedError } from "./ref-moved-error.js";
10
26
  import { InvalidRefNameError, isValidRefName } from "./ref-names.js";
11
27
  import type {
@@ -24,7 +40,21 @@ function assertUuid(value: string): void {
24
40
  }
25
41
  }
26
42
 
43
+ const tracer = getTracer("@catamorphic/git");
44
+
27
45
  const SHA_RE = /^[0-9a-f]{40}$/;
46
+
47
+ /**
48
+ * What a save may hold and still be stored as single objects: beyond
49
+ * either, it is stored as one pack. Single objects need no Git and no disk
50
+ * to read back, which is what drafts and small saves want; a pack is the
51
+ * only form a large history can take.
52
+ */
53
+ const SINGLE_OBJECTS_MAX = 512;
54
+ const SINGLE_OBJECTS_MAX_BYTES = 16 * 1024 * 1024;
55
+
56
+ /** Single objects written to the store at once. */
57
+ const WRITE_CONCURRENCY = 16;
28
58
  const REF_RE = /^refs\/[A-Za-z0-9._/-]+$/;
29
59
 
30
60
  function assertRefName(ref: string): void {
@@ -89,28 +119,54 @@ export interface ObjectRemoteBackendOpts {
89
119
  * Project layout: `<keyPrefix><tenantId>/<projectId>/{repo.json,objects/,refs/}`.
90
120
  */
91
121
  keyPrefix?: string;
122
+ /**
123
+ * A folder on this machine for the packs of large histories (ADR 0356):
124
+ * Git reads them there, and copies on this machine borrow from it. It is
125
+ * a cache the store refills, never the only copy of anything, but it is
126
+ * the host's to place: somewhere nothing else removes files from one by
127
+ * one (not the system's temporary folder, which cleaners prune), and
128
+ * that is deleted whole or not at all. Nothing is written there until an
129
+ * origin holds a pack or lends its history to a copy.
130
+ */
131
+ cachePath: string;
92
132
  }
93
133
 
94
134
  /**
95
135
  * `RemoteBackend` storing each project's canonical bare repository directly
96
136
  * 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.
137
+ * immutable objects and conditional ref updates.
98
138
  *
99
139
  * 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.
140
+ * object storage: single objects for drafts and small saves, packs in parts
141
+ * for large histories (ADR 0356). Ref updates use conditional PUTs
142
+ * (`If-Match` / `If-None-Match`) for the compare-and-swap semantics
143
+ * `OriginRepo.updateRef` requires. Buckets don't speak the git protocol, so
144
+ * `getCloneSource` is not implemented and sandboxes receive file uploads
145
+ * (same as `FsRemoteBackend`). See docs/decisions/0012 and 0356.
105
146
  */
106
147
  export class ObjectRemoteBackend implements RemoteBackend {
107
148
  private readonly store: ObjectStore;
108
149
  private readonly keyPrefix: string;
109
150
  private draftCheck: Promise<DraftSupport> | undefined;
151
+ private readonly cachePath: string;
110
152
 
111
153
  constructor(opts: ObjectRemoteBackendOpts) {
112
154
  this.store = opts.store;
113
155
  this.keyPrefix = opts.keyPrefix ?? "";
156
+ this.cachePath = opts.cachePath;
157
+ }
158
+
159
+ /** Where this backend keeps its origins' packs on this machine. */
160
+ private cacheDirectory(tenantId: string, projectId: string): Promise<string> {
161
+ return Promise.resolve(path.join(this.cachePath, tenantId, projectId));
162
+ }
163
+
164
+ private cache(tenantId: string, projectId: string): ObjectOriginCache {
165
+ return new ObjectOriginCache({
166
+ store: this.store,
167
+ basePath: this.basePath(tenantId, projectId),
168
+ directory: () => this.cacheDirectory(tenantId, projectId),
169
+ });
114
170
  }
115
171
 
116
172
  private basePath(tenantId: string, projectId: string): string {
@@ -139,6 +195,7 @@ export class ObjectRemoteBackend implements RemoteBackend {
139
195
 
140
196
  async deleteRemote(tenantId: string, projectId: string): Promise<void> {
141
197
  await this.store.deletePrefix(`${this.basePath(tenantId, projectId)}/`);
198
+ await this.cache(tenantId, projectId).remove();
142
199
  }
143
200
 
144
201
  async exists(tenantId: string, projectId: string): Promise<boolean> {
@@ -177,6 +234,7 @@ export class ObjectRemoteBackend implements RemoteBackend {
177
234
  new ObjectOriginRepo({
178
235
  store: this.store,
179
236
  basePath: this.basePath(tenantId, projectId),
237
+ cache: this.cache(tenantId, projectId),
180
238
  }),
181
239
  );
182
240
  }
@@ -184,20 +242,31 @@ export class ObjectRemoteBackend implements RemoteBackend {
184
242
 
185
243
  /**
186
244
  * `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.
245
+ * - `objects/<sha>`: single git objects in wrapped form
246
+ * (`<type> <len>\0<content>`), so `sha1(body) == key` and every object is
247
+ * self-verifying.
248
+ * - `packs/<pack>.json` and `pack-parts/<pack>/<number>`: packs, which a
249
+ * large history is stored as (ADR 0356). Git reads them from a cache on
250
+ * this machine.
251
+ * - `refs/heads/<branch>`: the 40-char commit SHA as the body.
190
252
  */
191
253
  export class ObjectOriginRepo implements OriginRepo {
192
254
  private readonly store: ObjectStore;
193
255
  private readonly basePath: string;
256
+ private readonly cache: ObjectOriginCache;
194
257
  /** Synthetic identifier — this origin has no on-disk git directory. */
195
258
  readonly gitdir: string;
196
259
 
197
- constructor(opts: { store: ObjectStore; basePath: string }) {
260
+ constructor(opts: {
261
+ store: ObjectStore;
262
+ basePath: string;
263
+ /** This origin's packs on this machine. */
264
+ cache: ObjectOriginCache;
265
+ }) {
198
266
  this.store = opts.store;
199
267
  this.basePath = opts.basePath;
200
268
  this.gitdir = `objectstore://${opts.basePath}`;
269
+ this.cache = opts.cache;
201
270
  }
202
271
 
203
272
  private refKey(ref: string): string {
@@ -305,18 +374,35 @@ export class ObjectOriginRepo implements OriginRepo {
305
374
  }
306
375
 
307
376
  async hasObject(sha: string): Promise<boolean> {
308
- return this.store.has(this.objectKey(sha));
377
+ if (await this.cache.has(sha)) return true;
378
+ if (await this.store.has(this.objectKey(sha))) return true;
379
+ // Not a single object: it may be in a pack this machine lacks.
380
+ return (await this.cache.refreshPacks()) && this.cache.has(sha);
309
381
  }
310
382
 
311
- async readObject(sha: string): Promise<{
383
+ async readObject(
384
+ sha: string,
385
+ options?: { maxBytes?: number },
386
+ ): Promise<{
312
387
  type: GitObjectType;
313
388
  data: Uint8Array;
314
389
  }> {
390
+ const maxBytes = options?.maxBytes ?? OBJECT_MAX_BYTES;
391
+ // A packed object's size is asked before it is read.
392
+ const held = await this.cache.read(sha, maxBytes);
393
+ if (held) return { type: held.type, data: held.data };
315
394
  const entry = await this.store.get(this.objectKey(sha));
316
- if (!entry) {
317
- throw new Error(`Object not found: ${sha}`);
395
+ if (entry) {
396
+ // A single object arrives whole: the store names no size first.
397
+ if (entry.data.byteLength > maxBytes + 64)
398
+ throw new ObjectTooLargeError(sha, null, maxBytes);
399
+ return unwrapObject(entry.data);
318
400
  }
319
- return unwrapObject(entry.data);
401
+ if (await this.cache.refreshPacks()) {
402
+ const packed = await this.cache.read(sha, maxBytes);
403
+ if (packed) return { type: packed.type, data: packed.data };
404
+ }
405
+ throw new Error(`Object not found: ${sha}`);
320
406
  }
321
407
 
322
408
  async writeObject(opts: {
@@ -327,12 +413,185 @@ export class ObjectOriginRepo implements OriginRepo {
327
413
  // Objects are immutable and content-addressed; skip the PUT when the
328
414
  // object is already stored, otherwise write unconditionally (an
329
415
  // overwrite is byte-identical by construction).
330
- if (!(await this.hasObject(sha))) {
416
+ if (!(await this.store.has(this.objectKey(sha)))) {
331
417
  await this.store.put(this.objectKey(sha), wrapped);
332
418
  }
333
419
  return sha;
334
420
  }
335
421
 
422
+ /**
423
+ * Take `commit` and what it reaches from the repository at `repoPath`.
424
+ * What the origin holds is read off its refs (the one about to move, and
425
+ * `main`), never off single objects: a ref only ever moved to a history
426
+ * stored whole. A few objects are stored one by one; anything larger is
427
+ * one pack, built by Git and written in parts.
428
+ */
429
+ async receive(input: {
430
+ repoPath: string;
431
+ commit: string;
432
+ ref?: string;
433
+ }): Promise<void> {
434
+ if (!SHA_RE.test(input.commit))
435
+ throw new Error(`Invalid object sha: ${input.commit}`);
436
+ await withSpan(
437
+ {
438
+ tracer,
439
+ name: "git.origin.receive",
440
+ attributes: { "catamorphic.git.origin": "object-store" },
441
+ },
442
+ async (span) => {
443
+ const stored = [
444
+ ...new Set(
445
+ (
446
+ await Promise.all(
447
+ [...(input.ref ? [input.ref] : []), "refs/heads/main"].map(
448
+ (ref) => this.resolveRef(ref),
449
+ ),
450
+ )
451
+ ).filter((sha) => sha !== null),
452
+ ),
453
+ ];
454
+ if (stored.includes(input.commit)) return;
455
+ const bases: string[] = [];
456
+ for (const sha of stored)
457
+ if (
458
+ await nativeGit(input.repoPath, [
459
+ "cat-file",
460
+ "-e",
461
+ `${sha}^{commit}`,
462
+ ]).then(
463
+ () => true,
464
+ () => false,
465
+ )
466
+ )
467
+ bases.push(sha);
468
+ const objects: string[] = [];
469
+ try {
470
+ for await (const line of nativeGitLines({
471
+ cwd: input.repoPath,
472
+ args: ["rev-list", "--objects", input.commit, "--not", ...bases],
473
+ })) {
474
+ objects.push(line.slice(0, 40));
475
+ if (objects.length > SINGLE_OBJECTS_MAX) break;
476
+ }
477
+ } catch (error) {
478
+ throw new Error(
479
+ `Could not read the history of ${input.commit.slice(0, 12)} to publish it: ${gitErrorText(error)}`,
480
+ );
481
+ }
482
+ if (objects.length === 0) return;
483
+ if (
484
+ objects.length <= SINGLE_OBJECTS_MAX &&
485
+ (await this.storeSingly({ repoPath: input.repoPath, objects }))
486
+ ) {
487
+ span.setAttribute("catamorphic.git.objects", objects.length);
488
+ return;
489
+ }
490
+ const { bytes } = await this.cache.uploadPack({
491
+ repoPath: input.repoPath,
492
+ commit: input.commit,
493
+ bases,
494
+ });
495
+ span.setAttribute("catamorphic.git.pack_bytes", bytes);
496
+ },
497
+ );
498
+ }
499
+
500
+ /**
501
+ * Store a few objects of the repository at `repoPath` one by one.
502
+ * Returns false, having stored nothing, when together they are too large
503
+ * for that.
504
+ */
505
+ private async storeSingly(input: {
506
+ repoPath: string;
507
+ objects: readonly string[];
508
+ }): Promise<boolean> {
509
+ const headers = await openObjectReader({
510
+ gitdir: input.repoPath,
511
+ contents: false,
512
+ });
513
+ try {
514
+ let bytes = 0;
515
+ for (const oid of input.objects) {
516
+ bytes += (await headers.ask(oid))?.size ?? 0;
517
+ if (bytes > SINGLE_OBJECTS_MAX_BYTES) return false;
518
+ }
519
+ } finally {
520
+ headers.stop();
521
+ }
522
+ const contents = await openObjectReader({
523
+ gitdir: input.repoPath,
524
+ contents: true,
525
+ });
526
+ try {
527
+ await mapLimit(input.objects, WRITE_CONCURRENCY, async (oid) => {
528
+ const object = await contents.ask(oid);
529
+ if (!object)
530
+ throw new Error(`Object ${oid} is missing from the copy being saved`);
531
+ const { wrapped, sha } = wrapObject(object);
532
+ await this.store.put(this.objectKey(sha), wrapped);
533
+ });
534
+ } finally {
535
+ contents.stop();
536
+ }
537
+ return true;
538
+ }
539
+
540
+ /**
541
+ * Make `commit` and what it reaches readable in the repository at
542
+ * `repoPath`. The history is first made whole in this machine's cache
543
+ * (packs the store keeps, and single objects gathered into one); the
544
+ * repository then borrows the cache's objects, or is sent what it lacks.
545
+ */
546
+ async send(input: {
547
+ repoPath: string;
548
+ commit: string;
549
+ borrow?: boolean;
550
+ }): Promise<void> {
551
+ if (!SHA_RE.test(input.commit))
552
+ throw new Error(`Invalid object sha: ${input.commit}`);
553
+ await withSpan(
554
+ {
555
+ tracer,
556
+ name: "git.origin.send",
557
+ attributes: {
558
+ "catamorphic.git.origin": "object-store",
559
+ "catamorphic.git.borrow": input.borrow ?? false,
560
+ },
561
+ },
562
+ async () => {
563
+ await this.cache.materialize(input.commit);
564
+ if (input.borrow) {
565
+ await borrowObjects({
566
+ repoPath: input.repoPath,
567
+ objects: await this.cache.objects(),
568
+ });
569
+ return;
570
+ }
571
+ await nativeGit(
572
+ input.repoPath,
573
+ [
574
+ "-c",
575
+ "protocol.version=2",
576
+ "fetch",
577
+ "--quiet",
578
+ "--no-tags",
579
+ "--no-write-fetch-head",
580
+ "--end-of-options",
581
+ await this.cache.directory(),
582
+ input.commit,
583
+ ],
584
+ undefined,
585
+ { timeoutMs: TRANSFER_TIMEOUT_MS },
586
+ ).catch((error: unknown) => {
587
+ throw new Error(
588
+ `Could not copy ${input.commit.slice(0, 12)} from the project's origin: ${gitErrorText(error)}`,
589
+ );
590
+ });
591
+ },
592
+ );
593
+ }
594
+
336
595
  async log(ref: string, maxCount = 50): Promise<CommitInfo[]> {
337
596
  const tip = await this.resolveRef(ref);
338
597
  if (!tip) return [];
@@ -346,10 +605,8 @@ export class ObjectOriginRepo implements OriginRepo {
346
605
  if (!sha || seen.has(sha)) continue;
347
606
  seen.add(sha);
348
607
 
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;
608
+ const obj = await this.readObject(sha).catch(() => null);
609
+ if (obj?.type !== "commit") break;
353
610
 
354
611
  const commit = parseCommit(obj.data);
355
612
  commits.push({
@@ -7,6 +7,7 @@ import {
7
7
  SYSTEM_COMMIT_AUTHOR,
8
8
  } from "@catamorphic/workflow/project-layout";
9
9
  import { type FileReadOptions, readFileSnapshot } from "./file-reads.js";
10
+ import { ObjectTooLargeError } from "./git-objects.js";
10
11
  import { fetchRemote } from "./git-sync.js";
11
12
  import {
12
13
  DraftIgnoredPathError,
@@ -19,7 +20,7 @@ import {
19
20
  SYMLINK_MODE,
20
21
  type TreeChange,
21
22
  } from "./origin-objects.js";
22
- import { assertSafePath } from "./project-repo.js";
23
+ import { assertSafePath } from "./project-paths.js";
23
24
  import { RefMovedError } from "./ref-moved-error.js";
24
25
  import { assertValidRefName } from "./ref-names.js";
25
26
  import type {
@@ -387,16 +388,18 @@ export class OriginDraftRepo {
387
388
  .entry((await objects.commit(sha)).tree, normalized)
388
389
  .catch(() => null);
389
390
  if (!entry || isTreeMode(entry.mode)) return null;
390
- return objects.blob(entry.oid);
391
+ // Its size is asked before it is read: a file of any size may be
392
+ // in the project, and only what fits the limit comes into memory.
393
+ return objects
394
+ .blob(entry.oid, options?.maxBytes)
395
+ .catch((error: unknown) => {
396
+ if (error instanceof ObjectTooLargeError)
397
+ throw new Error(
398
+ `Project file '${normalized}' exceeds the ${error.maxBytes}-byte snapshot limit`,
399
+ );
400
+ throw error;
401
+ });
391
402
  });
392
- if (
393
- blob &&
394
- options?.maxBytes !== undefined &&
395
- blob.byteLength > options.maxBytes
396
- )
397
- throw new Error(
398
- `Project file '${normalized}' exceeds the ${options.maxBytes}-byte snapshot limit`,
399
- );
400
403
  return blob;
401
404
  }
402
405
 
@@ -432,11 +435,15 @@ export class OriginDraftRepo {
432
435
  read: async (file, maxBytes) => {
433
436
  const entry = files.get(file);
434
437
  if (!entry) return null;
435
- const blob = await objects.blob(entry.oid);
436
- if (blob.byteLength > maxBytes)
437
- throw new Error(
438
- `Project file '${file}' exceeds the ${maxBytes}-byte snapshot limit`,
439
- );
438
+ const blob = await objects
439
+ .blob(entry.oid, maxBytes)
440
+ .catch((error: unknown) => {
441
+ if (error instanceof ObjectTooLargeError)
442
+ throw new Error(
443
+ `Project file '${file}' exceeds the ${maxBytes}-byte snapshot limit`,
444
+ );
445
+ throw error;
446
+ });
440
447
  return new TextDecoder().decode(blob);
441
448
  },
442
449
  });
@@ -5,6 +5,7 @@ import {
5
5
  type ParsedCommit,
6
6
  parseCommit,
7
7
  } from "./git-object-codec.js";
8
+ import { ObjectTooLargeError } from "./git-objects.js";
8
9
  import { isPersonalFile } from "./personal-files.js";
9
10
  import type { ConflictEntry, OriginRepo } from "./types.js";
10
11
 
@@ -266,11 +267,26 @@ export class OriginObjects {
266
267
  private readonly cache: GitObjectCache,
267
268
  ) {}
268
269
 
269
- async read(oid: string): Promise<{ type: GitObjectType; data: Uint8Array }> {
270
+ /**
271
+ * One object, in memory. With `maxBytes`, one larger is refused
272
+ * (`ObjectTooLargeError`) before it is read wherever the origin knows
273
+ * its size first; without, the origin's own limit holds.
274
+ */
275
+ async read(
276
+ oid: string,
277
+ maxBytes?: number,
278
+ ): Promise<{ type: GitObjectType; data: Uint8Array }> {
270
279
  const key = `${this.origin.gitdir}\0${oid}`;
271
280
  const cached = this.cache.get(key);
272
- if (cached) return cached;
273
- const object = await this.origin.readObject(oid);
281
+ if (cached) {
282
+ if (maxBytes !== undefined && cached.data.byteLength > maxBytes)
283
+ throw new ObjectTooLargeError(oid, cached.data.byteLength, maxBytes);
284
+ return cached;
285
+ }
286
+ const object = await this.origin.readObject(
287
+ oid,
288
+ maxBytes !== undefined ? { maxBytes } : undefined,
289
+ );
274
290
  this.cache.set(key, object);
275
291
  return object;
276
292
  }
@@ -304,8 +320,8 @@ export class OriginObjects {
304
320
  return parseTree(object.data);
305
321
  }
306
322
 
307
- async blob(oid: string): Promise<Uint8Array> {
308
- const object = await this.read(oid);
323
+ async blob(oid: string, maxBytes?: number): Promise<Uint8Array> {
324
+ const object = await this.read(oid, maxBytes);
309
325
  if (object.type !== "blob") throw new Error(`${oid} is not a file`);
310
326
  return object.data;
311
327
  }