Skip to main content

faucet_sink_redshift/
sink.rs

1//! Amazon Redshift sink implementation.
2//!
3//! Two load paths, selected by `write_strategy`:
4//! - `copy` (default) — stage each page to S3 (JSONL or CSV) and bulk-load it
5//!   with `COPY … FROM 's3://…' IAM_ROLE '…'`, then best-effort delete the
6//!   staged object. This is Redshift's recommended, fastest load path.
7//! - `insert` — multi-row `INSERT INTO … VALUES (…), (…)`. Portable, no S3, but
8//!   slower for bulk data.
9//!
10//! Append-only (`supported_write_modes` = `[Append]`): Redshift has no
11//! `ON CONFLICT`, and `COPY` cannot upsert.
12
13use async_trait::async_trait;
14use aws_sdk_s3::Client as S3Client;
15use faucet_core::FaucetError;
16use serde_json::Value;
17use sqlx::{PgPool, Row};
18
19use crate::config::{RedshiftCopyFormat, RedshiftSinkConfig, RedshiftWriteStrategy};
20use crate::copy::{
21    columns_present, copy_statement, insert_statement, qualified_table_ref, s3_uri, serialize_csv,
22    serialize_jsonl,
23};
24
25/// Redshift caps bind parameters per statement; keep multi-row `INSERT`s under
26/// this by sub-chunking.
27const MAX_REDSHIFT_PARAMS: usize = 32_767;
28
29/// A sink that loads JSON records into an Amazon Redshift table.
30pub struct RedshiftSink {
31    config: RedshiftSinkConfig,
32    pool: PgPool,
33    /// S3 client, built only for the `copy` strategy.
34    s3: Option<S3Client>,
35}
36
37impl RedshiftSink {
38    /// Create a new sink. Validates config, builds a lazily-connected pool (no
39    /// DB I/O), and — for the `copy` strategy — an S3 client.
40    pub async fn new(config: RedshiftSinkConfig) -> Result<Self, FaucetError> {
41        config.validate()?;
42        let pool =
43            faucet_common_redshift::build_pool_lazy(&config.connection, config.max_connections)?;
44        let s3 = if config.write_strategy == RedshiftWriteStrategy::Copy {
45            Some(Self::build_s3_client(&config).await)
46        } else {
47            None
48        };
49        Ok(Self { config, pool, s3 })
50    }
51
52    /// Build an S3 client honouring the optional region / endpoint overrides.
53    async fn build_s3_client(config: &RedshiftSinkConfig) -> S3Client {
54        let mut loader = aws_config::defaults(aws_config::BehaviorVersion::latest());
55        if let Some(region) = &config.region {
56            loader = loader.region(aws_config::Region::new(region.clone()));
57        }
58        if let Some(endpoint) = &config.endpoint_url {
59            loader = loader.endpoint_url(endpoint);
60        }
61        let sdk_config = loader.load().await;
62        S3Client::new(&sdk_config)
63    }
64
65    fn table_ref(&self) -> String {
66        qualified_table_ref(self.config.schema.as_deref(), &self.config.table_name)
67    }
68
69    /// Generate a unique staging object key for one page.
70    fn staging_key(&self, ext: &str) -> String {
71        let id = uuid::Uuid::new_v4();
72        format!("{}{}.{}", self.config.staging_prefix, id, ext)
73    }
74
75    /// Discover the destination table's column names in ordinal order via
76    /// `information_schema.columns`. Used by the `insert` path and the CSV
77    /// `copy` path (both need the column set/order).
78    async fn discover_columns(&self) -> Result<Vec<String>, FaucetError> {
79        let rows = sqlx::query(
80            "SELECT column_name FROM information_schema.columns \
81             WHERE table_name = $1 AND ($2::text IS NULL OR table_schema = $2) \
82             ORDER BY ordinal_position",
83        )
84        .bind(&self.config.table_name)
85        .bind(self.config.schema.as_deref())
86        .fetch_all(&self.pool)
87        .await
88        .map_err(|e| FaucetError::Sink(format!("redshift: column discovery failed: {e}")))?;
89
90        let cols: Vec<String> = rows
91            .iter()
92            .map(|r| r.get::<String, _>("column_name"))
93            .collect();
94        if cols.is_empty() {
95            return Err(FaucetError::Sink(format!(
96                "redshift: table {} has no columns or does not exist",
97                self.config.table_name
98            )));
99        }
100        Ok(cols)
101    }
102
103    /// Load one chunk via the `COPY`-from-S3 fast path.
104    async fn copy_chunk(&self, records: &[Value]) -> Result<usize, FaucetError> {
105        if records.is_empty() {
106            return Ok(0);
107        }
108        let s3 = self.s3.as_ref().ok_or_else(|| {
109            FaucetError::Sink("redshift: S3 client not initialized for copy strategy".into())
110        })?;
111        let bucket = self.config.staging_bucket.as_deref().ok_or_else(|| {
112            FaucetError::Sink("redshift: staging_bucket is required for copy strategy".into())
113        })?;
114        let iam_role = self.config.iam_role.as_deref().ok_or_else(|| {
115            FaucetError::Sink("redshift: iam_role is required for copy strategy".into())
116        })?;
117
118        // Serialize the page and, for CSV, learn the destination column order.
119        let (body, columns): (Vec<u8>, Option<Vec<String>>) = match self.config.copy_format {
120            RedshiftCopyFormat::Jsonl => (serialize_jsonl(records)?, None),
121            RedshiftCopyFormat::Csv => {
122                let cols = self.discover_columns().await?;
123                (serialize_csv(records, &cols)?, Some(cols))
124            }
125        };
126        let ext = match self.config.copy_format {
127            RedshiftCopyFormat::Jsonl => "jsonl",
128            RedshiftCopyFormat::Csv => "csv",
129        };
130        let key = self.staging_key(ext);
131
132        // 1. Upload the staged object.
133        s3.put_object()
134            .bucket(bucket)
135            .key(&key)
136            .body(body.into())
137            .send()
138            .await
139            .map_err(|e| {
140                FaucetError::Sink(format!("redshift: S3 upload failed for key '{key}': {e}"))
141            })?;
142
143        // 2. COPY it into the table.
144        let sql = copy_statement(
145            &self.table_ref(),
146            columns.as_deref(),
147            &s3_uri(bucket, &key),
148            iam_role,
149            self.config.region.as_deref(),
150            self.config.copy_format,
151        );
152        let copy_result = sqlx::query(&sql).execute(&self.pool).await;
153
154        // 3. Best-effort cleanup of the staged object (regardless of COPY
155        //    outcome — a failed COPY still leaves the object behind).
156        if let Err(e) = s3.delete_object().bucket(bucket).key(&key).send().await {
157            tracing::warn!(key = %key, error = %e, "redshift: failed to delete staged S3 object (best-effort)");
158        }
159
160        copy_result.map_err(|e| FaucetError::Sink(format!("redshift: COPY failed: {e}")))?;
161        Ok(records.len())
162    }
163
164    /// Load one chunk via multi-row `INSERT`, sub-chunked to respect the bind
165    /// parameter cap.
166    async fn insert_chunk(&self, records: &[Value]) -> Result<usize, FaucetError> {
167        if records.is_empty() {
168            return Ok(0);
169        }
170        let table_columns = self.discover_columns().await?;
171        let present: Vec<String> = columns_present(records, &table_columns)
172            .into_iter()
173            .cloned()
174            .collect();
175        if present.is_empty() {
176            tracing::warn!(
177                table = %self.config.table_name,
178                "redshift: no record keys match table columns; skipping insert"
179            );
180            return Ok(0);
181        }
182
183        // Drop records that share *no* column with the table. `present` is the
184        // union of table columns across the page, so binding such a record would
185        // emit an all-NULL row rather than the data the caller sent — the DuckDB
186        // and SQLite sinks skip it, and so do we (#466 L1). A record with at
187        // least one matching column is still inserted (missing columns → NULL).
188        let insertable: Vec<&Value> = records
189            .iter()
190            .filter(|r| crate::copy::shares_a_column(r, &present))
191            .collect();
192        let skipped = records.len() - insertable.len();
193        if skipped > 0 {
194            tracing::warn!(
195                table = %self.config.table_name,
196                skipped,
197                "redshift: skipped record(s) with no column matching the table \
198                 (would have inserted an all-NULL row)"
199            );
200        }
201        if insertable.is_empty() {
202            return Ok(0);
203        }
204
205        let num_cols = present.len();
206        let max_rows = (MAX_REDSHIFT_PARAMS / num_cols).max(1);
207        let mut total = 0usize;
208
209        for sub in insertable.chunks(max_rows) {
210            let sql = insert_statement(&self.table_ref(), &present, sub.len());
211            let mut q = sqlx::query(&sql);
212            for record in sub {
213                let obj = record.as_object().ok_or_else(|| {
214                    FaucetError::Sink("redshift: insert requires JSON object records".into())
215                })?;
216                for col in &present {
217                    q = bind_json(q, obj.get(col), col)?;
218                }
219            }
220            q.execute(&self.pool)
221                .await
222                .map_err(|e| FaucetError::Sink(format!("redshift: INSERT failed: {e}")))?;
223            total += sub.len();
224        }
225        Ok(total)
226    }
227}
228
229/// Bind one JSON value onto a `sqlx` query as a native scalar type (so it lands
230/// in a typed Redshift column instead of being coerced from `jsonb`). Missing /
231/// null binds SQL NULL.
232fn bind_json<'q>(
233    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
234    v: Option<&Value>,
235    column: &str,
236) -> Result<sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>, FaucetError> {
237    Ok(match v {
238        None | Some(Value::Null) => query.bind(None::<String>),
239        Some(Value::String(s)) => query.bind(s.clone()),
240        Some(Value::Bool(b)) => query.bind(*b),
241        Some(Value::Number(n)) => {
242            if n.is_i64() {
243                query.bind(n.as_i64().unwrap())
244            } else if n.is_u64() {
245                // Above `i64::MAX`. Redshift's BIGINT is signed and `as i64`
246                // would *wrap*, writing the id as a large negative number with
247                // nothing raised. Refuse instead (#462).
248                query.bind(faucet_core::util::u64_to_signed(
249                    n.as_u64().unwrap(),
250                    &format!("column {}", faucet_core::util::quote_ident(column)),
251                )?)
252            } else {
253                query.bind(n.as_f64().unwrap_or(0.0))
254            }
255        }
256        Some(other) => query.bind(other.to_string()),
257    })
258}
259
260#[async_trait]
261impl faucet_core::Sink for RedshiftSink {
262    fn connector_name(&self) -> &'static str {
263        "redshift"
264    }
265
266    fn config_schema(&self) -> Value {
267        serde_json::to_value(faucet_core::schema_for!(RedshiftSinkConfig))
268            .expect("schema serialization")
269    }
270
271    fn supported_write_modes(&self) -> &'static [faucet_core::WriteMode] {
272        // Append-only: Redshift has no ON CONFLICT and COPY cannot upsert.
273        &[faucet_core::WriteMode::Append]
274    }
275
276    fn dataset_uri(&self) -> String {
277        let table = match &self.config.schema {
278            Some(s) => format!("{}.{}", s, self.config.table_name),
279            None => self.config.table_name.clone(),
280        };
281        format!(
282            "redshift://{}:{}/{}?table={}",
283            self.config.connection.host,
284            self.config.connection.port,
285            self.config.connection.database,
286            table
287        )
288    }
289
290    async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
291        if records.is_empty() {
292            return Ok(0);
293        }
294        let chunks: Vec<&[Value]> = if self.config.batch_size == 0 {
295            vec![records]
296        } else {
297            records.chunks(self.config.batch_size).collect()
298        };
299
300        let mut total = 0;
301        for chunk in chunks {
302            total += match self.config.write_strategy {
303                RedshiftWriteStrategy::Copy => self.copy_chunk(chunk).await?,
304                RedshiftWriteStrategy::Insert => self.insert_chunk(chunk).await?,
305            };
306        }
307
308        tracing::info!(
309            table = %self.config.table_name,
310            rows = total,
311            strategy = self.config.write_strategy.as_str(),
312            "Redshift write complete"
313        );
314        Ok(total)
315    }
316
317    /// Preflight connectivity probe (`faucet doctor`): acquire a connection and
318    /// run `SELECT 1`. Non-mutating and idempotent.
319    async fn check(
320        &self,
321        ctx: &faucet_core::check::CheckContext,
322    ) -> Result<faucet_core::check::CheckReport, FaucetError> {
323        use faucet_core::check::{CheckReport, Probe};
324
325        let started = std::time::Instant::now();
326        let probe =
327            match tokio::time::timeout(ctx.timeout, sqlx::query("SELECT 1").execute(&self.pool))
328                .await
329            {
330                Ok(Ok(_)) => Probe::pass("auth", started.elapsed()),
331                Ok(Err(e)) => Probe::fail_hint(
332                    "auth",
333                    started.elapsed(),
334                    e.to_string(),
335                    "check host/port/database/user/credentials and that the cluster is reachable",
336                ),
337                Err(_) => Probe::fail_hint(
338                    "auth",
339                    started.elapsed(),
340                    "timed out",
341                    "check host/port/database/user/credentials and that the cluster is reachable",
342                ),
343            };
344        Ok(CheckReport::single(probe))
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351    use crate::config::{RedshiftCopyFormat, RedshiftWriteStrategy};
352    use faucet_common_redshift::RedshiftConnection;
353    use faucet_core::Sink as _;
354    use serde_json::json;
355
356    fn insert_config() -> RedshiftSinkConfig {
357        RedshiftSinkConfig {
358            connection: RedshiftConnection::new("host", "db", "user", "pw"),
359            table_name: "events".into(),
360            schema: Some("public".into()),
361            write_strategy: RedshiftWriteStrategy::Insert,
362            copy_format: RedshiftCopyFormat::Jsonl,
363            staging_bucket: None,
364            staging_prefix: String::new(),
365            iam_role: None,
366            region: None,
367            endpoint_url: None,
368            batch_size: 1000,
369            max_connections: 5,
370        }
371    }
372
373    fn copy_config() -> RedshiftSinkConfig {
374        RedshiftSinkConfig {
375            write_strategy: RedshiftWriteStrategy::Copy,
376            staging_bucket: Some("stage".into()),
377            staging_prefix: "rs/".into(),
378            iam_role: Some("arn:aws:iam::1:role/r".into()),
379            // Explicit region so building the S3 client resolves without the
380            // default region provider probing IMDS (hermetic, fast tests).
381            region: Some("us-east-1".into()),
382            ..insert_config()
383        }
384    }
385
386    async fn sink(c: RedshiftSinkConfig) -> RedshiftSink {
387        RedshiftSink::new(c).await.unwrap()
388    }
389
390    #[tokio::test]
391    async fn new_insert_has_no_s3_client() {
392        let s = sink(insert_config()).await;
393        assert!(s.s3.is_none());
394    }
395
396    #[tokio::test]
397    async fn new_copy_builds_s3_client() {
398        let s = sink(copy_config()).await;
399        assert!(s.s3.is_some());
400    }
401
402    #[tokio::test]
403    async fn new_rejects_copy_without_bucket() {
404        let mut c = copy_config();
405        c.staging_bucket = None;
406        assert!(matches!(
407            RedshiftSink::new(c).await,
408            Err(FaucetError::Config(_))
409        ));
410    }
411
412    #[tokio::test]
413    async fn new_surfaces_unsupported_credentials() {
414        let mut c = insert_config();
415        c.connection.credentials = faucet_common_redshift::RedshiftCredentials::RedshiftDataApi {
416            region: None,
417            cluster_identifier: None,
418            workgroup_name: None,
419            secret_arn: None,
420            db_user: None,
421        };
422        assert!(matches!(
423            RedshiftSink::new(c).await,
424            Err(FaucetError::Config(_))
425        ));
426    }
427
428    #[tokio::test]
429    async fn connector_name_is_redshift() {
430        assert_eq!(sink(insert_config()).await.connector_name(), "redshift");
431    }
432
433    #[tokio::test]
434    async fn supported_write_modes_is_append_only() {
435        let s = sink(insert_config()).await;
436        assert_eq!(
437            s.supported_write_modes(),
438            [faucet_core::WriteMode::Append].as_slice()
439        );
440    }
441
442    #[tokio::test]
443    async fn dataset_uri_schema_qualified() {
444        let s = sink(insert_config()).await;
445        assert_eq!(
446            s.dataset_uri(),
447            "redshift://host:5439/db?table=public.events"
448        );
449    }
450
451    #[tokio::test]
452    async fn config_schema_reports_required_fields() {
453        let s = sink(insert_config()).await;
454        let schema = s.config_schema();
455        assert!(schema["properties"]["table_name"].is_object());
456        let required = schema["required"].as_array().expect("required array");
457        assert!(required.iter().any(|v| v == "table_name"));
458    }
459
460    #[tokio::test]
461    async fn write_batch_empty_is_zero() {
462        let s = sink(insert_config()).await;
463        assert_eq!(s.write_batch(&[]).await.unwrap(), 0);
464    }
465
466    #[tokio::test]
467    async fn table_ref_and_staging_key() {
468        let s = sink(copy_config()).await;
469        assert_eq!(s.table_ref(), "\"public\".\"events\"");
470        let key = s.staging_key("jsonl");
471        assert!(key.starts_with("rs/"));
472        assert!(key.ends_with(".jsonl"));
473    }
474
475    #[test]
476    fn bind_json_covers_all_scalar_kinds() {
477        // Smoke: binding must not panic for every JSON scalar kind. The actual
478        // wire encoding is exercised by the live integration test.
479        let q = sqlx::query("SELECT $1, $2, $3, $4, $5, $6");
480        let q = bind_json(q, Some(&json!("s")), "c").unwrap();
481        let q = bind_json(q, Some(&json!(7)), "c").unwrap();
482        let q = bind_json(q, Some(&json!(7.5)), "c").unwrap();
483        let q = bind_json(q, Some(&json!(true)), "c").unwrap();
484        let q = bind_json(q, Some(&Value::Null), "c").unwrap();
485        let _q = bind_json(q, None, "c").unwrap();
486
487        // #462: a u64 above i64::MAX must be refused, not wrapped negative.
488        let q = sqlx::query("SELECT 1");
489        let err = match bind_json(q, Some(&json!(u64::MAX)), "big_id") {
490            Err(e) => e.to_string(),
491            Ok(_) => panic!("u64::MAX must not bind to a signed BIGINT"),
492        };
493        assert!(err.contains("big_id"), "{err}");
494        assert!(err.contains(&u64::MAX.to_string()), "{err}");
495    }
496}