Skip to main content

rivet/source/
mod.rs

1pub(crate) mod batch_controller;
2pub(crate) mod cdc;
3pub mod mssql;
4pub mod mysql;
5pub(crate) mod pg_numeric_wire;
6pub mod postgres;
7pub(crate) mod query;
8pub(crate) mod tls;
9
10use arrow::datatypes::SchemaRef;
11use arrow::record_batch::RecordBatch;
12
13use crate::config::{SourceConfig, TlsConfig};
14use crate::error::Result;
15use crate::plan::IncrementalCursorPlan;
16use crate::tuning::SourceTuning;
17use crate::types::{ColumnOverrides, CursorState, TypeMapping};
18
19/// A statement-DURATION timeout that **rivet itself** raised — distinct from a
20/// driver-native timeout that carries a structured code (PG 57014, MySQL 3024).
21///
22/// The MSSQL engine has no server-side statement-duration `SET`, so rivet
23/// enforces `tuning.statement_timeout_s` client-side and raises this when the
24/// budget is exceeded (see [`mssql`]). Before this type the retry classifier's
25/// permanence hinged on substring-matching rivet's OWN prose ("statement
26/// timeout after …"); a reworded message would silently flip the error back to
27/// *transient*, and the identical query would be retried until it burned the
28/// budget N times (measured: 3×300 s = 20 min for 0 rows). Carrying a typed
29/// marker means [`crate::pipeline::retry::classify_error`] downcasts the TYPE,
30/// so permanence survives any change to the human-facing wording. The string
31/// branches in the classifier remain a fallback for genuinely driver-native
32/// timeout messages we do not control.
33#[derive(Debug)]
34pub struct StatementDurationTimeout {
35    /// Full actionable message shown to the operator. The classifier keys off
36    /// the TYPE, not this text — it exists only for Display.
37    message: String,
38}
39
40impl StatementDurationTimeout {
41    /// MSSQL client-side statement-duration timeout (no server-side `SET`).
42    pub fn mssql(seconds: u64) -> Self {
43        Self {
44            message: format!(
45                "mssql: statement timeout after {seconds}s (tuning.statement_timeout_s) — \
46                 this query cannot finish within the budget; split it with `mode: chunked` \
47                 (per-chunk statements stay under the limit) or raise \
48                 `tuning.statement_timeout_s`"
49            ),
50        }
51    }
52}
53
54impl std::fmt::Display for StatementDurationTimeout {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        f.write_str(&self.message)
57    }
58}
59
60impl std::error::Error for StatementDurationTimeout {}
61
62/// Summary of a source table relevant to chunked-mode planning. Source-neutral
63/// shape so plan-build can ask either Postgres or MySQL for the same answer.
64///
65/// Populated by `crate::source::postgres::introspect_pg_table_for_chunking` and
66/// `crate::source::mysql::introspect_mysql_table_for_chunking`. Both helpers
67/// rely on catalog stats (`pg_class` / `information_schema.TABLES`) so the
68/// numbers are only as fresh as the last `ANALYZE` / autoanalyse.
69///
70/// # Why this is a data-shape seam, not a trait
71///
72/// The two per-engine introspection functions have identical signatures
73/// (`fn(url, tls, qualified_table) -> Result<TableIntrospection>`) and return
74/// this shared struct. The parallel shape sometimes invites a refactor along
75/// the lines of `trait Introspector { fn introspect_table(...) }` with one
76/// impl per engine — that refactor adds ceremony without reducing duplication,
77/// because the *bodies* share nothing useful: PG queries `pg_class` /
78/// `pg_index` / `pg_attribute` / `pg_type` (PG-specific type names like
79/// `int2`/`int4`/`int8`) via the `postgres` client; MySQL queries
80/// `information_schema.TABLES` / `STATISTICS` with the InnoDB
81/// `AVG_ROW_LENGTH` overflow correction via the `mysql` client. No shared
82/// implementation logic exists to extract into trait-default methods. A
83/// trait would only rename where the engine match happens
84/// (`match config.source.source_type { … }` at the call site → factory
85/// returning `Box<dyn Introspector>`); the match doesn't disappear.
86///
87/// The seam therefore lives at the **data shape**: this struct is the
88/// shared contract, the two free functions are the adapters, the per-call
89/// dispatch is an `enum`-driven `match`. See ADR-0015 for the full
90/// rationale and the architecture-review walks that led here.
91#[derive(Debug, Clone, Default)]
92pub(crate) struct TableIntrospection {
93    /// Name of the single integer-family PK column, if present and safe to
94    /// range-chunk. `None` when the table has no PK, has a composite PK, or
95    /// the PK type is not an integer family (text, uuid, decimal, …).
96    pub single_int_pk: Option<String>,
97    /// Single-column, NOT NULL, **unique** index columns usable as a keyset
98    /// (seek) pagination key — PK first (any type), then other UNIQUE indexes
99    /// (OPT-4). Index-backed and unique by construction, so `ORDER BY key
100    /// LIMIT n` is a bounded index range scan (never a filesort) and
101    /// `WHERE key > last` never skips rows with a duplicate key. Empty when the
102    /// table has no such key.
103    pub keyset_keys: Vec<String>,
104    /// Best-effort row count: PG `reltuples`, MySQL `TABLE_ROWS`. `0` means
105    /// the table is empty or stats are unavailable.
106    pub row_estimate: i64,
107    /// Heap-size-per-row in bytes. `None` for empty / unanalysed tables.
108    /// Used to convert `chunk_size_memory_mb` into a row count.
109    pub avg_row_bytes: Option<i64>,
110}
111
112impl TableIntrospection {
113    /// The auto-selected keyset key: the first usable single-column unique
114    /// NOT NULL key (PK preferred). `None` when the table has none.
115    pub fn auto_keyset_key(&self) -> Option<&str> {
116        self.keyset_keys.first().map(String::as_str)
117    }
118
119    /// Whether `col` is a usable keyset key (single-column, unique, NOT NULL,
120    /// index-backed). Used to validate an explicit `chunk_by_key`.
121    pub fn is_usable_keyset_key(&self, col: &str) -> bool {
122        self.keyset_keys.iter().any(|k| k == col)
123    }
124}
125
126/// Receives schema and batches from a source, one at a time.
127pub trait BatchSink {
128    fn on_schema(&mut self, schema: SchemaRef) -> Result<()>;
129    fn on_batch(&mut self, batch: &RecordBatch) -> Result<()>;
130}
131
132/// Read-only inputs for a single export call.
133///
134/// Packs the parameters that used to live as 5 positional args on
135/// `Source::export` into a named struct. `sink` is **not** part of this struct
136/// — it is `&mut` and conceptually the output channel, separate from the
137/// read-only request configuration.
138pub struct ExportRequest<'a> {
139    /// Already-materialized SQL (after `resolve_query`). The driver still wraps
140    /// it with the dialect-specific incremental predicate via
141    /// [`crate::source::query::build_incremental_query`] when `incremental` is set.
142    pub query: &'a str,
143    /// The *unwrapped* base query to resolve catalog-dependent type hints from
144    /// (PostgreSQL `NUMERIC` precision/scale, which the wire protocol omits — the
145    /// driver parses the `FROM` clause and asks `pg_catalog`). Chunked, dense and
146    /// keyset runners wrap `query` in a `SELECT … FROM (<base>) …` subquery that
147    /// hides the source table from the catalog parser, so they pass the original
148    /// base query here. `None` ⇒ resolve from `query` (full/incremental, where it
149    /// is already the unwrapped form). Drivers that read precision from the wire
150    /// (MySQL) ignore this field.
151    pub catalog_hint_query: Option<&'a str>,
152    pub incremental: Option<&'a IncrementalCursorPlan>,
153    pub cursor: Option<&'a CursorState>,
154    pub tuning: &'a SourceTuning,
155    /// Per-column type declarations from `rivet.yaml` (`exports[].columns:`).
156    /// Drivers apply them during schema building so e.g. a `NUMERIC` column
157    /// without declared precision can still be exported as `Decimal128(18,2)`
158    /// when the user has stated the type explicitly.
159    pub column_overrides: &'a ColumnOverrides,
160    /// Keyset (seek) pagination page size (OPT-4). When `Some(n)` *and*
161    /// `incremental` carries the key plan, the driver builds one keyset page
162    /// (`WHERE key > cursor ORDER BY key LIMIT n`) instead of the unbounded
163    /// incremental/snapshot query. The keyset runner drives the outer loop.
164    pub page_limit: Option<usize>,
165}
166
167impl<'a> ExportRequest<'a> {
168    /// A request whose `query` is already the **unwrapped base** form, so
169    /// catalog type hints resolve directly from it. Use for snapshot,
170    /// incremental and keyset runners: the driver applies any incremental /
171    /// keyset predicate internally, so the source table stays visible to the
172    /// catalog parser and `catalog_hint_query` is `None`.
173    pub fn unwrapped(
174        query: &'a str,
175        tuning: &'a SourceTuning,
176        column_overrides: &'a ColumnOverrides,
177    ) -> Self {
178        Self {
179            query,
180            catalog_hint_query: None,
181            incremental: None,
182            cursor: None,
183            tuning,
184            column_overrides,
185            page_limit: None,
186        }
187    }
188
189    /// A request whose `query` is a `SELECT … FROM (<base>) …` **wrapper** that
190    /// hides the source table (chunked / dense / time-window). `base` — the
191    /// unwrapped query catalog hints resolve from — is a required argument, so a
192    /// wrapping runner cannot silently fall back to the table-hiding wrapper and
193    /// lose PG `NUMERIC` precision (the bug the catalog-hint fix / ADR-0020
194    /// closed). Drivers that read precision from the wire (MySQL) ignore it.
195    pub fn wrapped(
196        query: &'a str,
197        base: &'a str,
198        tuning: &'a SourceTuning,
199        column_overrides: &'a ColumnOverrides,
200    ) -> Self {
201        Self {
202            query,
203            catalog_hint_query: Some(base),
204            incremental: None,
205            cursor: None,
206            tuning,
207            column_overrides,
208            page_limit: None,
209        }
210    }
211
212    /// Attach the incremental cursor plan (the driver builds the `WHERE cursor >
213    /// ? ORDER BY` predicate). Pass-through `Option` so mode-polymorphic callers
214    /// can forward `strategy.incremental_plan()` directly.
215    pub fn with_incremental(mut self, plan: Option<&'a IncrementalCursorPlan>) -> Self {
216        self.incremental = plan;
217        self
218    }
219
220    /// Attach the last committed cursor value the next run resumes after.
221    pub fn with_cursor(mut self, cursor: Option<&'a CursorState>) -> Self {
222        self.cursor = cursor;
223        self
224    }
225
226    /// Set the keyset (seek) page size — one bounded `… WHERE key > cursor ORDER
227    /// BY key LIMIT n` page instead of the unbounded query.
228    pub fn with_page_limit(mut self, page_limit: usize) -> Self {
229        self.page_limit = Some(page_limit);
230        self
231    }
232}
233
234pub trait Source: Send {
235    /// Execute `request.query` and stream batches into `sink`.
236    fn export(&mut self, request: &ExportRequest<'_>, sink: &mut dyn BatchSink) -> Result<()>;
237
238    fn query_scalar(&mut self, sql: &str) -> Result<Option<String>>;
239
240    /// Return `TypeMapping` for every column in `query` without fetching rows.
241    ///
242    /// Used by `rivet check --type-report` to show the full type provenance
243    /// (source native type → RivetType → Arrow type → fidelity) before export.
244    /// Implementations execute `SELECT * FROM (...) AS _q LIMIT 0` so only
245    /// server-side type metadata is transferred.
246    fn type_mappings(
247        &mut self,
248        query: &str,
249        column_overrides: &ColumnOverrides,
250    ) -> Result<Vec<TypeMapping>>;
251
252    /// Sample a monotonic source-pressure counter for the OPT-2 concurrency
253    /// governor (`pipeline::chunked::exec`).
254    ///
255    /// Higher = more pressure. The governor compares successive samples
256    /// (`cur > prev` ⇒ under pressure) — the same convention the adaptive
257    /// batch-size loop already uses. Returns `None` when the engine can't
258    /// cheaply sample a pressure proxy, in which case the governor holds
259    /// parallelism flat. Default: `None`.
260    fn sample_pressure(&mut self) -> Option<u64> {
261        None
262    }
263}
264
265pub fn create_source(config: &SourceConfig) -> Result<Box<dyn Source>> {
266    use crate::config::SourceType;
267    let url = config.resolve_url()?;
268    warn_if_tls_disabled(config);
269    match config.source_type {
270        SourceType::Postgres => Ok(Box::new(postgres::PostgresSource::connect_with_tls(
271            &url,
272            config.tls.as_ref(),
273        )?)),
274        SourceType::Mysql => Ok(Box::new(mysql::MysqlSource::connect_with_tls(
275            &url,
276            config.tls.as_ref(),
277        )?)),
278        SourceType::Mssql => Ok(Box::new(mssql::MssqlSource::connect_with_tls(
279            &url,
280            config.tls.as_ref(),
281        )?)),
282    }
283}
284
285/// Pre-allocation per-value size guard, shared by every engine's
286/// `arrow_convert`. The sink-side `check_value_ceiling`
287/// (`pipeline::sink::mod`) scans the *already-built* Arrow batch, so an
288/// oversized cell costs the driver-decode copy **and** the Arrow-build copy
289/// before that guard fires. This check runs at the decode/`Value` stage — after
290/// the unavoidable driver copy, but *before* the value is appended into the
291/// `StringBuilder` / `BinaryBuilder` — so the Arrow allocation never grows to
292/// hold it. Only variable-length values (Utf8 / Binary) can be individually
293/// huge; fixed-width arms (ints/floats/dates) never call this.
294///
295/// `max_value_bytes` is `tuning.max_value_bytes()` (MB → bytes with the
296/// `Some(0)`/`None` ⇒ disabled semantics). The message mirrors the sink guard's
297/// `RIVET_VALUE_TOO_LARGE` so both read identically; the sink guard stays as the
298/// backstop (it also covers meta / enriched columns and is the contract test).
299pub(crate) fn value_within_ceiling(
300    column: &str,
301    len: usize,
302    max_value_bytes: Option<usize>,
303) -> Result<()> {
304    if let Some(limit) = max_value_bytes
305        && len > limit
306    {
307        anyhow::bail!(
308            "RIVET_VALUE_TOO_LARGE: column '{}' has a single value of {:.1} MB, exceeding the \
309             per-value ceiling of {} MB. One oversized cell can OOM the process regardless of \
310             batch size. Raise `tuning.max_value_mb` (or set it to 0 to disable the guard) if \
311             this value is expected.",
312            column,
313            len as f64 / (1024.0 * 1024.0),
314            limit / (1024 * 1024),
315        );
316    }
317    Ok(())
318}
319
320#[cfg(test)]
321mod value_ceiling_tests {
322    use super::value_within_ceiling;
323
324    #[test]
325    fn sec_value_ceiling_pre_alloc_over_limit_errors() {
326        let err = value_within_ceiling("payload", 2 * 1024 * 1024, Some(1024 * 1024)).unwrap_err();
327        let msg = format!("{err:#}");
328        assert!(msg.contains("RIVET_VALUE_TOO_LARGE"), "got: {msg}");
329        assert!(msg.contains("payload"), "names the column: {msg}");
330    }
331
332    #[test]
333    fn sec_value_ceiling_pre_alloc_at_or_under_limit_ok() {
334        assert!(value_within_ceiling("c", 1024 * 1024, Some(1024 * 1024)).is_ok());
335        assert!(value_within_ceiling("c", 0, Some(1024 * 1024)).is_ok());
336    }
337
338    #[test]
339    fn sec_value_ceiling_pre_alloc_disabled_never_errors() {
340        // `None` (set when tuning.max_value_mb is 0 or unset) disables the guard.
341        assert!(value_within_ceiling("c", usize::MAX, None).is_ok());
342    }
343}
344
345/// One-time nudge to enable TLS when the current config connects in plaintext.
346/// Emitted at `warn` level so operators see it even at the default log level.
347/// `create_source` is called multiple times per run (plan/preflight/exec/chunk
348/// workers), so we gate the warning behind a `Once` to fire exactly once per
349/// process rather than 3-4 times in stderr.
350pub(crate) fn warn_if_tls_disabled(config: &SourceConfig) {
351    let enforced = config.tls.as_ref().is_some_and(|t| t.mode.is_enforced());
352    if enforced {
353        return;
354    }
355    // Loopback (localhost / 127.0.0.0/8 / ::1) is the local-dev / docker case:
356    // the bytes never leave the box, so the plaintext warning is just noise on
357    // a newcomer's laptop. Resolve best-effort — if the URL can't be resolved we
358    // fall through and warn (fail-safe). The real CWE-319 signal still fires for
359    // any remote host.
360    if config.resolve_url().is_ok_and(|u| host_is_loopback(&u)) {
361        return;
362    }
363    static WARNED: std::sync::Once = std::sync::Once::new();
364    WARNED.call_once(|| {
365        log::warn!(
366            "source: TLS is not enforced — credentials and result rows cross the network in plaintext. \
367             Add `source.tls.mode: verify-full` (with `ca_file:` if your CA is private) to enable transport security."
368        );
369    });
370}
371
372/// Whether the host in a `scheme://[user[:pass]@]host[:port][/db][?…]`
373/// connection URL is a loopback address (`127.0.0.0/8`, `::1`) or the literal
374/// `localhost`.
375///
376/// Used by [`require_tls_or_loopback`] to decide TLS posture from the host:
377/// loopback is the docker / local-dev case where the bytes never leave the box,
378/// so plaintext is fine; a remote host without TLS leaks credentials and rows.
379///
380/// Fails **closed**: any URL we cannot confidently parse a loopback host out of
381/// is treated as non-loopback, so a parse gap can only ever *tighten* the gate
382/// (refuse a connection), never silently allow plaintext to an unverified host.
383pub(crate) fn host_is_loopback(url: &str) -> bool {
384    // Strip the scheme (`postgresql://`, `mysql://`, `sqlserver://`, …).
385    let after_scheme = match url.split_once("://") {
386        Some((_, rest)) => rest,
387        None => url,
388    };
389    // Authority ends at the first `/`, `?` or `#`.
390    let authority = after_scheme
391        .split(['/', '?', '#'])
392        .next()
393        .unwrap_or(after_scheme);
394    // Drop `user[:pass]@` — rsplit the last `@` so an `@` inside a password is
395    // tolerated (it belongs to the userinfo, not the host).
396    let host_port = match authority.rsplit_once('@') {
397        Some((_, hp)) => hp,
398        None => authority,
399    };
400    // Host vs port. IPv6 literals are bracketed (`[::1]:5432`); for those the
401    // host is the bracketed span, and any `:` inside is part of the address.
402    let host = if let Some(rest) = host_port.strip_prefix('[') {
403        match rest.split_once(']') {
404            Some((h, _)) => h,
405            None => return false, // unterminated bracket — fail closed
406        }
407    } else {
408        // Bare host or IPv4: the host ends at the (single) port `:`.
409        host_port.split(':').next().unwrap_or(host_port)
410    };
411
412    if host.eq_ignore_ascii_case("localhost") {
413        return true;
414    }
415    // `IpAddr::is_loopback` covers the whole 127.0.0.0/8 block and `::1`.
416    host.parse::<std::net::IpAddr>()
417        .is_ok_and(|ip| ip.is_loopback())
418}
419
420/// Gate plaintext / trust-any-cert connections by host (CWE-319 / CWE-295).
421///
422/// When no `tls:` block is configured (`tls == None`) **and** the resolved host
423/// is not loopback, refuse the connection *before any network I/O* with a
424/// TLS-required policy error. This stops the per-engine connect helpers from
425/// silently dialing a remote database in cleartext (Postgres/MySQL `NoTls`) or
426/// trusting any server certificate (MSSQL `trust_cert`).
427///
428/// Loopback hosts (docker / local dev) keep today's behaviour — plaintext is
429/// allowed there because the bytes never leave the box. An explicit
430/// `tls: { mode: disable }` is `Some(..)`, so it is the operator's opt-in to
431/// remote plaintext and is **not** refused here.
432pub(crate) fn require_tls_or_loopback(url: &str, tls: Option<&TlsConfig>) -> Result<()> {
433    if tls.is_none() && !host_is_loopback(url) {
434        // The message must name TLS *and* that it is a policy refusal for a
435        // remote host. Emit it at `error` level (→ stderr) as well as returning
436        // it: callers like `doctor` print the `Err` to stdout in their own
437        // `[FAIL]` style and only re-raise a generic summary, so the log line is
438        // what guarantees the TLS-required reason reaches stderr. Deliberately
439        // avoids socket-error vocabulary ("could not connect", "timeout", "os
440        // error") so it is never mistaken for a connect-time failure.
441        let msg = "source: TLS required — refusing to connect to a remote (non-loopback) \
442             host without TLS; credentials and every exported row would cross the network \
443             in cleartext. Add `source.tls: { mode: verify-full }` (with `ca_file:` for a \
444             private CA) to enable transport security, or explicitly opt into remote \
445             plaintext with `source.tls: { mode: disable }` if this network path is \
446             already trusted.";
447        log::error!("{msg}");
448        anyhow::bail!("{msg}");
449    }
450    Ok(())
451}
452
453#[cfg(test)]
454mod tls_gate_tests {
455    use super::{host_is_loopback, require_tls_or_loopback};
456    use crate::config::{TlsConfig, TlsMode};
457
458    #[test]
459    fn loopback_variants_are_loopback() {
460        assert!(host_is_loopback(
461            "postgresql://rivet:rivet@127.0.0.1:5432/rivet"
462        ));
463        assert!(host_is_loopback(
464            "postgresql://rivet:rivet@localhost:5432/rivet"
465        ));
466        assert!(host_is_loopback("mysql://root@127.0.0.1:3306/db"));
467        // Whole 127.0.0.0/8 block is loopback.
468        assert!(host_is_loopback("postgresql://u:p@127.255.0.9/db"));
469        // IPv6 loopback, bracketed with and without a port.
470        assert!(host_is_loopback("postgresql://u:p@[::1]:5432/db"));
471        assert!(host_is_loopback("sqlserver://sa:pw@[::1]/master"));
472        // Case-insensitive host, no port, no db.
473        assert!(host_is_loopback("mysql://root@LOCALHOST"));
474        // An `@` inside the password must not be mistaken for the host boundary.
475        assert!(host_is_loopback("postgresql://u:p@ss@127.0.0.1:5432/db"));
476    }
477
478    #[test]
479    fn remote_hosts_are_not_loopback() {
480        assert!(!host_is_loopback(
481            "postgresql://rivet:rivet@10.255.255.1:5432/rivet"
482        ));
483        assert!(!host_is_loopback(
484            "postgresql://u:p@db.example.com:5432/app"
485        ));
486        assert!(!host_is_loopback("mysql://root@192.168.1.10:3306/db"));
487        assert!(!host_is_loopback("sqlserver://sa:pw@10.0.0.5:1433/master"));
488        // Not loopback: an unbracketed IPv6-looking address won't parse here, so
489        // it fails closed (treated as remote).
490        assert!(!host_is_loopback("postgresql://u:p@::1:5432/db"));
491    }
492
493    #[test]
494    fn gate_refuses_remote_plaintext_only() {
495        let remote = "postgresql://rivet:rivet@10.255.255.1:5432/rivet";
496        let loopback = "postgresql://rivet:rivet@127.0.0.1:5432/rivet";
497        let disable = TlsConfig {
498            mode: TlsMode::Disable,
499            ..Default::default()
500        };
501        let verify = TlsConfig {
502            mode: TlsMode::VerifyFull,
503            ..Default::default()
504        };
505
506        // Remote + no tls block → refused.
507        assert!(require_tls_or_loopback(remote, None).is_err());
508        // Loopback + no tls block → allowed (docker / dev path).
509        assert!(require_tls_or_loopback(loopback, None).is_ok());
510        // Explicit `mode: disable` is the remote-plaintext opt-in → allowed.
511        assert!(require_tls_or_loopback(remote, Some(&disable)).is_ok());
512        // Enforced TLS to a remote host → allowed (the connect path uses TLS).
513        assert!(require_tls_or_loopback(remote, Some(&verify)).is_ok());
514    }
515}