import { Logger } from 'besonders-logger' import { CID } from 'multiformats' import { SignedDelegation } from './types.ts' import { delegationToBase64 } from './delegation.ts' import { stripUrlOfTrailingSlash } from './utils.ts' const { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.INFO) // eslint-disable-line no-unused-vars export class DagIncompleteError extends Error { rootCID: string reason: string constructor(rootCID: string, reason: string) { super(`DAG incomplete for ${rootCID}: ${reason}`) this.name = 'DagIncompleteError' this.rootCID = rootCID this.reason = reason } } /** * Options that tune the store upload path. * * The whole push (retries included) still throws if the proxy never accepts the * CAR, so contracts are preserved; the improvements are resilience and reduced * log noise: transient network hiccups no longer fail on the very first attempt, * and a warning is only emitted once all attempts are exhausted. */ export interface StoreCarOptions { /** Timeout budget per attempt (ms). Default: size-aware floor (see DEFAULT_TIMEOUT_MS). */ timeoutMs?: number /** Number of redelivery attempts AFTER the initial one. Default: 2 (3 attempts total). */ retries?: number /** Delay between failed attempts (ms). Default: 500. */ retryDelayMs?: number } /** Floor for the per-attempt upload timeout — generous enough for a slow/saturated proxy. */ export const DEFAULT_TIMEOUT_MS = 600_000 // 10 min /** Default number of retries before the first warning/error is logged. */ export const DEFAULT_RETRIES = 2 /** Default delay between retry attempts. */ export const DEFAULT_RETRY_DELAY_MS = 500 /** * Store a CAR file using UCAN delegation authentication. * * Uses the delegation spec format (cmd/sub/pol) for authorization. * The delegation and its proof chain are sent via HTTP headers: * - Authorization: Bearer * - ucans: * * Transient (transport/timeout) failures are retried up to `opts.retries` * (default 2, i.e. 3 attempts total) before an error is surfaced. Only the final * failing attempt logs a warning; intermediate attempts are DEBUG-only. HTTP-status * and DAG-verification failures are surfaced immediately and are not retried. * * @param baseUrl - Base URL of the storage server * @param car - CAR file blob to upload * @param delegation - Signed delegation authorizing the store operation * @param signal - Optional external abort signal; when provided the caller owns * timing/cancellation and no retries are applied. * @param opts - Optional per-call tuning (timeoutMs, retries, retryDelayMs). * @returns CID of the stored content */ export async function storeCar( baseUrl: string, car: Blob, delegation: SignedDelegation, signal?: AbortSignal, opts: StoreCarOptions = {}, ): Promise { baseUrl = stripUrlOfTrailingSlash(baseUrl) const sizeMB = (car.size / 1_048_576).toFixed(1) // When the caller supplies an external signal it owns cancellation/timing, so we // neither impose our own timeout nor retry — one shot, caller-controlled. Otherwise // we build a fresh AbortSignal.timeout per attempt and retry transient failures. const attempts = signal ? 1 : (opts.retries ?? DEFAULT_RETRIES) + 1 const perAttemptTimeoutMs = signal ? undefined : opts.timeoutMs ?? Math.max(DEFAULT_TIMEOUT_MS, car.size / 1000) const retryDelayMs = opts.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS LOG( `[storeCar] Uploading CAR: ${sizeMB} MB, attempts: ${attempts}` + (perAttemptTimeoutMs ? `, per-attempt timeout: ${(perAttemptTimeoutMs / 1000).toFixed(0)}s` : ', external signal'), ) if (attempts > 1) { DEBUG(`[storeCar] will retry ${attempts - 1} time(s) (delay ${retryDelayMs}ms) before logging a warning`) } // Convert delegation to base64 for Authorization header const base64Delegation = delegationToBase64(delegation) // Collect all delegations (request + proofs) for ucans header const allTokens = [base64Delegation] for (const proof of delegation.proofs) { allTokens.push(delegationToBase64(proof)) } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) let response: Response | null = null let lastErr: unknown for (let attempt = 1; attempt <= attempts; attempt++) { if (signal?.aborted) throw signal.reason ?? new Error('Aborted') try { response = await fetch(`${baseUrl}/upload`, { method: 'PUT', headers: { 'Authorization': `Bearer ${base64Delegation}`, 'Accept': 'application/json', 'Content-Type': `application/car`, 'ucans': allTokens.join(', '), }, body: car, mode: 'cors', signal: perAttemptTimeoutMs !== undefined ? AbortSignal.timeout(perAttemptTimeoutMs) : signal, }) break // uploaded — stop retrying } catch (err) { if (signal?.aborted) throw err // never retry an externally-aborted request lastErr = err if (attempt < attempts) { // Intermediate attempts stay silent (DEBUG) to avoid log spam during a // brief network outage; only the final failure logs a warning/error. DEBUG(`[storeCar] attempt ${attempt}/${attempts} failed (will retry in ${retryDelayMs}ms):`, err) await sleep(retryDelayMs) } else { ERROR('Failed to upload to ucan proxy:', err) } } } if (!response) throw lastErr // Docs: https://nft.storage/api-docs/#operations-NFT_Storage-upload const result = await response.json() if (!response.ok) { const dagMsg = result?.reason ?? result?.error if (response.status === 422 && typeof dagMsg === 'string' && dagMsg.startsWith('DAG incomplete for ')) { throw new DagIncompleteError(dagMsg.match(/DAG incomplete for ([^:]+)/)?.[1] ?? '', dagMsg) } throw ERROR(`[storeCar] failed:`, result?.error || result || response, { result, response }) } DEBUG('[storeCar] result', { response, result }) // Server returns {Roots: [{Cid: {"/": "..."}, PinErrorMsg: ""}, ...]} const roots = result.Roots ?? (result.Root ? [result.Root] : []) // support both new (Roots array) and legacy (Root object) format if (!roots.length || !roots[0]?.Cid) throw ERROR(`[storeCar] unexpected response shape — no root CID:`, { result }) if (roots.length > 1) WARN(`[storeCar] CAR has ${roots.length} roots, returning first only`) for (const root of roots) { const pinErr = root.PinErrorMsg if (pinErr) WARN(`Pin error for ${root.Cid?.['/']}: ${pinErr}`, { result }) } const err = result.Type === 'error' ? result.Message : null if (err) WARN(`Pin error:`, err, { result }) return CID.parse(roots[0].Cid['/']) // docs: https://docs.ipfs.tech/reference/kubo/rpc/#api-v0-dag-import }