import { randomUUID } from 'node:crypto' import { setTimeout as sleep } from 'node:timers/promises' import { SpanStatusCode, trace, type Span } from '@opentelemetry/api' import pLimit, { type LimitFunction } from 'p-limit' import pRetry, { AbortError } from 'p-retry' import { z } from 'zod' import { ingestionColumns, moveUnknownFields, REST_COLUMN, toJsonRow } from './destination.js' import { BudgetExhausted, classifyFailure, describeError } from './errors.js' import { canonicalJson, digest, emptyCheckpoint } from './journal.js' import { simpleLoader } from './loader.js' import { createBoundedQueue } from './queue.js' import type { SelectedStream } from './registry.js' import { createRequestQueue, type RequestQueue } from './request-queue.js' import { createSourceServices } from './source-context.js' import type { AnyStreamDefinition, CheckpointEnvelope, CommittedCheckpoint, DestinationAdapter, ExecutionResult, Fetch, Journal, JournalEvent, PipelineDefinition, RetryOptions, Row, SinkReceipt, StreamOutcome, StreamResult, } from './types.js' // Run facts are correlation only, so each run owns its own namespace: two // overlapping processes never share the telemetry namespace. const RUN_NAMESPACE_PREFIX = '@run:' const DEFAULT_BATCH_SIZE = 10_000 const DEFAULT_PREFETCH_BATCHES = 1 const DEFAULT_MAX_DURATION_MS = 60 * 60_000 /** Largest delay a timer accepts: a signed 32-bit millisecond count. */ export const MAX_DURATION_MS = 2_147_483_647 const LOAD_ATTEMPTS = 3 const JOURNAL_APPEND_ATTEMPTS = 4 // Terminal facts get a bounded chance to land even after the execution is interrupted. const TERMINAL_JOURNAL_TIMEOUT_MS = 5000 const DEFAULT_MAX_CHUNK_ROWS = 100_000 // How long a failed stream waits for an uncooperative reader before abandoning it. const READER_SHUTDOWN_GRACE_MS = 5000 const tracer = trace.getTracer('@chkit/plugin-ingest') const StrategyIdentitySchema = z.object({ id: z.string().min(1), version: z.int().min(1) }) export interface BackfillRequest { /** Stable identity: resuming the same backfill reuses its isolated checkpoint namespace. */ id: string from: Date | undefined to: Date | undefined } export interface ExecutionRequest { selected: readonly SelectedStream[] backfill: BackfillRequest | undefined } export interface ExecutionEnv { journal: Journal destination: DestinationAdapter signal?: AbortSignal /** Host-default execution budget. Exhaustion preserves committed progress. */ maxDurationMs?: number /** Finite number of mapped batches buffered between fetch and load. */ prefetchBatches?: number now?: () => Date log?: (message: string) => void fetch?: Fetch /** Request retries; defaults to 5 with exponential backoff from 1 second. */ retry?: RetryOptions } interface ResolvedEnv extends Required> { /** Host cancellation combined with the execution deadline. */ signal: AbortSignal /** Host cancellation only: distinguishes a cancelled run from an exhausted budget. */ hostSignal: AbortSignal } interface PipelinePermits { streams: LimitFunction requests: RequestQueue loads: LimitFunction } interface PendingBatch { rows: Row[] /** Declared source-interval ids, or `undefined` once any chunk omitted its id. */ intervalIds: string[] | undefined /** Candidate provider state that becomes safe once these rows have sink evidence. */ state: { value: unknown } | undefined } interface StreamProgress { base: CommittedCheckpoint startedAt: string /** Last journal sequence confirmed within this run. */ seq: number /** Serializes appends so a sequence number is only consumed by a confirmed fact. */ appendChain: Promise version: number checkpointId: string successId: string envelope: CheckpointEnvelope | undefined rows: number batches: number chunks: number /** Unknown fields committed into `_chkit_rest` during this run. */ restFields: Set } type AppendInput = { namespaceId: string; runId: string; progress: StreamProgress; env: ResolvedEnv } type FactFields = Partial> /** * One transient execution context for one exact stream selection. The run id * correlates journal and telemetry evidence only: every stream plans and * recovers independently from its own journal-backed checkpoint. */ export async function runIngestion(request: ExecutionRequest, input: ExecutionEnv): Promise { const deadline = new AbortController() const env = resolveEnv(input, deadline.signal) // The budget is a real bound: it interrupts hung readers, retry timers and waits. const deadlineTimer = setTimeout(() => deadline.abort(new BudgetExhausted('execution budget exhausted')), env.maxDurationMs) const runId = randomUUID() const cutoff = env.now() const streamIds = request.selected.map((entry) => entry.stream.id) return tracer.startActiveSpan('chkit.ingest.execution', async (span) => { span.setAttribute('chkit.ingest.run_id', runId) span.setAttribute('chkit.ingest.stream_ids', streamIds) try { await abortable(() => env.journal.ensure(), env.signal) await appendRunEvent(env, runEvent(1, 'run_started', runId, '', { streamIds, cutoff: cutoff.toISOString(), backfill: request.backfill?.id, }), env.signal) const permits = new Map() const streams = await Promise.all( request.selected.map((entry) => executeSelectedStream(entry, permitsFor(permits, entry.pipeline), request.backfill, runId, cutoff, env) ) ) const ok = streams.every((stream) => stream.outcome === 'succeeded') await appendRunEvent(env, runEvent(2, 'run_finished', runId, ok ? 'succeeded' : 'failed', { outcomes: Object.fromEntries(streams.map((stream) => [stream.namespaceId, stream.outcome])), }), terminalSignal(env.signal)) if (!ok) span.setStatus({ code: SpanStatusCode.ERROR }) return { runId, cutoff: cutoff.toISOString(), streams, ok } } finally { clearTimeout(deadlineTimer) span.end() } }) } // An ordinary failure in one stream never prevents unrelated selected streams // from being attempted: every failure is folded into that stream's result. async function executeSelectedStream( entry: SelectedStream, permits: PipelinePermits, backfill: BackfillRequest | undefined, runId: string, cutoff: Date, env: ResolvedEnv ): Promise { const { stream, pipeline } = entry const namespaceId = backfill ? `${stream.id}#backfill:${backfill.id}` : stream.id const progress: StreamProgress = { base: emptyCheckpoint(), startedAt: cutoff.toISOString(), seq: 0, appendChain: Promise.resolve(), version: 0, checkpointId: '', successId: '', envelope: undefined, rows: 0, batches: 0, chunks: 0, restFields: new Set() } const result = (outcome: StreamOutcome, error: string | undefined): StreamResult => ({ streamId: stream.id, pipelineId: pipeline.id, namespaceId, outcome, rows: progress.rows, batches: progress.batches, chunks: progress.chunks, checkpointVersion: progress.version, error, }) return permits.streams(async () => { if (env.signal.aborted) { return result(env.hostSignal.aborted ? 'cancelled' : 'budget_exhausted', 'execution interrupted before start') } return tracer.startActiveSpan('chkit.ingest.stream', async (span) => { span.setAttribute('chkit.ingest.stream_id', stream.id) span.setAttribute('chkit.ingest.namespace_id', namespaceId) try { const outcome = await executeStream({ stream, pipeline, namespaceId, backfill, runId, cutoff, permits, progress, env }) env.log?.(`${namespaceId}: ${outcome} (${progress.rows} rows, ${progress.batches} batches, checkpoint v${progress.version})`) return result(outcome, undefined) } catch (error) { const message = describeError(error) const outcome: StreamOutcome = env.hostSignal.aborted ? 'cancelled' : env.signal.aborted ? 'budget_exhausted' : 'failed' recordFailure(span, error) env.log?.(`${namespaceId}: ${outcome}`) return result(outcome, message) } finally { span.end() } }) }) } async function executeStream(input: { stream: AnyStreamDefinition pipeline: PipelineDefinition namespaceId: string backfill: BackfillRequest | undefined runId: string cutoff: Date permits: PipelinePermits progress: StreamProgress env: ResolvedEnv }): Promise { const { stream, pipeline, namespaceId, progress, env } = input const committed = await abortable(() => env.journal.readCheckpoint(namespaceId), env.signal) progress.base = committed progress.version = committed.version progress.checkpointId = committed.checkpointId progress.successId = committed.successId progress.envelope = committed.envelope let workId = '' let outcome: StreamOutcome = 'failed' let failure: unknown try { const missing = ingestionColumns.filter((required) => !stream.destination.columns.some((column) => column.name === required.name)) if (missing.length > 0) { throw new Error(`Stream "${stream.id}" destination ${stream.destination.database}.${stream.destination.name} is missing ${missing.map((column) => column.name).join(', ')}. Spread ingestionColumns into its columns.`) } const state = restoreState(stream, progress.envelope, namespaceId) const selection: unknown = stream.incremental.plan({ state, cutoff: input.cutoff, range: input.backfill ? { from: input.backfill.from, to: input.backfill.to } : undefined, }) workId = digest([namespaceId, progress.successId, progress.checkpointId, canonicalJson(selection)]).slice(0, 24) // A planned unit of work and its attempt share one insert. await appendFacts(input, [ { eventKind: 'work_planned', fields: { workId, workState: 'planned', detail: { selection, strategy: stream.incremental.id, strategyVersion: stream.incremental.version, pipelineId: pipeline.id } } }, { eventKind: 'attempt_started', fields: { workId, attemptNo: 1, workState: 'running' } }, ]) outcome = await readAndLoad({ ...input, workId, attemptNo: 1, state, selection }) } catch (error) { failure = error if (env.signal.aborted) { outcome = env.hostSignal.aborted ? 'cancelled' : 'budget_exhausted' // Exhausting the budget is incomplete: committed progress stands. if (outcome === 'budget_exhausted') failure = undefined } } if (progress.restFields.size > 0) { env.log?.(`${namespaceId}: kept fields without a column in ${REST_COLUMN}: ${[...progress.restFields].sort().join(', ')}`) } await append(input, 'work_finished', { workId, workState: failure === undefined ? outcome : outcome === 'cancelled' ? 'cancelled' : 'failed', errorClass: failure === undefined ? '' : classifyFailure(failure, env.signal).kind, detail: { rows: progress.rows, batches: progress.batches, chunks: progress.chunks, error: failure === undefined ? undefined : describeError(failure) }, }) if (failure !== undefined) throw failure return outcome } /** * Pull the reader through a finite buffer into the loader. Exactly one next() * is pending at a time, and source progress is appended to the journal only * after the covering rows have sink evidence. */ async function readAndLoad(input: { stream: AnyStreamDefinition namespaceId: string runId: string cutoff: Date permits: PipelinePermits progress: StreamProgress env: ResolvedEnv workId: string attemptNo: number state: unknown selection: unknown }): Promise { const { stream, namespaceId, progress, env } = input const maxChunks = stream.budget?.maxChunks ?? Infinity if (progress.chunks >= maxChunks) return 'budget_exhausted' const local = new AbortController() const signal = AbortSignal.any([env.signal, local.signal]) const queue = createBoundedQueue(env.prefetchBatches) const batchSize = stream.batchSize ?? DEFAULT_BATCH_SIZE let budgetExhausted = false // Set once this attempt has reported its outcome: detached work that finishes // later may have written rows (at-least-once) but must never commit progress. let abandoned = false const produce = async () => { let pending = emptyBatch() const reader = stream.read({ streamId: stream.id, selection: input.selection, state: input.state, cutoff: input.cutoff, ...createSourceServices({ signal, fetch: env.fetch, retry: env.retry, queue: input.permits.requests, onRetry: (context, retryAfterMs, options) => { // p-retry owns the randomized backoff; record only a provider's known not-before time, // and none when it lies beyond the range of a Date. const retryAt = new Date(env.now().getTime() + (retryAfterMs ?? Number.NaN)) return append(input, 'retry_scheduled', { workId: input.workId, attemptNo: input.attemptNo, retryAt: Number.isNaN(retryAt.getTime()) ? undefined : retryAt, errorClass: context.error.classification.kind, detail: { label: options?.label ?? 'source', sourceAttempt: context.attemptNumber, error: context.error.message }, }) }, }), }) // Iterate by hand so a hung next() can be abandoned on abort; return() still // runs on every exit so the reader's finally blocks own cursor cleanup. const iterator = reader[Symbol.asyncIterator]() const maxChunkRows = stream.budget?.maxChunkRows ?? DEFAULT_MAX_CHUNK_ROWS try { while (!budgetExhausted) { const step = await abortable(() => iterator.next(), signal) if (step.done) break const chunk: unknown = step.value assertValidChunk(stream.id, chunk, maxChunkRows) progress.chunks += 1 // A chunk that declares its source interval is one logical write unit: // it is never merged with neighbours, so a replay regroups identically // even when row counts changed. if (chunk.id !== undefined && pending.rows.length > 0) { await queue.push(pending, signal) pending = emptyBatch() } for (const row of chunk.rows) pending.rows.push(row) if (pending.intervalIds) { if (chunk.id === undefined) pending.intervalIds = undefined else pending.intervalIds.push(chunk.id) } if (chunk.state !== undefined) pending.state = { value: chunk.state } if (chunk.id !== undefined || pending.rows.length >= batchSize) { await queue.push(pending, signal) pending = emptyBatch() } if (progress.chunks >= maxChunks) budgetExhausted = true } } finally { // Never await an uncooperative reader: cleanup is best effort once we leave. void (async () => iterator.return?.())().catch(() => undefined) } // Only a fully consumed selection may claim the strategy's completion state. if (!budgetExhausted) { const completed: unknown = stream.incremental.complete?.({ state: input.state, selection: input.selection }) if (completed !== undefined) pending.state = { value: completed } } if (pending.rows.length > 0 || pending.state !== undefined) await queue.push(pending, signal) queue.close() } const consume = async () => { // Batch identity uses the last successful sync and checkpoint identities, // plus the batch's position since that boundary, so a // replay in a fresh process reproduces the same id and deduplication token. // Declared source-interval ids complete the identity; without them a // content hash does, preferring a possible duplicate over suppressing rows // that changed between attempts. let sinceBoundary = 0 for (let batch = await queue.pop(signal); batch !== undefined; batch = await queue.pop(signal)) { const shaped = moveUnknownFields(stream.id, stream.destination, batch.rows) const discriminator = batch.intervalIds ? `interval:${canonicalJson(batch.intervalIds)}` : `content:${digest(rowContents(shaped.rows))}` const batchId = digest([namespaceId, progress.successId, progress.checkpointId, String(sinceBoundary), discriminator]).slice(0, 32) const receipt = await loadBatch(input, batchId, shaped.rows, signal) if (abandoned) return const envelope: CheckpointEnvelope | undefined = batch.state ? { strategy: stream.incremental.id, version: stream.incremental.version, state: batch.state.value } : progress.envelope const advanced = canonicalJson(envelope ?? null) !== canonicalJson(progress.envelope ?? null) const expected = progress.version const version = advanced ? expected + 1 : expected await append(input, 'batch_committed', { workId: input.workId, attemptNo: input.attemptNo, batchId, expectedCheckpointVersion: expected, checkpointVersion: version, checkpoint: envelope, sinkEvidence: receipt.evidence, detail: { rows: receipt.rows, writeUnits: receipt.writeUnits }, }) sinceBoundary = advanced ? 0 : sinceBoundary + 1 progress.version = version progress.envelope = envelope progress.rows += receipt.rows progress.batches += 1 for (const field of shaped.fields) progress.restFields.add(field) } } // The first failure is the root cause; the sibling only fails because of the // induced abort, so it must not mask what actually went wrong. let rootCause: { error: unknown } | undefined const settled = Promise.allSettled( [produce(), consume()].map((task) => task.catch((error: unknown) => { rootCause ??= { error } local.abort(error) }) ) ) // After a failure, a source operation that ignores its signal must not pin // the stream (and its permits) forever. try { await Promise.race([settled, graceAfterAbort(signal, READER_SHUTDOWN_GRACE_MS)]) if (rootCause) throw rootCause.error signal.throwIfAborted() if (budgetExhausted) { env.log?.(`${namespaceId}: ${new BudgetExhausted('execution budget exhausted; committed progress is preserved').message}`) return 'budget_exhausted' } return 'succeeded' } finally { abandoned = true local.abort(new DOMException('Reader attempt has ended', 'AbortError')) } } // A fresh Loader instance per attempt. An ambiguous acknowledgement replays the // same stable batch identity and accepts a possible duplicate over data loss. async function loadBatch( input: { stream: AnyStreamDefinition; runId: string; permits: PipelinePermits; env: ResolvedEnv }, batchId: string, rows: readonly Row[], signal: AbortSignal ): Promise { const factory = input.stream.loader ?? simpleLoader() return tracer.startActiveSpan('chkit.ingest.load', async (span) => { span.setAttribute('chkit.ingest.batch_id', batchId) span.setAttribute('chkit.ingest.rows', rows.length) try { return await pRetry(() => input.permits.loads(async () => { signal.throwIfAborted() // The load limit covers only the active write, never p-retry's backoff. let loader: ReturnType try { loader = factory({ streamId: input.stream.id, runId: input.runId, table: input.stream.destination, destination: input.env.destination, signal, }) } catch (error) { // Construction errors are not ambiguous sink acknowledgements. throw new AbortError(error instanceof Error ? error : new Error(String(error))) } try { await loader.write({ batchId, rows }) return await loader.finalize() } catch (error) { // Cleanup must not replace the write failure that decides the retry. await loader.abort(error).catch((cleanupError: unknown) => { span.recordException(cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError))) }) throw error } }), { retries: LOAD_ATTEMPTS - 1, minTimeout: 1000, signal, }) } catch (error) { recordFailure(span, error) throw error } finally { span.end() } }) } function restoreState(stream: AnyStreamDefinition, envelope: CheckpointEnvelope | undefined, namespaceId: string): unknown { if (!StrategyIdentitySchema.safeParse(stream.incremental).success) { throw new Error(`Stream "${stream.id}": incremental strategy must have a non-empty id and a safe integer version of at least 1, otherwise its checkpoints can never be read back.`) } if (!envelope) return undefined if (envelope.strategy !== stream.incremental.id || envelope.version !== stream.incremental.version) { throw new Error( `Checkpoint for "${namespaceId}" was written by strategy ${envelope.strategy}@${envelope.version}, but the stream now declares ${stream.incremental.id}@${stream.incremental.version}. ` + 'ChKit never silently reinterprets a checkpoint: migrate the state explicitly, use a new stream id, or run a separately namespaced backfill.' ) } return stream.incremental.parseState(envelope.state) } function append(input: AppendInput, eventKind: JournalEvent['eventKind'], fields: FactFields): Promise { return appendFacts(input, [{ eventKind, fields }]) } // Appends for one namespace are serialized and sequence numbers are taken only // when the write starts, so facts that never land cannot leave a gap. Facts // passed together share one atomic insert. An ambiguous failure retries the // exact same deterministic facts. function appendFacts(input: AppendInput, facts: ReadonlyArray<{ eventKind: JournalEvent['eventKind']; fields: FactFields }>): Promise { const { progress, env } = input const signal = facts.some((fact) => fact.eventKind === 'work_finished') ? terminalSignal(env.signal) : env.signal const write = progress.appendChain.then(async () => { signal.throwIfAborted() const events = facts.map(({ eventKind, fields }, index): JournalEvent => ({ namespaceId: input.namespaceId, eventSeq: progress.seq + 1 + index, eventKind, runId: input.runId, workId: fields.workId ?? '', attemptNo: fields.attemptNo ?? 0, batchId: fields.batchId ?? '', expectedCheckpointVersion: fields.expectedCheckpointVersion ?? progress.version, checkpointVersion: fields.checkpointVersion ?? progress.version, checkpoint: fields.checkpoint, workState: fields.workState ?? '', sinkEvidence: fields.sinkEvidence ?? '', retryAt: fields.retryAt, errorClass: fields.errorClass ?? '', detail: progress.seq === 0 && index === 0 ? { ...fields.detail, journal: { version: 2, startedAt: progress.startedAt, base: progress.base } } : fields.detail ?? {}, })) await pRetry(() => abortable(() => env.journal.append(events), signal), { retries: JOURNAL_APPEND_ATTEMPTS - 1, minTimeout: 250, signal, }) for (const event of events) { if (event.eventKind === 'batch_committed' && event.checkpointVersion > event.expectedCheckpointVersion) { progress.checkpointId = `${event.runId}:${event.eventSeq}` } } progress.seq += events.length }) // A fact that could not be confirmed poisons the chain: a later append must // not reuse its sequence number, because the unconfirmed write may have landed. progress.appendChain = write write.catch(() => undefined) return abortable(() => write, signal) } // Run facts are deterministic too, so they get the same bounded retry as // namespace appends instead of failing the whole run on one transient error. function appendRunEvent(env: ResolvedEnv, event: JournalEvent, signal: AbortSignal): Promise { return abortable(() => pRetry(() => abortable(() => env.journal.append([event]), signal), { retries: JOURNAL_APPEND_ATTEMPTS - 1, minTimeout: 250, signal, }), signal) } // A live run bounds terminal facts by its own deadline, not by a fixed window // that a slow but healthy journal write can outlast. Only once the run has // been interrupted does the fixed grace period apply. function terminalSignal(runSignal: AbortSignal): AbortSignal { if (runSignal.aborted) return AbortSignal.timeout(TERMINAL_JOURNAL_TIMEOUT_MS) const grace = new AbortController() void graceAfterAbort(runSignal, TERMINAL_JOURNAL_TIMEOUT_MS).then(() => { grace.abort(new DOMException('The operation timed out.', 'TimeoutError')) }) return grace.signal } function runEvent(seq: number, eventKind: 'run_started' | 'run_finished', runId: string, workState: JournalEvent['workState'], detail: Record): JournalEvent { return { namespaceId: `${RUN_NAMESPACE_PREFIX}${runId}`, eventSeq: seq, eventKind, runId, workId: runId, attemptNo: 0, batchId: '', expectedCheckpointVersion: 0, checkpointVersion: 0, checkpoint: undefined, workState, sinkEvidence: '', retryAt: undefined, errorClass: '', detail, } } function assertValidChunk( streamId: string, chunk: unknown, maxChunkRows: number ): asserts chunk is { rows: readonly Row[]; state?: unknown; id?: string } { if (typeof chunk !== 'object' || chunk === null || !('rows' in chunk) || !Array.isArray(chunk.rows)) { throw new Error(`Stream "${streamId}" yielded a chunk without a "rows" array.`) } if ('id' in chunk && chunk.id !== undefined && typeof chunk.id !== 'string') { throw new Error(`Stream "${streamId}" yielded a chunk whose "id" is not a string.`) } if (chunk.rows.length > maxChunkRows) { throw new Error( `Stream "${streamId}" yielded a chunk of ${chunk.rows.length} rows, above the ${maxChunkRows}-row bound. Yield smaller chunks or raise budget.maxChunkRows.` ) } } function emptyBatch(): PendingBatch { return { rows: [], intervalIds: [], state: undefined } } function* rowContents(rows: readonly Row[]): Iterable { for (const row of rows) yield canonicalJson(toJsonRow(row)) } /** Resolves a fixed grace period after the signal aborts; never resolves otherwise. */ function graceAfterAbort(signal: AbortSignal, graceMs: number): Promise { return new Promise((resolve) => { const start = () => { void sleep(graceMs, undefined, { ref: false }).then(resolve) } if (signal.aborted) start() else signal.addEventListener('abort', start, { once: true }) }) } /** Settle with the promise, or reject as soon as the signal aborts. */ function abortable(operation: () => Promise, signal: AbortSignal): Promise { if (signal.aborted) return Promise.reject(signal.reason) return new Promise((resolve, reject) => { const onAbort = () => reject(signal.reason) signal.addEventListener('abort', onAbort, { once: true }) Promise.resolve().then(() => { signal.throwIfAborted() return operation() }).then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort)) }) } function permitsFor(cache: Map, pipeline: PipelineDefinition): PipelinePermits { const existing = cache.get(pipeline.id) if (existing) return existing const created: PipelinePermits = { streams: pLimit(pipeline.maxStreams), requests: createRequestQueue(pipeline.maxFetches), loads: pLimit(pipeline.maxLoads), } cache.set(pipeline.id, created) return created } const NEVER_ABORTED = new AbortController().signal function resolveEnv(input: ExecutionEnv, deadlineSignal: AbortSignal): ResolvedEnv { const now = input.now ?? (() => new Date()) const maxDurationMs = input.maxDurationMs ?? DEFAULT_MAX_DURATION_MS // setTimeout clamps a delay outside the signed 32-bit range (Infinity included) to 1 ms, // which would expire the budget before the first fetch instead of never. if (!Number.isFinite(maxDurationMs) || maxDurationMs <= 0 || maxDurationMs > MAX_DURATION_MS) { throw new Error(`maxDurationMs must be a positive number of milliseconds up to ${MAX_DURATION_MS}.`) } const prefetchBatches = input.prefetchBatches ?? DEFAULT_PREFETCH_BATCHES if (!Number.isInteger(prefetchBatches) || prefetchBatches <= 0) { throw new Error('prefetchBatches must be a positive integer.') } return { journal: input.journal, destination: input.destination, signal: AbortSignal.any([input.signal ?? NEVER_ABORTED, deadlineSignal]), hostSignal: input.signal ?? NEVER_ABORTED, maxDurationMs, prefetchBatches, now, log: input.log ?? (() => undefined), fetch: input.fetch ?? ((url, init) => fetch(url, init)), retry: input.retry ?? {}, } } function recordFailure(span: Span, error: unknown): void { span.setStatus({ code: SpanStatusCode.ERROR, message: describeError(error) }) if (error instanceof Error) span.recordException(error) }