@ipab/ipfs-store 0.1.0-rc.3 → 0.1.0-rc.5

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/src/retention.ts CHANGED
@@ -1,20 +1,45 @@
1
1
  import { mkdirSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { join, resolve } from "node:path";
3
3
  import type { DatabaseSync } from "node:sqlite";
4
4
  import type * as sqlite from "node:sqlite";
5
5
  import { createRequire } from "node:module";
6
6
  import { setTimeout as sleep } from "node:timers/promises";
7
7
  import { CID } from "multiformats/cid";
8
- import { ContentError } from "./errors.js";
8
+ import { abortError, ContentError } from "./errors.js";
9
+
10
+ const coordinationQueues = new Map<string, Promise<void>>();
11
+
12
+ function queueKeyFor(mutexPath: string): string {
13
+ return resolve(mutexPath);
14
+ }
15
+
16
+ function waitForTurn(
17
+ previous: Promise<void>,
18
+ signal: AbortSignal | undefined,
19
+ ): Promise<void> {
20
+ if (!signal) return previous;
21
+ return new Promise<void>((resolveTurn, rejectTurn) => {
22
+ const onAbort = () => {
23
+ rejectTurn(abortError(signal));
24
+ };
25
+ signal.addEventListener("abort", onAbort, { once: true });
26
+ void previous.then(() => {
27
+ signal.removeEventListener("abort", onAbort);
28
+ resolveTurn();
29
+ });
30
+ });
31
+ }
9
32
 
10
33
  interface RetentionPort {
11
34
  prepare(root: string, signal?: AbortSignal): Promise<void>;
35
+ prepareDirect?: (root: string, signal?: AbortSignal) => Promise<void>;
12
36
  }
13
37
  /** The separate SQLite mutex preserves durable intents during content acquisition. */
14
38
  export class Retention {
15
39
  private readonly Database: typeof DatabaseSync;
16
40
  private readonly db: DatabaseSync;
17
41
  private readonly mutexPath: string;
42
+ private readonly queueKey: string;
18
43
  private readonly pending = new Set<Promise<unknown>>();
19
44
  private closed = false;
20
45
  constructor(
@@ -27,21 +52,29 @@ export class Retention {
27
52
  mkdirSync(directory, { recursive: true });
28
53
  this.db = new this.Database(join(directory, "retention.sqlite"));
29
54
  this.mutexPath = join(directory, "mutex.sqlite");
55
+ this.queueKey = queueKeyFor(this.mutexPath);
30
56
  this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
31
57
  CREATE TABLE IF NOT EXISTS owners (id TEXT PRIMARY KEY, roots TEXT NOT NULL);
32
58
  CREATE TABLE IF NOT EXISTS stages (id TEXT NOT NULL, cid TEXT NOT NULL, PRIMARY KEY(id,cid));
33
59
  CREATE TABLE IF NOT EXISTS intents (
34
60
  id TEXT NOT NULL, cid TEXT NOT NULL, count INTEGER NOT NULL CHECK(count>0), PRIMARY KEY(id,cid));
35
- CREATE TABLE IF NOT EXISTS pins (cid TEXT PRIMARY KEY, phase TEXT NOT NULL);`);
61
+ CREATE TABLE IF NOT EXISTS pins (cid TEXT PRIMARY KEY, phase TEXT NOT NULL);
62
+ CREATE TABLE IF NOT EXISTS direct_owners (id TEXT PRIMARY KEY, roots TEXT NOT NULL);
63
+ CREATE TABLE IF NOT EXISTS direct_intents (
64
+ id TEXT NOT NULL, cid TEXT NOT NULL, count INTEGER NOT NULL CHECK(count>0), PRIMARY KEY(id,cid));
65
+ CREATE TABLE IF NOT EXISTS direct_pins (cid TEXT PRIMARY KEY, phase TEXT NOT NULL);`);
36
66
  }
37
67
  private roots(values: readonly string[]): string[] {
38
68
  return [
39
69
  ...new Set(values.map((value) => CID.parse(value).toV1().toString())),
40
70
  ].sort();
41
71
  }
42
- private readOwner(owner: string): string[] {
72
+ private readOwner(
73
+ owner: string,
74
+ table: "owners" | "direct_owners" = "owners",
75
+ ): string[] {
43
76
  const row = this.db
44
- .prepare("SELECT roots FROM owners WHERE id=?")
77
+ .prepare(`SELECT roots FROM ${table} WHERE id=?`)
45
78
  .get(owner);
46
79
  if (!row) return [];
47
80
  const roots: unknown = JSON.parse(String(row.roots));
@@ -53,21 +86,65 @@ export class Retention {
53
86
  owner: string,
54
87
  roots: readonly string[],
55
88
  replace = false,
89
+ table: "owners" | "direct_owners" = "owners",
56
90
  ): void {
57
91
  if (typeof owner !== "string" || !owner || owner.length > 4096)
58
92
  throw new Error("A stable retention owner is required.");
59
93
  const values = this.roots(
60
- replace ? roots : [...this.readOwner(owner), ...roots],
94
+ replace ? roots : [...this.readOwner(owner, table), ...roots],
61
95
  );
62
96
  this.db
63
- .prepare("INSERT OR REPLACE INTO owners VALUES (?,?)")
97
+ .prepare(
98
+ `INSERT INTO ${table} VALUES (?,?)
99
+ ON CONFLICT(id) DO UPDATE SET roots=excluded.roots
100
+ WHERE ${table}.roots<>excluded.roots`,
101
+ )
64
102
  .run(owner, JSON.stringify(values));
65
103
  }
104
+ private transaction<T>(action: () => T): T {
105
+ this.db.exec("BEGIN IMMEDIATE");
106
+ try {
107
+ const result = action();
108
+ this.db.exec("COMMIT");
109
+ return result;
110
+ } catch (error) {
111
+ this.db.exec("ROLLBACK");
112
+ throw error;
113
+ }
114
+ }
66
115
  private begin(mutex: DatabaseSync): void {
67
116
  if (this.closed) throw new Error("Retention coordinator is closed.");
68
117
  mutex.exec("BEGIN IMMEDIATE");
69
118
  }
70
119
  register(owner: string, roots: readonly string[]): void {
120
+ this.registerInTable(owner, roots, "owners");
121
+ }
122
+ registerDirect(owner: string, roots: readonly string[]): void {
123
+ this.registerInTable(owner, roots, "direct_owners");
124
+ }
125
+ registerAsync(
126
+ owner: string,
127
+ roots: readonly string[],
128
+ signal?: AbortSignal,
129
+ ): Promise<void> {
130
+ return this.locked(signal, () => {
131
+ this.publish(owner, roots, false, "owners");
132
+ });
133
+ }
134
+ registerDirectAsync(
135
+ owner: string,
136
+ roots: readonly string[],
137
+ signal?: AbortSignal,
138
+ ): Promise<void> {
139
+ return this.locked(signal, () => {
140
+ this.publish(owner, roots, false, "direct_owners");
141
+ });
142
+ }
143
+ private registerInTable(
144
+ owner: string,
145
+ roots: readonly string[],
146
+ table: "owners" | "direct_owners",
147
+ ): void {
71
148
  const mutex = new this.Database(this.mutexPath);
72
149
  mutex.exec("PRAGMA busy_timeout=0");
73
150
  try {
@@ -80,7 +157,7 @@ export class Retention {
80
157
  );
81
158
  }
82
159
  try {
83
- this.publish(owner, roots);
160
+ this.publish(owner, roots, false, table);
84
161
  } finally {
85
162
  mutex.exec("ROLLBACK");
86
163
  mutex.close();
@@ -101,56 +178,84 @@ export class Retention {
101
178
  signal: AbortSignal | undefined,
102
179
  action: () => Promise<T> | T,
103
180
  ): Promise<T> {
104
- const mutex = new this.Database(this.mutexPath);
105
- mutex.exec("PRAGMA busy_timeout=0");
106
- const deadline = Date.now() + 30_000;
107
- try {
108
- for (;;) {
109
- signal?.throwIfAborted();
110
- try {
111
- this.begin(mutex);
112
- break;
113
- } catch (error) {
114
- if (
115
- (error as { errcode?: number }).errcode !== 5 ||
116
- Date.now() >= deadline
117
- )
118
- throw new ContentError(
119
- "retention_unfinished",
120
- "Retention coordination is unavailable.",
121
- );
122
- await sleep(10, undefined, signal ? { signal } : {});
123
- }
181
+ signal?.throwIfAborted();
182
+ const previous = coordinationQueues.get(this.queueKey) ?? Promise.resolve();
183
+ let releaseTurn!: () => void;
184
+ const current = new Promise<void>((resolveTurn) => {
185
+ releaseTurn = resolveTurn;
186
+ });
187
+ const tail = previous.then(() => current);
188
+ coordinationQueues.set(this.queueKey, tail);
189
+ const release = () => {
190
+ releaseTurn();
191
+ if (coordinationQueues.get(this.queueKey) === tail) {
192
+ coordinationQueues.delete(this.queueKey);
124
193
  }
194
+ };
195
+ try {
196
+ await waitForTurn(previous, signal);
125
197
  } catch (error) {
126
- mutex.close();
127
- signal?.throwIfAborted();
198
+ release();
128
199
  throw error;
129
200
  }
130
201
  try {
131
- return await action();
132
- } catch (error) {
133
- if (signal?.aborted) throw signal.reason;
134
- throw new ContentError(
135
- "retention_unfinished",
136
- `Retention hints are unfinished; durable intents remain for retry. ${
137
- error instanceof ContentError
138
- ? `${error.code}: ${error.message}`
139
- : error instanceof Error &&
140
- ["TimeoutError", "AbortError"].includes(error.name)
141
- ? error.name
142
- : "verification_or_storage_failure"
143
- }`,
144
- { cause: error },
145
- );
202
+ const mutex = new this.Database(this.mutexPath);
203
+ mutex.exec("PRAGMA busy_timeout=0");
204
+ const deadline = Date.now() + 30_000;
205
+ try {
206
+ for (;;) {
207
+ signal?.throwIfAborted();
208
+ try {
209
+ this.begin(mutex);
210
+ break;
211
+ } catch (error) {
212
+ if (
213
+ (error as { errcode?: number }).errcode !== 5 ||
214
+ Date.now() >= deadline
215
+ )
216
+ throw new ContentError(
217
+ "retention_unfinished",
218
+ "Retention coordination is unavailable.",
219
+ );
220
+ await sleep(10, undefined, signal ? { signal } : {});
221
+ }
222
+ }
223
+ } catch (error) {
224
+ mutex.close();
225
+ signal?.throwIfAborted();
226
+ throw error;
227
+ }
228
+ try {
229
+ return await action();
230
+ } catch (error) {
231
+ if (signal?.aborted) throw signal.reason;
232
+ throw new ContentError(
233
+ "retention_unfinished",
234
+ `Retention hints are unfinished; durable intents remain for retry. ${
235
+ error instanceof ContentError
236
+ ? `${error.code}: ${error.message}`
237
+ : error instanceof Error &&
238
+ ["TimeoutError", "AbortError"].includes(error.name)
239
+ ? error.name
240
+ : "verification_or_storage_failure"
241
+ }`,
242
+ { cause: error },
243
+ );
244
+ } finally {
245
+ mutex.exec("ROLLBACK");
246
+ mutex.close();
247
+ }
146
248
  } finally {
147
- mutex.exec("ROLLBACK");
148
- mutex.close();
249
+ release();
149
250
  }
150
251
  }
151
- private phase(root: string, phase: string): void {
252
+ private phase(
253
+ root: string,
254
+ phase: string,
255
+ table: "pins" | "direct_pins" = "pins",
256
+ ): void {
152
257
  this.db
153
- .prepare("INSERT OR REPLACE INTO pins VALUES (?,?)")
258
+ .prepare(`INSERT OR REPLACE INTO ${table} VALUES (?,?)`)
154
259
  .run(root, phase);
155
260
  }
156
261
  private async ensure(root: string, signal?: AbortSignal): Promise<void> {
@@ -158,47 +263,108 @@ export class Retention {
158
263
  await this.port.prepare(root, signal);
159
264
  this.phase(root, "pinned");
160
265
  }
266
+ private async ensureDirect(
267
+ root: string,
268
+ signal?: AbortSignal,
269
+ ): Promise<void> {
270
+ this.phase(root, "pin-pending", "direct_pins");
271
+ await (this.port.prepareDirect
272
+ ? this.port.prepareDirect(root, signal)
273
+ : this.port.prepare(root, signal));
274
+ this.phase(root, "pinned", "direct_pins");
275
+ }
161
276
  pin(root: string, signal?: AbortSignal): Promise<void> {
162
277
  root = this.roots([root])[0]!;
163
278
  return this.locked(signal, () => this.ensure(root, signal));
164
279
  }
280
+ pinDirect(root: string, signal?: AbortSignal): Promise<void> {
281
+ root = this.roots([root])[0]!;
282
+ return this.locked(signal, () => this.ensureDirect(root, signal));
283
+ }
165
284
  retain(
166
285
  owner: string,
167
286
  roots: readonly string[],
168
287
  signal?: AbortSignal,
169
288
  ): Promise<void> {
170
289
  return this.locked(signal, async () => {
171
- this.publish(owner, roots);
172
- for (const root of this.roots(roots)) this.intent(owner, root);
290
+ this.transaction(() => {
291
+ this.publish(owner, roots);
292
+ for (const root of this.roots(roots)) this.intent(owner, root);
293
+ });
173
294
  for (const root of this.roots(roots)) await this.ensure(root, signal);
174
295
  });
175
296
  }
297
+ retainDirect(
298
+ owner: string,
299
+ roots: readonly string[],
300
+ signal?: AbortSignal,
301
+ ): Promise<void> {
302
+ return this.locked(signal, async () => {
303
+ this.transaction(() => {
304
+ this.publish(owner, roots, false, "direct_owners");
305
+ for (const root of this.roots(roots))
306
+ this.intent(owner, root, "direct_intents");
307
+ });
308
+ for (const root of this.roots(roots))
309
+ await this.ensureDirect(root, signal);
310
+ });
311
+ }
176
312
  confirm(
177
313
  owner: string,
178
314
  roots: readonly string[],
179
315
  signal?: AbortSignal,
316
+ ): Promise<void> {
317
+ return this.confirmInTable(owner, roots, "owners", "intents", signal);
318
+ }
319
+ confirmDirect(
320
+ owner: string,
321
+ roots: readonly string[],
322
+ signal?: AbortSignal,
323
+ ): Promise<void> {
324
+ return this.confirmInTable(
325
+ owner,
326
+ roots,
327
+ "direct_owners",
328
+ "direct_intents",
329
+ signal,
330
+ );
331
+ }
332
+ private confirmInTable(
333
+ owner: string,
334
+ roots: readonly string[],
335
+ ownerTable: "owners" | "direct_owners",
336
+ intentTable: "intents" | "direct_intents",
337
+ signal?: AbortSignal,
180
338
  ): Promise<void> {
181
339
  return this.locked(signal, () => {
182
- this.publish(owner, roots);
183
- for (const root of this.roots(roots)) {
184
- const row = this.db
185
- .prepare("SELECT count FROM intents WHERE id=? AND cid=?")
186
- .get(owner, root);
187
- if (row && Number(row.count) > 1)
188
- this.db
189
- .prepare("UPDATE intents SET count=count-1 WHERE id=? AND cid=?")
190
- .run(owner, root);
191
- else
192
- this.db
193
- .prepare("DELETE FROM intents WHERE id=? AND cid=?")
194
- .run(owner, root);
195
- }
340
+ this.transaction(() => {
341
+ this.publish(owner, roots, false, ownerTable);
342
+ for (const root of this.roots(roots)) {
343
+ const row = this.db
344
+ .prepare(`SELECT count FROM ${intentTable} WHERE id=? AND cid=?`)
345
+ .get(owner, root);
346
+ if (row && Number(row.count) > 1)
347
+ this.db
348
+ .prepare(
349
+ `UPDATE ${intentTable} SET count=count-1 WHERE id=? AND cid=?`,
350
+ )
351
+ .run(owner, root);
352
+ else
353
+ this.db
354
+ .prepare(`DELETE FROM ${intentTable} WHERE id=? AND cid=?`)
355
+ .run(owner, root);
356
+ }
357
+ });
196
358
  });
197
359
  }
198
- private intent(owner: string, root: string): void {
360
+ private intent(
361
+ owner: string,
362
+ root: string,
363
+ table: "intents" | "direct_intents" = "intents",
364
+ ): void {
199
365
  this.db
200
366
  .prepare(
201
- `INSERT INTO intents VALUES (?,?,1)
367
+ `INSERT INTO ${table} VALUES (?,?,1)
202
368
  ON CONFLICT(id,cid) DO UPDATE SET count=count+1`,
203
369
  )
204
370
  .run(owner, root);
@@ -216,11 +382,21 @@ export class Retention {
216
382
  ): Promise<void> {
217
383
  return this.locked(signal, () => {
218
384
  if (isIdle && !isIdle()) return;
219
- this.publish(owner, typeof roots === "function" ? roots() : roots, true);
220
- this.db.prepare("DELETE FROM intents WHERE id=?").run(owner);
221
- for (const row of this.db.prepare("SELECT DISTINCT id FROM stages").all())
222
- if (String(row.id).startsWith(`${owner}/`))
223
- this.db.prepare("DELETE FROM stages WHERE id=?").run(String(row.id));
385
+ this.transaction(() => {
386
+ this.publish(
387
+ owner,
388
+ typeof roots === "function" ? roots() : roots,
389
+ true,
390
+ );
391
+ this.db.prepare("DELETE FROM intents WHERE id=?").run(owner);
392
+ for (const row of this.db
393
+ .prepare("SELECT DISTINCT id FROM stages")
394
+ .all())
395
+ if (String(row.id).startsWith(`${owner}/`))
396
+ this.db
397
+ .prepare("DELETE FROM stages WHERE id=?")
398
+ .run(String(row.id));
399
+ });
224
400
  });
225
401
  }
226
402
  stage(
@@ -231,13 +407,15 @@ export class Retention {
231
407
  ): Promise<void> {
232
408
  root = this.roots([root])[0]!;
233
409
  return this.locked(signal, async () => {
234
- this.db
235
- .prepare("INSERT OR IGNORE INTO stages VALUES (?,?)")
236
- .run(session, root);
237
410
  const alreadyPinned =
238
411
  this.db.prepare("SELECT phase FROM pins WHERE cid=?").get(root)
239
412
  ?.phase === "pinned";
240
- this.phase(root, "stage-pending");
413
+ this.transaction(() => {
414
+ this.db
415
+ .prepare("INSERT OR IGNORE INTO stages VALUES (?,?)")
416
+ .run(session, root);
417
+ this.phase(root, "stage-pending");
418
+ });
241
419
  await write();
242
420
  this.phase(root, alreadyPinned ? "pinned" : "staged");
243
421
  });
@@ -251,21 +429,27 @@ export class Retention {
251
429
  root = this.roots([root])[0]!;
252
430
  return this.locked(signal, async () => {
253
431
  if (owner) {
254
- this.publish(owner, [root]);
255
- this.intent(owner, root);
432
+ this.transaction(() => {
433
+ this.publish(owner, [root]);
434
+ this.intent(owner, root);
435
+ });
256
436
  }
257
437
  await this.ensure(root, signal);
258
438
  this.db.prepare("DELETE FROM stages WHERE id=?").run(session);
259
439
  });
260
440
  }
261
- private remove(root: string, signal?: AbortSignal): boolean {
441
+ private remove(
442
+ root: string,
443
+ signal?: AbortSignal,
444
+ table: "pins" | "direct_pins" = "pins",
445
+ ): boolean {
262
446
  const record = this.db
263
- .prepare("SELECT phase FROM pins WHERE cid=?")
447
+ .prepare(`SELECT phase FROM ${table} WHERE cid=?`)
264
448
  .get(root);
265
449
  if (!record) return false;
266
- this.phase(root, "unpin-pending");
450
+ this.phase(root, "unpin-pending", table);
267
451
  signal?.throwIfAborted();
268
- this.db.prepare("DELETE FROM pins WHERE cid=?").run(root);
452
+ this.db.prepare(`DELETE FROM ${table} WHERE cid=?`).run(root);
269
453
  return true;
270
454
  }
271
455
  unpin(root: string, signal?: AbortSignal): Promise<void> {
@@ -276,6 +460,16 @@ export class Retention {
276
460
  this.remove(root, signal);
277
461
  });
278
462
  }
463
+ unpinDirect(root: string, signal?: AbortSignal): Promise<void> {
464
+ root = this.roots([root])[0]!;
465
+ return this.locked(signal, () => {
466
+ if (this.allDirectRoots().includes(root))
467
+ throw new Error(
468
+ "A participating owner still retains this direct block.",
469
+ );
470
+ this.remove(root, signal, "direct_pins");
471
+ });
472
+ }
279
473
  private allRoots(): string[] {
280
474
  return this.roots([
281
475
  ...this.db
@@ -292,6 +486,18 @@ export class Retention {
292
486
  .map((row) => String(row.cid)),
293
487
  ]);
294
488
  }
489
+ private allDirectRoots(): string[] {
490
+ return this.roots([
491
+ ...this.db
492
+ .prepare("SELECT id FROM direct_owners")
493
+ .all()
494
+ .flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
495
+ ...this.db
496
+ .prepare("SELECT cid FROM direct_intents")
497
+ .all()
498
+ .map((row) => String(row.cid)),
499
+ ]);
500
+ }
295
501
  reconcile(
296
502
  owner: string,
297
503
  roots: readonly string[] | (() => readonly string[]),
@@ -310,16 +516,47 @@ export class Retention {
310
516
  return removed;
311
517
  });
312
518
  }
519
+ reconcileDirect(
520
+ owner: string,
521
+ roots: readonly string[] | (() => readonly string[]),
522
+ signal?: AbortSignal,
523
+ ): Promise<number> {
524
+ return this.locked(signal, async () => {
525
+ this.publish(
526
+ owner,
527
+ typeof roots === "function" ? roots() : roots,
528
+ true,
529
+ "direct_owners",
530
+ );
531
+ const marked = new Set(this.allDirectRoots());
532
+ for (const root of marked) await this.ensureDirect(root, signal);
533
+ let removed = 0;
534
+ for (const row of this.db.prepare("SELECT cid FROM direct_pins").all()) {
535
+ const root = String(row.cid);
536
+ if (!marked.has(root) && this.remove(root, signal, "direct_pins"))
537
+ removed++;
538
+ }
539
+ return removed;
540
+ });
541
+ }
313
542
  pins(): string[] {
314
543
  return this.db
315
544
  .prepare("SELECT cid FROM pins WHERE phase='pinned' ORDER BY cid")
316
545
  .all()
317
546
  .map((row) => String(row.cid));
318
547
  }
548
+ directPins(): string[] {
549
+ return this.db
550
+ .prepare("SELECT cid FROM direct_pins WHERE phase='pinned' ORDER BY cid")
551
+ .all()
552
+ .map((row) => String(row.cid));
553
+ }
319
554
  maintain<T>(
320
555
  action: (references: {
321
556
  pinned: readonly string[];
322
557
  roots: readonly string[];
558
+ directPinned: readonly string[];
559
+ directRoots: readonly string[];
323
560
  staged: readonly string[];
324
561
  }) => Promise<T>,
325
562
  signal?: AbortSignal,
@@ -343,6 +580,23 @@ export class Retention {
343
580
  .all()
344
581
  .map((row) => String(row.cid)),
345
582
  ]),
583
+ directPinned: this.directPins(),
584
+ directRoots: this.roots([
585
+ ...this.db
586
+ .prepare("SELECT id FROM direct_owners")
587
+ .all()
588
+ .flatMap((row) => this.readOwner(String(row.id), "direct_owners")),
589
+ ...this.db
590
+ .prepare("SELECT cid FROM direct_intents")
591
+ .all()
592
+ .map((row) => String(row.cid)),
593
+ ...this.db
594
+ .prepare(
595
+ "SELECT cid FROM direct_pins WHERE phase NOT IN ('staged','stage-pending')",
596
+ )
597
+ .all()
598
+ .map((row) => String(row.cid)),
599
+ ]),
346
600
  // Import parents may arrive before their children; protect staged blocks individually.
347
601
  staged: this.db
348
602
  .prepare("SELECT DISTINCT cid FROM stages")
package/src/storage.ts CHANGED
@@ -157,6 +157,15 @@ export class SharedContent implements GatewayClient {
157
157
  const metadata = await lstat(directory);
158
158
  if (!metadata.isDirectory() || metadata.isSymbolicLink())
159
159
  throw new Error("Invalid shared content directory.");
160
+ let existing = false;
161
+ try {
162
+ await this.local(cid);
163
+ existing = true;
164
+ } catch (error) {
165
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
166
+ }
167
+ signal.throwIfAborted();
168
+ if (existing) return;
160
169
  const temporary = join(directory, `.pending-${randomUUID()}`);
161
170
  const destination = join(directory, cid.toV1().toString());
162
171
  let owned = false;