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