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 /// Return a JSON Schema describing the configuration this source accepts.
154 fn config_schema(&self) -> Value {
155 serde_json::json!({"type": "object", "properties": {}})
156 }
157
158 /// Stable key under which this source's incremental-replication bookmark
159 /// should be persisted in a [`StateStore`](crate::state::StateStore).
160 ///
161 /// Returning `Some(key)` opts this source into resumable runs: when the
162 /// pipeline is configured with a state store via
163 /// [`Pipeline::with_state_store`](crate::Pipeline::with_state_store), it
164 /// reads the bookmark at `key` before fetching and writes the new
165 /// bookmark back only after the sink confirms the batch was written.
166 ///
167 /// The default returns `None`, meaning the source is not persisted.
168 /// Keys must satisfy [`validate_state_key`](crate::state::validate_state_key).
169 fn state_key(&self) -> Option<String> {
170 None
171 }
172
173 /// Apply a bookmark loaded from a [`StateStore`](crate::state::StateStore)
174 /// as this run's starting point.
175 ///
176 /// The default implementation ignores the value, which keeps existing
177 /// sources backwards-compatible. Sources that support incremental
178 /// replication override this — typically by storing the value behind
179 /// interior mutability and consulting it inside
180 /// `fetch_with_context_incremental`.
181 async fn apply_start_bookmark(&self, _bookmark: Value) -> Result<(), FaucetError> {
182 Ok(())
183 }
184
185 /// Capture the source's current replication position **without consuming
186 /// any changes**, ensuring any server-side resource (e.g. a logical
187 /// replication slot) needed to later resume from that position exists.
188 ///
189 /// Returns the position as a bookmark [`Value`] — the same shape
190 /// [`apply_start_bookmark`](Self::apply_start_bookmark) accepts — or `None`
191 /// if this source does not support position capture.
192 ///
193 /// Used by the snapshot→CDC replication orchestrator (`faucet replicate`)
194 /// to anchor the CDC stream at-or-before the bulk snapshot's read point so
195 /// the handoff has no gap. The default returns `None`.
196 async fn capture_resume_position(&self) -> Result<Option<Value>, FaucetError> {
197 Ok(None)
198 }
199
200 /// Whether this source **deterministically replays** the same page sequence
201 /// from a given bookmark — the requirement for the atomic-watermark
202 /// effectively-once path (a non-deterministic replay could cause the pipeline
203 /// to skip a page whose contents differ from the one already committed).
204 /// Default: `false`.
205 ///
206 /// Sources with a durable monotonic position and per-page bookmarks (CDC)
207 /// override this to return `true`. The pipeline rejects
208 /// `DeliveryMode::ExactlyOnce` against a source that returns `false`.
209 fn supports_exactly_once(&self) -> bool {
210 false
211 }
212
213 /// The typed replay capability this source advertises — see
214 /// [`ReplayGuarantee`](crate::ReplayGuarantee).
215 ///
216 /// The default derives from [`supports_exactly_once`](Self::supports_exactly_once)
217 /// (the boolean stays the back-compat primitive: existing connectors that
218 /// override only the boolean automatically advertise `Deterministic`
219 /// here). Override this directly only to *diverge* from the boolean —
220 /// there is currently no reason to.
221 fn replay_guarantee(&self) -> crate::idempotency::ReplayGuarantee {
222 if self.supports_exactly_once() {
223 crate::idempotency::ReplayGuarantee::Deterministic
224 } else {
225 crate::idempotency::ReplayGuarantee::NonDeterministic
226 }
227 }
228
229 /// Whether this source can split its work into independent shards for
230 /// clustered (Mode B) execution. Default: `false` (single whole-dataset
231 /// shard). Sources with a natural partition (object-store prefixes, table
232 /// primary-key ranges) override this to `true` and implement
233 /// [`enumerate_shards`](Self::enumerate_shards) +
234 /// [`apply_shard`](Self::apply_shard).
235 fn is_shardable(&self) -> bool {
236 false
237 }
238
239 /// Enumerate the shards this source splits into, aiming for roughly `target`
240 /// of them (a hint — the source may return fewer, e.g. when the dataset is
241 /// small, or one per natural partition regardless of `target`).
242 ///
243 /// Called **once per run** by the cluster coordinator; enumeration must be
244 /// deterministic enough that re-enumeration yields a compatible set (stable
245 /// shard ids), since it may run on more than one instance and is reconciled
246 /// by idempotent insert. May perform read-only I/O (a `LIST`, a `MIN/MAX`
247 /// query). The default returns a single whole-dataset shard
248 /// ([`ShardSpec::whole`](crate::ShardSpec::whole)), preserving today's
249 /// single-worker behavior.
250 async fn enumerate_shards(
251 &self,
252 _target: usize,
253 ) -> Result<Vec<crate::shard::ShardSpec>, FaucetError> {
254 Ok(vec![crate::shard::ShardSpec::whole()])
255 }
256
257 /// Narrow this source instance to a single shard before streaming.
258 ///
259 /// Called on the worker that claims `shard`, after construction and before
260 /// any `stream_pages` call. Like [`apply_start_bookmark`](Self::apply_start_bookmark)
261 /// this takes `&self` and is expected to record the shard behind interior
262 /// mutability (the source consults it when building its query / listing).
263 /// The default ignores the shard — a non-shardable source only ever receives
264 /// [`ShardSpec::whole`](crate::ShardSpec::whole), so ignoring it streams the
265 /// whole dataset. Implementations should accept the whole shard as a no-op.
266 async fn apply_shard(&self, _shard: &crate::shard::ShardSpec) -> Result<(), FaucetError> {
267 Ok(())
268 }
269
270 /// Whether this source can enumerate the datasets behind its connection
271 /// via [`discover`](Self::discover). Default: `false`. Sources backed by
272 /// an introspectable catalog (database `information_schema`, MongoDB
273 /// collections, Elasticsearch indices, object-store prefixes) override
274 /// this to `true`.
275 fn supports_discover(&self) -> bool {
276 false
277 }
278
279 /// Enumerate the datasets living behind this source's connection — one
280 /// [`DatasetDescriptor`](crate::discover::DatasetDescriptor) per table /
281 /// collection / index / prefix, each carrying a partial config override
282 /// that selects it (used by `faucet discover` to scaffold one matrix row
283 /// per dataset).
284 ///
285 /// Must be **read-only and cheap**: catalog metadata queries and listings
286 /// only, never a data scan. Descriptors must never embed credentials.
287 /// The default returns a typed "unsupported" error; override it (and
288 /// return `true` from [`supports_discover`](Self::supports_discover))
289 /// only for sources with a real catalog to introspect.
290 async fn discover(&self) -> Result<Vec<crate::discover::DatasetDescriptor>, FaucetError> {
291 Err(FaucetError::Source(format!(
292 "source '{}' does not support dataset discovery",
293 self.connector_name()
294 )))
295 }
296
297 /// Stable identifier used as the `connector` label on metrics and the
298 /// `connector` attribute on spans. Defaults to the final segment of
299 /// `std::any::type_name::<Self>()`, e.g. `"RestSource"`. Built-in
300 /// connectors override with a short, friendly snake_case name (e.g.
301 /// `"rest"`). Must return a non-empty string; observability decorators
302 /// fall back to `"unknown"` in release builds if it is empty (and
303 /// `debug_assert!` in debug builds).
304 fn connector_name(&self) -> &'static str {
305 crate::observability::strip_type_name(std::any::type_name::<Self>())
306 }
307
308 /// Logical dataset identity for lineage emission, following OpenLineage
309 /// naming conventions (<https://openlineage.io/docs/spec/naming>).
310 ///
311 /// The default returns `"<connector_name>://unknown"`. Built-in connectors
312 /// override with a credential-free URI derived from their config. Strip any
313 /// credentials with [`redact_uri_credentials`](crate::redact_uri_credentials).
314 /// Informational metadata only — never used for I/O.
315 fn dataset_uri(&self) -> String {
316 format!("{}://unknown", self.connector_name())
317 }
318
319 /// Run a fast, non-mutating preflight probe (used by `faucet doctor`).
320 ///
321 /// The default pulls a **single page** via
322 /// [`stream_pages`](Self::stream_pages) and reports success/failure — it
323 /// exercises the real read path (DNS, TLS, auth, the first request, the
324 /// first-record decode) but never paginates the full dataset and never
325 /// repeats. The page stream is dropped immediately after the first page.
326 ///
327 /// Sources whose first page *blocks* waiting for inbound data (webhook,
328 /// websocket) or has *side effects* (CDC consuming WAL) override this with a
329 /// cheaper, side-effect-free probe. Probe-level failures are returned as a
330 /// [`ProbeStatus::Fail`](crate::check::ProbeStatus) inside `Ok(report)`.
331 async fn check(
332 &self,
333 ctx: &crate::check::CheckContext,
334 ) -> Result<crate::check::CheckReport, FaucetError> {
335 use crate::check::{CheckReport, Probe};
336 use futures::StreamExt;
337
338 let empty = std::collections::HashMap::new();
339 let start = std::time::Instant::now();
340 let mut pages = self.stream_pages(&empty, 1);
341 let probe = match tokio::time::timeout(ctx.timeout, pages.next()).await {
342 Err(_) => Probe::fail("read", start.elapsed(), "timed out fetching first page"),
343 Ok(None) | Ok(Some(Ok(_))) => Probe::pass("read", start.elapsed()),
344 Ok(Some(Err(e))) => Probe::fail("read", start.elapsed(), e.to_string()),
345 };
346 Ok(CheckReport::single(probe))
347 }
348}
349
350/// Per-row outcome from [`Sink::write_batch_partial`].
351///
352/// `Ok(())` — the row was durably written to the sink.
353/// `Err(_)` — the row failed; the pipeline will route it to the DLQ when
354/// one is configured.
355pub type RowOutcome = Result<(), FaucetError>;
356
357/// A sink writes records to an external system.
358#[async_trait]
359pub trait Sink: Send + Sync {
360 /// Write a batch of records to the destination.
361 ///
362 /// Returns the number of records successfully written.
363 async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError>;
364
365 /// Flush any buffered data to the destination.
366 ///
367 /// The default implementation is a no-op (suitable for sinks that
368 /// write immediately in `write_batch`).
369 async fn flush(&self) -> Result<(), FaucetError> {
370 Ok(())
371 }
372
373 /// Write a batch and report per-row outcomes.
374 ///
375 /// Sinks whose underlying API exposes per-row results (BigQuery
376 /// `insertAll`, Elasticsearch `_bulk`) override this. The default
377 /// implementation delegates to [`Self::write_batch`] and maps a single success
378 /// onto a uniform all-`Ok(())` vector. An outer failure is bubbled up
379 /// unchanged so the pipeline's DLQ router can apply its `on_batch_error`
380 /// policy at a single decision point.
381 async fn write_batch_partial(&self, records: &[Value]) -> Result<Vec<RowOutcome>, FaucetError> {
382 self.write_batch(records).await?;
383 Ok(records.iter().map(|_| Ok(())).collect())
384 }
385
386 /// Whether this sink can consume **columnar** (`arrow::RecordBatch`) writes
387 /// via [`write_batch_columnar`](Self::write_batch_columnar) without first
388 /// converting to `Value`. Default: `false`.
389 ///
390 /// The pipeline takes the columnar fast path only when *both* the source and
391 /// sink return `true` (RFC 0002 / #375).
392 #[cfg(feature = "arrow")]
393 fn supports_columnar(&self) -> bool {
394 false
395 }
396
397 /// Write a columnar `RecordBatch` to the destination, returning the number of
398 /// rows written.
399 ///
400 /// The default converts the batch to `Value` rows via the
401 /// [`columnar`](crate::columnar) shim and delegates to
402 /// [`write_batch`](Self::write_batch), so every sink participates correctly
403 /// even without a native columnar path. Sinks that write Arrow/Parquet
404 /// directly override this — and return `true` from
405 /// [`supports_columnar`](Self::supports_columnar) — to skip the conversion.
406 #[cfg(feature = "arrow")]
407 async fn write_batch_columnar(
408 &self,
409 batch: &arrow::array::RecordBatch,
410 ) -> Result<usize, FaucetError> {
411 let rows = crate::columnar::record_batch_to_values(batch)?;
412 self.write_batch(&rows).await
413 }
414
415 /// Whether this sink can durably commit a page's rows **and** a commit token
416 /// in a single atomic transaction. Default: `false` (at-least-once only).
417 ///
418 /// Only return `true` from a sink that genuinely commits both atomically —
419 /// see [`write_batch_idempotent`](Self::write_batch_idempotent). The pipeline
420 /// rejects `DeliveryMode::ExactlyOnce` against a sink that returns `false`.
421 fn supports_idempotent_writes(&self) -> bool {
422 false
423 }
424
425 /// The strongest delivery guarantee this sink can uphold — see
426 /// [`SinkGuarantee`](crate::SinkGuarantee).
427 ///
428 /// The default derives from the two back-compat primitives:
429 /// [`supports_idempotent_writes`](Self::supports_idempotent_writes) →
430 /// `AtomicWatermark`, else an upsert-capable
431 /// [`supported_write_modes`](Self::supported_write_modes) → `KeyedUpsert`,
432 /// else `AtLeastOnce`. Existing connectors that override only the
433 /// primitives automatically advertise the right capability here.
434 fn sink_guarantee(&self) -> crate::idempotency::SinkGuarantee {
435 if self.supports_idempotent_writes() {
436 crate::idempotency::SinkGuarantee::AtomicWatermark
437 } else if self
438 .supported_write_modes()
439 .contains(&crate::write_mode::WriteMode::Upsert)
440 {
441 crate::idempotency::SinkGuarantee::KeyedUpsert
442 } else {
443 crate::idempotency::SinkGuarantee::AtLeastOnce
444 }
445 }
446
447 /// Whether this sink instance is **configured** to dedup by key — i.e.
448 /// `write_mode: upsert` (or `delete`) with a non-empty `key`, so
449 /// re-applying a record with the same key converges instead of
450 /// duplicating. Default: `false`.
451 ///
452 /// Distinct from [`sink_guarantee`](Self::sink_guarantee) (capability):
453 /// this reflects the *live config*. Sinks that flatten a
454 /// [`WriteSpec`](crate::write_mode::WriteSpec) into their config override
455 /// it as `self.config.write.dedups_by_key()`. The pipeline consults it to
456 /// derive the keyed-upsert effectively-once mechanism at run time.
457 fn dedups_by_key(&self) -> bool {
458 false
459 }
460
461 /// Write modes this sink can apply. Default: append-only. Sinks that
462 /// implement key-based merge override this to include
463 /// [`WriteMode::Upsert`](crate::write_mode::WriteMode) /
464 /// [`WriteMode::Delete`](crate::write_mode::WriteMode). The CLI rejects a
465 /// configured mode that is not in this set at config-load time.
466 fn supported_write_modes(&self) -> &'static [crate::write_mode::WriteMode] {
467 &[crate::write_mode::WriteMode::Append]
468 }
469
470 /// The sink's live destination schema as an `infer_schema`-shaped object
471 /// (`{"type":"object","properties":{ <col>: <type-fragment>, … }}`), or
472 /// `None` for a schemaless sink or a target that does not exist yet.
473 ///
474 /// Used by the schema-drift policy to diff each page's shape against the
475 /// real destination. Default: `Ok(None)` (drift handling is inert).
476 async fn current_schema(&self) -> Result<Option<Value>, FaucetError> {
477 Ok(None)
478 }
479
480 /// Whether this sink can apply additive/widening DDL via
481 /// [`evolve_schema`](Self::evolve_schema). Default: `false`. The CLI rejects
482 /// `on_drift: evolve` against a sink that returns `false` at config-load.
483 fn supports_schema_evolution(&self) -> bool {
484 false
485 }
486
487 /// Apply an additive schema evolution (new columns, lossless widenings,
488 /// nullability relaxations) to the destination. MUST be idempotent
489 /// (`ADD COLUMN IF NOT EXISTS` semantics) so concurrent runs converge.
490 ///
491 /// Default: a typed "unsupported" error. Override only when the backend
492 /// supports in-place additive DDL (and return `true` from
493 /// `supports_schema_evolution`).
494 async fn evolve_schema(
495 &self,
496 evolution: &crate::drift::SchemaEvolution,
497 ) -> Result<(), FaucetError> {
498 let _ = evolution;
499 Err(FaucetError::Sink(format!(
500 "sink '{}' does not support schema evolution",
501 self.connector_name()
502 )))
503 }
504
505 /// Whether this sink can delete a scoped set of rows for scoped cleanup
506 /// (#478). Default `false`; the upsert-capable sinks override it.
507 fn supports_cleanup(&self) -> bool {
508 false
509 }
510
511 /// Whether this sink can bulk-load via an object-store stage — write the
512 /// page to S3/GCS/Azure, then pull it with the warehouse's native load
513 /// command (`COPY` / `COPY INTO` / `s3()` table function) (#528). Default
514 /// `false`; warehouse sinks that honour a [`StagingSpec`](crate::StagingSpec)
515 /// override it. Object-safe (no args, no generics) so `Box<dyn Sink>` is
516 /// unaffected.
517 fn supports_staged_load(&self) -> bool {
518 false
519 }
520
521 /// Delete rows matching `scope` whose key is **not** in `seen`.
522 ///
523 /// Called at most once per invocation, only after the run completed
524 /// successfully and uncancelled — see [`crate::cleanup`] for why the timing
525 /// is load-bearing. `scope` is a set of equality predicates in destination
526 /// column terms, AND-ed together; `seen` holds the key tuples this run wrote.
527 ///
528 /// Returns the number of rows deleted. Implementations **must** be
529 /// all-or-nothing where the backend allows it: a partial delete would remove
530 /// rows the run actually wrote.
531 ///
532 /// The default is a typed "unsupported" error, so no existing or third-party
533 /// connector breaks.
534 async fn cleanup_scope(
535 &self,
536 scope: &std::collections::BTreeMap<String, Value>,
537 seen: &crate::cleanup::SeenKeys,
538 ) -> Result<u64, FaucetError> {
539 let _ = (scope, seen);
540 Err(FaucetError::Sink(format!(
541 "sink '{}' does not support scoped cleanup",
542 self.connector_name()
543 )))
544 }
545
546 /// Write `records` AND durably record `token` for `scope`, atomically.
547 ///
548 /// `scope` namespaces the watermark (the pipeline passes the per-row state
549 /// key, e.g. `"{name}::{row_id}"`). `token` is a monotonic, fixed-width
550 /// string (see [`format_token`](crate::format_token)).
551 ///
552 /// The default is **not** idempotent: it ignores the token and delegates to
553 /// [`write_batch`](Self::write_batch). Override only when the commit is
554 /// genuinely atomic (and return `true` from `supports_idempotent_writes`).
555 async fn write_batch_idempotent(
556 &self,
557 records: &[Value],
558 scope: &str,
559 token: &str,
560 ) -> Result<usize, FaucetError> {
561 let _ = (scope, token);
562 self.write_batch(records).await
563 }
564
565 /// The last token durably committed for `scope`, or `None` if this sink has
566 /// never committed under that scope. Default: `None`.
567 async fn last_committed_token(&self, scope: &str) -> Result<Option<String>, FaucetError> {
568 let _ = scope;
569 Ok(None)
570 }
571
572 /// Whether this sink instance is configured for full-destination
573 /// replacement ([`WriteMode::Overwrite`](crate::write_mode::WriteMode)).
574 ///
575 /// The pipeline consults this to drive the overwrite lifecycle:
576 /// [`begin_overwrite`](Self::begin_overwrite) before the first page, then
577 /// [`commit_overwrite`](Self::commit_overwrite) once the run finishes
578 /// successfully, or [`abort_overwrite`](Self::abort_overwrite) on
579 /// failure/cancel. Sinks that flatten a [`WriteSpec`](crate::write_mode::WriteSpec)
580 /// into their config return `self.config.write.is_overwrite()`. Default `false`.
581 fn is_overwrite(&self) -> bool {
582 false
583 }
584
585 /// Prepare a staging target for an overwrite run.
586 ///
587 /// Called once, before the first [`write_batch`](Self::write_batch), only
588 /// when [`is_overwrite`](Self::is_overwrite) is true. The sink stages this
589 /// run's writes (a temp table / new index / temp prefix) so the existing
590 /// destination is untouched until the run succeeds. Subsequent
591 /// `write_batch` calls for this sink must land in the staging target.
592 ///
593 /// Default: a typed "unsupported" error, so a sink that advertises
594 /// `WriteMode::Overwrite` but forgets to implement the lifecycle fails
595 /// loudly rather than silently appending. Never called for sinks whose
596 /// `is_overwrite()` is false.
597 async fn begin_overwrite(&self) -> Result<(), FaucetError> {
598 Err(FaucetError::Sink(format!(
599 "sink '{}' does not support write_mode: overwrite",
600 self.connector_name()
601 )))
602 }
603
604 /// Atomically replace the destination with the staged data.
605 ///
606 /// Called **once, only after the run completed successfully and
607 /// uncancelled**. Implementations MUST swap staging → destination
608 /// atomically (or as close as the backend allows) so a reader never sees a
609 /// half-replaced dataset, and MUST NOT have destroyed the prior contents
610 /// before this point — a failed run leaves the old data in place.
611 ///
612 /// Default: a typed "unsupported" error (unreachable for a correct sink
613 /// whose `is_overwrite()` is false).
614 async fn commit_overwrite(&self) -> Result<(), FaucetError> {
615 Err(FaucetError::Sink(format!(
616 "sink '{}' does not support write_mode: overwrite",
617 self.connector_name()
618 )))
619 }
620
621 /// Discard the staging target after a failed or cancelled overwrite run.
622 ///
623 /// Called (best-effort) when an overwrite run does not reach
624 /// [`commit_overwrite`](Self::commit_overwrite). The destination must be
625 /// left exactly as it was before the run. Default: no-op — a leftover
626 /// staging object is untidy but never data loss, so a sink may skip it.
627 async fn abort_overwrite(&self) -> Result<(), FaucetError> {
628 Ok(())
629 }
630
631 /// Return a JSON Schema describing the configuration this sink accepts.
632 ///
633 /// The schema is auto-generated from the config struct using `schemars`.
634 /// Callers can inspect it to discover required fields, types, defaults,
635 /// and descriptions before constructing the sink.
636 ///
637 /// The default returns an empty object schema.
638 fn config_schema(&self) -> Value {
639 serde_json::json!({"type": "object", "properties": {}})
640 }
641
642 /// Stable identifier used as the `connector` label on metrics and the
643 /// `connector` attribute on spans. See `Source::connector_name`.
644 fn connector_name(&self) -> &'static str {
645 crate::observability::strip_type_name(std::any::type_name::<Self>())
646 }
647
648 /// Logical dataset identity for lineage emission, following OpenLineage
649 /// naming conventions (<https://openlineage.io/docs/spec/naming>).
650 ///
651 /// The default returns `"<connector_name>://unknown"`. Built-in connectors
652 /// override with a credential-free URI derived from their config. Strip any
653 /// credentials with [`redact_uri_credentials`](crate::redact_uri_credentials).
654 /// Informational metadata only — never used for I/O.
655 fn dataset_uri(&self) -> String {
656 format!("{}://unknown", self.connector_name())
657 }
658
659 /// Run a fast, non-mutating preflight probe (used by `faucet doctor`).
660 ///
661 /// Unlike sources, a sink has no non-mutating "first page" equivalent
662 /// (`write_batch` mutates the destination), so the default returns
663 /// [`CheckReport::not_implemented`](crate::check::CheckReport::not_implemented).
664 /// Built-in sinks override this with a connect / auth / metadata probe.
665 ///
666 /// The probe **MUST be idempotent and side-effect-free** — no inserts, no
667 /// residual rows or objects — and must never put credentials or connection
668 /// strings in a probe `reason`/`hint`.
669 async fn check(
670 &self,
671 _ctx: &crate::check::CheckContext,
672 ) -> Result<crate::check::CheckReport, FaucetError> {
673 Ok(crate::check::CheckReport::not_implemented())
674 }
675}
676
677#[cfg(test)]
678mod tests {
679 use super::*;
680 use serde_json::json;
681
682 // ── Mock Source ──────────────────────────────────────────────────────────
683
684 struct MockSource {
685 records: Vec<Value>,
686 }
687
688 #[async_trait]
689 impl Source for MockSource {
690 async fn fetch_with_context(
691 &self,
692 _context: &std::collections::HashMap<String, Value>,
693 ) -> Result<Vec<Value>, FaucetError> {
694 Ok(self.records.clone())
695 }
696 }
697
698 struct IncrementalSource {
699 records: Vec<Value>,
700 bookmark: Value,
701 }
702
703 #[async_trait]
704 impl Source for IncrementalSource {
705 async fn fetch_with_context(
706 &self,
707 _context: &std::collections::HashMap<String, Value>,
708 ) -> Result<Vec<Value>, FaucetError> {
709 Ok(self.records.clone())
710 }
711
712 async fn fetch_with_context_incremental(
713 &self,
714 _context: &std::collections::HashMap<String, Value>,
715 ) -> Result<(Vec<Value>, Option<Value>), FaucetError> {
716 Ok((self.records.clone(), Some(self.bookmark.clone())))
717 }
718 }
719
720 struct FailingSource;
721
722 #[async_trait]
723 impl Source for FailingSource {
724 async fn fetch_with_context(
725 &self,
726 _context: &std::collections::HashMap<String, Value>,
727 ) -> Result<Vec<Value>, FaucetError> {
728 Err(FaucetError::Auth("no credentials".into()))
729 }
730 }
731
732 // ── Mock Sink ───────────────────────────────────────────────────────────
733
734 struct MockSink {
735 written: std::sync::Mutex<Vec<Value>>,
736 }
737
738 impl MockSink {
739 fn new() -> Self {
740 Self {
741 written: std::sync::Mutex::new(Vec::new()),
742 }
743 }
744 }
745
746 #[async_trait]
747 impl Sink for MockSink {
748 async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
749 let mut w = self.written.lock().unwrap();
750 w.extend(records.iter().cloned());
751 Ok(records.len())
752 }
753 }
754
755 struct FailingSink;
756
757 #[async_trait]
758 impl Sink for FailingSink {
759 async fn write_batch(&self, _records: &[Value]) -> Result<usize, FaucetError> {
760 Err(FaucetError::Sink("write failed".into()))
761 }
762 }
763
764 #[tokio::test]
765 async fn default_overwrite_methods_reject_or_noop() {
766 // A sink that does not opt into overwrite (MockSink uses the defaults):
767 // `is_overwrite` is false, begin/commit return the typed "unsupported"
768 // error, and abort is a no-op success.
769 let sink = MockSink::new();
770 assert!(!sink.is_overwrite());
771 assert!(sink.begin_overwrite().await.is_err());
772 assert!(sink.commit_overwrite().await.is_err());
773 assert!(sink.abort_overwrite().await.is_ok());
774 }
775
776 // ── Source tests ────────────────────────────────────────────────────────
777
778 #[tokio::test]
779 async fn source_fetch_all_returns_records() {
780 let source = MockSource {
781 records: vec![json!({"id": 1}), json!({"id": 2})],
782 };
783 let records = source.fetch_all().await.unwrap();
784 assert_eq!(records.len(), 2);
785 assert_eq!(records[0]["id"], 1);
786 }
787
788 #[tokio::test]
789 async fn source_fetch_all_empty() {
790 let source = MockSource { records: vec![] };
791 let records = source.fetch_all().await.unwrap();
792 assert!(records.is_empty());
793 }
794
795 #[tokio::test]
796 async fn source_default_incremental_returns_none_bookmark() {
797 let source = MockSource {
798 records: vec![json!({"id": 1})],
799 };
800 let (records, bookmark) = source.fetch_all_incremental().await.unwrap();
801 assert_eq!(records.len(), 1);
802 assert!(bookmark.is_none());
803 }
804
805 #[tokio::test]
806 async fn source_custom_incremental_returns_bookmark() {
807 let source = IncrementalSource {
808 records: vec![json!({"id": 1})],
809 bookmark: json!("2024-12-01"),
810 };
811 let (records, bookmark) = source.fetch_all_incremental().await.unwrap();
812 assert_eq!(records.len(), 1);
813 assert_eq!(bookmark, Some(json!("2024-12-01")));
814 }
815
816 #[tokio::test]
817 async fn source_error_propagates() {
818 let source = FailingSource;
819 let result = source.fetch_all().await;
820 assert!(result.is_err());
821 assert!(matches!(result, Err(FaucetError::Auth(_))));
822 }
823
824 #[tokio::test]
825 async fn source_as_trait_object() {
826 let source: Box<dyn Source> = Box::new(MockSource {
827 records: vec![json!({"id": 42})],
828 });
829 let records = source.fetch_all().await.unwrap();
830 assert_eq!(records[0]["id"], 42);
831 }
832
833 // ── Sink tests ──────────────────────────────────────────────────────────
834
835 #[tokio::test]
836 async fn sink_write_batch_returns_count() {
837 let sink = MockSink::new();
838 let records = vec![json!({"id": 1}), json!({"id": 2}), json!({"id": 3})];
839 let count = sink.write_batch(&records).await.unwrap();
840 assert_eq!(count, 3);
841 }
842
843 #[tokio::test]
844 async fn sink_write_batch_empty() {
845 let sink = MockSink::new();
846 let count = sink.write_batch(&[]).await.unwrap();
847 assert_eq!(count, 0);
848 }
849
850 #[tokio::test]
851 async fn sink_accumulates_records() {
852 let sink = MockSink::new();
853 sink.write_batch(&[json!({"a": 1})]).await.unwrap();
854 sink.write_batch(&[json!({"b": 2})]).await.unwrap();
855 let written = sink.written.lock().unwrap();
856 assert_eq!(written.len(), 2);
857 }
858
859 #[tokio::test]
860 async fn sink_default_flush_is_noop() {
861 let sink = MockSink::new();
862 assert!(sink.flush().await.is_ok());
863 }
864
865 #[tokio::test]
866 async fn sink_error_propagates() {
867 let sink = FailingSink;
868 let result = sink.write_batch(&[json!({"id": 1})]).await;
869 assert!(result.is_err());
870 assert!(matches!(result, Err(FaucetError::Sink(_))));
871 }
872
873 #[tokio::test]
874 async fn sink_as_trait_object() {
875 let sink: Box<dyn Sink> = Box::new(MockSink::new());
876 let count = sink.write_batch(&[json!({"id": 1})]).await.unwrap();
877 assert_eq!(count, 1);
878 }
879
880 // ── stream_pages tests ──────────────────────────────────────────────────
881
882 use crate::pipeline::DEFAULT_BATCH_SIZE;
883 use futures::StreamExt;
884
885 #[tokio::test]
886 async fn default_stream_pages_chunks_records() {
887 let source = MockSource {
888 records: (0..5).map(|i| json!({"i": i})).collect(),
889 };
890 let ctx = std::collections::HashMap::new();
891 let mut pages = source.stream_pages(&ctx, 2);
892 let mut all = Vec::new();
893 while let Some(page) = pages.next().await {
894 all.push(page.unwrap());
895 }
896 // 5 records, batch_size=2 → pages of [2, 2, 1]
897 assert_eq!(all.len(), 3);
898 assert_eq!(all[0].records.len(), 2);
899 assert_eq!(all[1].records.len(), 2);
900 assert_eq!(all[2].records.len(), 1);
901 }
902
903 #[tokio::test]
904 async fn default_stream_pages_attaches_bookmark_to_final_page_only() {
905 let source = IncrementalSource {
906 records: (0..5).map(|i| json!({"i": i})).collect(),
907 bookmark: json!("v1"),
908 };
909 let ctx = std::collections::HashMap::new();
910 let mut pages = source.stream_pages(&ctx, 2);
911 let mut collected = Vec::new();
912 while let Some(page) = pages.next().await {
913 collected.push(page.unwrap());
914 }
915 assert_eq!(collected.len(), 3);
916 assert!(collected[0].bookmark.is_none());
917 assert!(collected[1].bookmark.is_none());
918 assert_eq!(collected[2].bookmark, Some(json!("v1")));
919 }
920
921 #[tokio::test]
922 async fn default_stream_pages_single_page_when_batch_size_exceeds_total() {
923 let source = MockSource {
924 records: vec![json!({"id": 1}), json!({"id": 2})],
925 };
926 let ctx = std::collections::HashMap::new();
927 let mut pages = source.stream_pages(&ctx, 100);
928 let mut collected = Vec::new();
929 while let Some(page) = pages.next().await {
930 collected.push(page.unwrap());
931 }
932 assert_eq!(collected.len(), 1);
933 assert_eq!(collected[0].records.len(), 2);
934 }
935
936 #[tokio::test]
937 async fn default_stream_pages_batch_size_zero_emits_single_page() {
938 // batch_size = 0 is the "no batching" sentinel — yields every record
939 // in one page regardless of total count.
940 let source = MockSource {
941 records: (0..50_000).map(|i| json!({"i": i})).collect(),
942 };
943 let ctx = std::collections::HashMap::new();
944 let mut pages = source.stream_pages(&ctx, 0);
945 let mut collected = Vec::new();
946 while let Some(page) = pages.next().await {
947 collected.push(page.unwrap());
948 }
949 assert_eq!(
950 collected.len(),
951 1,
952 "batch_size=0 must emit exactly one page"
953 );
954 assert_eq!(collected[0].records.len(), 50_000);
955 }
956
957 #[tokio::test]
958 async fn default_stream_pages_batch_size_zero_attaches_bookmark_to_sole_page() {
959 let source = IncrementalSource {
960 records: (0..3).map(|i| json!({"i": i})).collect(),
961 bookmark: json!("v1"),
962 };
963 let ctx = std::collections::HashMap::new();
964 let mut pages = source.stream_pages(&ctx, 0);
965 let page = pages.next().await.unwrap().unwrap();
966 assert_eq!(page.records.len(), 3);
967 assert_eq!(page.bookmark, Some(json!("v1")));
968 assert!(pages.next().await.is_none());
969 }
970
971 #[tokio::test]
972 async fn default_stream_pages_empty_source_yields_no_pages() {
973 let source = MockSource { records: vec![] };
974 let ctx = std::collections::HashMap::new();
975 let mut pages = source.stream_pages(&ctx, DEFAULT_BATCH_SIZE);
976 assert!(pages.next().await.is_none());
977 }
978
979 #[tokio::test]
980 async fn default_stream_pages_empty_source_with_bookmark_yields_single_empty_page() {
981 let source = IncrementalSource {
982 records: vec![],
983 bookmark: json!("v0"),
984 };
985 let ctx = std::collections::HashMap::new();
986 let mut pages = source.stream_pages(&ctx, DEFAULT_BATCH_SIZE);
987 let mut collected = Vec::new();
988 while let Some(page) = pages.next().await {
989 collected.push(page.unwrap());
990 }
991 // One empty-records page that carries the bookmark, so the pipeline
992 // still persists progress on otherwise-empty incremental runs.
993 assert_eq!(collected.len(), 1);
994 assert!(collected[0].records.is_empty());
995 assert_eq!(collected[0].bookmark, Some(json!("v0")));
996 }
997
998 #[tokio::test]
999 async fn default_stream_pages_propagates_fetch_errors() {
1000 let source = FailingSource;
1001 let ctx = std::collections::HashMap::new();
1002 let mut pages = source.stream_pages(&ctx, DEFAULT_BATCH_SIZE);
1003 let first = pages.next().await.unwrap();
1004 assert!(matches!(first, Err(FaucetError::Auth(_))));
1005 }
1006
1007 #[test]
1008 fn source_default_connector_name_is_stripped_type_name() {
1009 // MockSource lives at `faucet_core::traits::tests::MockSource`; the
1010 // stripped type_name yields the trailing segment.
1011 let source = MockSource { records: vec![] };
1012 assert_eq!(source.connector_name(), "MockSource");
1013 }
1014
1015 #[test]
1016 fn sink_default_connector_name_is_stripped_type_name() {
1017 let sink = MockSink::new();
1018 assert_eq!(sink.connector_name(), "MockSink");
1019 }
1020
1021 #[test]
1022 fn source_default_dataset_uri_uses_connector_name() {
1023 let source = MockSource { records: vec![] };
1024 assert_eq!(source.dataset_uri(), "MockSource://unknown");
1025 }
1026
1027 #[test]
1028 fn sink_default_dataset_uri_uses_connector_name() {
1029 let sink = MockSink::new();
1030 assert_eq!(sink.dataset_uri(), "MockSink://unknown");
1031 }
1032
1033 // ── write_batch_partial tests ───────────────────────────────────────────
1034
1035 #[tokio::test]
1036 async fn default_write_batch_partial_success_returns_all_ok() {
1037 let sink = MockSink::new();
1038 let records = vec![json!({"id": 1}), json!({"id": 2}), json!({"id": 3})];
1039 let outcomes = sink.write_batch_partial(&records).await.unwrap();
1040 assert_eq!(outcomes.len(), 3);
1041 assert!(outcomes.iter().all(|o| o.is_ok()));
1042 assert_eq!(sink.written.lock().unwrap().len(), 3);
1043 }
1044
1045 #[tokio::test]
1046 async fn default_write_batch_partial_bubbles_outer_err() {
1047 let sink = FailingSink;
1048 let records = vec![json!({"id": 1}), json!({"id": 2})];
1049 let result = sink.write_batch_partial(&records).await;
1050 assert!(matches!(result, Err(FaucetError::Sink(_))));
1051 }
1052
1053 #[tokio::test]
1054 async fn default_write_batch_partial_empty_returns_empty_vec() {
1055 let sink = MockSink::new();
1056 let outcomes = sink.write_batch_partial(&[]).await.unwrap();
1057 assert!(outcomes.is_empty());
1058 }
1059
1060 #[tokio::test]
1061 async fn default_write_batch_partial_callable_through_trait_object() {
1062 let sink: Box<dyn Sink> = Box::new(MockSink::new());
1063 let records = vec![json!({"id": 1}), json!({"id": 2})];
1064 let outcomes = sink.write_batch_partial(&records).await.unwrap();
1065 assert_eq!(outcomes.len(), 2);
1066 assert!(outcomes.iter().all(|o| o.is_ok()));
1067 }
1068
1069 // ── check() tests ─────────────────────────────────────────────────────────
1070
1071 #[tokio::test]
1072 async fn source_default_check_pulls_first_page_and_passes() {
1073 let source = MockSource {
1074 records: vec![json!({"id": 1}), json!({"id": 2})],
1075 };
1076 let report = source
1077 .check(&crate::check::CheckContext::default())
1078 .await
1079 .unwrap();
1080 assert_eq!(report.failed_count(), 0);
1081 assert!(
1082 report
1083 .probes
1084 .iter()
1085 .any(|p| p.name == "read" && matches!(p.status, crate::check::ProbeStatus::Pass))
1086 );
1087 }
1088
1089 #[tokio::test]
1090 async fn source_default_check_passes_on_empty_source() {
1091 let source = MockSource { records: vec![] };
1092 let report = source
1093 .check(&crate::check::CheckContext::default())
1094 .await
1095 .unwrap();
1096 // Reachable but empty is still a healthy source.
1097 assert_eq!(report.failed_count(), 0);
1098 }
1099
1100 #[tokio::test]
1101 async fn source_default_check_fails_when_fetch_errors() {
1102 let source = FailingSource;
1103 let report = source
1104 .check(&crate::check::CheckContext::default())
1105 .await
1106 .unwrap();
1107 assert_eq!(report.failed_count(), 1);
1108 assert!(report.probes.iter().any(
1109 |p| p.name == "read" && matches!(p.status, crate::check::ProbeStatus::Fail { .. })
1110 ));
1111 }
1112
1113 #[tokio::test]
1114 async fn sink_default_check_is_not_implemented_skip() {
1115 let sink = MockSink::new();
1116 let report = sink
1117 .check(&crate::check::CheckContext::default())
1118 .await
1119 .unwrap();
1120 assert_eq!(report.probes.len(), 1);
1121 assert!(matches!(
1122 report.probes[0].status,
1123 crate::check::ProbeStatus::Skip { .. }
1124 ));
1125 }
1126
1127 #[tokio::test]
1128 async fn source_check_callable_through_trait_object() {
1129 let source: Box<dyn Source> = Box::new(MockSource {
1130 records: vec![json!({"id": 1})],
1131 });
1132 let report = source
1133 .check(&crate::check::CheckContext::default())
1134 .await
1135 .unwrap();
1136 assert_eq!(report.failed_count(), 0);
1137 }
1138
1139 // ── idempotent-write / exactly-once capability tests ──────────────────────
1140
1141 #[tokio::test]
1142 async fn sink_default_is_not_idempotent() {
1143 let sink = MockSink::new();
1144 assert!(!sink.supports_idempotent_writes());
1145 // Default write_batch_idempotent ignores the token and delegates.
1146 let n = sink
1147 .write_batch_idempotent(&[json!({"id": 1})], "scope::a", "00000000000000000001")
1148 .await
1149 .unwrap();
1150 assert_eq!(n, 1);
1151 assert_eq!(sink.last_committed_token("scope::a").await.unwrap(), None);
1152 assert_eq!(sink.written.lock().unwrap().len(), 1);
1153 }
1154
1155 #[test]
1156 fn source_default_does_not_support_exactly_once() {
1157 let source = MockSource { records: vec![] };
1158 assert!(!source.supports_exactly_once());
1159 }
1160
1161 #[test]
1162 fn sink_default_supported_write_modes_is_append_only() {
1163 use crate::write_mode::WriteMode;
1164 let sink = MockSink::new();
1165 assert_eq!(sink.supported_write_modes(), &[WriteMode::Append]);
1166 }
1167
1168 #[test]
1169 fn supported_write_modes_callable_through_trait_object() {
1170 use crate::write_mode::WriteMode;
1171 let sink: Box<dyn Sink> = Box::new(MockSink::new());
1172 assert!(sink.supported_write_modes().contains(&WriteMode::Append));
1173 }
1174
1175 #[tokio::test]
1176 async fn sink_default_current_schema_is_none() {
1177 let sink = MockSink::new();
1178 assert_eq!(sink.current_schema().await.unwrap(), None);
1179 }
1180
1181 #[test]
1182 fn sink_default_does_not_support_schema_evolution() {
1183 let sink = MockSink::new();
1184 assert!(!sink.supports_schema_evolution());
1185 }
1186
1187 #[tokio::test]
1188 async fn sink_default_evolve_schema_is_unsupported_error() {
1189 let sink = MockSink::new();
1190 let evo = crate::drift::SchemaEvolution::default();
1191 let err = sink.evolve_schema(&evo).await.unwrap_err();
1192 assert!(matches!(err, FaucetError::Sink(_)));
1193 assert!(err.to_string().contains("schema evolution"));
1194 }
1195
1196 #[tokio::test]
1197 async fn source_default_capture_resume_position_is_none() {
1198 let source = MockSource { records: vec![] };
1199 assert_eq!(source.capture_resume_position().await.unwrap(), None);
1200 }
1201
1202 #[tokio::test]
1203 async fn capture_resume_position_callable_through_trait_object() {
1204 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1205 assert!(source.capture_resume_position().await.unwrap().is_none());
1206 }
1207
1208 #[tokio::test]
1209 async fn source_default_does_not_support_discover() {
1210 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1211 assert!(!source.supports_discover());
1212 let err = source.discover().await.unwrap_err();
1213 assert!(matches!(err, FaucetError::Source(_)));
1214 assert!(
1215 err.to_string().contains("dataset discovery"),
1216 "typed unsupported error: {err}"
1217 );
1218 }
1219
1220 #[tokio::test]
1221 async fn source_default_is_not_shardable() {
1222 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1223 assert!(!source.is_shardable());
1224 }
1225
1226 #[tokio::test]
1227 async fn source_default_enumerates_single_whole_shard() {
1228 // A non-shardable source enumerates to exactly one whole-dataset shard,
1229 // regardless of the requested target — preserving single-worker behavior.
1230 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1231 let shards = source.enumerate_shards(8).await.unwrap();
1232 assert_eq!(shards.len(), 1);
1233 assert!(shards[0].is_whole());
1234 }
1235
1236 #[tokio::test]
1237 async fn source_default_apply_shard_is_noop() {
1238 let source: Box<dyn Source> = Box::new(MockSource { records: vec![] });
1239 // Applying the whole shard is a no-op and must not error.
1240 source
1241 .apply_shard(&crate::shard::ShardSpec::whole())
1242 .await
1243 .unwrap();
1244 }
1245}