rivet/config/export.rs
1//! Per-export configuration: query/table/mode, chunking, format, destination link.
2//!
3//! `SchemaDriftPolicy` lives here because it is only ever read via
4//! [`ExportConfig::on_schema_drift`].
5
6use std::path::Path;
7
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11use super::IncrementalCursorMode;
12use super::destination::DestinationConfig;
13use super::format::{CompressionProfile, CompressionType, FormatType, ParquetConfig};
14use super::resolve::{parse_file_size, resolve_vars};
15use crate::tuning::TuningConfig;
16
17/// What to do when structural schema drift is detected (column added, removed, or retyped).
18///
19/// ```yaml
20/// exports:
21/// - name: orders
22/// on_schema_drift: fail # warn (default), continue, fail
23/// ```
24/// How deep `--validate` must verify each part's integrity.
25#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq, Default)]
26#[serde(rename_all = "snake_case")]
27pub enum VerifyMode {
28 /// Accept size-only verification when no content checksum is available.
29 #[default]
30 Size,
31 /// Require every part's content to be MD5-verified against the store's
32 /// listing; fail validation for any part that is only size-verified.
33 Content,
34}
35
36impl VerifyMode {
37 /// Whether content (not just size) verification is required.
38 pub fn requires_content(self) -> bool {
39 matches!(self, VerifyMode::Content)
40 }
41}
42
43#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq, Default)]
44#[serde(rename_all = "snake_case")]
45pub enum SchemaDriftPolicy {
46 /// Log a warning and continue. The new schema fingerprint is stored. (Default.)
47 #[default]
48 Warn,
49 /// Silently accept schema changes — store the new schema, no log output.
50 Continue,
51 /// Abort the run with a non-zero exit. The schema store is NOT updated so the
52 /// next run will detect the same change again.
53 Fail,
54}
55#[derive(Debug, Deserialize, JsonSchema, Clone)]
56#[serde(deny_unknown_fields)]
57pub struct ExportConfig {
58 pub name: String,
59 #[serde(default)]
60 pub query: Option<String>,
61 pub query_file: Option<String>,
62 /// Shortcut for `query: "SELECT * FROM <schema>.<table>"`.
63 ///
64 /// Accepts `table` or `schema.table` with ASCII-only identifiers
65 /// (`[A-Za-z_][A-Za-z0-9_]*`). Generates an unquoted single-table
66 /// query so the Postgres NUMERIC catalog-hint resolver recognises it
67 /// and auto-types `numeric(p,s)` columns without manual overrides.
68 ///
69 /// Mutually exclusive with `query` and `query_file`.
70 #[serde(default)]
71 pub table: Option<String>,
72 /// CDC only: capture **several** tables through ONE change stream (one
73 /// PostgreSQL slot / one MySQL binlog connection) instead of one export —
74 /// and one slot — per table. Each table's parts land under
75 /// `<destination>/<table>/` with their own `manifest.json` + `_SUCCESS`;
76 /// the checkpoint (stream position) is shared. Mutually exclusive with
77 /// `table:`. Not yet supported for SQL Server (capture instances are
78 /// per-table).
79 #[serde(default)]
80 pub tables: Option<Vec<String>>,
81 #[serde(default = "default_mode")]
82 pub mode: ExportMode,
83 /// Change-data-capture settings, required when `mode: cdc`. Reuses the
84 /// export's `table`, `destination`, and `format`; carries only the
85 /// CDC-specific knobs (resume checkpoint, per-engine stream params).
86 #[serde(default)]
87 pub cdc: Option<CdcExportConfig>,
88 pub cursor_column: Option<String>,
89 /// Secondary column for [`IncrementalCursorMode::Coalesce`] only (see ADR-0007).
90 #[serde(default)]
91 pub cursor_fallback_column: Option<String>,
92 /// How primary (and optional fallback) columns drive incremental progression.
93 #[serde(default)]
94 pub incremental_cursor_mode: IncrementalCursorMode,
95 pub chunk_column: Option<String>,
96 #[serde(default)]
97 pub chunk_dense: bool,
98 #[serde(default = "default_chunk_size")]
99 pub chunk_size: usize,
100 /// Target memory budget per chunk in MB. When set, `chunk_size` is derived
101 /// from this budget at plan-build time using a `pg_class` row-size estimate
102 /// (`pg_relation_size / reltuples`), clamped to `[10_000, 5_000_000]` rows.
103 ///
104 /// Mutually exclusive with an explicit non-default `chunk_size:`. Only
105 /// applies to `mode: chunked` on a Postgres source using the `table:`
106 /// shortcut (the row-size probe needs a known relation).
107 ///
108 /// ```yaml
109 /// exports:
110 /// - name: page_views
111 /// table: public.page_views
112 /// mode: chunked
113 /// chunk_size_memory_mb: 256
114 /// ```
115 #[serde(default)]
116 pub chunk_size_memory_mb: Option<u64>,
117 /// Divide the column range into exactly this many equal chunks.
118 /// Mutually exclusive with `chunk_dense` and `chunk_by_days`.
119 /// When set, `chunk_size` is computed dynamically from min/max.
120 pub chunk_count: Option<usize>,
121 pub chunk_by_days: Option<u32>,
122 /// Keyset (seek) pagination on this single index-backed unique key — the
123 /// source-safe shape for tables without a single-integer PK (OPT-4). The
124 /// column MUST be backed by a usable index (PK or unique); the planner
125 /// refuses a non-indexed key rather than emit a full-scan + filesort query.
126 pub chunk_by_key: Option<String>,
127 #[serde(default = "default_parallel")]
128 pub parallel: usize,
129
130 /// Advisory execution wave (1 = highest priority, run first). Written by
131 /// `rivet plan` from the source-aware prioritization score (see ADR-0006)
132 /// and consumed by `rivet apply`, which runs exports wave-by-wave in
133 /// ascending order. `None` = unscheduled (apply treats it as the last wave).
134 /// Operators may hand-edit it; a later `rivet plan` refreshes it in place.
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub wave: Option<u32>,
137
138 /// Whether this export is cheap enough to run concurrently with its
139 /// wave-mates under `rivet apply --parallel-export-processes`. Written by
140 /// `rivet plan` (true when the source-aware cost class is `Low`, i.e.
141 /// < ~100K rows); a heavier table already chunk-parallelizes internally, so
142 /// two of them at once would overload the source. `None`/`false` → the
143 /// export runs alone within its wave. Operators may hand-edit it; a later
144 /// `rivet plan` refreshes it in place.
145 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub parallel_safe: Option<bool>,
147 pub time_column: Option<String>,
148 #[serde(default = "default_time_column_type")]
149 pub time_column_type: TimeColumnType,
150 pub days_window: Option<u32>,
151
152 /// Date/time output partitioning: split this export's rows into one
153 /// destination sub-prefix per calendar bucket of this **DATE or TIMESTAMP**
154 /// column, bucketed by `partition_granularity`
155 /// (`day` / `month` / `year`), in a Hive-style `col=value/` layout
156 /// (`created_at=2023-01-01/`, `created_at=2023-01/`, `created_at=2023/`).
157 /// Requires a `{partition}` token in `destination.path` /
158 /// `destination.prefix`.
159 ///
160 /// This is **not** arbitrary value partitioning: the column's min/max is
161 /// read and parsed as a date to generate contiguous calendar buckets, so a
162 /// non-temporal column (e.g. `partition_by: status`) fails at run time with
163 /// "could not parse partition min `<value>` from column `<col>` as a date".
164 /// To split by a categorical column, write one export per value with a
165 /// `WHERE` filter instead.
166 ///
167 /// Orthogonal to `mode`: each partition runs the export's own mode, so
168 /// `mode: chunked` chunks *within* a day. Rows whose partition column is
169 /// NULL land in `col=__HIVE_DEFAULT_PARTITION__/` (Hive default partition)
170 /// so no row is silently dropped. Not compatible with `mode: time_window`.
171 ///
172 /// ```yaml
173 /// exports:
174 /// - name: events
175 /// table: events
176 /// partition_by: created_at # must be a DATE or TIMESTAMP column
177 /// partition_granularity: day
178 /// destination:
179 /// type: s3
180 /// bucket: my-bucket
181 /// prefix: "events/{partition}/" # → events/created_at=2023-01-01/
182 /// ```
183 #[serde(default)]
184 pub partition_by: Option<String>,
185
186 /// Calendar bucket width for `partition_by`:
187 /// `day` (default), `month`, or `year`. Determines how the partition
188 /// column's date/timestamp range is split into contiguous Hive buckets
189 /// (`col=2023-01-01/` / `col=2023-01/` / `col=2023/`). Has no effect
190 /// unless `partition_by` is set.
191 #[serde(default)]
192 pub partition_granularity: PartitionGranularity,
193 pub format: FormatType,
194 #[serde(default)]
195 pub compression: CompressionType,
196 pub compression_level: Option<u32>,
197 pub compression_profile: Option<CompressionProfile>,
198 #[serde(default)]
199 pub skip_empty: bool,
200 pub destination: DestinationConfig,
201 /// Integrity depth required of `--validate` for this export's parts.
202 /// `size` (default) accepts size-only verification; `content` requires every
203 /// part's content MD5 to be checked against the store's listing (no
204 /// download) and **fails** validation for any part that could only be
205 /// size-verified — e.g. a part too large to upload as a single PUT (raise
206 /// `max_file_size` down so it fits), or a backend that exposes no checksum.
207 #[serde(default)]
208 pub verify: VerifyMode,
209 #[serde(default)]
210 pub meta_columns: MetaColumns,
211 #[serde(default)]
212 pub quality: Option<QualityConfig>,
213 /// Rotate to a new part when the current file reaches this size.
214 /// Accepts `B`/`KB`/`MB`/`GB` (case-insensitive) or a bare byte count;
215 /// a fractional value is allowed (`1.5GB`). Units are binary (IEC-style):
216 /// `KB` = 1024 bytes, `MB` = 1024 KB, `GB` = 1024 MB. Example: `256MB`.
217 pub max_file_size: Option<String>,
218 /// Persist per-chunk / per-page progress so a **crashed** run resumes from the
219 /// last durably committed point instead of re-reading from the start. This is
220 /// pure crash-recovery: a *clean* re-run (the prior run finished) still does a
221 /// full pass — it never silently skips already-exported rows. Safe to enable
222 /// on any table; `rivet init` defaults it on for chunked and keyset exports.
223 #[serde(default)]
224 pub chunk_checkpoint: bool,
225 /// Keyset only (`chunk_by_key`): on a **clean** re-run, continue from the last
226 /// exported key — pull ONLY rows with a key past the high-water mark. This is
227 /// incremental-by-key, correct ONLY for APPEND-ONLY tables (a mutable row whose
228 /// key already passed is silently never re-read). Opt-in and off by default;
229 /// crash-recovery does not need it (that is `chunk_checkpoint`). For a mutable
230 /// table use `mode: incremental` on a timestamp cursor instead.
231 #[serde(default)]
232 pub keyset_incremental: bool,
233 pub chunk_max_attempts: Option<u32>,
234 #[serde(default)]
235 pub tuning: Option<TuningConfig>,
236 /// Optional logical group for shared source capacity (replica, host). Advisory prioritization only.
237 #[serde(default)]
238 pub source_group: Option<String>,
239 /// Hint (Epic C / ADR-0006) that this export should always be treated as reconcile-heavy
240 /// by planning, independent of the `--reconcile` CLI flag. Advisory only.
241 #[serde(default)]
242 pub reconcile_required: bool,
243
244 /// Per-column type overrides (roadmap §8). Keys are column names; values
245 /// are short type strings such as `decimal(18,2)`, `timestamp_tz`, `json`.
246 ///
247 /// ```yaml
248 /// exports:
249 /// - name: payments
250 /// columns:
251 /// amount: decimal(18,2)
252 /// fee: decimal(18,6)
253 /// created_at: timestamp_tz
254 /// ```
255 ///
256 /// Overrides take priority over autodetection and are validated at
257 /// plan time — an invalid type string fails before the export runs.
258 #[serde(default)]
259 pub columns: std::collections::HashMap<String, String>,
260
261 /// Downstream warehouse this export targets (`bigquery` / `bq`,
262 /// `duckdb`). When set, `rivet check --type-report` resolves each column
263 /// against it (native type, honest autoload type, recovery hint) without
264 /// needing `--target` on the CLI — the CLI flag still wins when both are
265 /// present. The Parquet interchange stays target-neutral (ADR-0014 T2);
266 /// `target:` only drives guidance and the future load-schema artifact.
267 ///
268 /// ```yaml
269 /// exports:
270 /// - name: payments
271 /// target: bigquery
272 /// ```
273 #[serde(default)]
274 pub target: Option<String>,
275
276 /// Per-export overrides for the top-level `load:` block (`pk`,
277 /// `cleanup_source`, `gc_orphans`, `cluster_by`, `allow_source_drift`); any
278 /// field omitted here inherits the top-level value. The warehouse `target`
279 /// is shared and stays in the top-level `load:` — it cannot be overridden
280 /// per export.
281 ///
282 /// ```yaml
283 /// load: { target: bigquery, project: p, dataset: d } # shared default
284 /// exports:
285 /// - name: orders
286 /// table: orders
287 /// mode: cdc
288 /// load: { pk: [id] } # this table's pk
289 /// ```
290 ///
291 /// Raw JSON (parsed by the load module) so `config` carries no load types —
292 /// mirrors the top-level [`crate::config::Config::load`].
293 #[serde(default)]
294 pub load: Option<serde_json::Value>,
295
296 /// Policy applied when structural schema drift is detected (column added, removed, or retyped).
297 /// Defaults to `warn`: log a warning and continue.
298 #[serde(default)]
299 pub on_schema_drift: SchemaDriftPolicy,
300
301 /// Growth-factor threshold for data shape drift warnings (Epic 8).
302 /// When a string/binary column's max observed byte length in the current run
303 /// exceeds `stored_max * shape_drift_warn_factor`, Rivet logs a warning.
304 /// `None` uses the default of 2.0. Set to `0.0` to disable shape tracking.
305 ///
306 /// **Scope: single-batch exports only** (`mode: full` / `incremental`). Shape
307 /// tracking needs the run-wide per-column max byte length, which only the
308 /// single sink accumulates; the multi-part runners (chunked, keyset, and
309 /// parallel-Mongo) each write through several sinks and do not aggregate it,
310 /// so this factor is inert there. (Schema drift — added/dropped/retyped
311 /// columns — IS enforced on every path via `on_schema_drift`.)
312 #[serde(default)]
313 pub shape_drift_warn_factor: Option<f64>,
314
315 /// Parquet row group tuning. Only meaningful when `format: parquet`.
316 /// When absent, the parquet library default (1,048,576 rows/group) is used.
317 #[serde(default)]
318 pub parquet: Option<ParquetConfig>,
319}
320
321impl ExportConfig {
322 /// Resolve the effective `(CompressionType, level)` for this export.
323 /// `compression_profile` takes precedence over `compression` + `compression_level`.
324 ///
325 /// L24: when a profile is set *and* a conflicting explicit codec/level was
326 /// written, warn once that the profile wins rather than silently dropping the
327 /// explicit choice. An explicit codec is only detectable when it differs from
328 /// the `#[serde(default)]` (Zstd) — a literal `compression: zstd` alongside a
329 /// profile is indistinguishable from an omitted field and stays silent.
330 pub fn effective_compression(&self) -> (CompressionType, Option<u32>) {
331 if let Some(profile) = self.compression_profile {
332 let explicit_codec =
333 (self.compression != CompressionType::default()).then_some(self.compression);
334 if let Some(msg) = super::format::compression_profile_override_warning(
335 profile,
336 explicit_codec,
337 self.compression_level,
338 ) {
339 log::warn!("export '{}': {}", self.name, msg);
340 }
341 profile.to_codec()
342 } else {
343 (self.compression, self.compression_level)
344 }
345 }
346
347 pub fn max_file_size_bytes(&self) -> Option<u64> {
348 self.max_file_size
349 .as_ref()
350 .and_then(|s| parse_file_size(s).ok())
351 }
352
353 pub fn resolve_query(
354 &self,
355 config_dir: &Path,
356 params: Option<&std::collections::HashMap<String, String>>,
357 ) -> crate::error::Result<String> {
358 // table: shortcut takes precedence — already validated by
359 // `validate_business_rules` to be mutually exclusive with query/query_file.
360 if let Some(tbl) = &self.table {
361 validate_table_shortcut_ident(&self.name, tbl)?;
362 return Ok(format!("SELECT * FROM {tbl}"));
363 }
364 match (&self.query, &self.query_file) {
365 (Some(q), None) => {
366 if params.is_some() {
367 resolve_vars(q, params)
368 } else {
369 Ok(q.clone())
370 }
371 }
372 (None, Some(file)) => {
373 let file_path = std::path::Path::new(file);
374 // SecOps: block absolute paths and `..` traversal components.
375 if file_path.is_absolute() {
376 anyhow::bail!(
377 "export '{}': query_file must be a relative path: '{}'",
378 self.name,
379 file
380 );
381 }
382 if file_path
383 .components()
384 .any(|c| c == std::path::Component::ParentDir)
385 {
386 anyhow::bail!(
387 "export '{}': query_file path must not contain '..': '{}'",
388 self.name,
389 file
390 );
391 }
392 let joined = config_dir.join(file);
393 // Canonicalize-based check catches symlink-based evasion for files
394 // that already exist on disk.
395 if let Ok(canonical) = joined.canonicalize() {
396 let base = config_dir
397 .canonicalize()
398 .unwrap_or_else(|_| config_dir.to_path_buf());
399 if !canonical.starts_with(&base) {
400 anyhow::bail!(
401 "export '{}': query_file '{}' resolves outside the config directory",
402 self.name,
403 file
404 );
405 }
406 }
407 let raw = std::fs::read_to_string(&joined)?;
408 resolve_vars(&raw, params)
409 }
410 (Some(_), Some(_)) => {
411 anyhow::bail!(
412 "export '{}': specify either 'query' or 'query_file', not both",
413 self.name
414 )
415 }
416 (None, None) => {
417 anyhow::bail!(
418 "export '{}': must specify exactly one of 'query', 'query_file', or 'table'",
419 self.name
420 )
421 }
422 }
423 }
424}
425
426/// Validate the value of the `table:` YAML shortcut.
427///
428/// Accepts ASCII identifiers in the form `<table>` or `<schema>.<table>`. Each
429/// segment must match `[A-Za-z_][A-Za-z0-9_]*`. Anything else (quoted
430/// identifiers, exotic chars, three-part names, SQL injection attempts) is
431/// rejected — the user should fall back to `query:` for those cases.
432///
433/// The bound on identifier shape keeps generated SQL safe to interpolate
434/// without quoting and ensures the generated `SELECT * FROM <ident>` form is
435/// recognised by the PG catalog-hint parser ([src/source/postgres.rs]).
436fn validate_table_shortcut_ident(export_name: &str, raw: &str) -> crate::error::Result<()> {
437 let trimmed = raw.trim();
438 if trimmed.is_empty() {
439 anyhow::bail!("export '{export_name}': 'table' is empty");
440 }
441 let parts: Vec<&str> = trimmed.split('.').collect();
442 if parts.len() > 2 {
443 anyhow::bail!(
444 "export '{export_name}': 'table' must be `<name>` or `<schema>.<name>` (got '{raw}')"
445 );
446 }
447 for part in &parts {
448 if part.is_empty() {
449 anyhow::bail!("export '{export_name}': 'table' has an empty segment in '{raw}'");
450 }
451 let mut chars = part.chars();
452 let first = chars.next().unwrap();
453 if !(first.is_ascii_alphabetic() || first == '_') {
454 anyhow::bail!(
455 "export '{export_name}': 'table' segment '{part}' must start with a letter or underscore (use 'query:' for quoted identifiers)"
456 );
457 }
458 if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
459 anyhow::bail!(
460 "export '{export_name}': 'table' segment '{part}' contains non-identifier characters (use 'query:' for quoted identifiers)"
461 );
462 }
463 }
464 Ok(())
465}
466
467#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone)]
468#[serde(deny_unknown_fields)]
469pub struct QualityConfig {
470 pub row_count_min: Option<usize>,
471 pub row_count_max: Option<usize>,
472 #[serde(default)]
473 pub null_ratio_max: std::collections::HashMap<String, f64>,
474 #[serde(default)]
475 pub unique_columns: Vec<String>,
476 /// Cap on the number of distinct values tracked per column during uniqueness checks.
477 /// When the limit is hit, a Warn issue is emitted and tracking stops for that column.
478 /// Prevents unbounded HashSet growth on high-cardinality columns.
479 pub unique_max_entries: Option<usize>,
480}
481
482#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Default)]
483#[serde(deny_unknown_fields)]
484pub struct MetaColumns {
485 #[serde(default)]
486 pub exported_at: bool,
487 #[serde(default)]
488 pub row_hash: bool,
489}
490
491impl MetaColumns {
492 /// True iff the operator asked for at least one meta column. The batch
493 /// runners inject these at the shared `ExportSink` seam; the CDC path has
494 /// its OWN sink (`__op`/`__pos`/`__seq` + typed after-image) and does not,
495 /// so a CDC run uses this to warn that the request has no effect.
496 pub fn any_enabled(&self) -> bool {
497 self.exported_at || self.row_hash
498 }
499}
500
501fn default_mode() -> ExportMode {
502 ExportMode::Full
503}
504
505pub(crate) fn default_chunk_size() -> usize {
506 100_000
507}
508
509fn default_parallel() -> usize {
510 1
511}
512
513fn default_time_column_type() -> TimeColumnType {
514 TimeColumnType::Timestamp
515}
516
517/// `until_current` defaults to `true` — the OSS model is the BOUNDED, scheduler-
518/// driven drain ("read to the log end and exit"). Continuous streaming
519/// (`until_current: false`) is an explicit opt-in; making it the default silently
520/// put a hand-written CDC config onto the never-terminating streaming path.
521fn default_true() -> bool {
522 true
523}
524
525#[derive(Debug, Deserialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
526#[serde(rename_all = "snake_case")]
527pub enum ExportMode {
528 Full,
529 Incremental,
530 Chunked,
531 TimeWindow,
532 /// Log-based change data capture (see [`CdcExportConfig`]): stream
533 /// INSERT/UPDATE/DELETE from the source's transaction log instead of querying
534 /// the table. Reuses the export's `table` / `destination` / `format`.
535 Cdc,
536}
537
538/// Default PostgreSQL logical slot when `cdc.slot` is omitted — shared by the
539/// runner ([`crate::pipeline`]'s cdc job) and config validation, so the
540/// same-slot conflict check sees the value that will actually be used.
541pub const DEFAULT_PG_SLOT: &str = "rivet_slot";
542/// Default MySQL replica `server_id` when `cdc.server_id` is omitted (see
543/// [`DEFAULT_PG_SLOT`] for why this is a shared const).
544pub const DEFAULT_MYSQL_SERVER_ID: u32 = 4271;
545
546/// What the FIRST CDC run does before draining changes.
547#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
548#[serde(rename_all = "lowercase")]
549pub enum CdcInitialMode {
550 /// Anchor-then-snapshot: create the resume anchor (PostgreSQL slot /
551 /// MySQL binlog checkpoint / SQL Server LSN checkpoint) FIRST, then run a
552 /// full batch snapshot of each table into `<destination>[/<table>]/snapshot/`,
553 /// then drain CDC. Because the anchor predates the snapshot read, anything
554 /// changed during the snapshot also appears in the change stream — an
555 /// overlap (dedupe by PK + `__op`), never a gap. The safe switch ordering,
556 /// enforced by construction instead of operator discipline.
557 Snapshot,
558}
559
560/// Per-export CDC settings, required when `mode: cdc`. The output `table`,
561/// `destination`, and `format` come from the export itself; this carries only the
562/// CDC-specific knobs (resume + per-engine stream params).
563#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone)]
564pub struct CdcExportConfig {
565 /// First-run behaviour: `snapshot` = anchor → full snapshot → drain (see
566 /// [`CdcInitialMode`]). Omitted ⇒ capture changes only (the default; the
567 /// operator owns the initial load).
568 #[serde(default)]
569 pub initial: Option<CdcInitialMode>,
570 /// Persist/resume the source log position to this file. Omit to tail from the
571 /// current position without checkpointing.
572 pub checkpoint: Option<String>,
573 /// Catch up to the source's current end and exit (a bounded run), instead of
574 /// streaming indefinitely — ideal for a scheduler. For MySQL this is a
575 /// non-blocking binlog dump; PostgreSQL / SQL Server already drain-and-exit.
576 /// **Defaults to `true`** (bounded): the OSS model is scheduler-driven, and
577 /// omitting this must NOT silently start a never-terminating stream. Set it to
578 /// `false` to opt into continuous streaming explicitly.
579 #[serde(default = "default_true")]
580 pub until_current: bool,
581 /// Stop after N change events (default: until end of stream / interrupted).
582 pub max_events: Option<usize>,
583 /// Rows per output part file (default 100000). A part also rolls at a
584 /// transaction boundary, so it never splits a transaction. Larger ⇒ fewer,
585 /// bigger files but more drain memory — the PostgreSQL peek reads a part's
586 /// worth per batch, so drain RSS is O(rollover). Tune per workload: raise it
587 /// to cut file count, lower it to cap memory on a small extractor.
588 pub rollover: Option<usize>,
589 /// Roll a part once its buffered changes reach this many MB, whichever comes
590 /// first with `rollover`. Caps the in-memory buffer and the part file size by
591 /// bytes instead of a fixed row count — predictable for tables with wide
592 /// (large JSON / blob) rows, mirroring the batch path's `batch_size_memory_mb`.
593 pub rollover_memory_mb: Option<usize>,
594 /// MySQL replica server-id for the binlog connection (default 4271; must be
595 /// distinct from the source's and any other replica).
596 pub server_id: Option<u32>,
597 /// PostgreSQL logical replication slot name (default `rivet_slot`).
598 pub slot: Option<String>,
599 /// SQL Server CDC capture instance, e.g. `dbo_orders` — required for
600 /// `sqlserver://` sources.
601 pub capture_instance: Option<String>,
602}
603
604// Hand-written so the Rust `Default` MATCHES the serde default: `until_current`
605// must be `true` (bounded). The derived `Default` would use `bool::default()` =
606// `false`, and serde's `default = "default_true"` only affects Deserialize — so
607// `CdcExportConfig::default()` would silently mean `DrainMode::Continuous`. That
608// default is reached on the drain path (`cdc_job.rs`: `export.cdc.clone()
609// .unwrap_or_default()`) whenever a `mode: cdc` export omits the whole `cdc:`
610// block (valid for PG/MySQL), turning a minimal bounded drain into a
611// never-terminating daemon that persists no resume position — the exact footgun
612// `default_true` was added to kill. Mirrors `MongoConfig`'s hand-written Default.
613impl Default for CdcExportConfig {
614 fn default() -> Self {
615 Self {
616 initial: None,
617 checkpoint: None,
618 until_current: true,
619 max_events: None,
620 rollover: None,
621 rollover_memory_mb: None,
622 server_id: None,
623 slot: None,
624 capture_instance: None,
625 }
626 }
627}
628
629#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq)]
630#[serde(rename_all = "lowercase")]
631pub enum TimeColumnType {
632 Timestamp,
633 Unix,
634}
635
636/// Calendar bucket width for date/timestamp output partitioning
637/// ([`ExportConfig::partition_by`]). The partition column must be a DATE or
638/// TIMESTAMP column; this picks how its range is split into contiguous Hive
639/// buckets. It is not a knob for partitioning by arbitrary column values.
640#[derive(Debug, Deserialize, Serialize, JsonSchema, Clone, Copy, PartialEq, Eq, Default)]
641#[serde(rename_all = "lowercase")]
642pub enum PartitionGranularity {
643 /// One bucket per calendar day (`col=2023-01-01/`). Default.
644 #[default]
645 Day,
646 /// One bucket per calendar month (`col=2023-01/`).
647 Month,
648 /// One bucket per calendar year (`col=2023/`).
649 Year,
650}
651
652/// Canonical fully-populated [`ExportConfig`] for tests across the crate.
653///
654/// One place lists every field, so adding a field is a single-site edit (the
655/// compiler still flags this literal if a field is missing). Test call sites
656/// take this baseline and override only the fields they exercise, rather than
657/// hand-writing the full struct — see `plan::build` and `preflight` tests.
658#[cfg(test)]
659pub(crate) fn sample_export(name: &str) -> ExportConfig {
660 ExportConfig {
661 name: name.into(),
662 target: None,
663 load: None,
664 verify: VerifyMode::Size,
665 query: Some("SELECT 1".into()),
666 query_file: None,
667 table: None,
668 tables: None,
669 mode: ExportMode::Full,
670 cdc: None,
671 cursor_column: None,
672 cursor_fallback_column: None,
673 incremental_cursor_mode: Default::default(),
674 chunk_column: None,
675 chunk_dense: false,
676 chunk_size: 100_000,
677 chunk_size_memory_mb: None,
678 chunk_count: None,
679 chunk_by_days: None,
680 chunk_by_key: None,
681 parallel: 1,
682 wave: None,
683 parallel_safe: None,
684 time_column: None,
685 time_column_type: TimeColumnType::Timestamp,
686 days_window: None,
687 partition_by: None,
688 partition_granularity: PartitionGranularity::Day,
689 format: FormatType::Parquet,
690 compression: CompressionType::None,
691 compression_level: None,
692 compression_profile: None,
693 skip_empty: false,
694 destination: crate::config::DestinationConfig {
695 destination_type: crate::config::DestinationType::Local,
696 path: Some("/tmp".into()),
697 ..Default::default()
698 },
699 meta_columns: MetaColumns::default(),
700 quality: None,
701 max_file_size: None,
702 chunk_checkpoint: false,
703 keyset_incremental: false,
704 chunk_max_attempts: None,
705 tuning: None,
706 source_group: None,
707 reconcile_required: false,
708 columns: Default::default(),
709 on_schema_drift: Default::default(),
710 shape_drift_warn_factor: None,
711 parquet: None,
712 }
713}
714
715#[cfg(test)]
716mod tests {
717 use super::*;
718
719 // ── ExportConfig::max_file_size_bytes ───────────────────────────────────
720
721 fn make_export_yaml(name: &str, extra: &str) -> ExportConfig {
722 let yaml = format!(
723 "name: {name}\nquery: \"SELECT 1\"\nformat: parquet\ndestination:\n type: local\n path: /tmp\n{extra}"
724 );
725 serde_yaml_ng::from_str(&yaml).expect("parse ExportConfig")
726 }
727
728 #[test]
729 fn max_file_size_bytes_none_when_unset() {
730 let exp = make_export_yaml("no_limit", "");
731 assert!(exp.max_file_size_bytes().is_none());
732 }
733
734 #[test]
735 fn max_file_size_bytes_parses_mb() {
736 let exp = make_export_yaml("sized", "max_file_size: \"128MB\"\n");
737 assert_eq!(exp.max_file_size_bytes(), Some(128 * 1024 * 1024));
738 }
739
740 #[test]
741 fn max_file_size_bytes_parses_gb() {
742 let exp = make_export_yaml("sized_gb", "max_file_size: \"2GB\"\n");
743 assert_eq!(exp.max_file_size_bytes(), Some(2 * 1024 * 1024 * 1024));
744 }
745
746 #[test]
747 fn max_file_size_bytes_returns_none_on_invalid() {
748 let exp = make_export_yaml("bad_size", "max_file_size: \"notanumber\"\n");
749 assert!(exp.max_file_size_bytes().is_none());
750 }
751
752 // ── ExportConfig::resolve_query ─────────────────────────────────────────
753
754 // Build a minimal ExportConfig directly, bypassing Config::from_yaml validation.
755 // This lets us test the four branches inside resolve_query itself, including
756 // the (both-set / neither-set) error paths that are normally prevented by the
757 // top-level validator.
758 fn make_export_direct(query: Option<&str>, query_file: Option<&str>) -> ExportConfig {
759 ExportConfig {
760 query: query.map(|s| s.to_string()),
761 query_file: query_file.map(|s| s.to_string()),
762 ..sample_export("test")
763 }
764 }
765
766 fn params(pairs: &[(&str, &str)]) -> std::collections::HashMap<String, String> {
767 pairs
768 .iter()
769 .map(|(k, v)| (k.to_string(), v.to_string()))
770 .collect()
771 }
772
773 #[test]
774 fn resolve_query_inline_no_params_returns_query_as_is() {
775 let exp = make_export_direct(Some("SELECT id FROM orders"), None);
776 let q = exp.resolve_query(Path::new("/tmp"), None).unwrap();
777 assert_eq!(q, "SELECT id FROM orders");
778 }
779
780 #[test]
781 fn resolve_query_inline_with_params_substitutes_vars() {
782 let exp = make_export_direct(Some("SELECT ${col} FROM ${table}"), None);
783 let p = params(&[("col", "id"), ("table", "orders")]);
784 let q = exp.resolve_query(Path::new("/tmp"), Some(&p)).unwrap();
785 assert_eq!(q, "SELECT id FROM orders");
786 }
787
788 #[test]
789 fn resolve_query_inline_params_empty_map_is_noop() {
790 let exp = make_export_direct(Some("SELECT 1"), None);
791 let p = params(&[]);
792 let q = exp.resolve_query(Path::new("/tmp"), Some(&p)).unwrap();
793 assert_eq!(q, "SELECT 1");
794 }
795
796 #[test]
797 fn resolve_query_inline_missing_var_returns_error() {
798 // SAFETY: test-only; this binary is single-threaded in the test runner context.
799 unsafe { std::env::remove_var("UNSET_RIVET_TEST_VAR") };
800 let exp = make_export_direct(Some("SELECT ${UNSET_RIVET_TEST_VAR}"), None);
801 let p = params(&[]);
802 let result = exp.resolve_query(Path::new("/tmp"), Some(&p));
803 assert!(result.is_err());
804 let msg = format!("{:#}", result.unwrap_err());
805 assert!(
806 msg.contains("UNSET_RIVET_TEST_VAR") || msg.contains("not set"),
807 "got: {msg}"
808 );
809 }
810
811 #[test]
812 fn resolve_query_file_reads_content() {
813 let dir = tempfile::TempDir::new().unwrap();
814 let sql_path = dir.path().join("query.sql");
815 std::fs::write(&sql_path, "SELECT * FROM customers").unwrap();
816 let exp = make_export_direct(None, Some("query.sql"));
817 let q = exp.resolve_query(dir.path(), None).unwrap();
818 assert_eq!(q, "SELECT * FROM customers");
819 }
820
821 #[test]
822 fn resolve_query_file_with_params_substitutes() {
823 let dir = tempfile::TempDir::new().unwrap();
824 let sql_path = dir.path().join("q.sql");
825 std::fs::write(&sql_path, "SELECT ${col} FROM ${tbl}").unwrap();
826 let exp = make_export_direct(None, Some("q.sql"));
827 let p = params(&[("col", "name"), ("tbl", "users")]);
828 let q = exp.resolve_query(dir.path(), Some(&p)).unwrap();
829 assert_eq!(q, "SELECT name FROM users");
830 }
831
832 // ── `table:` shortcut ───────────────────────────────────────────────────
833
834 #[test]
835 fn resolve_query_table_shortcut_qualified() {
836 let mut exp = make_export_direct(None, None);
837 exp.table = Some("public.users".into());
838 let q = exp.resolve_query(Path::new("/tmp"), None).unwrap();
839 assert_eq!(q, "SELECT * FROM public.users");
840 }
841
842 #[test]
843 fn resolve_query_table_shortcut_unqualified() {
844 let mut exp = make_export_direct(None, None);
845 exp.table = Some("orders".into());
846 let q = exp.resolve_query(Path::new("/tmp"), None).unwrap();
847 assert_eq!(q, "SELECT * FROM orders");
848 }
849
850 #[test]
851 fn resolve_query_table_shortcut_rejects_three_part_name() {
852 let mut exp = make_export_direct(None, None);
853 exp.table = Some("db.public.users".into());
854 let err = exp.resolve_query(Path::new("/tmp"), None).unwrap_err();
855 let msg = format!("{err:#}");
856 assert!(msg.contains("<schema>.<name>"), "got: {msg}");
857 }
858
859 #[test]
860 fn resolve_query_table_shortcut_rejects_sql_injection() {
861 for bad in [
862 "users; DROP TABLE x",
863 "users--",
864 "users'",
865 "users\"",
866 "public.\"My Table\"",
867 "0starts_with_digit",
868 "",
869 ".trailing",
870 "leading.",
871 "two..dots",
872 ] {
873 let mut exp = make_export_direct(None, None);
874 exp.table = Some(bad.into());
875 assert!(
876 exp.resolve_query(Path::new("/tmp"), None).is_err(),
877 "should reject `table:` value '{bad}'",
878 );
879 }
880 }
881
882 #[test]
883 fn resolve_query_table_shortcut_takes_precedence_over_query() {
884 let mut exp = make_export_direct(Some("SELECT id FROM x"), None);
885 exp.table = Some("public.y".into());
886 let q = exp.resolve_query(Path::new("/tmp"), None).unwrap();
887 assert_eq!(q, "SELECT * FROM public.y");
888 }
889
890 #[test]
891 fn resolve_query_file_missing_returns_error() {
892 let dir = tempfile::TempDir::new().unwrap();
893 let exp = make_export_direct(None, Some("nonexistent.sql"));
894 let result = exp.resolve_query(dir.path(), None);
895 assert!(result.is_err());
896 let msg = format!("{:#}", result.unwrap_err());
897 assert!(
898 msg.contains("nonexistent.sql") || msg.contains("No such file"),
899 "got: {msg}"
900 );
901 }
902
903 #[test]
904 fn resolve_query_both_set_returns_error() {
905 let mut exp = make_export_direct(Some("SELECT 1"), None);
906 exp.query_file = Some("file.sql".into());
907 let result = exp.resolve_query(Path::new("/tmp"), None);
908 assert!(result.is_err());
909 let msg = format!("{:#}", result.unwrap_err());
910 assert!(
911 msg.contains("not both") || msg.contains("query_file"),
912 "got: {msg}"
913 );
914 }
915
916 #[test]
917 fn resolve_query_neither_set_returns_error() {
918 let exp = make_export_direct(None, None);
919 let result = exp.resolve_query(Path::new("/tmp"), None);
920 assert!(result.is_err());
921 let msg = format!("{:#}", result.unwrap_err());
922 assert!(
923 msg.contains("query") || msg.contains("query_file"),
924 "got: {msg}"
925 );
926 }
927
928 // ── SecOps: query_file path traversal prevention ──────────────────────────
929
930 #[test]
931 fn resolve_query_file_dotdot_is_rejected() {
932 let dir = tempfile::TempDir::new().unwrap();
933 let exp = make_export_direct(None, Some("../secret.sql"));
934 let result = exp.resolve_query(dir.path(), None);
935 assert!(result.is_err());
936 let msg = format!("{:#}", result.unwrap_err());
937 assert!(
938 msg.contains("..") || msg.contains("traversal"),
939 "got: {msg}"
940 );
941 }
942
943 #[test]
944 fn resolve_query_file_nested_dotdot_is_rejected() {
945 let dir = tempfile::TempDir::new().unwrap();
946 let exp = make_export_direct(None, Some("subdir/../../etc/passwd"));
947 let result = exp.resolve_query(dir.path(), None);
948 assert!(result.is_err());
949 let msg = format!("{:#}", result.unwrap_err());
950 assert!(
951 msg.contains("..") || msg.contains("traversal"),
952 "got: {msg}"
953 );
954 }
955
956 #[test]
957 fn resolve_query_file_absolute_path_is_rejected() {
958 let dir = tempfile::TempDir::new().unwrap();
959 let exp = make_export_direct(None, Some("/etc/passwd"));
960 let result = exp.resolve_query(dir.path(), None);
961 assert!(result.is_err());
962 let msg = format!("{:#}", result.unwrap_err());
963 assert!(
964 msg.contains("relative") || msg.contains("absolute"),
965 "got: {msg}"
966 );
967 }
968
969 #[test]
970 fn resolve_query_file_in_subdir_is_allowed() {
971 let dir = tempfile::TempDir::new().unwrap();
972 let subdir = dir.path().join("queries");
973 std::fs::create_dir(&subdir).unwrap();
974 std::fs::write(subdir.join("orders.sql"), "SELECT * FROM orders").unwrap();
975 let exp = make_export_direct(None, Some("queries/orders.sql"));
976 let q = exp.resolve_query(dir.path(), None).unwrap();
977 assert_eq!(q, "SELECT * FROM orders");
978 }
979}