rivet/source/mod.rs
1pub mod mysql;
2pub(crate) mod pg_numeric_wire;
3pub mod postgres;
4pub(crate) mod query;
5pub(crate) mod tls;
6
7use arrow::datatypes::SchemaRef;
8use arrow::record_batch::RecordBatch;
9
10use crate::config::SourceConfig;
11use crate::error::Result;
12use crate::plan::IncrementalCursorPlan;
13use crate::tuning::SourceTuning;
14use crate::types::{ColumnOverrides, CursorState, TypeMapping};
15
16/// Summary of a source table relevant to chunked-mode planning. Source-neutral
17/// shape so plan-build can ask either Postgres or MySQL for the same answer.
18///
19/// Populated by `crate::source::postgres::introspect_pg_table_for_chunking` and
20/// `crate::source::mysql::introspect_mysql_table_for_chunking`. Both helpers
21/// rely on catalog stats (`pg_class` / `information_schema.TABLES`) so the
22/// numbers are only as fresh as the last `ANALYZE` / autoanalyse.
23///
24/// # Why this is a data-shape seam, not a trait
25///
26/// The two per-engine introspection functions have identical signatures
27/// (`fn(url, tls, qualified_table) -> Result<TableIntrospection>`) and return
28/// this shared struct. The parallel shape sometimes invites a refactor along
29/// the lines of `trait Introspector { fn introspect_table(...) }` with one
30/// impl per engine — that refactor adds ceremony without reducing duplication,
31/// because the *bodies* share nothing useful: PG queries `pg_class` /
32/// `pg_index` / `pg_attribute` / `pg_type` (PG-specific type names like
33/// `int2`/`int4`/`int8`) via the `postgres` client; MySQL queries
34/// `information_schema.TABLES` / `STATISTICS` with the InnoDB
35/// `AVG_ROW_LENGTH` overflow correction via the `mysql` client. No shared
36/// implementation logic exists to extract into trait-default methods. A
37/// trait would only rename where the engine match happens
38/// (`match config.source.source_type { … }` at the call site → factory
39/// returning `Box<dyn Introspector>`); the match doesn't disappear.
40///
41/// The seam therefore lives at the **data shape**: this struct is the
42/// shared contract, the two free functions are the adapters, the per-call
43/// dispatch is an `enum`-driven `match`. See ADR-0015 for the full
44/// rationale and the architecture-review walks that led here.
45#[derive(Debug, Clone, Default)]
46pub(crate) struct TableIntrospection {
47 /// Name of the single integer-family PK column, if present and safe to
48 /// range-chunk. `None` when the table has no PK, has a composite PK, or
49 /// the PK type is not an integer family (text, uuid, decimal, …).
50 pub single_int_pk: Option<String>,
51 /// Single-column, NOT NULL, **unique** index columns usable as a keyset
52 /// (seek) pagination key — PK first (any type), then other UNIQUE indexes
53 /// (OPT-4). Index-backed and unique by construction, so `ORDER BY key
54 /// LIMIT n` is a bounded index range scan (never a filesort) and
55 /// `WHERE key > last` never skips rows with a duplicate key. Empty when the
56 /// table has no such key.
57 pub keyset_keys: Vec<String>,
58 /// Best-effort row count: PG `reltuples`, MySQL `TABLE_ROWS`. `0` means
59 /// the table is empty or stats are unavailable.
60 pub row_estimate: i64,
61 /// Heap-size-per-row in bytes. `None` for empty / unanalysed tables.
62 /// Used to convert `chunk_size_memory_mb` into a row count.
63 pub avg_row_bytes: Option<i64>,
64}
65
66impl TableIntrospection {
67 /// The auto-selected keyset key: the first usable single-column unique
68 /// NOT NULL key (PK preferred). `None` when the table has none.
69 pub fn auto_keyset_key(&self) -> Option<&str> {
70 self.keyset_keys.first().map(String::as_str)
71 }
72
73 /// Whether `col` is a usable keyset key (single-column, unique, NOT NULL,
74 /// index-backed). Used to validate an explicit `chunk_by_key`.
75 pub fn is_usable_keyset_key(&self, col: &str) -> bool {
76 self.keyset_keys.iter().any(|k| k == col)
77 }
78}
79
80/// Receives schema and batches from a source, one at a time.
81pub trait BatchSink {
82 fn on_schema(&mut self, schema: SchemaRef) -> Result<()>;
83 fn on_batch(&mut self, batch: &RecordBatch) -> Result<()>;
84}
85
86/// Read-only inputs for a single export call.
87///
88/// Packs the parameters that used to live as 5 positional args on
89/// `Source::export` into a named struct. `sink` is **not** part of this struct
90/// — it is `&mut` and conceptually the output channel, separate from the
91/// read-only request configuration.
92pub struct ExportRequest<'a> {
93 /// Already-materialized SQL (after `resolve_query`). The driver still wraps
94 /// it with the dialect-specific incremental predicate via
95 /// [`crate::source::query::build_incremental_query`] when `incremental` is set.
96 pub query: &'a str,
97 /// The *unwrapped* base query to resolve catalog-dependent type hints from
98 /// (PostgreSQL `NUMERIC` precision/scale, which the wire protocol omits — the
99 /// driver parses the `FROM` clause and asks `pg_catalog`). Chunked, dense and
100 /// keyset runners wrap `query` in a `SELECT … FROM (<base>) …` subquery that
101 /// hides the source table from the catalog parser, so they pass the original
102 /// base query here. `None` ⇒ resolve from `query` (full/incremental, where it
103 /// is already the unwrapped form). Drivers that read precision from the wire
104 /// (MySQL) ignore this field.
105 pub catalog_hint_query: Option<&'a str>,
106 pub incremental: Option<&'a IncrementalCursorPlan>,
107 pub cursor: Option<&'a CursorState>,
108 pub tuning: &'a SourceTuning,
109 /// Per-column type declarations from `rivet.yaml` (`exports[].columns:`).
110 /// Drivers apply them during schema building so e.g. a `NUMERIC` column
111 /// without declared precision can still be exported as `Decimal128(18,2)`
112 /// when the user has stated the type explicitly.
113 pub column_overrides: &'a ColumnOverrides,
114 /// Keyset (seek) pagination page size (OPT-4). When `Some(n)` *and*
115 /// `incremental` carries the key plan, the driver builds one keyset page
116 /// (`WHERE key > cursor ORDER BY key LIMIT n`) instead of the unbounded
117 /// incremental/snapshot query. The keyset runner drives the outer loop.
118 pub page_limit: Option<usize>,
119}
120
121impl<'a> ExportRequest<'a> {
122 /// A request whose `query` is already the **unwrapped base** form, so
123 /// catalog type hints resolve directly from it. Use for snapshot,
124 /// incremental and keyset runners: the driver applies any incremental /
125 /// keyset predicate internally, so the source table stays visible to the
126 /// catalog parser and `catalog_hint_query` is `None`.
127 pub fn unwrapped(
128 query: &'a str,
129 tuning: &'a SourceTuning,
130 column_overrides: &'a ColumnOverrides,
131 ) -> Self {
132 Self {
133 query,
134 catalog_hint_query: None,
135 incremental: None,
136 cursor: None,
137 tuning,
138 column_overrides,
139 page_limit: None,
140 }
141 }
142
143 /// A request whose `query` is a `SELECT … FROM (<base>) …` **wrapper** that
144 /// hides the source table (chunked / dense / time-window). `base` — the
145 /// unwrapped query catalog hints resolve from — is a required argument, so a
146 /// wrapping runner cannot silently fall back to the table-hiding wrapper and
147 /// lose PG `NUMERIC` precision (the bug the catalog-hint fix / ADR-0020
148 /// closed). Drivers that read precision from the wire (MySQL) ignore it.
149 pub fn wrapped(
150 query: &'a str,
151 base: &'a str,
152 tuning: &'a SourceTuning,
153 column_overrides: &'a ColumnOverrides,
154 ) -> Self {
155 Self {
156 query,
157 catalog_hint_query: Some(base),
158 incremental: None,
159 cursor: None,
160 tuning,
161 column_overrides,
162 page_limit: None,
163 }
164 }
165
166 /// Attach the incremental cursor plan (the driver builds the `WHERE cursor >
167 /// ? ORDER BY` predicate). Pass-through `Option` so mode-polymorphic callers
168 /// can forward `strategy.incremental_plan()` directly.
169 pub fn with_incremental(mut self, plan: Option<&'a IncrementalCursorPlan>) -> Self {
170 self.incremental = plan;
171 self
172 }
173
174 /// Attach the last committed cursor value the next run resumes after.
175 pub fn with_cursor(mut self, cursor: Option<&'a CursorState>) -> Self {
176 self.cursor = cursor;
177 self
178 }
179
180 /// Set the keyset (seek) page size — one bounded `… WHERE key > cursor ORDER
181 /// BY key LIMIT n` page instead of the unbounded query.
182 pub fn with_page_limit(mut self, page_limit: usize) -> Self {
183 self.page_limit = Some(page_limit);
184 self
185 }
186}
187
188pub trait Source: Send {
189 /// Execute `request.query` and stream batches into `sink`.
190 fn export(&mut self, request: &ExportRequest<'_>, sink: &mut dyn BatchSink) -> Result<()>;
191
192 fn query_scalar(&mut self, sql: &str) -> Result<Option<String>>;
193
194 /// Return `TypeMapping` for every column in `query` without fetching rows.
195 ///
196 /// Used by `rivet check --type-report` to show the full type provenance
197 /// (source native type → RivetType → Arrow type → fidelity) before export.
198 /// Implementations execute `SELECT * FROM (...) AS _q LIMIT 0` so only
199 /// server-side type metadata is transferred.
200 fn type_mappings(
201 &mut self,
202 query: &str,
203 column_overrides: &ColumnOverrides,
204 ) -> Result<Vec<TypeMapping>>;
205
206 /// Sample a monotonic source-pressure counter for the OPT-2 concurrency
207 /// governor (`pipeline::chunked::exec`).
208 ///
209 /// Higher = more pressure. The governor compares successive samples
210 /// (`cur > prev` ⇒ under pressure) — the same convention the adaptive
211 /// batch-size loop already uses. Returns `None` when the engine can't
212 /// cheaply sample a pressure proxy, in which case the governor holds
213 /// parallelism flat. Default: `None`.
214 fn sample_pressure(&mut self) -> Option<u64> {
215 None
216 }
217}
218
219pub fn create_source(config: &SourceConfig) -> Result<Box<dyn Source>> {
220 use crate::config::SourceType;
221 let url = config.resolve_url()?;
222 warn_if_tls_disabled(config);
223 match config.source_type {
224 SourceType::Postgres => Ok(Box::new(postgres::PostgresSource::connect_with_tls(
225 &url,
226 config.tls.as_ref(),
227 )?)),
228 SourceType::Mysql => Ok(Box::new(mysql::MysqlSource::connect_with_tls(
229 &url,
230 config.tls.as_ref(),
231 )?)),
232 }
233}
234
235/// One-time nudge to enable TLS when the current config connects in plaintext.
236/// Emitted at `warn` level so operators see it even at the default log level.
237/// `create_source` is called multiple times per run (plan/preflight/exec/chunk
238/// workers), so we gate the warning behind a `Once` to fire exactly once per
239/// process rather than 3-4 times in stderr.
240pub(crate) fn warn_if_tls_disabled(config: &SourceConfig) {
241 let enforced = config.tls.as_ref().is_some_and(|t| t.mode.is_enforced());
242 if !enforced {
243 static WARNED: std::sync::Once = std::sync::Once::new();
244 WARNED.call_once(|| {
245 log::warn!(
246 "source: TLS is not enforced — credentials and result rows cross the network in plaintext. \
247 Add `source.tls.mode: verify-full` (with `ca_file:` if your CA is private) to enable transport security."
248 );
249 });
250 }
251}