@ipab/ipfs-store 0.0.0-stage → 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 +245 -2
  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 +72 -3
  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
package/src/index.ts ADDED
@@ -0,0 +1,520 @@
1
+ import { trustlessGateway } from "@helia/block-brokers";
2
+ import { createHeliaHTTP } from "@helia/http";
3
+ import { httpGatewayRouting } from "@helia/routers";
4
+ import { unixfs } from "@helia/unixfs";
5
+ import { ContentError } from "./errors.js";
6
+ import { MemoryBlockstore } from "blockstore-core";
7
+ import {
8
+ type ExportContentOptions,
9
+ exporter,
10
+ type UnixFSEntry,
11
+ } from "ipfs-unixfs-exporter";
12
+ import { CID } from "multiformats/cid";
13
+ import { abortError } from "./errors.js";
14
+ import { sha256 } from "multiformats/hashes/sha2";
15
+ import { acquireBlock, contentLinks } from "./dag.js";
16
+ export type { IpfsNode, IpfsEntry } from "@silvermoon-work/ipfs-access";
17
+ export { ContentError } from "./errors.js";
18
+ export {
19
+ IpfsStore,
20
+ type IpfsStoreOptions,
21
+ type IpfsReadOptions,
22
+ type UnixfsNode,
23
+ type StoreConfiguration,
24
+ } from "./store.js";
25
+
26
+ class GatewayCleanupError extends ContentError {
27
+ constructor() {
28
+ super(
29
+ "reclamation_unknown",
30
+ "IPFS Gateway resource cleanup is unconfirmed.",
31
+ );
32
+ }
33
+ }
34
+ async function stopOwnedNode(node: { stop(): Promise<void> }): Promise<void> {
35
+ try {
36
+ await node.stop();
37
+ } catch {
38
+ throw new GatewayCleanupError();
39
+ }
40
+ }
41
+ async function closeOwnedReader(
42
+ reader: ReadableStreamDefaultReader<Uint8Array>,
43
+ ): Promise<void> {
44
+ try {
45
+ await reader.cancel();
46
+ } catch {
47
+ throw new GatewayCleanupError();
48
+ } finally {
49
+ reader.releaseLock();
50
+ }
51
+ }
52
+
53
+ /** Caller-owned read port. Production hosts use createIpfsGatewayClient. */
54
+ export interface IpfsClient {
55
+ block: {
56
+ get(cid: string, options?: { signal?: AbortSignal }): Promise<Uint8Array>;
57
+ };
58
+ }
59
+ export interface GatewayClient extends IpfsClient {
60
+ /** Seal reads, abort acquisition, and await owned per-read Helia nodes. */
61
+ close(): Promise<void>;
62
+ }
63
+ export interface GatewayClientOptions {
64
+ allowPath?: boolean;
65
+ /** Total budget for all sources for one missing block. */
66
+ timeoutMs?: number;
67
+ attemptTimeoutMs?: number;
68
+ }
69
+ export interface GatewayAttempt {
70
+ source: string;
71
+ outcome: "timeout" | "read_or_verification_failed";
72
+ }
73
+ export class GatewayReadError extends Error {
74
+ constructor(
75
+ readonly attempts: readonly GatewayAttempt[],
76
+ readonly budgetExhausted: boolean,
77
+ ) {
78
+ super(
79
+ `IPFS Gateway acquisition failed${budgetExhausted ? " (total budget exhausted)" : ""}: ${attempts
80
+ .map(({ source, outcome }) => `${source} [${outcome}]`)
81
+ .join("; ")}.`,
82
+ );
83
+ this.name = "GatewayReadError";
84
+ }
85
+ }
86
+ interface ReadSource {
87
+ source: string;
88
+ read(cid: string, signal: AbortSignal): Promise<Uint8Array>;
89
+ allowed?(cid: string): boolean;
90
+ }
91
+ interface ReadPlan {
92
+ sources: ReadSource[];
93
+ timeoutMs: number;
94
+ attemptTimeoutMs: number;
95
+ }
96
+ const plans = new WeakMap<IpfsClient, ReadPlan>();
97
+
98
+ function bounded<T>(action: () => Promise<T>, signal: AbortSignal): Promise<T> {
99
+ signal.throwIfAborted();
100
+ return new Promise<T>((resolve, reject) => {
101
+ const abort = () => {
102
+ reject(abortError(signal));
103
+ };
104
+ signal.addEventListener("abort", abort, { once: true });
105
+ void Promise.resolve()
106
+ .then(() => {
107
+ signal.throwIfAborted();
108
+ return action();
109
+ })
110
+ .then(resolve, reject)
111
+ .finally(() => {
112
+ signal.removeEventListener("abort", abort);
113
+ });
114
+ });
115
+ }
116
+ function readClient(plan: ReadPlan): GatewayClient {
117
+ const lifetime = new AbortController();
118
+ const active = new Set<Promise<Uint8Array>>();
119
+ const cleanupFailures: unknown[] = [];
120
+ let closing: Promise<void> | undefined;
121
+ const read = (source: ReadSource, cid: string, signal: AbortSignal) => {
122
+ const operation = Promise.resolve().then(() => source.read(cid, signal));
123
+ active.add(operation);
124
+ void operation.then(
125
+ () => active.delete(operation),
126
+ (error) => {
127
+ active.delete(operation);
128
+ if (error instanceof GatewayCleanupError && cleanupFailures.length < 16)
129
+ cleanupFailures.push(error);
130
+ },
131
+ );
132
+ return operation;
133
+ };
134
+ const client: GatewayClient = {
135
+ close() {
136
+ closing ??= (async () => {
137
+ lifetime.abort(new Error("IPFS Gateway client is closing."));
138
+ let timer: ReturnType<typeof setTimeout> | undefined;
139
+ try {
140
+ await Promise.race([
141
+ Promise.allSettled([...active]),
142
+ new Promise<never>((_, reject) => {
143
+ timer = setTimeout(() => {
144
+ reject(
145
+ new Error("IPFS Gateway resource cleanup is unconfirmed."),
146
+ );
147
+ }, plan.timeoutMs);
148
+ }),
149
+ ]);
150
+ if (cleanupFailures.length)
151
+ throw new AggregateError(
152
+ cleanupFailures,
153
+ "IPFS Gateway resource cleanup failed.",
154
+ );
155
+ } finally {
156
+ if (timer) clearTimeout(timer);
157
+ }
158
+ })();
159
+ return closing;
160
+ },
161
+ block: {
162
+ async get(cid, request = {}) {
163
+ CID.parse(cid);
164
+ const requestSignal = AbortSignal.any([
165
+ lifetime.signal,
166
+ ...(request.signal ? [request.signal] : []),
167
+ ]);
168
+ requestSignal.throwIfAborted();
169
+ const deadline = performance.now() + plan.timeoutMs;
170
+ const total = AbortSignal.timeout(plan.timeoutMs);
171
+ const attempts: GatewayAttempt[] = [];
172
+ for (const source of plan.sources) {
173
+ requestSignal.throwIfAborted();
174
+ if (total.aborted || performance.now() >= deadline) break;
175
+ if (source.allowed && !source.allowed(cid)) continue;
176
+ if (performance.now() >= deadline) break;
177
+ const attemptDeadline = Math.min(
178
+ deadline,
179
+ performance.now() + plan.attemptTimeoutMs,
180
+ );
181
+ // Node 22 may collect inline timeout signals composed with AbortSignal.any.
182
+ const attempt = new AbortController();
183
+ const timer = setTimeout(
184
+ () => {
185
+ attempt.abort(
186
+ new DOMException("Gateway attempt timed out.", "TimeoutError"),
187
+ );
188
+ },
189
+ Math.max(1, Math.ceil(attemptDeadline - performance.now())),
190
+ );
191
+ const signal = AbortSignal.any([
192
+ total,
193
+ attempt.signal,
194
+ requestSignal,
195
+ ]);
196
+ try {
197
+ const bytes = await bounded(
198
+ () => read(source, cid, signal),
199
+ signal,
200
+ );
201
+ signal.throwIfAborted();
202
+ if (performance.now() >= attemptDeadline) {
203
+ attempts.push({ source: source.source, outcome: "timeout" });
204
+ continue;
205
+ }
206
+ return bytes;
207
+ } catch {
208
+ requestSignal.throwIfAborted();
209
+ attempts.push({
210
+ source: source.source,
211
+ outcome: signal.aborted
212
+ ? "timeout"
213
+ : "read_or_verification_failed",
214
+ });
215
+ } finally {
216
+ clearTimeout(timer);
217
+ }
218
+ }
219
+ throw new GatewayReadError(
220
+ attempts,
221
+ total.aborted || performance.now() >= deadline,
222
+ );
223
+ },
224
+ },
225
+ };
226
+ plans.set(client, plan);
227
+ return client;
228
+ }
229
+ function isolatedNodeOptions() {
230
+ return {
231
+ libp2p: {
232
+ services: {},
233
+ addresses: { listen: [] },
234
+ transports: [],
235
+ connectionEncrypters: [],
236
+ streamMuxers: [],
237
+ peerDiscovery: [],
238
+ },
239
+ routers: [],
240
+ };
241
+ }
242
+ /** Ordered host-owned sources only; no discovery, public fallback or redirects. */
243
+ export function createIpfsGatewayClient(
244
+ url: string | readonly string[],
245
+ options: GatewayClientOptions = {},
246
+ ): GatewayClient {
247
+ const urls = typeof url === "string" ? [url] : url;
248
+ if (!Array.isArray(urls) || urls.length === 0 || urls.length > 16)
249
+ throw new Error("IPFS Gateway list must contain 1 to 16 base URLs.");
250
+ const timeoutMs = options.timeoutMs ?? 30_000;
251
+ const attemptTimeoutMs = options.attemptTimeoutMs ?? 5_000;
252
+ for (const value of [timeoutMs, attemptTimeoutMs])
253
+ if (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647)
254
+ throw new Error("Invalid IPFS Gateway timeout.");
255
+ const sources = urls.map((base: string) =>
256
+ gatewaySource(base, options.allowPath),
257
+ );
258
+ if (new Set(sources.map(({ source }) => source)).size !== sources.length)
259
+ throw new Error("Duplicate IPFS Gateway base URL.");
260
+ return readClient({ sources, timeoutMs, attemptTimeoutMs });
261
+ }
262
+ function gatewaySource(url: string, allowPath = false): ReadSource {
263
+ const endpoint = new URL(url);
264
+ if (
265
+ !["http:", "https:"].includes(endpoint.protocol) ||
266
+ endpoint.username ||
267
+ endpoint.password ||
268
+ endpoint.href.includes("?") ||
269
+ endpoint.href.includes("#") ||
270
+ (!allowPath && endpoint.pathname !== "/")
271
+ )
272
+ throw new Error("IPFS endpoint must be an HTTP(S) Gateway base URL.");
273
+ if (allowPath && endpoint.pathname !== "/")
274
+ return {
275
+ source: endpoint.href,
276
+ async read(value, signal) {
277
+ const cid = CID.parse(value);
278
+ const target = new URL(endpoint);
279
+ target.pathname = `${target.pathname.replace(/\/$/, "")}/ipfs/${encodeURIComponent(value)}`;
280
+ target.searchParams.set("format", "raw");
281
+ const response = await fetch(target, {
282
+ signal,
283
+ redirect: "error",
284
+ credentials: "omit",
285
+ headers: { accept: "application/vnd.ipld.raw" },
286
+ });
287
+ if (!response.ok || !response.body)
288
+ throw new Error("Gateway block read failed.");
289
+ const reader = response.body.getReader(),
290
+ parts: Uint8Array[] = [];
291
+ let length = 0;
292
+ try {
293
+ for (;;) {
294
+ const item = await reader.read();
295
+ if (item.done) break;
296
+ const chunk: unknown = item.value;
297
+ if (!(chunk instanceof Uint8Array))
298
+ throw new Error("Gateway must return bytes.");
299
+ length += chunk.length;
300
+ if (length > 2 * 1024 * 1024)
301
+ throw new Error("IPFS block capacity exceeded.");
302
+ parts.push(chunk);
303
+ }
304
+ } finally {
305
+ await closeOwnedReader(reader);
306
+ }
307
+ const bytes = Buffer.concat(parts, length);
308
+ if (
309
+ cid.multihash.code !== sha256.code ||
310
+ !Buffer.from((await sha256.digest(bytes)).bytes).equals(
311
+ Buffer.from(cid.multihash.bytes),
312
+ )
313
+ )
314
+ throw new Error("Gateway CID verification failed.");
315
+ return bytes;
316
+ },
317
+ };
318
+ return {
319
+ source: endpoint.href,
320
+ async read(cid, signal) {
321
+ signal.throwIfAborted();
322
+ const node = await createHeliaHTTP({
323
+ ...isolatedNodeOptions(),
324
+ routers: [
325
+ httpGatewayRouting({ gateways: [endpoint.href], shuffle: false }),
326
+ ],
327
+ blockBrokers: [
328
+ trustlessGateway({
329
+ allowInsecure: endpoint.protocol === "http:",
330
+ allowLocal: true,
331
+ transformRequestInit: (init) => ({
332
+ ...init,
333
+ redirect: "error",
334
+ credentials: "omit",
335
+ signal: AbortSignal.any([
336
+ signal,
337
+ ...(init.signal ? [init.signal] : []),
338
+ ]),
339
+ }),
340
+ }),
341
+ ],
342
+ });
343
+ try {
344
+ const parts: Uint8Array[] = [];
345
+ for await (const part of node.blockstore.get(CID.parse(cid), {
346
+ signal,
347
+ }))
348
+ parts.push(part);
349
+ signal.throwIfAborted();
350
+ return Buffer.concat(parts);
351
+ } finally {
352
+ await stopOwnedNode(node);
353
+ }
354
+ },
355
+ };
356
+ }
357
+
358
+ /** Existing explicit hint policy is retained, never inferred from request data. */
359
+ export function withGatewayHints(
360
+ primary: IpfsClient,
361
+ hints: readonly string[],
362
+ allowGateway?: (url: URL) => boolean,
363
+ ): IpfsClient {
364
+ if (!allowGateway || hints.length === 0) return primary;
365
+ const plan = plans.get(primary) ?? {
366
+ sources: [
367
+ {
368
+ source: "caller-owned IPFS client",
369
+ read: (cid: string, signal: AbortSignal) =>
370
+ primary.block.get(cid, { signal }),
371
+ },
372
+ ],
373
+ timeoutMs: 30_000,
374
+ attemptTimeoutMs: 5_000,
375
+ };
376
+ const sources = [...plan.sources];
377
+ for (const base of hints) {
378
+ if (sources.some(({ source }) => source === new URL(base).href)) continue;
379
+ // Validate/access the base only after the policy approves this block's URL.
380
+ sources.push({
381
+ source: new URL(base).href,
382
+ allowed: (cid) =>
383
+ allowGateway(
384
+ new URL(`${base.replace(/\/+$/, "")}/ipfs/${cid}?format=raw`),
385
+ ),
386
+ read: (cid, signal) => gatewaySource(base).read(cid, signal),
387
+ });
388
+ }
389
+ return readClient({ ...plan, sources });
390
+ }
391
+ export interface ContentAccessOptions {
392
+ cacheBlocks?: boolean;
393
+ signal: AbortSignal;
394
+ retainedBlocks: Map<string, Uint8Array>;
395
+ retentionBudget: { bytes: number; limit: number };
396
+ maxBlockBytes: number;
397
+ maxDagBlocks: number;
398
+ depth?: number;
399
+ }
400
+
401
+ /** Reader-owned unique-block accounting; no task or logical-path policy. */
402
+ export function contentStore(
403
+ client: IpfsClient,
404
+ options: ContentAccessOptions,
405
+ ) {
406
+ return Object.assign(new MemoryBlockstore(), {
407
+ get: async function* (cid: CID) {
408
+ options.signal.throwIfAborted();
409
+ const key = cid.toV1().toString();
410
+ const retained = options.retainedBlocks.get(key);
411
+ if (retained) {
412
+ yield Uint8Array.from(retained);
413
+ return;
414
+ }
415
+ const bytes = await acquireBlock(client, cid, {
416
+ signal: options.signal,
417
+ blockBytes: options.maxBlockBytes,
418
+ });
419
+ options.signal.throwIfAborted();
420
+ // Another concurrent read may have retained this block during the await.
421
+ if (options.cacheBlocks !== false && !options.retainedBlocks.has(key)) {
422
+ if (
423
+ options.retainedBlocks.size >= options.maxDagBlocks ||
424
+ options.retentionBudget.bytes + bytes.byteLength >
425
+ options.retentionBudget.limit
426
+ )
427
+ throw new ContentError(
428
+ "capacity_exceeded",
429
+ "IPFS retention capacity exceeded.",
430
+ );
431
+ options.retentionBudget.bytes += bytes.byteLength;
432
+ options.retainedBlocks.set(key, bytes);
433
+ }
434
+ yield Uint8Array.from(bytes);
435
+ },
436
+ });
437
+ }
438
+ export async function openContent(
439
+ client: IpfsClient,
440
+ path: string,
441
+ options: ContentAccessOptions,
442
+ ): Promise<UnixFSEntry> {
443
+ const store = contentStore(client, options);
444
+ const entry = await exporter(path, store, { signal: options.signal });
445
+ if (entry.type !== "file" && entry.type !== "raw") return entry;
446
+ const [root, ...parts] = path.split("/");
447
+ const fs = unixfs({ blockstore: store });
448
+ return {
449
+ ...entry,
450
+ content: async function* (contentOptions: ExportContentOptions = {}) {
451
+ const signal = contentOptions.signal
452
+ ? AbortSignal.any([options.signal, contentOptions.signal])
453
+ : options.signal;
454
+ signal.throwIfAborted();
455
+ if (entry.size > BigInt(Number.MAX_SAFE_INTEGER))
456
+ throw new Error("IPFS file capacity exceeded.");
457
+ const start = contentOptions.offset ?? 0;
458
+ const length = contentOptions.length ?? Number(entry.size) - start;
459
+ if (
460
+ !Number.isSafeInteger(start) ||
461
+ !Number.isSafeInteger(length) ||
462
+ start < 0 ||
463
+ length < 0 ||
464
+ start + length > Number(entry.size)
465
+ )
466
+ throw new Error("Invalid UnixFS content range.");
467
+ // UnixFS' exporter queues eagerly. One range per pull bounds its read-ahead.
468
+ const window = 262_144;
469
+ for (let offset = start; offset < start + length; offset += window) {
470
+ const range = {
471
+ path: parts.join("/"),
472
+ signal,
473
+ blockReadConcurrency: 1,
474
+ offset,
475
+ length: Math.min(window, start + length - offset),
476
+ };
477
+ for await (const chunk of fs.cat(CID.parse(root!), range)) {
478
+ signal.throwIfAborted();
479
+ if (chunk.byteLength) yield chunk;
480
+ }
481
+ }
482
+ signal.throwIfAborted();
483
+ },
484
+ };
485
+ }
486
+
487
+ /** Verify and retain every linked block, not only file bytes read by the caller. */
488
+ export async function prepareContent(
489
+ client: IpfsClient,
490
+ root: string,
491
+ options: ContentAccessOptions,
492
+ ): Promise<void> {
493
+ const store = contentStore(client, options);
494
+ const heights = new Map<string, number>();
495
+ const seen = new Set<string>();
496
+ const walk = async (cid: CID, depth: number): Promise<number> => {
497
+ options.signal.throwIfAborted();
498
+ if (depth > (options.depth ?? 64))
499
+ throw new Error("IPFS DAG depth capacity exceeded.");
500
+ const key = cid.toV1().toString();
501
+ const known = heights.get(key);
502
+ if (known !== undefined) {
503
+ if (depth + known > (options.depth ?? 64))
504
+ throw new Error("IPFS DAG depth capacity exceeded.");
505
+ return known;
506
+ }
507
+ seen.add(key);
508
+ if (seen.size > options.maxDagBlocks)
509
+ throw new Error("IPFS block capacity exceeded.");
510
+ const parts: Uint8Array[] = [];
511
+ for await (const part of store.get(cid)) parts.push(part);
512
+ const bytes = Buffer.concat(parts);
513
+ let height = 0;
514
+ for (const link of contentLinks(cid, bytes))
515
+ height = Math.max(height, 1 + (await walk(link, depth + 1)));
516
+ heights.set(key, height);
517
+ return height;
518
+ };
519
+ await walk(CID.parse(root), 0);
520
+ }