@ipab/ipfs-store 0.0.0 → 0.1.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +244 -1
  3. package/dist/configuration.d.ts +21 -0
  4. package/dist/configuration.d.ts.map +1 -0
  5. package/dist/configuration.js +62 -0
  6. package/dist/configuration.js.map +1 -0
  7. package/dist/dag.d.ts +49 -0
  8. package/dist/dag.d.ts.map +1 -0
  9. package/dist/dag.js +216 -0
  10. package/dist/dag.js.map +1 -0
  11. package/dist/errors.d.ts +6 -0
  12. package/dist/errors.d.ts.map +1 -0
  13. package/dist/errors.js +15 -0
  14. package/dist/errors.js.map +1 -0
  15. package/dist/index.d.ts +57 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +417 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/kubo.d.ts +38 -0
  20. package/dist/kubo.d.ts.map +1 -0
  21. package/dist/kubo.js +189 -0
  22. package/dist/kubo.js.map +1 -0
  23. package/dist/node.d.ts +11 -0
  24. package/dist/node.d.ts.map +1 -0
  25. package/dist/node.js +60 -0
  26. package/dist/node.js.map +1 -0
  27. package/dist/retention.d.ts +44 -0
  28. package/dist/retention.d.ts.map +1 -0
  29. package/dist/retention.js +328 -0
  30. package/dist/retention.js.map +1 -0
  31. package/dist/storage.d.ts +28 -0
  32. package/dist/storage.d.ts.map +1 -0
  33. package/dist/storage.js +161 -0
  34. package/dist/storage.js.map +1 -0
  35. package/dist/store.d.ts +71 -0
  36. package/dist/store.d.ts.map +1 -0
  37. package/dist/store.js +412 -0
  38. package/dist/store.js.map +1 -0
  39. package/package.json +67 -5
  40. package/src/configuration.ts +93 -0
  41. package/src/dag.ts +281 -0
  42. package/src/errors.ts +25 -0
  43. package/src/index.ts +520 -0
  44. package/src/kubo.ts +293 -0
  45. package/src/node.ts +78 -0
  46. package/src/retention.ts +398 -0
  47. package/src/storage.ts +181 -0
  48. package/src/store.ts +577 -0
