Skip to main content

faucet_source_redshift/
config.rs

1//! Amazon Redshift source configuration.
2
3use faucet_common_redshift::RedshiftConnection;
4use faucet_core::{DEFAULT_BATCH_SIZE, FaucetError};
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9/// How the Redshift source replicates rows across runs.
10///
11/// Serializes as `{ type: full }` or
12/// `{ type: incremental, column: "...", initial_value: ... }`.
13#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, Default, PartialEq)]
14#[serde(tag = "type", rename_all = "snake_case")]
15pub enum RedshiftReplication {
16    /// Every run re-fetches the full result set (default).
17    #[default]
18    Full,
19    /// Only rows not yet read, in `column` order, resuming from the stored
20    /// bookmark (or `initial_value` on the first run).
21    ///
22    /// The source wraps the query as
23    /// `SELECT * FROM (<query>) AS q WHERE q."column" >= CAST($n AS <type>) ORDER BY q."column"`
24    /// (the column's type as the server describes it) and drops the rows it
25    /// already emitted at the bookmark value, so rows that share a cursor
26    /// value (batch loads stamped with one `updated_at`, COPY jobs landing in
27    /// several commits) are never skipped. Every page carries a bookmark, so
28    /// a crash replays at most one page. Write `${bookmark}` in the query
29    /// (with `>=`) to apply the cursor further inside it; a strict `>` is
30    /// refused. Rows whose `column` is NULL are never read.
31    Incremental {
32        /// Column whose value is the replication cursor (e.g. `updated_at`).
33        column: String,
34        /// Lower bound (inclusive) used on the first run, before any bookmark
35        /// is stored.
36        initial_value: Value,
37    },
38}
39
40fn default_max_connections() -> u32 {
41    10
42}
43
44fn default_batch_size() -> usize {
45    DEFAULT_BATCH_SIZE
46}
47
48/// Configuration for the Amazon Redshift query source.
49#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
50pub struct RedshiftSourceConfig {
51    /// Connection block (host / port / database / user / credentials / tls),
52    /// flattened to the config top level.
53    #[serde(flatten)]
54    pub connection: RedshiftConnection,
55    /// SQL query to execute. May contain `${field.path}` parent-context tokens
56    /// (resolved to positional binds at runtime) and, for incremental
57    /// replication, a `${bookmark}` token.
58    pub query: String,
59    /// Positional bind parameters for the query, applied in `$1, $2, …` order
60    /// before any context- or bookmark-derived values. Defaults to empty.
61    #[serde(default)]
62    pub params: Vec<Value>,
63    /// Maximum number of connections in the pool. Defaults to 10.
64    #[serde(default = "default_max_connections")]
65    pub max_connections: u32,
66    /// Records per emitted [`StreamPage`](faucet_core::StreamPage). Rows are
67    /// drained from the `sqlx` cursor and yielded whenever the buffer reaches
68    /// this size. Defaults to [`DEFAULT_BATCH_SIZE`].
69    ///
70    /// `batch_size = 0` is the "no batching" sentinel: the cursor is fully
71    /// drained and the entire result set is emitted in a single page.
72    #[serde(default = "default_batch_size")]
73    pub batch_size: usize,
74    /// Replication mode. Defaults to [`RedshiftReplication::Full`].
75    #[serde(default)]
76    pub replication: RedshiftReplication,
77    /// Explicit state-store key for the incremental bookmark. When unset, a key
78    /// is derived from the host / database and a query fingerprint.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub state_key: Option<String>,
81}
82
83impl RedshiftSourceConfig {
84    /// Validate the config; returns a human-readable error if invalid.
85    pub fn validate(&self) -> Result<(), FaucetError> {
86        if self.query.trim().is_empty() {
87            return Err(FaucetError::Config(
88                "redshift: `query` must not be empty".into(),
89            ));
90        }
91        faucet_core::validate_batch_size(self.batch_size)?;
92        let RedshiftReplication::Incremental {
93            column,
94            initial_value,
95        } = &self.replication
96        else {
97            return Ok(());
98        };
99        if column.trim().is_empty() {
100            return Err(FaucetError::Config(
101                "redshift: incremental replication `column` must not be empty".into(),
102            ));
103        }
104        if initial_value.is_null() {
105            return Err(FaucetError::Config(
106                "redshift: incremental replication requires a non-null `initial_value`".into(),
107            ));
108        }
109        if faucet_core::replication::cursor::strict_comparison(&self.query, BOOKMARK_TOKEN) {
110            return Err(FaucetError::Config(format!(
111                "redshift: compare `{BOOKMARK_TOKEN}` with `>=`, not `>`: the source re-reads \
112                 the bookmark value and drops the rows it already emitted, and a strict \
113                 comparison skips rows that share it"
114            )));
115        }
116        Ok(())
117    }
118}
119
120/// The token a query uses to read the incremental bookmark
121/// (`WHERE updated_at >= ${bookmark}`).
122pub const BOOKMARK_TOKEN: &str = "${bookmark}";
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use faucet_common_redshift::RedshiftConnection;
128    use serde_json::json;
129
130    fn base() -> RedshiftSourceConfig {
131        RedshiftSourceConfig {
132            connection: RedshiftConnection::new("host", "db", "user", "pw"),
133            query: "SELECT * FROM events".into(),
134            params: Vec::new(),
135            max_connections: default_max_connections(),
136            batch_size: DEFAULT_BATCH_SIZE,
137            replication: RedshiftReplication::Full,
138            state_key: None,
139        }
140    }
141
142    #[test]
143    fn valid_config_passes() {
144        base().validate().unwrap();
145    }
146
147    #[test]
148    fn rejects_empty_query() {
149        let mut c = base();
150        c.query = "  ".into();
151        assert!(c.validate().is_err());
152    }
153
154    #[test]
155    fn rejects_empty_incremental_column() {
156        let mut c = base();
157        c.replication = RedshiftReplication::Incremental {
158            column: "".into(),
159            initial_value: json!(0),
160        };
161        assert!(c.validate().is_err());
162    }
163
164    #[test]
165    fn rejects_bad_incremental_settings() {
166        for (query, initial, needle) in [
167            ("SELECT * FROM t", json!(null), "initial_value"),
168            ("SELECT * FROM t WHERE ts > ${bookmark}", json!(0), ">="),
169        ] {
170            let mut c = base();
171            c.query = query.into();
172            c.replication = RedshiftReplication::Incremental {
173                column: "ts".into(),
174                initial_value: initial,
175            };
176            let err = c.validate().unwrap_err().to_string();
177            assert!(err.contains(needle), "{err}");
178        }
179    }
180
181    #[test]
182    fn rejects_oversized_batch() {
183        let mut c = base();
184        c.batch_size = faucet_core::MAX_BATCH_SIZE + 1;
185        assert!(c.validate().is_err());
186    }
187
188    #[test]
189    fn deserializes_flattened_connection_and_defaults() {
190        let json = r#"{
191            "host": "h",
192            "database": "db",
193            "user": "u",
194            "credentials": {"type": "password", "config": {"password": "pw"}},
195            "query": "SELECT 1"
196        }"#;
197        let c: RedshiftSourceConfig = serde_json::from_str(json).unwrap();
198        assert_eq!(c.connection.host, "h");
199        assert_eq!(c.connection.port, faucet_common_redshift::DEFAULT_PORT);
200        assert_eq!(c.max_connections, 10);
201        assert_eq!(c.batch_size, DEFAULT_BATCH_SIZE);
202        assert!(matches!(c.replication, RedshiftReplication::Full));
203        c.validate().unwrap();
204    }
205
206    #[test]
207    fn deserializes_incremental_replication() {
208        let json = r#"{
209            "host": "h",
210            "database": "db",
211            "user": "u",
212            "credentials": {"type": "password", "config": {"password": "pw"}},
213            "query": "SELECT * FROM t WHERE ts >= ${bookmark}",
214            "replication": {"type": "incremental", "column": "ts", "initial_value": "2026-01-01"},
215            "state_key": "my-key"
216        }"#;
217        let c: RedshiftSourceConfig = serde_json::from_str(json).unwrap();
218        match &c.replication {
219            RedshiftReplication::Incremental {
220                column,
221                initial_value,
222            } => {
223                assert_eq!(column, "ts");
224                assert_eq!(initial_value, &json!("2026-01-01"));
225            }
226            _ => panic!("expected incremental"),
227        }
228        assert_eq!(c.state_key.as_deref(), Some("my-key"));
229    }
230}