faucet_core/traits.rs
1//! Shared traits for faucet sources and sinks.
2
3use crate::error::FaucetError;
4use crate::pipeline::StreamPage;
5use async_trait::async_trait;
6use futures_core::Stream;
7use serde_json::Value;
8use std::pin::Pin;
9
10/// A source fetches records from an external system.
11#[async_trait]
12pub trait Source: Send + Sync {
13 /// Primary fetch method. Receives context from a parent source's records.
14 ///
15 /// An empty context map means this is a root source (no parent).
16 /// Connectors that support being a child should use
17 /// [`substitute_context()`](crate::util::substitute_context) to resolve
18 /// `{placeholder}` tokens in their URL path, query parameters, headers,
19 /// or body. Connectors that don't need parent context ignore the map.
20 async fn fetch_with_context(
21 &self,
22 context: &std::collections::HashMap<String, Value>,
23 ) -> Result<Vec<Value>, FaucetError>;
24
25 /// Convenience: fetch with no parent context.
26 async fn fetch_all(&self) -> Result<Vec<Value>, FaucetError> {
27 self.fetch_with_context(&std::collections::HashMap::new())
28 .await
29 }
30
31 /// Incremental fetch with parent context support.
32 ///
33 /// Returns the records and an optional bookmark value for incremental
34 /// replication. The default delegates to `fetch_with_context` and
35 /// returns `None` for the bookmark.
36 async fn fetch_with_context_incremental(
37 &self,
38 context: &std::collections::HashMap<String, Value>,
39 ) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
40 let records = self.fetch_with_context(context).await?;
41 Ok((records, None))
42 }
43
44 /// Convenience: incremental fetch with no parent context.
45 async fn fetch_all_incremental(&self) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
46 self.fetch_with_context_incremental(&std::collections::HashMap::new())
47 .await
48 }
49
50 /// Stream records page-by-page so the pipeline can write to the sink as
51 /// pages arrive instead of buffering the full result set.
52 ///
53 /// `batch_size` is the *hint* the pipeline passes down; sources are free
54 /// to use a larger or smaller native chunk (e.g. one page per HTTP
55 /// response, one row-group per Parquet file) but should approximate it
56 /// where feasible. The special value `batch_size = 0` means "do not
57 /// batch — emit the entire result set in a single page." Sources that
58 /// stream natively should treat `0` as "skip the chunking layer and
59 /// yield one page after the underlying read completes" (useful for
60 /// small lookup tables or for sinks like SQL `COPY` / BigQuery load
61 /// jobs that prefer one large request).
62 ///
63 /// The default implementation fetches the full result set via
64 /// [`fetch_with_context_incremental`](Self::fetch_with_context_incremental)
65 /// and chunks it in memory by `batch_size`. The bookmark (when present)
66 /// is attached to the *final* page so the pipeline only persists after
67 /// the entire fetch has been written. Sources that can stream natively
68 /// override this method and may emit per-page bookmarks (e.g. CDC).
69 ///
70 /// An empty result with a `Some(bookmark)` still yields one empty page
71 /// carrying the bookmark, so incremental runs that produce no records
72 /// still advance their checkpoint.
73 fn stream_pages<'a>(
74 &'a self,
75 context: &'a std::collections::HashMap<String, Value>,
76 batch_size: usize,
77 ) -> Pin<Box<dyn Stream<Item = Result<StreamPage, FaucetError>> + Send + 'a>> {
78 Box::pin(async_stream::try_stream! {
79 let (records, bookmark) = self
80 .fetch_with_context_incremental(context)
81 .await?;
82 let total = records.len();
83 // batch_size == 0 means "no batching" — emit all records as one
84 // page. Otherwise chunk into pages of size `batch_size`.
85 let chunk = if batch_size == 0 { usize::MAX } else { batch_size };
86
87 if total == 0 {
88 if bookmark.is_some() {
89 yield StreamPage {
90 records: Vec::new(),
91 bookmark,
92 };
93 }
94 return;
95 }
96
97 let mut iter = records.into_iter();
98 let mut consumed = 0usize;
99 loop {
100 let batch: Vec<Value> = iter.by_ref().take(chunk).collect();
101 if batch.is_empty() {
102 break;
103 }
104 consumed += batch.len();
105 let page_bookmark = if consumed >= total {
106 bookmark.clone()
107 } else {
108 None
109 };
110 yield StreamPage {
111 records: batch,
112 bookmark: page_bookmark,
113 };
114 }
115 })
116 }
117
118 /// Whether this source can emit **columnar** ([`ColumnarPage`](crate::columnar::ColumnarPage))
119 /// pages via [`stream_batches`](Self::stream_batches). Default: `false`.
120 ///
121 /// The pipeline uses the columnar fast path only when *both* the source and
122 /// sink return `true` here (and no `Value`-shaped stage needs to observe the
123 /// records), so an Arrow-native `parquet → parquet` chain never materializes
124 /// `Value`. Opt-in and additive — see [`crate::columnar`] (RFC 0002 / #375).
125 #[cfg(feature = "arrow")]
126 fn supports_columnar(&self) -> bool {
127 false
128 }
129
130 /// Stream the source natively as Arrow
131 /// [`ColumnarPage`](crate::columnar::ColumnarPage)s.
132 ///
133 /// Only invoked when [`supports_columnar`](Self::supports_columnar) returns
134 /// `true`; the default yields a single typed "unsupported" error so a source
135 /// that advertises support but forgets to override this fails loudly rather
136 /// than silently. Each page's `bookmark` carries the same checkpoint
137 /// semantics as [`StreamPage`].
138 #[cfg(feature = "arrow")]
139 fn stream_batches<'a>(
140 &'a self,
141 context: &'a std::collections::HashMap<String, Value>,
142 batch_size: usize,
143 ) -> Pin<Box<dyn Stream<Item = Result<crate::columnar::ColumnarPage, FaucetError>> + Send + 'a>>
144 {
145 let _ = (context, batch_size);
146 let name = self.connector_name();
147 let err: Result<crate::columnar::ColumnarPage, FaucetError> = Err(FaucetError::Source(
148 format!("source '{name}' does not support columnar streaming (stream_batches)"),
149 ));
150 Box::pin(futures::stream::once(async move { err }))
151 }
152
153 /// Wire formats this source can emit as raw bytes for the **native
154 /// byte-passthrough** fast path (#633), in preference order (first = best).
155 /// Default: `&[]` (no native fast path).
156 ///
157 /// The pipeline uses the path only when this returns a non-empty slice, a
158 /// sink advertises a matching [`NativeLoadCapability`](crate::NativeLoadCapability),
159 /// and every prerequisite holds (see [`plan_native_transfer`](crate::plan_native_transfer)).
160 /// A [`TransformingSource`](crate::TransformingSource) deliberately does not
161 /// override this, so any attached transform disables the fast path.
162 fn native_output_formats(&self) -> &'static [crate::native::NativeFormat] {
163 &[]
164 }
165
166 /// Stream the source natively as byte batches in `format` (#633).
167 ///
168 /// Only invoked after the pipeline negotiated `format` — one this source
169 /// advertised via [`native_output_formats`](Self::native_output_formats). The
170 /// default yields a single typed "unsupported" error so a source that
171 /// advertises support but forgets to override this fails loudly. Each batch's
172 /// `bookmark` carries the same checkpoint semantics as [`StreamPage`].
173 fn stream_native<'a>(
174 &'a self,
175 context: &'a std::collections::HashMap<String, Value>,
176 format: crate::native::NativeFormat,
177 batch_size: usize,
178 ) -> Pin<Box<dyn Stream<Item = Result<crate::native::NativeBatch, FaucetError>> + Send + 'a>>
179 {
180 let _ = (context, batch_size, format);
181 let name = self.connector_name();
182 let err: Result<crate::native::NativeBatch, FaucetError> = Err(FaucetError::Source(
183 format!("source '{name}' does not support native byte streaming (stream_native)"),
184 ));
185 Box::pin(futures::stream::once(async move { err }))
186 }
187
188 /// Return a JSON Schema describing the configuration this source accepts.
189 fn config_schema(&self) -> Value {
190 serde_json::json!({"type": "object", "properties": {}})
191 }
192
193 /// Stable key under which this source's incremental-replication bookmark
194 /// should be persisted in a [`StateStore`](crate::state::StateStore).
195 ///
196 /// Returning `Some(key)` opts this source into resumable runs: when the
197 /// pipeline is configured with a state store via
198 /// [`Pipeline::with_state_store`](crate::Pipeline::with_state_store), it
199 /// reads the bookmark at `key` before fetching and writes the new
200 /// bookmark back only after the sink confirms the batch was written.
201 ///
202 /// The default returns `None`, meaning the source is not persisted.
203 /// Keys must satisfy [`validate_state_key`](crate::state::validate_state_key).
204 fn state_key(&self) -> Option<String> {
205 None
206 }
207
208 /// Apply a bookmark loaded from a [`StateStore`](crate::state::StateStore)
209 /// as this run's starting point.
210 ///
211 /// The default implementation ignores the value, which keeps existing
212 /// sources backwards-compatible. Sources that support incremental
213 /// replication override this — typically by storing the value behind
214 /// interior mutability and consulting it inside
215 /// `fetch_with_context_incremental`.
216 async fn apply_start_bookmark(&self, _bookmark: Value) -> Result<(), FaucetError> {
217 Ok(())
218 }
219
220 /// Capture the source's current replication position **without consuming
221 /// any changes**, ensuring any server-side resource (e.g. a logical
222 /// replication slot) needed to later resume from that position exists.
223 ///
224 /// Returns the position as a bookmark [`Value`] — the same shape
225 /// [`apply_start_bookmark`](Self::apply_start_bookmark) accepts — or `None`
226 /// if this source does not support position capture.
227 ///
228 /// Used by the snapshot→CDC replication orchestrator (`faucet replicate`)
229 /// to anchor the CDC stream at-or-before the bulk snapshot's read point so
230 /// the handoff has no gap. The default returns `None`.
231 async fn capture_resume_position(&self) -> Result<Option<Value>, FaucetError> {
232 Ok(None)
233 }
234
235 /// How far this source is behind its head (#733) — unread WAL bytes, binlog
236 /// distance, unconsumed messages, or the age of the oldest unread change.
237 ///
238 /// The pipeline polls it at page boundaries and exports
239 /// `faucet_source_lag_{bytes,events,seconds}`; `faucet status --probe`
240 /// asks for it on demand after applying the stored bookmark. It must be a
241 /// cheap, read-only query. An `Err` is logged once and reported as no lag;
242 /// it never fails a run. Default: `Ok(None)` (no notion of a head).
243 /// Decorators must forward this.
244 async fn lag(&self) -> Result<Option<crate::lag::SourceLag>, FaucetError> {
245 Ok(None)
246 }
247
248 /// The version of this source's bookmark shape (#736). Stored state carries
249 /// it; bump it whenever the shape changes and teach
250 /// [`migrate_state`](Self::migrate_state) the step. Default `0`. Decorators
251 /// must forward this.
252 fn state_schema(&self) -> u32 {
253 0
254 }
255
256 /// Bring a bookmark stored at shape version `from` up to
257 /// [`state_schema`](Self::state_schema) (#736). Must be pure — the
258 /// migrated value is only persisted by the next bookmark write, so a crash
259 /// in between re-runs it. The default knows only its own version. Decorators
260 /// must forward this.
261 fn migrate_state(&self, from: u32, data: Value) -> Result<Value, FaucetError> {
262 if from == self.state_schema() {
263 Ok(data)
264 } else {
265 Err(FaucetError::State(format!(
266 "{} has no migration from bookmark schema {from} to {}",
267 self.connector_name(),
268 self.state_schema()
269 )))
270 }
271 }
272
273 /// Whether this source **deterministically replays** the same page sequence
274 /// from a given bookmark — the requirement for the atomic-watermark
275 /// effectively-once path (a non-deterministic replay could cause the pipeline
276 /// to skip a page whose contents differ from the one already committed).
277 /// Default: `false`.
278 ///
279 /// Sources with a durable monotonic position and per-page bookmarks (CDC)
280 /// override this to return `true`. The pipeline rejects
281 /// `DeliveryMode::ExactlyOnce` against a source that returns `false`.
282 fn supports_exactly_once(&self) -> bool {
283 false
284 }
285
286 /// Whether reading from this source **removes data from its backend** —
287 /// a queue source that acks, deletes or settles messages as the pipeline
288 /// moves past each page (SQS, Pub/Sub, JetStream, RabbitMQ). Such a source
289 /// relies on the linear pipeline writing and flushing a page before it is
290 /// polled again; anything that reads without durably writing (a preview, a
291 /// dry run, a `--limit` run, a plan sample) or that polls ahead of its
292 /// sinks (a topology graph) would lose those messages for good, so callers
293 /// refuse it. Default `false`.
294 fn consumes_destructively(&self) -> bool {
295 false
296 }
297
298 /// The typed replay capability this source advertises — see
299 /// [`ReplayGuarantee`](crate::ReplayGuarantee).
300 ///
301 /// The default derives from [`supports_exactly_once`](Self::supports_exactly_once)
302 /// (the boolean stays the back-compat primitive: existing connectors that
303 /// override only the boolean automatically advertise `Deterministic`
304 /// here). Override this directly only to *diverge* from the boolean —
305 /// there is currently no reason to.
306 fn replay_guarantee(&self) -> crate::idempotency::ReplayGuarantee {
307 if self.supports_exactly_once() {
308 crate::idempotency::ReplayGuarantee::Deterministic
309 } else {
310 crate::idempotency::ReplayGuarantee::NonDeterministic
311 }
312 }
313
314 /// What this source can do (RFC 0013, #876). The default derives every
315 /// field from the per-capability methods above
316 /// ([`Capabilities::of_source`](crate::Capabilities::of_source)); override
317 /// it to declare a capability no method expresses (range digests, lag),
318 /// keeping the connector's [`ConnectorDescriptor`](crate::ConnectorDescriptor)
319 /// in agreement. Decorators must forward this.
320 fn capabilities(&self) -> crate::capabilities::Capabilities {
321 crate::capabilities::Capabilities::of_source(self)
322 }
323
324 /// Whether this source can split its work into independent shards for
325 /// clustered (Mode B) execution. Default: `false` (single whole-dataset
326 /// shard). Sources with a natural partition (object-store prefixes, table
327 /// primary-key ranges) override this to `true` and implement
328 /// [`enumerate_shards`](Self::enumerate_shards) +
329 /// [`apply_shard`](Self::apply_shard).
330 fn is_shardable(&self) -> bool {
331 false
332 }
333
334 /// Enumerate the shards this source splits into, aiming for roughly `target`
335 /// of them (a hint — the source may return fewer, e.g. when the dataset is
336 /// small, or one per natural partition regardless of `target`).
337 ///
338 /// Called **once per run** by the cluster coordinator; enumeration must be
339 /// deterministic enough that re-enumeration yields a compatible set (stable
340 /// shard ids), since it may run on more than one instance and is reconciled
341 /// by idempotent insert. May perform read-only I/O (a `LIST`, a `MIN/MAX`
342 /// query). The default returns a single whole-dataset shard
343 /// ([`ShardSpec::whole`](crate::ShardSpec::whole)), preserving today's
344 /// single-worker behavior.
345 async fn enumerate_shards(
346 &self,
347 _target: usize,
348 ) -> Result<Vec<crate::shard::ShardSpec>, FaucetError> {
349 Ok(vec![crate::shard::ShardSpec::whole()])
350 }
351
352 /// Narrow this source instance to a single shard before streaming.
353 ///
354 /// Called on the worker that claims `shard`, after construction and before
355 /// any `stream_pages` call. Like [`apply_start_bookmark`](Self::apply_start_bookmark)
356 /// this takes `&self` and is expected to record the shard behind interior
357 /// mutability (the source consults it when building its query / listing).
358 /// The default ignores the shard — a non-shardable source only ever receives
359 /// [`ShardSpec::whole`](crate::ShardSpec::whole), so ignoring it streams the
360 /// whole dataset. Implementations should accept the whole shard as a no-op.
361 async fn apply_shard(&self, _shard: &crate::shard::ShardSpec) -> Result<(), FaucetError> {
362 Ok(())
363 }
364
365 /// Compute a [`ServerDigest`](crate::diff::ServerDigest) of the rows in
366 /// `range` **inside the backend**, so a matching range ships no rows
367 /// (#701). `columns` are the compared columns; `key` the integer key the
368 /// range is over. Default `Ok(None)`: not supported, the verifier streams
369 /// the range instead. Two digests compare only when both sides report the
370 /// same `algorithm`.
371 async fn range_digest(
372 &self,
373 range: &crate::diff::KeyRange,
374 key: &str,
375 columns: &[String],
376 ) -> Result<Option<crate::diff::ServerDigest>, FaucetError> {
377 let _ = (range, key, columns);
378 Ok(None)
379 }
380
381 /// Whether this source can enumerate the datasets behind its connection
382 /// via [`discover`](Self::discover). Default: `false`. Sources backed by
383 /// an introspectable catalog (database `information_schema`, MongoDB
384 /// collections, Elasticsearch indices, object-store prefixes) override
385 /// this to `true`.
386 fn supports_discover(&self) -> bool {
387 false
388 }
389
390 /// Enumerate the datasets living behind this source's connection — one
391 /// [`DatasetDescriptor`](crate::discover::DatasetDescriptor) per table /
392 /// collection / index / prefix, each carrying a partial config override
393 /// that selects it (used by `faucet discover` to scaffold one matrix row
394 /// per dataset).
395 ///
396 /// Must be **read-only and cheap**: catalog metadata queries and listings
397 /// only, never a data scan. Descriptors must never embed credentials.
398 /// The default returns a typed "unsupported" error; override it (and
399 /// return `true` from [`supports_discover`](Self::supports_discover))
400 /// only for sources with a real catalog to introspect.
401 async fn discover(&self) -> Result<Vec<crate::discover::DatasetDescriptor>, FaucetError> {
402 Err(FaucetError::Source(format!(
403 "source '{}' does not support dataset discovery",
404 self.connector_name()
405 )))
406 }
407
408 /// The dataset (table / collection) a change record belongs to, for a
409 /// change stream that carries several tables (#731). A multi-table
410 /// `faucet mirror` runs one stream and routes each record to its table's
411 /// pipeline by this name, which must match the name the paired bulk
412 /// source's [`discover`](Self::discover) reports (e.g. `public.orders`).
413 /// `None` means the record belongs to no table (a DDL / control event) —
414 /// and is the default, so a source that does not override this cannot be
415 /// used for a multi-table mirror.
416 fn record_table(&self, _record: &Value) -> Option<String> {
417 None
418 }
419
420 /// Order two of this source's bookmarks (#731): `Some(true)` when stream
421 /// position `a` is at or before `b` (every change up to `a` is also covered
422 /// by `b`), `Some(false)` when it is not, and `None` when the source cannot
423 /// tell (the default, or two positions it cannot relate). A multi-table
424 /// mirror uses it to resume one shared stream from the earliest table and
425 /// skip, per table, pages that table has already committed.
426 fn position_le(&self, _a: &Value, _b: &Value) -> Option<bool> {
427 None
428 }
429
430 /// Whether the stream had already delivered `record`'s change at stream
431 /// position `position` (#854): `Some(true)` when a run resumed from
432 /// `position` would not deliver it again, `Some(false)` when it would, and
433 /// `None` when the source cannot tell (the default). A multi-table mirror
434 /// resumes one shared stream from the earliest table, so a replayed page
435 /// can straddle another table's committed position; this per-record test
436 /// drops the records that table already applied, which a per-page
437 /// [`position_le`](Self::position_le) check cannot when the replay cuts its
438 /// pages at different points than the run that committed them.
439 fn record_covered(&self, _record: &Value, _position: &Value) -> Option<bool> {
440 None
441 }
442
443 /// The earliest stream position every one of `positions` can resume from
444 /// (#731): the shared change stream restarts there and each table skips
445 /// what it has already applied. The default picks the position that
446 /// [`position_le`](Self::position_le) orders at or before all the others,
447 /// and `None` when there is none (an empty slice, or positions this source
448 /// cannot order). Sources whose positions are only partially ordered (one
449 /// cursor per capture instance, say) override it with a component-wise
450 /// minimum.
451 fn position_min(&self, positions: &[Value]) -> Option<Value> {
452 let first = positions.first()?;
453 if positions.iter().all(|p| p == first) {
454 return Some(first.clone());
455 }
456 positions
457 .iter()
458 .find(|cand| {
459 positions
460 .iter()
461 .all(|other| self.position_le(cand, other) == Some(true))
462 })
463 .cloned()
464 }
465
466 /// Stable identifier used as the `connector` label on metrics and the
467 /// `connector` attribute on spans. Defaults to the final segment of
468 /// `std::any::type_name::<Self>()`, e.g. `"RestSource"`. Built-in
469 /// connectors override with a short, friendly snake_case name (e.g.
470 /// `"rest"`). Must return a non-empty string; observability decorators
471 /// fall back to `"unknown"` in release builds if it is empty (and
472 /// `debug_assert!` in debug builds).
473 fn connector_name(&self) -> &'static str {
474 crate::observability::strip_type_name(std::any::type_name::<Self>())
475 }
476
477 /// Receive a pre-labelled handle for counting **upstream round trips**
478 /// (#638) — calls this connector makes to its own backend.
479 ///
480 /// The pipeline calls this once before streaming, because it is the only
481 /// place that knows the `pipeline` / `row` / `connector` labels every other
482 /// metric carries. A connector opts in by storing the handle behind
483 /// interior mutability (the pattern the REST source already uses for
484 /// `runtime_start`) and calling `recorder.record("<op>")` at each real
485 /// backend call — including retries, which are real round trips.
486 ///
487 /// Defaulted to a no-op: an uninstrumented connector emits nothing, so
488 /// instrumentation lands connector by connector with no behaviour change
489 /// in between, and a third-party connector is unaffected.
490 fn set_roundtrip_recorder(
491 &self,
492 _recorder: std::sync::Arc<crate::observability::RoundtripRecorder>,
493 ) {
494 }
495
496 /// Receive the run clock (#769): the instant `${now.*}` renders from —
497 /// `faucet run --clock`, a schedule tick, a backfill unit's start — so a
498 /// source that bounds reads by "now" (REST window slicing) reproduces the
499 /// run as of that instant rather than the wall clock.
500 ///
501 /// Called once before streaming. Defaulted to a no-op; a connector opts in
502 /// by storing the instant behind interior mutability.
503 fn set_run_clock(&self, _now: chrono::DateTime<chrono::Utc>) {}
504
505 /// Receive the run's [`CallContext`](crate::io::CallContext) (#880): the
506 /// cancel token, the round-trip recorder and any deadline every backend
507 /// call should honour. Called once before streaming.
508 ///
509 /// A connector stores it in a [`CallSlot`](crate::io::CallSlot) and runs
510 /// its backend calls through [`CallSlot::call`](crate::io::CallSlot::call),
511 /// which layers the connector's own timeout and retry settings over it.
512 /// Defaulted to a no-op; a wrapping source forwards it.
513 fn set_call_context(&self, _ctx: crate::io::CallContext) {}
514
515 /// Receive the run's cancellation token ([`Pipeline::with_cancel`](crate::Pipeline::with_cancel)),
516 /// installed once before streaming.
517 ///
518 /// Return `true` when the source handles the cancel itself: it stops
519 /// reading, yields the records it has buffered and ends its stream
520 /// promptly. The pipeline then keeps polling the stream to its end instead
521 /// of stopping at the next page boundary, so that buffered tail is
522 /// written. A source that buffers records it cannot re-read (a live feed)
523 /// opts in; the default ignores the token and returns `false`. A wrapping
524 /// source forwards the call and returns the inner source's answer.
525 fn set_cancel(&self, _cancel: tokio_util::sync::CancellationToken) -> bool {
526 false
527 }
528
529 /// Logical dataset identity for lineage emission, following OpenLineage
530 /// naming conventions (<https://openlineage.io/docs/spec/naming>).
531 ///
532 /// The default returns `"<connector_name>://unknown"`. Built-in connectors
533 /// override with a credential-free URI derived from their config. Strip any
534 /// credentials with [`redact_uri_credentials`](crate::redact_uri_credentials).
535 /// Informational metadata only — never used for I/O.
536 fn dataset_uri(&self) -> String {
537 format!("{}://unknown", self.connector_name())
538 }
539
540 /// Run a fast, non-mutating preflight probe (used by `faucet doctor`).
541 ///
542 /// The default pulls a **single page** via
543 /// [`stream_pages`](Self::stream_pages) and reports success/failure — it
544 /// exercises the real read path (DNS, TLS, auth, the first request, the
545 /// first-record decode) but never paginates the full dataset and never
546 /// repeats. The page stream is dropped immediately after the first page.
547 ///
548 /// Sources whose first page *blocks* waiting for inbound data (webhook,
549 /// websocket) or has *side effects* (CDC consuming WAL) override this with a
550 /// cheaper, side-effect-free probe. Probe-level failures are returned as a
551 /// [`ProbeStatus::Fail`](crate::check::ProbeStatus) inside `Ok(report)`.
552 async fn check(
553 &self,
554 ctx: &crate::check::CheckContext,
555 ) -> Result<crate::check::CheckReport, FaucetError> {
556 use crate::check::{CheckReport, Probe};
557 use futures::StreamExt;
558
559 let empty = std::collections::HashMap::new();
560 let start = std::time::Instant::now();
561 let mut pages = self.stream_pages(&empty, 1);
562 let probe = match tokio::time::timeout(ctx.timeout, pages.next()).await {
563 Err(_) => Probe::fail("read", start.elapsed(), "timed out fetching first page"),
564 Ok(None) | Ok(Some(Ok(_))) => Probe::pass("read", start.elapsed()),
565 Ok(Some(Err(e))) => Probe::fail("read", start.elapsed(), e.to_string()),
566 };
567 Ok(CheckReport::single(probe))
568 }
569}
570
571/// Per-row outcome from [`Sink::write_batch_partial`].
572///
573/// `Ok(())` — the row was durably written to the sink.
574/// `Err(_)` — the row failed; the pipeline will route it to the DLQ when
575/// one is configured.
576pub type RowOutcome = Result<(), FaucetError>;
577
578/// A sink writes records to an external system.
579#[async_trait]
580pub trait Sink: Send + Sync {
581 /// Write a batch of records to the destination.
582 ///
583 /// Returns the number of records successfully written.
584 async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError>;
585
586 /// Flush any buffered data to the destination.
587 ///
588 /// The default implementation is a no-op (suitable for sinks that
589 /// write immediately in `write_batch`).
590 async fn flush(&self) -> Result<(), FaucetError> {
591 Ok(())
592 }
593
594 /// Write a batch and report per-row outcomes.
595 ///
596 /// Sinks whose underlying API exposes per-row results (BigQuery
597 /// `insertAll`, Elasticsearch `_bulk`) override this. The default
598 /// implementation delegates to [`Self::write_batch`] and maps a single success
599 /// onto a uniform all-`Ok(())` vector. An outer failure is bubbled up
600 /// unchanged so the pipeline's DLQ router can apply its `on_batch_error`
601 /// policy at a single decision point.
602 ///
603 /// The default checks the write's [`WriteReport`](crate::WriteReport)
604 /// (#879): rows it neither wrote nor reported as coalesced fail the batch
605 /// with [`FaucetError::RowsUnaccounted`] instead of being reported `Ok`.
606 async fn write_batch_partial(&self, records: &[Value]) -> Result<Vec<RowOutcome>, FaucetError> {
607 self.write_batch_reported(records)
608 .await?
609 .check(records.len())?;
610 Ok(records.iter().map(|_| Ok(())).collect())
611 }
612
613 /// Write a batch and report what happened to every row offered (#879).
614 ///
615 /// The pipeline calls this instead of [`Self::write_batch`] and checks that
616 /// `accepted + coalesced + skipped` covers the page; a shortfall fails the
617 /// page with [`FaucetError::RowsUnaccounted`]. The default wraps
618 /// `write_batch`'s count; for a sink configured to merge rows by key
619 /// ([`Self::dedups_by_key`] — keyed upsert / delete, last write wins) it
620 /// counts the rows the count falls short by as
621 /// [`coalesced`](crate::WriteReport::coalesced). A sink that declines rows
622 /// by design of its configuration overrides this and reports them as
623 /// [`skipped`](crate::WriteReport::skipped).
624 async fn write_batch_reported(
625 &self,
626 records: &[Value],
627 ) -> Result<crate::accounting::WriteReport, FaucetError> {
628 let n = self.write_batch(records).await?;
629 Ok(if self.dedups_by_key() {
630 crate::accounting::WriteReport::keyed(records.len(), n)
631 } else {
632 crate::accounting::WriteReport::accepted(n)
633 })
634 }
635
636 /// Write a page the engine governed (RFC 0014): it went through masking,
637 /// quality, contract and schema drift, so the records are exactly what
638 /// may reach the destination. The engine's plain write path calls this.
639 ///
640 /// The default delegates to [`write_batch_reported`](Self::write_batch_reported)
641 /// with the page's records, so existing sinks behave as before. A
642 /// [`GovernedPage`](crate::governance::GovernedPage) cannot be built
643 /// outside [`governance`](crate::governance), so a sink that overrides
644 /// this receives only governed data. Decorators forward it.
645 async fn write_governed(
646 &self,
647 page: &crate::governance::GovernedPage<'_>,
648 ) -> Result<crate::accounting::WriteReport, FaucetError> {
649 self.write_batch_reported(page.records()).await
650 }
651
652 /// What a failed batch write leaves behind (#737): nothing
653 /// ([`Atomic`](crate::BatchAtomicity::Atomic)), per-row outcomes with
654 /// nothing committed on an outer `Err`
655 /// ([`PerRow`](crate::BatchAtomicity::PerRow)), or possibly some rows
656 /// ([`BestEffort`](crate::BatchAtomicity::BestEffort), the default).
657 ///
658 /// `on_batch_error: dlq_all` is refused on a best-effort sink unless it
659 /// writes by key or the user opts in to the duplicates. Decorators must
660 /// forward this.
661 fn batch_atomicity(&self) -> crate::dlq::BatchAtomicity {
662 crate::dlq::BatchAtomicity::BestEffort
663 }
664
665 /// Called with a whole page before the pipeline splits it into adaptive
666 /// sub-batches. A sink enforcing a ceiling that must hold for the page as
667 /// a unit (a run budget) refuses here, so no sub-batch of a refused page
668 /// lands. Default: accept. Decorators must forward this.
669 async fn admit_page(&self, records: &[Value]) -> Result<(), FaucetError> {
670 let _ = records;
671 Ok(())
672 }
673
674 /// Whether this sink can consume **columnar** (`arrow::RecordBatch`) writes
675 /// via [`write_batch_columnar`](Self::write_batch_columnar) without first
676 /// converting to `Value`. Default: `false`.
677 ///
678 /// The pipeline takes the columnar fast path only when *both* the source and
679 /// sink return `true` (RFC 0002 / #375).
680 #[cfg(feature = "arrow")]
681 fn supports_columnar(&self) -> bool {
682 false
683 }
684
685 /// Write a columnar `RecordBatch` to the destination, returning the number of
686 /// rows written.
687 ///
688 /// The default converts the batch to `Value` rows via the
689 /// [`columnar`](crate::columnar) shim and delegates to
690 /// [`write_batch`](Self::write_batch), so every sink participates correctly
691 /// even without a native columnar path. Sinks that write Arrow/Parquet
692 /// directly override this — and return `true` from
693 /// [`supports_columnar`](Self::supports_columnar) — to skip the conversion.
694 #[cfg(feature = "arrow")]
695 async fn write_batch_columnar(
696 &self,
697 batch: &arrow::array::RecordBatch,
698 ) -> Result<usize, FaucetError> {
699 let rows = crate::columnar::record_batch_to_values(batch)?;
700 self.write_batch(&rows).await
701 }
702
703 /// Native byte-passthrough load mechanisms this sink offers, each naming
704 /// the wire format and the write modes it can honor (#633). Default:
705 /// `vec![]` (no fast path; use [`write_batch`](Self::write_batch)).
706 ///
707 /// The pipeline takes the native path only when a source advertises a
708 /// format this returns and the run passes the pipeline-owned gates — no
709 /// transforms, no quality/contract/masking pass, no DLQ, at-least-once
710 /// delivery, no upsert/delete `write_mode`, and (for overwrite) an
711 /// all-or-nothing load session finalized by a single terminal `flush` —
712 /// see [`plan_native_transfer`](crate::plan_native_transfer). A capability
713 /// cannot waive those gates.
714 fn native_load_capabilities(&self) -> Vec<crate::native::NativeLoadCapability> {
715 Vec::new()
716 }
717
718 /// Bulk-load one native-format byte batch directly (#633), returning the
719 /// number of rows written.
720 ///
721 /// Only invoked when the pipeline negotiated one of this sink's
722 /// [`native_load_capabilities`](Self::native_load_capabilities) and the
723 /// pipeline-owned gates passed. `ctx.first_batch` lets an overwrite sink
724 /// truncate on the first load and append thereafter. The default returns a
725 /// typed "unsupported" error so a sink that advertises a capability but
726 /// forgets to override this fails loudly.
727 ///
728 /// **Contract:** an **empty payload must be a successful no-op** returning
729 /// `Ok(0)` — sources emit a trailing empty batch to carry the final
730 /// bookmark, and an error here would break bookmark persistence. Under
731 /// `Overwrite`, nothing may become visible in the destination until the
732 /// terminal [`flush`](Self::flush) — the pipeline flushes exactly once, on
733 /// success only, so a mechanism that commits per batch must omit
734 /// `Overwrite` from its capability's `write_modes`.
735 async fn load_native(
736 &self,
737 batch: crate::native::NativeBatch,
738 scope: &str,
739 ctx: crate::native::NativeLoadContext,
740 ) -> Result<usize, FaucetError> {
741 let _ = (batch, scope, ctx);
742 Err(FaucetError::Sink(format!(
743 "sink '{}' does not support native byte loading (load_native)",
744 self.connector_name()
745 )))
746 }
747
748 /// Whether this sink can durably commit a page's rows **and** a commit token
749 /// in a single atomic transaction. Default: `false` (at-least-once only).
750 ///
751 /// Only return `true` from a sink that genuinely commits both atomically —
752 /// see [`write_batch_idempotent`](Self::write_batch_idempotent). The pipeline
753 /// rejects `DeliveryMode::ExactlyOnce` against a sink that returns `false`.
754 fn supports_idempotent_writes(&self) -> bool {
755 false
756 }
757
758 /// The strongest delivery guarantee this sink can uphold — see
759 /// [`SinkGuarantee`](crate::SinkGuarantee).
760 ///
761 /// The default derives from the two back-compat primitives:
762 /// [`supports_idempotent_writes`](Self::supports_idempotent_writes) →
763 /// `AtomicWatermark`, else an upsert-capable
764 /// [`supported_write_modes`](Self::supported_write_modes) → `KeyedUpsert`,
765 /// else `AtLeastOnce`. Existing connectors that override only the
766 /// primitives automatically advertise the right capability here.
767 fn sink_guarantee(&self) -> crate::idempotency::SinkGuarantee {
768 if self.supports_idempotent_writes() {
769 crate::idempotency::SinkGuarantee::AtomicWatermark
770 } else if self
771 .supported_write_modes()
772 .contains(&crate::write_mode::WriteMode::Upsert)
773 {
774 crate::idempotency::SinkGuarantee::KeyedUpsert
775 } else {
776 crate::idempotency::SinkGuarantee::AtLeastOnce
777 }
778 }
779
780 /// What this sink can do (RFC 0013, #876). The default derives every field
781 /// from the per-capability methods
782 /// ([`Capabilities::of_sink`](crate::Capabilities::of_sink)); override it
783 /// to declare a capability no method expresses (how unknown fields are
784 /// treated, scoped overwrite), keeping the connector's
785 /// [`ConnectorDescriptor`](crate::ConnectorDescriptor) in agreement.
786 /// Decorators must forward this.
787 fn capabilities(&self) -> crate::capabilities::Capabilities {
788 crate::capabilities::Capabilities::of_sink(self)
789 }
790
791 /// Whether a **plain [`write_batch`](Self::write_batch) is safe to replay**
792 /// — i.e. re-sending the same page after an ambiguous failure converges
793 /// instead of duplicating rows. Default: `false`.
794 ///
795 /// This is the property the pipeline needs before it may retry a
796 /// non-idempotent write, and it is **not** the same as
797 /// [`supports_idempotent_writes`](Self::supports_idempotent_writes), which
798 /// promises only that rows *and a commit token* can be committed in one
799 /// transaction (the [`write_batch_idempotent`](Self::write_batch_idempotent)
800 /// path). A sink can offer that token protocol and still have a plain
801 /// `write_batch` that is a bare multi-row `INSERT` — replaying it after the
802 /// server committed but the response was lost duplicates every row, which
803 /// is this repo's worst bug class (F29/F32).
804 ///
805 /// The default implementation is therefore conservative and derives from
806 /// the live config: a keyed upsert/delete converges on replay, anything
807 /// else does not. Override only for a sink whose plain write is genuinely
808 /// replay-safe by construction.
809 fn write_batch_is_replay_safe(&self) -> bool {
810 self.dedups_by_key()
811 }
812
813 /// Whether this sink instance is **configured** to dedup by key — i.e.
814 /// `write_mode: upsert` (or `delete`) with a non-empty `key`, so
815 /// re-applying a record with the same key converges instead of
816 /// duplicating. Default: `false`.
817 ///
818 /// Distinct from [`sink_guarantee`](Self::sink_guarantee) (capability):
819 /// this reflects the *live config*. Sinks that flatten a
820 /// [`WriteSpec`](crate::write_mode::WriteSpec) into their config override
821 /// it as `self.config.write.dedups_by_key()`. The pipeline consults it to
822 /// derive the keyed-upsert effectively-once mechanism at run time.
823 fn dedups_by_key(&self) -> bool {
824 false
825 }
826
827 /// Write modes this sink can apply. Default: append-only. Sinks that
828 /// implement key-based merge override this to include
829 /// [`WriteMode::Upsert`](crate::write_mode::WriteMode) /
830 /// [`WriteMode::Delete`](crate::write_mode::WriteMode). The CLI rejects a
831 /// configured mode that is not in this set at config-load time.
832 fn supported_write_modes(&self) -> &'static [crate::write_mode::WriteMode] {
833 &[crate::write_mode::WriteMode::Append]
834 }
835
836 /// The sink's live destination schema as an `infer_schema`-shaped object
837 /// (`{"type":"object","properties":{ <col>: <type-fragment>, … }}`), or
838 /// `None` for a schemaless sink or a target that does not exist yet.
839 ///
840 /// Used by the schema-drift policy to diff each page's shape against the
841 /// real destination. Default: `Ok(None)` (drift handling is inert).
842 async fn current_schema(&self) -> Result<Option<Value>, FaucetError> {
843 Ok(None)
844 }
845
846 /// Whether this sink can apply additive/widening DDL via
847 /// [`evolve_schema`](Self::evolve_schema). Default: `false`. The CLI rejects
848 /// `on_drift: evolve` against a sink that returns `false` at config-load.
849 fn supports_schema_evolution(&self) -> bool {
850 false
851 }
852
853 /// Apply an additive schema evolution (new columns, lossless widenings,
854 /// nullability relaxations) to the destination. MUST be idempotent
855 /// (`ADD COLUMN IF NOT EXISTS` semantics) so concurrent runs converge.
856 ///
857 /// Default: a typed "unsupported" error. Override only when the backend
858 /// supports in-place additive DDL (and return `true` from
859 /// `supports_schema_evolution`).
860 async fn evolve_schema(
861 &self,
862 evolution: &crate::drift::SchemaEvolution,
863 ) -> Result<(), FaucetError> {
864 let _ = evolution;
865 Err(FaucetError::Sink(format!(
866 "sink '{}' does not support schema evolution",
867 self.connector_name()
868 )))
869 }
870
871 /// Whether this sink can delete a scoped set of rows for scoped cleanup
872 /// (#478). Default `false`; the upsert-capable sinks override it.
873 fn supports_cleanup(&self) -> bool {
874 false
875 }
876
877 /// Whether this sink can bulk-load via an object-store stage — write the
878 /// page to S3/GCS/Azure, then pull it with the warehouse's native load
879 /// command (`COPY` / `COPY INTO` / `s3()` table function) (#528). Default
880 /// `false`; warehouse sinks that honour a [`StagingSpec`](crate::StagingSpec)
881 /// override it. Object-safe (no args, no generics) so `Box<dyn Sink>` is
882 /// unaffected.
883 fn supports_staged_load(&self) -> bool {
884 false
885 }
886
887 /// Delete rows matching `scope` whose key is **not** in `seen`.
888 ///
889 /// Called at most once per invocation, only after the run completed
890 /// successfully and uncancelled — see [`crate::cleanup`] for why the timing
891 /// is load-bearing. `scope` is a set of equality predicates in destination
892 /// column terms, AND-ed together; `seen` holds the key tuples this run wrote.
893 ///
894 /// Returns the number of rows deleted. Implementations **must** be
895 /// all-or-nothing where the backend allows it: a partial delete would remove
896 /// rows the run actually wrote.
897 ///
898 /// The default is a typed "unsupported" error, so no existing or third-party
899 /// connector breaks.
900 #[deprecated(
901 since = "1.14.0",
902 note = "implement `faucet_core::driver::CleanupDriver` on a family driver; see RFC 0014"
903 )]
904 async fn cleanup_scope(
905 &self,
906 scope: &std::collections::BTreeMap<String, Value>,
907 seen: &crate::cleanup::SeenKeys,
908 ) -> Result<u64, FaucetError> {
909 let _ = (scope, seen);
910 Err(FaucetError::Sink(format!(
911 "sink '{}' does not support scoped cleanup",
912 self.connector_name()
913 )))
914 }
915
916 /// Write `records` AND durably record `token` for `scope`, atomically.
917 ///
918 /// `scope` namespaces the watermark (the pipeline passes the per-row state
919 /// key, e.g. `"{name}::{row_id}"`). `token` is a monotonic, fixed-width
920 /// string (see [`format_token`](crate::format_token)).
921 ///
922 /// The default is **not** idempotent: it ignores the token and delegates to
923 /// [`write_batch`](Self::write_batch). Override only when the commit is
924 /// genuinely atomic (and return `true` from `supports_idempotent_writes`).
925 #[deprecated(
926 since = "1.14.0",
927 note = "implement `faucet_core::driver::CommitTokenDriver` on a family driver; see RFC 0014"
928 )]
929 async fn write_batch_idempotent(
930 &self,
931 records: &[Value],
932 scope: &str,
933 token: &str,
934 ) -> Result<usize, FaucetError> {
935 let _ = (scope, token);
936 self.write_batch(records).await
937 }
938
939 /// [`write_batch_idempotent`](Self::write_batch_idempotent) with a
940 /// [`WriteReport`](crate::accounting::WriteReport): the exactly-once path
941 /// calls this, and a page whose report does not account for every row it
942 /// offered fails with [`FaucetError::RowsUnaccounted`] before its bookmark
943 /// is persisted (#879). Override it when the sink declines rows by design
944 /// inside the atomic commit (a record without a key under a skip policy)
945 /// and report them as `skipped`.
946 ///
947 /// The default credits the rows `write_batch_idempotent` returns — as
948 /// coalesced-by-key when [`dedups_by_key`](Self::dedups_by_key) — so a
949 /// sink that silently writes fewer rows than it was offered fails the page.
950 #[deprecated(
951 since = "1.14.0",
952 note = "implement `faucet_core::driver::CommitTokenDriver` on a family driver; see RFC 0014"
953 )]
954 #[allow(deprecated)] // drives the 1.x lifecycle hook until faucet-core 2.0 (RFC 0014)
955 async fn write_batch_idempotent_reported(
956 &self,
957 records: &[Value],
958 scope: &str,
959 token: &str,
960 ) -> Result<crate::accounting::WriteReport, FaucetError> {
961 let n = self.write_batch_idempotent(records, scope, token).await?;
962 Ok(if self.dedups_by_key() {
963 crate::accounting::WriteReport::keyed(records.len(), n)
964 } else {
965 crate::accounting::WriteReport::accepted(n)
966 })
967 }
968
969 /// The last token durably committed for `scope`, or `None` if this sink has
970 /// never committed under that scope. Default: `None`.
971 #[deprecated(
972 since = "1.14.0",
973 note = "implement `faucet_core::driver::CommitTokenDriver` on a family driver; see RFC 0014"
974 )]
975 async fn last_committed_token(&self, scope: &str) -> Result<Option<String>, FaucetError> {
976 let _ = scope;
977 Ok(None)
978 }
979
980 /// Whether this sink instance is configured for full-destination
981 /// replacement ([`WriteMode::Overwrite`](crate::write_mode::WriteMode)).
982 ///
983 /// The pipeline consults this to drive the overwrite lifecycle:
984 /// [`begin_overwrite`](Self::begin_overwrite) before the first page, then
985 /// [`commit_overwrite`](Self::commit_overwrite) once the run finishes
986 /// successfully, or [`abort_overwrite`](Self::abort_overwrite) on
987 /// failure/cancel. Sinks that flatten a [`WriteSpec`](crate::write_mode::WriteSpec)
988 /// into their config return `self.config.write.is_overwrite()`. Default `false`.
989 fn is_overwrite(&self) -> bool {
990 false
991 }
992
993 /// Prepare a staging target for an overwrite run.
994 ///
995 /// Called once, before the first [`write_batch`](Self::write_batch), only
996 /// when [`is_overwrite`](Self::is_overwrite) is true. The sink stages this
997 /// run's writes (a temp table / new index / temp prefix) so the existing
998 /// destination is untouched until the run succeeds. Subsequent
999 /// `write_batch` calls for this sink must land in the staging target.
1000 ///
1001 /// Default: a typed "unsupported" error, so a sink that advertises
1002 /// `WriteMode::Overwrite` but forgets to implement the lifecycle fails
1003 /// loudly rather than silently appending. Never called for sinks whose
1004 /// `is_overwrite()` is false.
1005 #[deprecated(
1006 since = "1.14.0",
1007 note = "implement `faucet_core::driver::StagingDriver` on a family driver; see RFC 0014"
1008 )]
1009 async fn begin_overwrite(&self) -> Result<(), FaucetError> {
1010 Err(FaucetError::Sink(format!(
1011 "sink '{}' does not support write_mode: overwrite",
1012 self.connector_name()
1013 )))
1014 }
1015
1016 /// Atomically replace the destination with the staged data.
1017 ///
1018 /// Called **once, only after the run completed successfully and
1019 /// uncancelled**. Implementations MUST swap staging → destination
1020 /// atomically (or as close as the backend allows) so a reader never sees a
1021 /// half-replaced dataset, and MUST NOT have destroyed the prior contents
1022 /// before this point — a failed run leaves the old data in place.
1023 ///
1024 /// Default: a typed "unsupported" error (unreachable for a correct sink
1025 /// whose `is_overwrite()` is false).
1026 #[deprecated(
1027 since = "1.14.0",
1028 note = "implement `faucet_core::driver::StagingDriver` on a family driver; see RFC 0014"
1029 )]
1030 async fn commit_overwrite(&self) -> Result<(), FaucetError> {
1031 Err(FaucetError::Sink(format!(
1032 "sink '{}' does not support write_mode: overwrite",
1033 self.connector_name()
1034 )))
1035 }
1036
1037 /// Whether this sink can undo a run it wrote (#706) through
1038 /// [`rollback_run`](Self::rollback_run). Default `false`.
1039 fn supports_rollback(&self) -> bool {
1040 false
1041 }
1042
1043 /// Undo everything `run_id` wrote to this destination, per
1044 /// `opts.mode`: delete the run's rows (append), restore journaled
1045 /// before-images (upsert / delete), or swap the kept previous table back
1046 /// (overwrite). Must be all-or-nothing per destination where the backend
1047 /// allows it, and must leave the destination untouched when `opts.dry_run`
1048 /// is set or when conflicts block it (see
1049 /// [`RollbackOutcome`](crate::rollback::RollbackOutcome)).
1050 ///
1051 /// Default: a typed "unsupported" error.
1052 async fn rollback_run(
1053 &self,
1054 run_id: &str,
1055 opts: &crate::rollback::RollbackOptions,
1056 ) -> Result<crate::rollback::RollbackOutcome, FaucetError> {
1057 let _ = (run_id, opts);
1058 Err(FaucetError::Sink(format!(
1059 "sink '{}' does not support rollback",
1060 self.connector_name()
1061 )))
1062 }
1063
1064 /// Drop whatever this sink kept to make `run_id` undoable (journal rows, a
1065 /// previous table) once the run is past the retention window. Default:
1066 /// no-op.
1067 async fn forget_run(&self, run_id: &str) -> Result<(), FaucetError> {
1068 let _ = run_id;
1069 Ok(())
1070 }
1071
1072 /// Rewind the exactly-once watermark for `scope` to `token` (`None` clears
1073 /// it), so a rolled-back run's pages are not skipped on the next run.
1074 /// Default: a typed "unsupported" error.
1075 async fn rewind_commit_token(
1076 &self,
1077 scope: &str,
1078 token: Option<&str>,
1079 ) -> Result<(), FaucetError> {
1080 let _ = (scope, token);
1081 Err(FaucetError::Sink(format!(
1082 "sink '{}' does not support rewinding its commit token",
1083 self.connector_name()
1084 )))
1085 }
1086
1087 /// A source `(kind, config)` that reads this destination back — what
1088 /// `faucet verify` (#701) compares the pipeline's source against. Default
1089 /// `None`: the user names the destination reader in `verify.destination`.
1090 /// The config must not need a credential the sink config lacks.
1091 fn readback_source(&self) -> Option<(String, Value)> {
1092 None
1093 }
1094
1095 /// Discard the staging target after a failed or cancelled overwrite run.
1096 ///
1097 /// Called (best-effort) when an overwrite run does not reach
1098 /// [`commit_overwrite`](Self::commit_overwrite). The destination must be
1099 /// left exactly as it was before the run. Default: no-op — a leftover
1100 /// staging object is untidy but never data loss, so a sink may skip it.
1101 #[deprecated(
1102 since = "1.14.0",
1103 note = "implement `faucet_core::driver::StagingDriver` on a family driver; see RFC 0014"
1104 )]
1105 async fn abort_overwrite(&self) -> Result<(), FaucetError> {
1106 Ok(())
1107 }
1108
1109 /// Finalize this run's output after [`Pipeline::run`](crate::Pipeline::run)
1110 /// finished **successfully and uncancelled**, on every transfer path
1111 /// (`Value`, columnar, native), after the terminal flush.
1112 ///
1113 /// A sink whose destination must reflect *this* run even when it wrote
1114 /// nothing uses it: the file sinks with `append: false` truncate (or, for
1115 /// a fixed-path Parquet file, remove) the previous run's output here when
1116 /// no record arrived, so a source that became empty never leaves stale
1117 /// rows presented as current (#753). Never called after a failed or
1118 /// cancelled run, so the previous good output survives those. Decorators
1119 /// must forward it. Default: no-op.
1120 async fn complete_run(&self) -> Result<(), FaucetError> {
1121 Ok(())
1122 }
1123
1124 /// Whether an overwrite staging object (the `…__faucet_ovw` table or
1125 /// collection a [`begin_overwrite`](Self::begin_overwrite) creates) exists
1126 /// right now — a read-only probe used by `faucet status --probe` to report
1127 /// staging a crashed or aborted overwrite left behind.
1128 ///
1129 /// `Ok(None)` means the sink cannot tell (the default); overwrite-capable
1130 /// sinks return `Ok(Some(_))`.
1131 #[deprecated(
1132 since = "1.14.0",
1133 note = "implement `faucet_core::driver::StagingDriver` on a family driver; see RFC 0014"
1134 )]
1135 async fn overwrite_staging_exists(&self) -> Result<Option<bool>, FaucetError> {
1136 Ok(None)
1137 }
1138
1139 /// Return a JSON Schema describing the configuration this sink accepts.
1140 ///
1141 /// The schema is auto-generated from the config struct using `schemars`.
1142 /// Callers can inspect it to discover required fields, types, defaults,
1143 /// and descriptions before constructing the sink.
1144 ///
1145 /// The default returns an empty object schema.
1146 fn config_schema(&self) -> Value {
1147 serde_json::json!({"type": "object", "properties": {}})
1148 }
1149
1150 /// Stable identifier used as the `connector` label on metrics and the
1151 /// `connector` attribute on spans. See `Source::connector_name`.
1152 fn connector_name(&self) -> &'static str {
1153 crate::observability::strip_type_name(std::any::type_name::<Self>())
1154 }
1155
1156 /// Receive a pre-labelled handle for counting **upstream round trips**
1157 /// (#638). See [`Source::set_roundtrip_recorder`]; defaulted to a no-op.
1158 fn set_roundtrip_recorder(
1159 &self,
1160 _recorder: std::sync::Arc<crate::observability::RoundtripRecorder>,
1161 ) {
1162 }
1163
1164 /// Receive the run's [`CallContext`](crate::io::CallContext) (#880). See
1165 /// [`Source::set_call_context`]. A sink's context never carries the run's
1166 /// cancel token — a cancelled run still flushes its sinks — nor a retry
1167 /// policy: writes are retried page by page under ADR 0007. Defaulted to a
1168 /// no-op; a wrapping sink forwards it.
1169 fn set_call_context(&self, _ctx: crate::io::CallContext) {}
1170
1171 /// Logical dataset identity for lineage emission, following OpenLineage
1172 /// naming conventions (<https://openlineage.io/docs/spec/naming>).
1173 ///
1174 /// The default returns `"<connector_name>://unknown"`. Built-in connectors
1175 /// override with a credential-free URI derived from their config. Strip any
1176 /// credentials with [`redact_uri_credentials`](crate::redact_uri_credentials).
1177 /// Informational metadata only — never used for I/O.
1178 fn dataset_uri(&self) -> String {
1179 format!("{}://unknown", self.connector_name())
1180 }
1181
1182 /// The concrete **local files** this sink instance opened during the run.
1183 ///
1184 /// The provenance record faucet's local-output retention GC (#587) deletes
1185 /// from: it may only remove files faucet recorded here, never a glob or a
1186 /// directory. A sink that writes local files (jsonl, csv, parquet to a local
1187 /// destination) accumulates a
1188 /// [`LocalOutputLog`](crate::local_outputs::LocalOutputLog) as it opens them
1189 /// and returns its snapshot; every other sink keeps the empty default, which
1190 /// simply means "nothing local to collect".
1191 ///
1192 /// Two properties the GC depends on, so an implementation must preserve them:
1193 ///
1194 /// 1. **Every file, individually named.** A rolling parquet sink returns one
1195 /// entry per UUID-named part — the directory itself is not an output.
1196 /// 2. **[`LocalOutput::pre_existing`](crate::local_outputs::LocalOutput) is
1197 /// honest**, captured before the first open. A file faucet appended to but
1198 /// did not create is never collected.
1199 ///
1200 /// Called after the run (and by `faucet cleanup`), never on the data path, so
1201 /// an implementation may take a lock. Decorating sinks **must forward** this
1202 /// to their inner sink, exactly as they do
1203 /// [`dataset_uri`](Self::dataset_uri) — a decorator that returns the default
1204 /// hides its inner sink's files from the GC and they are never reclaimed.
1205 async fn local_outputs(&self) -> Vec<crate::local_outputs::LocalOutput> {
1206 Vec::new()
1207 }
1208
1209 /// Run a fast, non-mutating preflight probe (used by `faucet doctor`).
1210 ///
1211 /// Unlike sources, a sink has no non-mutating "first page" equivalent
1212 /// (`write_batch` mutates the destination), so the default returns
1213 /// [`CheckReport::not_implemented`](crate::check::CheckReport::not_implemented).
1214 /// Built-in sinks override this with a connect / auth / metadata probe.
1215 ///
1216 /// The probe **MUST be idempotent and side-effect-free** — no inserts, no
1217 /// residual rows or objects — and must never put credentials or connection
1218 /// strings in a probe `reason`/`hint`.
1219 async fn check(
1220 &self,
1221 _ctx: &crate::check::CheckContext,
1222 ) -> Result<crate::check::CheckReport, FaucetError> {
1223 Ok(crate::check::CheckReport::not_implemented())
1224 }
1225}
1226
1227#[allow(deprecated)] // the tests drive the 1.x lifecycle hooks directly (RFC 0014)
1228#[cfg(test)]
1229mod tests {
1230 use super::*;
1231 use serde_json::json;
1232
1233 // ── Mock Source ──────────────────────────────────────────────────────────
1234
1235 struct MockSource {
1236 records: Vec<Value>,
1237 }
1238
1239 #[async_trait]
1240 impl Source for MockSource {
1241 async fn fetch_with_context(
1242 &self,
1243 _context: &std::collections::HashMap<String, Value>,
1244 ) -> Result<Vec<Value>, FaucetError> {
1245 Ok(self.records.clone())
1246 }
1247 }
1248
1249 #[test]
1250 fn default_migrate_state_accepts_only_its_own_schema() {
1251 let src = MockSource { records: vec![] };
1252 assert_eq!(src.state_schema(), 0);
1253 assert_eq!(
1254 src.migrate_state(0, json!({"id": 1})).unwrap(),
1255 json!({"id": 1})
1256 );
1257 let err = src.migrate_state(3, json!({})).unwrap_err().to_string();
1258 assert!(
1259 err.contains("no migration from bookmark schema 3 to 0"),
1260 "{err}"
1261 );
1262 }
1263
1264 #[test]
1265 fn default_multi_table_hooks_route_nothing_and_order_nothing() {
1266 let src = MockSource { records: vec![] };
1267 assert_eq!(src.record_table(&json!({"table": "t"})), None);
1268 assert_eq!(src.position_le(&json!(1), &json!(2)), None);
1269 assert_eq!(src.record_covered(&json!({}), &json!(1)), None);
1270 assert_eq!(src.position_min(&[]), None);
1271 assert_eq!(src.position_min(&[json!(3), json!(3)]), Some(json!(3)));
1272 assert_eq!(src.position_min(&[json!(1), json!(2)]), None);
1273 }
1274
1275 #[tokio::test]
1276 async fn ordered_double_fetches_nothing() {
1277 use crate::Source as _;
1278 assert!(
1279 OrderedSource
1280 .fetch_with_context(&Default::default())
1281 .await
1282 .unwrap()
1283 .is_empty()
1284 );
1285 }
1286
1287 struct OrderedSource;
1288
1289 #[async_trait]
1290 impl Source for OrderedSource {
1291 async fn fetch_with_context(
1292 &self,
1293 _context: &std::collections::HashMap<String, Value>,
1294 ) -> Result<Vec<Value>, FaucetError> {
1295 Ok(vec![])
1296 }
1297
1298 fn position_le(&self, a: &Value, b: &Value) -> Option<bool> {
1299 Some(a.as_u64()? <= b.as_u64()?)
1300 }
1301 }
1302
1303 #[test]
1304 fn default_position_min_uses_position_le() {
1305 let src = OrderedSource;
1306 assert_eq!(
1307 src.position_min(&[json!(5), json!(2), json!(9)]),
1308 Some(json!(2))
1309 );
1310 assert_eq!(src.position_min(&[json!(5), json!("x")]), None);
1311 }
1312
1313 struct IncrementalSource {
1314 records: Vec<Value>,
1315 bookmark: Value,
1316 }
1317
1318 #[async_trait]
1319 impl Source for IncrementalSource {
1320 async fn fetch_with_context(
1321 &self,
1322 _context: &std::collections::HashMap<String, Value>,
1323 ) -> Result<Vec<Value>, FaucetError> {
1324 Ok(self.records.clone())
1325 }
1326
1327 async fn fetch_with_context_incremental(
1328 &self,
1329 _context: &std::collections::HashMap<String, Value>,
1330 ) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
1331 Ok((self.records.clone(), Some(self.bookmark.clone())))
1332 }
1333 }
1334
1335 struct FailingSource;
1336
1337 #[async_trait]
1338 impl Source for FailingSource {
1339 async fn fetch_with_context(
1340 &self,
1341 _context: &std::collections::HashMap<String, Value>,
1342 ) -> Result<Vec<Value>, FaucetError> {
1343 Err(FaucetError::Auth("no credentials".into()))
1344 }
1345 }
1346
1347 // ── Mock Sink ───────────────────────────────────────────────────────────
1348
1349 struct MockSink {
1350 written: std::sync::Mutex<Vec<Value>>,
1351 }
1352
1353 impl MockSink {
1354 fn new() -> Self {
1355 Self {
1356 written: std::sync::Mutex::new(Vec::new()),
1357 }
1358 }
1359 }
1360
1361 #[async_trait]
1362 impl Sink for MockSink {
1363 async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
1364 let mut w = self.written.lock().unwrap();
1365 w.extend(records.iter().cloned());
1366 Ok(records.len())
1367 }
1368 }
1369
1370 struct FailingSink;
1371
1372 #[async_trait]
1373 impl Sink for FailingSink {
1374 async fn write_batch(&self, _records: &[Value]) -> Result<usize, FaucetError> {
1375 Err(FaucetError::Sink("write failed".into()))
1376 }
1377 }
1378
1379 // ── Native byte-passthrough defaults (#633) ──────────────────────────────
1380
1381 /// A source/sink pair that advertises nothing native, so the defaulted
1382 /// trait methods are what answer.
1383 struct PlainSink;
1384
1385 #[async_trait]
1386 impl Sink for PlainSink {
1387 async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
1388 Ok(records.len())
1389 }
1390 }
1391
1392 #[tokio::test]
1393 async fn native_defaults_advertise_nothing_and_fail_loudly() {
1394 use futures::StreamExt as _;
1395
1396 // A source that never overrides the native methods advertises no
1397 // formats, so the pipeline can never negotiate the byte path…
1398 let src = MockSource { records: vec![] };
1399 assert!(src.native_output_formats().is_empty());
1400 // …and calling it anyway yields one typed error rather than silently
1401 // producing an empty stream (which would look like "no rows").
1402 let ctx = std::collections::HashMap::new();
1403 let mut batches = src.stream_native(&ctx, crate::native::NativeFormat::NdJson, 10);
1404 let err = batches
1405 .next()
1406 .await
1407 .expect("one item")
1408 .expect_err("default must error");
1409 assert!(
1410 err.to_string()
1411 .contains("does not support native byte streaming"),
1412 "{err}"
1413 );
1414 assert!(batches.next().await.is_none(), "exactly one item");
1415
1416 // Same on the sink side: no capabilities, and `load_native` is a typed
1417 // error so a sink that advertises but forgets to implement is obvious.
1418 let sink = PlainSink;
1419 assert!(sink.native_load_capabilities().is_empty());
1420 let err = sink
1421 .load_native(
1422 crate::native::NativeBatch::bytes(
1423 crate::native::NativeFormat::NdJson,
1424 b"{}\n".to_vec(),
1425 ),
1426 "scope",
1427 crate::native::NativeLoadContext {
1428 write_mode: crate::write_mode::WriteMode::Append,
1429 first_batch: true,
1430 },
1431 )
1432 .await
1433 .expect_err("default must error");
1434 assert!(
1435 err.to_string()
1436 .contains("does not support native byte loading"),
1437 "{err}"
1438 );
1439 }
1440
1441 #[tokio::test]
1442 async fn default_rollback_and_readback_hooks() {
1443 let sink = MockSink::new();
1444 assert!(!sink.supports_rollback());
1445 let opts = crate::rollback::RollbackOptions {
1446 run_id_column: "_faucet_run_id".into(),
1447 mode: crate::rollback::RollbackMode::Append,
1448 force: false,
1449 dry_run: false,
1450 later_runs: false,
1451 };
1452 let err = sink.rollback_run("r1", &opts).await.unwrap_err();
1453 assert!(
1454 err.to_string().contains("does not support rollback"),
1455 "{err}"
1456 );
1457 assert!(sink.forget_run("r1").await.is_ok());
1458 let err = sink.rewind_commit_token("s", None).await.unwrap_err();
1459 assert!(err.to_string().contains("commit token"), "{err}");
1460 assert!(sink.readback_source().is_none());
1461 let source = MockSource { records: vec![] };
1462 let digest = source
1463 .range_digest(&crate::diff::KeyRange::ALL, "id", &["v".into()])
1464 .await
1465 .unwrap();
1466 assert!(digest.is_none(), "not supported by default");
1467 }
1468
1469 #[tokio::test]
1470 async fn default_overwrite_methods_reject_or_noop() {
1471 // A sink that does not opt into overwrite (MockSink uses the defaults):
1472 // `is_overwrite` is false, begin/commit return the typed "unsupported"
1473 // error, and abort is a no-op success.
1474 let sink = MockSink::new();
1475 assert!(!sink.is_overwrite());
1476 assert!(sink.begin_overwrite().await.is_err());
1477 assert!(sink.commit_overwrite().await.is_err());
1478 assert!(sink.abort_overwrite().await.is_ok());
1479 assert_eq!(sink.overwrite_staging_exists().await.unwrap(), None);
1480 }
1481
1482 // ── Source tests ────────────────────────────────────────────────────────
1483
1484 #[tokio::test]
1485 async fn source_fetch_all_returns_records() {
1486 let source = MockSource {
1487 records: vec![json!({"id": 1}), json!({"id": 2})],
1488 };
1489 let records = source.fetch_all().await.unwrap();
1490 assert_eq!(records.len(), 2);
1491 assert_eq!(records[0]["id"], 1);
1492 }
1493
1494 #[tokio::test]
1495 async fn source_fetch_all_empty() {
1496 let source = MockSource { records: vec![] };
1497 let records = source.fetch_all().await.unwrap();
1498 assert!(records.is_empty());
1499 }
1500
1501 #[tokio::test]
1502 async fn source_default_incremental_returns_none_bookmark() {
1503 let source = MockSource {
1504 records: vec![json!({"id": 1})],
1505 };
1506 let (records, bookmark) = source.fetch_all_incremental().await.unwrap();
1507 assert_eq!(records.len(), 1);
1508 assert!(bookmark.is_none());
1509 }
1510
1511 #[tokio::test]
1512 async fn source_custom_incremental_returns_bookmark() {
1513 let source = IncrementalSource {
1514 records: vec![json!({"id": 1})],
1515 bookmark: json!("2024-12-01"),
1516 };
1517 let (records, bookmark) = source.fetch_all_incremental().await.unwrap();
1518 assert_eq!(records.len(), 1);
1519 assert_eq!(bookmark, Some(json!("2024-12-01")));
1520 }
1521
1522 #[tokio::test]
1523 async fn source_error_propagates() {
1524 let source = FailingSource;
1525 let result = source.fetch_all().await;
1526 assert!(result.is_err());
1527 assert!(matches!(result, Err(FaucetError::Auth(_))));
1528 }
1529
1530 #[tokio::test]
1531 async fn source_as_trait_object() {
1532 let source: Box<dyn Source> = Box::new(MockSource {
1533 records: vec![json!({"id": 42})],
1534 });
1535 let records = source.fetch_all().await.unwrap();
1536 assert_eq!(records[0]["id"], 42);
1537 }
1538
1539 // ── Sink tests ──────────────────────────────────────────────────────────
1540
1541 #[tokio::test]
1542 async fn sink_write_batch_returns_count() {
1543 let sink = MockSink::new();
1544 let records = vec![json!({"id": 1}), json!({"id": 2}), json!({"id": 3})];
1545 let count = sink.write_batch(&records).await.unwrap();
1546 assert_eq!(count, 3);
1547 }
1548
1549 #[tokio::test]
1550 async fn sink_write_batch_empty() {
1551 let sink = MockSink::new();
1552 let count = sink.write_batch(&[]).await.unwrap();
1553 assert_eq!(count, 0);
1554 }
1555
1556 #[tokio::test]
1557 async fn sink_accumulates_records() {
1558 let sink = MockSink::new();
1559 sink.write_batch(&[json!({"a": 1})]).await.unwrap();
1560 sink.write_batch(&[json!({"b": 2})]).await.unwrap();
1561 let written = sink.written.lock().unwrap();
1562 assert_eq!(written.len(), 2);
1563 }
1564
1565 #[tokio::test]
1566 async fn sink_default_flush_is_noop() {
1567 let sink = MockSink::new();
1568 assert!(sink.flush().await.is_ok());
1569 }
1570
1571 #[tokio::test]
1572 async fn sink_error_propagates() {
1573 let sink = FailingSink;
1574 let result = sink.write_batch(&[json!({"id": 1})]).await;
1575 assert!(result.is_err());
1576 assert!(matches!(result, Err(FaucetError::Sink(_))));
1577 }
1578
1579 #[tokio::test]
1580 async fn sink_as_trait_object() {
1581 let sink: Box<dyn Sink> = Box::new(MockSink::new());
1582 let count = sink.write_batch(&[json!({"id": 1})]).await.unwrap();
1583 assert_eq!(count, 1);
1584 }
1585
1586 // ── stream_pages tests ──────────────────────────────────────────────────
1587
1588 use crate::pipeline::DEFAULT_BATCH_SIZE;
1589 use futures::StreamExt;
1590
1591 #[tokio::test]
1592 async fn default_stream_pages_chunks_records() {
1593 let source = MockSource {
1594 records: (0..5).map(|i| json!({"i": i})).collect(),
1595 };
1596 let ctx = std::collections::HashMap::new();
1597 let mut pages = source.stream_pages(&ctx, 2);
1598 let mut all = Vec::new();
1599 while let Some(page) = pages.next().await {
1600 all.push(page.unwrap());
1601 }
1602 // 5 records, batch_size=2 → pages of [2, 2, 1]
1603 assert_eq!(all.len(), 3);
1604 assert_eq!(all[0].records.len(), 2);
1605 assert_eq!(all[1].records.len(), 2);
1606 assert_eq!(all[2].records.len(), 1);
1607 }
1608
1609 #[tokio::test]
1610 async fn default_stream_pages_attaches_bookmark_to_final_page_only() {
1611 let source = IncrementalSource {
1612 records: (0..5).map(|i| json!({"i": i})).collect(),
1613 bookmark: json!("v1"),
1614 };
1615 let ctx = std::collections::HashMap::new();
1616 let mut pages = source.stream_pages(&ctx, 2);
1617 let mut collected = Vec::new();
1618 while let Some(page) = pages.next().await {
1619 collected.push(page.unwrap());
1620 }
1621 assert_eq!(collected.len(), 3);
1622 assert!(collected[0].bookmark.is_none());
1623 assert!(collected[1].bookmark.is_none());
1624 assert_eq!(collected[2].bookmark, Some(json!("v1")));
1625 }
1626
1627 #[tokio::test]
1628 async fn default_stream_pages_single_page_when_batch_size_exceeds_total() {
1629 let source = MockSource {
1630 records: vec![json!({"id": 1}), json!({"id": 2})],
1631 };
1632 let ctx = std::collections::HashMap::new();
1633 let mut pages = source.stream_pages(&ctx, 100);
1634 let mut collected = Vec::new();
1635 while let Some(page) = pages.next().await {
1636 collected.push(page.unwrap());
1637 }
1638 assert_eq!(collected.len(), 1);
1639 assert_eq!(collected[0].records.len(), 2);
1640 }
1641
1642 #[tokio::test]
1643 async fn default_stream_pages_batch_size_zero_emits_single_page() {
1644 // batch_size = 0 is the "no batching" sentinel — yields every record
1645 // in one page regardless of total count.
1646 let source = MockSource {
1647 records: (0..50_000).map(|i| json!({"i": i})).collect(),
1648 };
1649 let ctx = std::collections::HashMap::new();
1650 let mut pages = source.stream_pages(&ctx, 0);
1651 let mut collected = Vec::new();
1652 while let Some(page) = pages.next().await {
1653 collected.push(page.unwrap());
1654 }
1655 assert_eq!(
1656 collected.len(),
1657 1,
1658 "batch_size=0 must emit exactly one page"
1659 );
1660 assert_eq!(collected[0].records.len(), 50_000);
1661 }
1662
1663 #[tokio::test]
1664 async fn default_stream_pages_batch_size_zero_attaches_bookmark_to_sole_page() {
1665 let source = IncrementalSource {
1666 records: (0..3).map(|i| json!({"i": i})).collect(),
1667 bookmark: json!("v1"),
1668 };
1669 let ctx = std::collections::HashMap::new();
1670 let mut pages = source.stream_pages(&ctx, 0);
1671 let page = pages.next().await.unwrap().unwrap();
1672 assert_eq!(page.records.len(), 3);
1673 assert_eq!(page.bookmark, Some(json!("v1")));
1674 assert!(pages.next().await.is_none());
1675 }
1676
1677 #[tokio::test]
1678 async fn default_stream_pages_empty_source_yields_no_pages() {
1679 let source = MockSource { records: vec![] };
1680 let ctx = std::collections::HashMap::new();
1681 let mut pages = source.stream_pages(&ctx, DEFAULT_BATCH_SIZE);
1682 assert!(pages.next().await.is_none());
1683 }
1684
1685 #[tokio::test]
1686 async fn default_stream_pages_empty_source_with_bookmark_yields_single_empty_page() {
1687 let source = IncrementalSource {
1688 records: vec![],
1689 bookmark: json!("v0"),
1690 };
1691 let ctx = std::collections::HashMap::new();
1692 let mut pages = source.stream_pages(&ctx, DEFAULT_BATCH_SIZE);
1693 let mut collected = Vec::new();
1694 while let Some(page) = pages.next().await {
1695 collected.push(page.unwrap());
1696 }
1697 // One empty-records page that carries the bookmark, so the pipeline
1698 // still persists progress on otherwise-empty incremental runs.
1699 assert_eq!(collected.len(), 1);
1700 assert!(collected[0].records.is_empty());
1701 assert_eq!(collected[0].bookmark, Some(json!("v0")));
1702 }
1703
1704 #[tokio::test]
1705 async fn default_stream_pages_propagates_fetch_errors() {
1706 let source = FailingSource;
1707 let ctx = std::collections::HashMap::new();
1708 let mut pages = source.stream_pages(&ctx, DEFAULT_BATCH_SIZE);
1709 let first = pages.next().await.unwrap();
1710 assert!(matches!(first, Err(FaucetError::Auth(_))));
1711 }
1712
1713 #[test]
1714 fn source_default_connector_name_is_stripped_type_name() {
1715 // MockSource lives at `faucet_core::traits::tests::MockSource`; the
1716 // stripped type_name yields the trailing segment.
1717 let source = MockSource { records: vec![] };
1718 assert_eq!(source.connector_name(), "MockSource");
1719 }
1720
1721 #[test]
1722 fn sink_default_connector_name_is_stripped_type_name() {
1723 let sink = MockSink::new();
1724 assert_eq!(sink.connector_name(), "MockSink");
1725 }
1726
1727 #[test]
1728 fn source_default_dataset_uri_uses_connector_name() {
1729 let source = MockSource { records: vec![] };
1730 assert_eq!(source.dataset_uri(), "MockSource://unknown");
1731 }
1732
1733 #[test]
1734 fn sink_default_dataset_uri_uses_connector_name() {
1735 let sink = MockSink::new();
1736 assert_eq!(sink.dataset_uri(), "MockSink://unknown");
1737 }
1738
1739 // ── write_batch_partial tests ───────────────────────────────────────────
1740
1741 #[tokio::test]
1742 async fn default_write_batch_partial_success_returns_all_ok() {
1743 let sink = MockSink::new();
1744 let records = vec![json!({"id": 1}), json!({"id": 2}), json!({"id": 3})];
1745 let outcomes = sink.write_batch_partial(&records).await.unwrap();
1746 assert_eq!(outcomes.len(), 3);
1747 assert!(outcomes.iter().all(|o| o.is_ok()));
1748 assert_eq!(sink.written.lock().unwrap().len(), 3);
1749 }
1750
1751 #[tokio::test]
1752 async fn default_write_batch_partial_bubbles_outer_err() {
1753 let sink = FailingSink;
1754 let records = vec![json!({"id": 1}), json!({"id": 2})];
1755 let result = sink.write_batch_partial(&records).await;
1756 assert!(matches!(result, Err(FaucetError::Sink(_))));
1757 }
1758
1759 #[tokio::test]
1760 async fn default_write_batch_partial_empty_returns_empty_vec() {
1761 let sink = MockSink::new();
1762 let outcomes = sink.write_batch_partial(&[]).await.unwrap();
1763 assert!(outcomes.is_empty());
1764 }
1765
1766 #[tokio::test]
1767 async fn default_write_batch_partial_callable_through_trait_object() {
1768 let sink: Box<dyn Sink> = Box::new(MockSink::new());
1769 let records = vec![json!({"id": 1}), json!({"id": 2})];
1770 let outcomes = sink.write_batch_partial(&records).await.unwrap();
1771 assert_eq!(outcomes.len(), 2);
1772 assert!(outcomes.iter().all(|o| o.is_ok()));
1773 }
1774
1775 // ── check() tests ─────────────────────────────────────────────────────────
1776
1777 #[tokio::test]
1778 async fn source_default_check_pulls_first_page_and_passes() {
1779 let source = MockSource {
1780 records: vec![json!({"id": 1}), json!({"id": 2})],
1781 };
1782 let report = source
1783 .check(&crate::check::CheckContext::default())
1784 .await
1785 .unwrap();
1786 assert_eq!(report.failed_count(), 0);
1787 assert!(
1788 report
1789 .probes
1790 .iter()
1791 .any(|p| p.name == "read" && matches!(p.status, crate::check::ProbeStatus::Pass))
1792 );
1793 }
1794
1795 #[tokio::test]
1796 async fn source_default_check_passes_on_empty_source() {
1797 let source = MockSource { records: vec![] };
1798 let report = source
1799 .check(&crate::check::CheckContext::default())
1800 .await
1801 .unwrap();
1802 // Reachable but empty is still a healthy source.
1803 assert_eq!(report.failed_count(), 0);
1804 }
1805
1806 #[tokio::test]
1807 async fn source_default_check_fails_when_fetch_errors() {
1808 let source = FailingSource;
1809 let report = source
1810 .check(&crate::check::CheckContext::default())
1811 .await
1812 .unwrap();
1813 assert_eq!(report.failed_count(), 1);
1814 assert!(report.probes.iter().any(
1815 |p| p.name == "read" && matches!(p.status, crate::check::ProbeStatus::Fail { .. })
1816 ));
1817 }
1818
1819 #[tokio::test]
1820 async fn sink_default_check_is_not_implemented_skip() {
1821 let sink = MockSink::new();
1822 let report = sink
1823 .check(&crate::check::CheckContext::default())
1824 .await
1825 .unwrap();
1826 assert_eq!(report.probes.len(), 1);
1827 assert!(matches!(
1828 report.probes[0].status,
1829 crate::check::ProbeStatus::Skip { .. }
1830 ));
1831 }
1832
1833 #[tokio::test]
1834 async fn source_check_callable_through_trait_object() {
1835 let source: Box<dyn Source> = Box::new(MockSource {
1836 records: vec![json!({"id": 1})],
1837 });
1838 let report = source
1839 .check(&crate::check::CheckContext::default())
1840 .await
1841 .unwrap();
1842 assert_eq!(report.failed_count(), 0);
1843 }
1844
1845 // ── idempotent-write / exactly-once capability tests ──────────────────────
1846
1847 #[tokio::test]
1848 async fn sink_default_is_not_idempotent() {
1849 let sink = MockSink::new();
1850 assert!(!sink.supports_idempotent_writes());
1851 // Default write_batch_idempotent ignores the token and delegates.
1852 let n = sink
1853 .write_batch_idempotent(&[json!({"id": 1})], "scope::a", "00000000000000000001")
1854 .await
1855 .unwrap();
1856 assert_eq!(n, 1);
1857 assert_eq!(sink.last_committed_token("scope::a").await.unwrap(), None);
1858 assert_eq!(sink.written.lock().unwrap().len(), 1);
1859 }
1860
1861 #[test]
1862 fn source_default_does_not_support_exactly_once() {
1863 let source = MockSource { records: vec![] };
1864 assert!(!source.supports_exactly_once());
1865 }
1866
1867 #[test]
1868 fn sink_default_supported_write_modes_is_append_only() {
1869 use crate::write_mode::WriteMode;
1870 let sink = MockSink::new();
1871 assert_eq!(sink.supported_write_modes(), &[WriteMode::Append]);
1872 }
1873
1874 #[test]
1875 fn supported_write_modes_callable_through_trait_object() {
1876 use crate::write_mode::WriteMode;
1877 let sink: Box<dyn Sink> = Box::new(MockSink::new());
1878 assert!(sink.supported_write_modes().contains(&WriteMode::Append));
1879 }
1880
1881 #[tokio::test]
1882 async fn sink_default_current_schema_is_none() {
1883 let sink = MockSink::new();
1884 assert_eq!(sink.current_schema().await.unwrap(), None);
1885 }
1886
1887 #[test]
1888 fn sink_default_does_not_support_schema_evolution() {
1889 let sink = MockSink::new();
1890 assert!(!sink.supports_schema_evolution());
1891 }
1892
1893 #[tokio::test]
1894 async fn sink_default_evolve_schema_is_unsupported_error() {
1895 let sink = MockSink::new();
1896 let evo = crate::drift::SchemaEvolution::default();
1897 let err = sink.evolve_schema(&evo).await.unwrap_err();
1898 assert!(matches!(err, FaucetError::Sink(_)));
1899 assert!(err.to_string().contains("schema evolution"));
1900 }
1901
1902 #[tokio::test]
1903 async fn source_default_capture_resume_position_is_none() {
1904 let source = MockSource { records: vec![] };
1905 assert_eq!(source.capture_resume_position().await.unwrap(), None);
1906 }
1907
1908 #[tokio::test]
1909 async fn capture_resume_position_callable_through_trait_object() {
1910 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1911 assert!(source.capture_resume_position().await.unwrap().is_none());
1912 }
1913
1914 #[tokio::test]
1915 async fn source_default_does_not_support_discover() {
1916 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1917 assert!(!source.supports_discover());
1918 let err = source.discover().await.unwrap_err();
1919 assert!(matches!(err, FaucetError::Source(_)));
1920 assert!(
1921 err.to_string().contains("dataset discovery"),
1922 "typed unsupported error: {err}"
1923 );
1924 }
1925
1926 #[tokio::test]
1927 async fn source_default_is_not_shardable() {
1928 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1929 assert!(!source.is_shardable());
1930 }
1931
1932 #[tokio::test]
1933 async fn source_default_enumerates_single_whole_shard() {
1934 // A non-shardable source enumerates to exactly one whole-dataset shard,
1935 // regardless of the requested target — preserving single-worker behavior.
1936 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1937 let shards = source.enumerate_shards(8).await.unwrap();
1938 assert_eq!(shards.len(), 1);
1939 assert!(shards[0].is_whole());
1940 }
1941
1942 #[tokio::test]
1943 async fn source_default_apply_shard_is_noop() {
1944 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1945 // Applying the whole shard is a no-op and must not error.
1946 source
1947 .apply_shard(&crate::shard::ShardSpec::whole())
1948 .await
1949 .unwrap();
1950 }
1951}