@@ -0,0 +1,398 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import type { DatabaseSync } from "node:sqlite";
5
+ import type * as sqlite from "node:sqlite";
6
+ import { createRequire } from "node:module";
7
+ import { setTimeout as sleep } from "node:timers/promises";
8
+ import { CID } from "multiformats/cid";
9
+ import { ContentError } from "./errors.js";
10
+ import type { PinRecord } from "./kubo.js";
11
+
12
+ interface RetentionPort {
13
+ prepare(root: string, signal?: AbortSignal): Promise<void>;
14
+ status?(root: string, signal?: AbortSignal): Promise<PinRecord | undefined>;
15
+ pin?(root: string, name: string, signal?: AbortSignal): Promise<void>;
16
+ unpin?(root: string, signal?: AbortSignal): Promise<void>;
17
+ }
18
+ /** The SQLite mutex is separate so write-ahead intents survive a crash during an RPC. */
19
+ export class Retention {
20
+ private readonly Database: typeof DatabaseSync;
21
+ readonly name: string;
22
+ private readonly db: DatabaseSync;
23
+ private readonly mutexPath: string;
24
+ private readonly pending = new Set<Promise<unknown>>();
25
+ private closed = false;
26
+ constructor(
27
+ directory: string,
28
+ private readonly port: RetentionPort,
29
+ ) {
30
+ this.Database = (
31
+ createRequire(import.meta.url)("node:sqlite") as typeof sqlite
32
+ ).DatabaseSync;
33
+ mkdirSync(directory, { recursive: true });
34
+ this.db = new this.Database(join(directory, "retention.sqlite"));
35
+ this.mutexPath = join(directory, "mutex.sqlite");
36
+ this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
37
+ CREATE TABLE IF NOT EXISTS identity (id TEXT PRIMARY KEY);
38
+ CREATE TABLE IF NOT EXISTS owners (id TEXT PRIMARY KEY, roots TEXT NOT NULL);
39
+ CREATE TABLE IF NOT EXISTS stages (id TEXT NOT NULL, cid TEXT NOT NULL, PRIMARY KEY(id,cid));
40
+ CREATE TABLE IF NOT EXISTS stage_claims (cid TEXT PRIMARY KEY);
41
+ CREATE TABLE IF NOT EXISTS intents (
42
+ id TEXT NOT NULL, cid TEXT NOT NULL, count INTEGER NOT NULL CHECK(count>0), PRIMARY KEY(id,cid));
43
+ CREATE TABLE IF NOT EXISTS pins (cid TEXT PRIMARY KEY, phase TEXT NOT NULL);`);
44
+ this.db
45
+ .prepare(
46
+ "INSERT INTO identity SELECT ? WHERE NOT EXISTS (SELECT 1 FROM identity)",
47
+ )
48
+ .run(randomUUID());
49
+ this.name = `@silvermoon-work/task-engine/${String(
50
+ this.db.prepare("SELECT id FROM identity").get()!.id,
51
+ )}`;
52
+ }
53
+ private roots(values: readonly string[]): string[] {
54
+ return [
55
+ ...new Set(values.map((value) => CID.parse(value).toV1().toString())),
56
+ ].sort();
57
+ }
58
+ private readOwner(owner: string): string[] {
59
+ const row = this.db
60
+ .prepare("SELECT roots FROM owners WHERE id=?")
61
+ .get(owner);
62
+ if (!row) return [];
63
+ const roots: unknown = JSON.parse(String(row.roots));
64
+ if (!Array.isArray(roots) || roots.some((root) => typeof root !== "string"))
65
+ throw new Error("Invalid retention owner references.");
66
+ return this.roots(roots);
67
+ }
68
+ private publish(
69
+ owner: string,
70
+ roots: readonly string[],
71
+ replace = false,
72
+ ): void {
73
+ if (typeof owner !== "string" || !owner || owner.length > 4096)
74
+ throw new Error("A stable retention owner is required.");
75
+ const values = this.roots(
76
+ replace ? roots : [...this.readOwner(owner), ...roots],
77
+ );
78
+ this.db
79
+ .prepare("INSERT OR REPLACE INTO owners VALUES (?,?)")
80
+ .run(owner, JSON.stringify(values));
81
+ }
82
+ private begin(mutex: DatabaseSync): void {
83
+ if (this.closed) throw new Error("Retention coordinator is closed.");
84
+ mutex.exec("BEGIN IMMEDIATE");
85
+ }
86
+ register(owner: string, roots: readonly string[]): void {
87
+ const mutex = new this.Database(this.mutexPath);
88
+ mutex.exec("PRAGMA busy_timeout=0");
89
+ try {
90
+ this.begin(mutex);
91
+ } catch {
92
+ mutex.close();
93
+ throw new ContentError(
94
+ "retention_unfinished",
95
+ "Retention coordination is unavailable; retry.",
96
+ );
97
+ }
98
+ try {
99
+ this.publish(owner, roots);
100
+ } finally {
101
+ mutex.exec("ROLLBACK");
102
+ mutex.close();
103
+ }
104
+ }
105
+ private async locked<T>(
106
+ signal: AbortSignal | undefined,
107
+ action: () => Promise<T> | T,
108
+ ): Promise<T> {
109
+ const operation = this.lock(signal, action);
110
+ this.pending.add(operation);
111
+ void operation
112
+ .finally(() => this.pending.delete(operation))
113
+ .catch(() => {});
114
+ return operation;
115
+ }
116
+ private async lock<T>(
117
+ signal: AbortSignal | undefined,
118
+ action: () => Promise<T> | T,
119
+ ): Promise<T> {
120
+ const mutex = new this.Database(this.mutexPath);
121
+ mutex.exec("PRAGMA busy_timeout=0");
122
+ const deadline = Date.now() + 30_000;
123
+ try {
124
+ for (;;) {
125
+ signal?.throwIfAborted();
126
+ try {
127
+ this.begin(mutex);
128
+ break;
129
+ } catch (error) {
130
+ if (
131
+ (error as { errcode?: number }).errcode !== 5 ||
132
+ Date.now() >= deadline
133
+ )
134
+ throw new ContentError(
135
+ "retention_unfinished",
136
+ "Retention coordination is unavailable.",
137
+ );
138
+ await sleep(10, undefined, signal ? { signal } : {});
139
+ }
140
+ }
141
+ } catch (error) {
142
+ mutex.close();
143
+ signal?.throwIfAborted();
144
+ throw error;
145
+ }
146
+ try {
147
+ return await action();
148
+ } catch (error) {
149
+ if (signal?.aborted) throw signal.reason;
150
+ throw new ContentError(
151
+ "retention_unfinished",
152
+ `Retention hints are unfinished; durable intents remain for retry. ${
153
+ error instanceof ContentError
154
+ ? `${error.code}: ${error.message}`
155
+ : error instanceof Error &&
156
+ ["TimeoutError", "AbortError"].includes(error.name)
157
+ ? error.name
158
+ : "verification_or_storage_failure"
159
+ }`,
160
+ { cause: error },
161
+ );
162
+ } finally {
163
+ mutex.exec("ROLLBACK");
164
+ mutex.close();
165
+ }
166
+ }
167
+ private phase(root: string, phase: string): void {
168
+ this.db
169
+ .prepare("INSERT OR REPLACE INTO pins VALUES (?,?)")
170
+ .run(root, phase);
171
+ }
172
+ private async restoreClaim(
173
+ root: string,
174
+ signal?: AbortSignal,
175
+ ): Promise<void> {
176
+ if (!this.db.prepare("SELECT 1 FROM stage_claims WHERE cid=?").get(root))
177
+ return;
178
+ if (!this.port.status || !this.port.pin)
179
+ throw new Error("The staging claim's RPC backend is unavailable.");
180
+ let status = await this.port.status(root, signal);
181
+ if (status && status.Type !== "indirect" && !status.Name) {
182
+ if (status.Type !== "recursive")
183
+ throw new Error(
184
+ "An uncertain staging pin changed type; ownership is unfinished.",
185
+ );
186
+ // Only a durable absent/indirect/own before-state authorizes this recovery.
187
+ await this.port.prepare(root, signal);
188
+ await this.port.pin(root, this.name, signal);
189
+ status = await this.port.status(root, signal);
190
+ if (status && status.Type !== "indirect" && !status.Name)
191
+ throw new Error(
192
+ "The staging pin is still unnamed; ownership is unfinished.",
193
+ );
194
+ }
195
+ this.db.prepare("DELETE FROM stage_claims WHERE cid=?").run(root);
196
+ }
197
+ private async ensure(root: string, signal?: AbortSignal): Promise<void> {
198
+ await this.restoreClaim(root, signal);
199
+ this.phase(root, "pin-pending");
200
+ await this.port.prepare(root, signal);
201
+ const status = await this.port.status?.(root, signal);
202
+ if (status && status.Type !== "indirect" && status.Name !== this.name) {
203
+ if (status.Type !== "recursive")
204
+ throw new ContentError(
205
+ "retention_unfinished",
206
+ "An external direct pin cannot be renamed into a recursive system hint.",
207
+ );
208
+ // Do not turn another application's visible pin into our hint.
209
+ this.phase(root, "external");
210
+ return;
211
+ }
212
+ await this.port.pin?.(root, this.name, signal);
213
+ this.phase(root, "pinned");
214
+ }
215
+ pin(root: string, signal?: AbortSignal): Promise<void> {
216
+ root = this.roots([root])[0]!;
217
+ return this.locked(signal, () => this.ensure(root, signal));
218
+ }
219
+ retain(
220
+ owner: string,
221
+ roots: readonly string[],
222
+ signal?: AbortSignal,
223
+ ): Promise<void> {
224
+ return this.locked(signal, async () => {
225
+ this.publish(owner, roots);
226
+ for (const root of this.roots(roots)) this.intent(owner, root);
227
+ for (const root of this.roots(roots)) await this.ensure(root, signal);
228
+ });
229
+ }
230
+ confirm(
231
+ owner: string,
232
+ roots: readonly string[],
233
+ signal?: AbortSignal,
234
+ ): Promise<void> {
235
+ return this.locked(signal, () => {
236
+ this.publish(owner, roots);
237
+ for (const root of this.roots(roots)) {
238
+ const row = this.db
239
+ .prepare("SELECT count FROM intents WHERE id=? AND cid=?")
240
+ .get(owner, root);
241
+ if (row && Number(row.count) > 1)
242
+ this.db
243
+ .prepare("UPDATE intents SET count=count-1 WHERE id=? AND cid=?")
244
+ .run(owner, root);
245
+ else
246
+ this.db
247
+ .prepare("DELETE FROM intents WHERE id=? AND cid=?")
248
+ .run(owner, root);
249
+ }
250
+ });
251
+ }
252
+ private intent(owner: string, root: string): void {
253
+ this.db
254
+ .prepare(
255
+ `INSERT INTO intents VALUES (?,?,1)
256
+ ON CONFLICT(id,cid) DO UPDATE SET count=count+1`,
257
+ )
258
+ .run(owner, root);
259
+ }
260
+ discard(session: string, signal?: AbortSignal): Promise<void> {
261
+ return this.locked(signal, () => {
262
+ this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
263
+ });
264
+ }
265
+ recover(
266
+ owner: string,
267
+ roots: readonly string[] | (() => readonly string[]),
268
+ signal?: AbortSignal,
269
+ isIdle?: () => boolean,
270
+ ): Promise<void> {
271
+ return this.locked(signal, () => {
272
+ if (isIdle && !isIdle()) return;
273
+ this.publish(owner, typeof roots === "function" ? roots() : roots, true);
274
+ this.db.prepare("DELETE FROM intents WHERE id=?").run(owner);
275
+ for (const row of this.db.prepare("SELECT DISTINCT id FROM stages").all())
276
+ if (String(row.id).startsWith(`${owner}/`))
277
+ this.db.prepare("DELETE FROM stages WHERE id=?").run(String(row.id));
278
+ });
279
+ }
280
+ stage(
281
+ session: string,
282
+ root: string,
283
+ write: (name: string, claim: boolean) => Promise<void>,
284
+ signal?: AbortSignal,
285
+ ): Promise<void> {
286
+ root = this.roots([root])[0]!;
287
+ return this.locked(signal, async () => {
288
+ await this.restoreClaim(root, signal);
289
+ this.db
290
+ .prepare("INSERT OR IGNORE INTO stages VALUES (?,?)")
291
+ .run(session, root);
292
+ const alreadyPinned =
293
+ this.db.prepare("SELECT phase FROM pins WHERE cid=?").get(root)
294
+ ?.phase === "pinned";
295
+ this.phase(root, "stage-pending");
296
+ const status = await this.port.status?.(root, signal);
297
+ const claim =
298
+ !status || status.Type === "indirect" || status.Name === this.name;
299
+ if (claim && this.port.status)
300
+ this.db
301
+ .prepare("INSERT OR IGNORE INTO stage_claims VALUES (?)")
302
+ .run(root);
303
+ await write(this.name, claim);
304
+ if (claim) await this.restoreClaim(root, signal);
305
+ this.phase(
306
+ root,
307
+ claim ? (alreadyPinned ? "pinned" : "staged") : "external",
308
+ );
309
+ });
310
+ }
311
+ finish(
312
+ session: string,
313
+ root: string,
314
+ owner?: string,
315
+ signal?: AbortSignal,
316
+ ): Promise<void> {
317
+ root = this.roots([root])[0]!;
318
+ return this.locked(signal, async () => {
319
+ if (owner) {
320
+ this.publish(owner, [root]);
321
+ this.intent(owner, root);
322
+ }
323
+ await this.ensure(root, signal);
324
+ this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
325
+ });
326
+ }
327
+ private async remove(root: string, signal?: AbortSignal): Promise<boolean> {
328
+ await this.restoreClaim(root, signal);
329
+ const record = this.db
330
+ .prepare("SELECT phase FROM pins WHERE cid=?")
331
+ .get(root);
332
+ if (!record) return false;
333
+ this.phase(root, "unpin-pending");
334
+ const status = await this.port.status?.(root, signal);
335
+ if (this.port.status && (!status || status.Name !== this.name)) {
336
+ this.db.prepare("DELETE FROM pins WHERE cid=?").run(root);
337
+ return false;
338
+ }
339
+ await this.port.unpin?.(root, signal);
340
+ this.db.prepare("DELETE FROM pins WHERE cid=?").run(root);
341
+ return true;
342
+ }
343
+ unpin(root: string, signal?: AbortSignal): Promise<void> {
344
+ root = this.roots([root])[0]!;
345
+ return this.locked(signal, async () => {
346
+ if (this.allRoots().includes(root))
347
+ throw new Error("A participating owner still retains this root.");
348
+ await this.remove(root, signal);
349
+ });
350
+ }
351
+ private allRoots(): string[] {
352
+ return this.roots([
353
+ ...this.db
354
+ .prepare("SELECT id FROM owners")
355
+ .all()
356
+ .flatMap((row) => this.readOwner(String(row.id))),
357
+ ...this.db
358
+ .prepare("SELECT cid FROM intents")
359
+ .all()
360
+ .map((row) => String(row.cid)),
361
+ ...this.db
362
+ .prepare("SELECT cid FROM stages")
363
+ .all()
364
+ .map((row) => String(row.cid)),
365
+ ]);
366
+ }
367
+ reconcile(
368
+ owner: string,
369
+ roots: readonly string[] | (() => readonly string[]),
370
+ signal?: AbortSignal,
371
+ ): Promise<number> {
372
+ return this.locked(signal, async () => {
373
+ this.publish(owner, typeof roots === "function" ? roots() : roots, true);
374
+ for (const row of this.db.prepare("SELECT cid FROM stage_claims").all())
375
+ await this.restoreClaim(String(row.cid), signal);
376
+ const marked = new Set(this.allRoots());
377
+ // Complete the entire mark before removing any hint. Recheck real blocks, not reader caches.
378
+ for (const root of marked) await this.ensure(root, signal);
379
+ let removed = 0;
380
+ for (const row of this.db.prepare("SELECT cid FROM pins").all()) {
381
+ const root = String(row.cid);
382
+ if (!marked.has(root) && (await this.remove(root, signal))) removed++;
383
+ }
384
+ return removed;
385
+ });
386
+ }
387
+ pins(): string[] {
388
+ return this.db
389
+ .prepare("SELECT cid FROM pins WHERE phase='pinned' ORDER BY cid")
390
+ .all()
391
+ .map((row) => String(row.cid));
392
+ }
393
+ async close(): Promise<void> {
394
+ this.closed = true;
395
+ await Promise.allSettled([...this.pending]);
396
+ this.db.close();
397
+ }
398
+ }
package/src/storage.ts ADDED
@@ -0,0 +1,181 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { link, lstat, mkdir, open, rm } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { CID } from "multiformats/cid";
5
+ import type { GatewayClient, IpfsClient } from "./index.js";
6
+ import { acquireBlock, verifyBlock } from "./dag.js";
7
+ import { abortError, ContentError } from "./errors.js";
8
+
9
+ /** Immutable verified publications, atomically linked; concurrent processes never see partial bytes. */
10
+ export class SharedContent implements GatewayClient {
11
+ private readonly pending = new Map<string, Promise<Uint8Array>>();
12
+ private readonly writes = new Set<Promise<void>>();
13
+ private readonly lifetime = new AbortController();
14
+ private closing?: Promise<void>;
15
+ constructor(
16
+ readonly directory: string,
17
+ private readonly source?: IpfsClient,
18
+ private readonly blockBytes = 2 * 1024 * 1024,
19
+ ) {}
20
+ private async local(cid: CID): Promise<Uint8Array> {
21
+ const path = join(this.directory, "blocks", cid.toV1().toString());
22
+ const stat = await lstat(path);
23
+ if (!stat.isFile() || stat.isSymbolicLink())
24
+ throw new Error("Invalid shared content block.");
25
+ if (stat.size > this.blockBytes)
26
+ throw new ContentError(
27
+ "capacity_exceeded",
28
+ "Content block capacity exceeded.",
29
+ );
30
+ const file = await open(path, "r");
31
+ let bytes: Uint8Array;
32
+ try {
33
+ // Bound the allocation even if an external writer changes a published file.
34
+ const buffer = Buffer.alloc(Math.min(stat.size + 1, this.blockBytes + 1));
35
+ let offset = 0;
36
+ while (offset < buffer.length) {
37
+ this.lifetime.signal.throwIfAborted();
38
+ const { bytesRead } = await file.read(
39
+ buffer,
40
+ offset,
41
+ buffer.length - offset,
42
+ offset,
43
+ );
44
+ if (!bytesRead) break;
45
+ offset += bytesRead;
46
+ }
47
+ if (offset > this.blockBytes)
48
+ throw new ContentError(
49
+ "capacity_exceeded",
50
+ "Content block capacity exceeded.",
51
+ );
52
+ bytes = buffer.subarray(0, offset);
53
+ } finally {
54
+ await file.close();
55
+ }
56
+ await verifyBlock(cid, bytes);
57
+ return bytes;
58
+ }
59
+ put(
60
+ cid: CID,
61
+ bytes: Uint8Array,
62
+ options: { signal?: AbortSignal } = {},
63
+ ): Promise<void> {
64
+ const operation = this.publish(cid, bytes, options);
65
+ this.writes.add(operation);
66
+ void operation.finally(() => this.writes.delete(operation)).catch(() => {});
67
+ return operation;
68
+ }
69
+ private async publish(
70
+ cid: CID,
71
+ bytes: Uint8Array,
72
+ options: { signal?: AbortSignal },
73
+ ): Promise<void> {
74
+ const signal = AbortSignal.any([
75
+ this.lifetime.signal,
76
+ ...(options.signal ? [options.signal] : []),
77
+ ]);
78
+ signal.throwIfAborted();
79
+ if (bytes.byteLength > this.blockBytes)
80
+ throw new ContentError(
81
+ "capacity_exceeded",
82
+ "Content block capacity exceeded.",
83
+ );
84
+ const snapshot = Uint8Array.from(bytes);
85
+ await verifyBlock(cid, snapshot);
86
+ signal.throwIfAborted();
87
+ const directory = join(this.directory, "blocks");
88
+ await mkdir(directory, { recursive: true });
89
+ const metadata = await lstat(directory);
90
+ if (!metadata.isDirectory() || metadata.isSymbolicLink())
91
+ throw new Error("Invalid shared content directory.");
92
+ const temporary = join(directory, `.pending-${randomUUID()}`);
93
+ const destination = join(directory, cid.toV1().toString());
94
+ let owned = false;
95
+ try {
96
+ const file = await open(temporary, "wx", 0o600);
97
+ owned = true;
98
+ try {
99
+ await file.writeFile(snapshot);
100
+ await file.sync();
101
+ } finally {
102
+ await file.close();
103
+ }
104
+ signal.throwIfAborted();
105
+ try {
106
+ await link(temporary, destination);
107
+ } catch (error) {
108
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
109
+ await this.local(cid);
110
+ }
111
+ } finally {
112
+ if (owned) await rm(temporary, { force: true });
113
+ }
114
+ }
115
+ readonly block = {
116
+ get: (
117
+ value: string,
118
+ options: { signal?: AbortSignal } = {},
119
+ ): Promise<Uint8Array> => this.readBlock(value, options),
120
+ };
121
+ async readBlock(
122
+ value: string,
123
+ options: { signal?: AbortSignal } = {},
124
+ source = this.source,
125
+ ): Promise<Uint8Array> {
126
+ const signal = AbortSignal.any([
127
+ this.lifetime.signal,
128
+ ...(options.signal ? [options.signal] : []),
129
+ ]);
130
+ signal.throwIfAborted();
131
+ const cid = CID.parse(value),
132
+ key = cid.toV1().toString();
133
+ let operation = this.pending.get(key);
134
+ if (!operation) {
135
+ operation = (async () => {
136
+ try {
137
+ return await this.local(cid);
138
+ } catch (error) {
139
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
140
+ }
141
+ if (!source)
142
+ throw new ContentError(
143
+ "missing_block",
144
+ `Missing local content block: ${cid.toString()}; configure a content gateway or import complete content.`,
145
+ );
146
+ const bytes = await acquireBlock(source, cid, {
147
+ signal: this.lifetime.signal,
148
+ blockBytes: this.blockBytes,
149
+ });
150
+ await this.put(cid, bytes, { signal: this.lifetime.signal });
151
+ return Uint8Array.from(bytes);
152
+ })();
153
+ this.pending.set(key, operation);
154
+ void operation.finally(() => this.pending.delete(key)).catch(() => {});
155
+ }
156
+ let abort = () => {};
157
+ try {
158
+ const bytes = await Promise.race([
159
+ operation,
160
+ new Promise<never>((_, reject) => {
161
+ abort = () => {
162
+ reject(abortError(signal));
163
+ };
164
+ signal.addEventListener("abort", abort, { once: true });
165
+ if (signal.aborted) abort();
166
+ }),
167
+ ]);
168
+ signal.throwIfAborted();
169
+ return Uint8Array.from(bytes);
170
+ } finally {
171
+ signal.removeEventListener("abort", abort);
172
+ }
173
+ }
174
+ close(): Promise<void> {
175
+ this.closing ??= (async () => {
176
+ this.lifetime.abort(new Error("Content client is closed."));
177
+ await Promise.allSettled([...this.pending.values(), ...this.writes]);
178
+ })();
179
+ return this.closing;
180
+ }
181
+ }