import type { Options as PRetryOptions, RetryContext as PRetryContext } from 'p-retry' import type { TableDefinition } from '@chkit/core' import type { FetchFailure } from './errors.js' // ───── Authoring: streams and pipelines ───── /** JSON-compatible column values; the ClickHouse destination also encodes bigint, non-finite floats and Maps. */ export type Row = Record /** * One bounded unit produced by a stream reader. Rows are already shaped for the * destination table: mapping is ordinary code inside the reader. * * `state` is optional and, when present, must be the COMPLETE candidate * provider state that is safe to commit once every row up to and including * this chunk has sink evidence. The executor never infers ordering: a reader * that cannot claim a safe frontier simply omits `state`. */ export interface SourceChunk { rows: readonly TRow[] state?: TState /** * Stable, non-secret identity of the logical source interval this chunk * covers (a page cursor, an id range, a day…). Declare it only when a replay * of the same interval is the same logical write: batch identity then ignores * row content, so mutable provider fields cannot defeat retry deduplication. * Without it, identity falls back to a content hash, which prefers a possible * duplicate over suppressing rows that changed between attempts. */ id?: string } export interface AttemptOptions { /** Short non-secret label used in journal and telemetry, e.g. `GET /v2/objects`. */ label?: string } export type Fetch = (input: string | URL, init?: RequestInit) => Promise /** Source services the run provides, independent of selection and checkpoint types. */ export interface SourceContext { signal: AbortSignal /** `fetch` with the pipeline's request queue, transient retries, a request timeout, and `HttpError` for unsuccessful responses. */ fetch(input: string | URL, init?: RequestInit): Promise /** * Run one source operation that is not a plain request, such as an SDK call, with the * same queue and retries. Only transient failures are retried; it rejects with the thrown value. */ attempt(operation: (signal: AbortSignal) => Promise, options?: AttemptOptions): Promise } export interface ReadContext extends SourceContext { streamId: string /** What to read this execution, planned by the incremental strategy. */ selection: TSelection /** Last committed provider state, already validated by the strategy. */ state: TState | undefined /** Immutable cutoff shared by every stream selected in this execution. */ cutoff: Date } /** * Provider-owned incremental strategy inside the ChKit-owned checkpoint * envelope `{ strategy, version, state }`. Core treats `state` as opaque. */ export interface IncrementalStrategy { readonly id: string readonly version: number /** Validate previously committed state. Throw when it cannot be trusted. */ parseState(raw: unknown): TState plan(input: PlanInput): TSelection /** * Candidate state once the WHOLE selection has sink evidence. Return * `undefined` to leave the checkpoint untouched. */ complete?(input: { state: TState | undefined; selection: TSelection }): TState | undefined } export interface PlanInput { state: TState | undefined cutoff: Date /** Explicit historical range from a backfill invocation. */ range: { from: Date | undefined; to: Date | undefined } | undefined } /** p-retry context with the original provider failure and its classification. */ export type RetryContext = Omit & { error: FetchFailure } export type RetryOptions = Pick export interface StreamBudget { /** Maximum source chunks pulled in one execution of this stream. */ maxChunks?: number /** Largest chunk a reader may yield. A bigger chunk fails the stream instead of being buffered. */ maxChunkRows?: number } export interface StreamDefinition { readonly kind: 'ingest_stream' /** Globally stable identity. Owns the checkpoint; never derived from the pipeline. */ readonly id: string readonly destination: TableDefinition readonly tags: readonly string[] readonly incremental: IncrementalStrategy readonly read: (context: ReadContext) => AsyncIterable> readonly loader: LoaderFactory | undefined readonly batchSize: number | undefined readonly budget: StreamBudget | undefined } // biome-ignore lint/suspicious/noExplicitAny: a heterogeneous stream list cannot share row/state generics export type AnyStreamDefinition = StreamDefinition export interface PipelineDefinition { readonly kind: 'ingest_pipeline' readonly id: string readonly tags: readonly string[] readonly streams: readonly AnyStreamDefinition[] readonly maxStreams: number readonly maxFetches: number readonly maxLoads: number } // ───── Failure classification ───── export type FailureClass = | { kind: 'cancelled' } | { kind: 'rate_limited'; retryAfterMs: number | undefined } | { kind: 'transient' } | { kind: 'permanent' } | { kind: 'unknown' } // ───── Loading ───── export type SinkEvidenceKind = 'clickhouse_ack' | 'none_required' export interface SinkReceipt { evidence: SinkEvidenceKind rows: number writeUnits: number } export interface LoadBatch { /** Stable across every retry and crash replay of the same logical batch. */ batchId: string rows: readonly Row[] } export interface LoaderContext { streamId: string runId: string table: TableDefinition destination: DestinationAdapter signal: AbortSignal } export interface Loader { readonly ctx: LoaderContext write(batch: LoadBatch): Promise finalize(): Promise abort(reason: unknown): Promise } export type LoaderFactory = (ctx: LoaderContext) => Loader /** Low-level destination writes performed on behalf of a portable Loader. */ export interface DestinationAdapter { insert(input: { table: TableDefinition rows: readonly Row[] /** Deterministic `insert_deduplication_token` for this write unit. */ token: string }): Promise } // ───── Journal ───── export type JournalEventKind = | 'run_started' | 'work_planned' | 'attempt_started' | 'retry_scheduled' | 'batch_committed' | 'work_finished' | 'run_finished' export type WorkState = '' | 'planned' | 'running' | 'succeeded' | 'failed' | 'budget_exhausted' | 'cancelled' export interface CheckpointEnvelope { strategy: string version: number state: unknown } export interface JournalEvent { namespaceId: string eventSeq: number eventKind: JournalEventKind runId: string workId: string attemptNo: number batchId: string expectedCheckpointVersion: number checkpointVersion: number checkpoint: CheckpointEnvelope | undefined workState: WorkState sinkEvidence: SinkEvidenceKind | '' retryAt: Date | undefined errorClass: string detail: Record } export interface CommittedCheckpoint { version: number envelope: CheckpointEnvelope | undefined /** Identity of the last state advancement; empty for an initial checkpoint. */ checkpointId: string /** Identity of the last successful sync; separates new syncs from crash replay. */ successId: string /** Last sequence observed within the selected run, not a shared allocator. */ headSeq: number /** Local sequence of the last successful work_finished, or zero. */ lastSuccessSeq: number } /** Append-only run histories; checkpoints are projections of acknowledged work. */ export interface Journal { ensure(): Promise /** * Facts written together share one insert. Retry an ambiguous failure with * the exact same run-scoped identities and payloads. */ append(events: readonly JournalEvent[]): Promise readCheckpoint(namespaceId: string): Promise } // ───── Execution ───── export type StreamOutcome = 'succeeded' | 'failed' | 'budget_exhausted' | 'cancelled' export interface StreamResult { streamId: string pipelineId: string namespaceId: string outcome: StreamOutcome rows: number batches: number chunks: number checkpointVersion: number error: string | undefined } export interface ExecutionResult { runId: string cutoff: string streams: StreamResult[] ok: boolean }