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        let num_cols = present.len();
184        let max_rows = (MAX_REDSHIFT_PARAMS / num_cols).max(1);
185        let mut total = 0usize;
186
187        for sub in records.chunks(max_rows) {
188            let sql = insert_statement(&self.table_ref(), &present, sub.len());
189            let mut q = sqlx::query(&sql);
190            for record in sub {
191                let obj = record.as_object().ok_or_else(|| {
192                    FaucetError::Sink("redshift: insert requires JSON object records".into())
193                })?;
194                for col in &present {
195                    q = bind_json(q, obj.get(col));
196                }
197            }
198            q.execute(&self.pool)
199                .await
200                .map_err(|e| FaucetError::Sink(format!("redshift: INSERT failed: {e}")))?;
201            total += sub.len();
202        }
203        Ok(total)
204    }
205}
206
207/// Bind one JSON value onto a `sqlx` query as a native scalar type (so it lands
208/// in a typed Redshift column instead of being coerced from `jsonb`). Missing /
209/// null binds SQL NULL.
210fn bind_json<'q>(
211    query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
212    v: Option<&Value>,
213) -> sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments> {
214    match v {
215        None | Some(Value::Null) => query.bind(None::<String>),
216        Some(Value::String(s)) => query.bind(s.clone()),
217        Some(Value::Bool(b)) => query.bind(*b),
218        Some(Value::Number(n)) => {
219            if n.is_i64() {
220                query.bind(n.as_i64().unwrap())
221            } else if n.is_u64() {
222                query.bind(n.as_u64().unwrap() as i64)
223            } else {
224                query.bind(n.as_f64().unwrap_or(0.0))
225            }
226        }
227        Some(other) => query.bind(other.to_string()),
228    }
229}
230
231#[async_trait]
232impl faucet_core::Sink for RedshiftSink {
233    fn connector_name(&self) -> &'static str {
234        "redshift"
235    }
236
237    fn config_schema(&self) -> Value {
238        serde_json::to_value(faucet_core::schema_for!(RedshiftSinkConfig))
239            .expect("schema serialization")
240    }
241
242    fn supported_write_modes(&self) -> &'static [faucet_core::WriteMode] {
243        // Append-only: Redshift has no ON CONFLICT and COPY cannot upsert.
244        &[faucet_core::WriteMode::Append]
245    }
246
247    fn dataset_uri(&self) -> String {
248        let table = match &self.config.schema {
249            Some(s) => format!("{}.{}", s, self.config.table_name),
250            None => self.config.table_name.clone(),
251        };
252        format!(
253            "redshift://{}:{}/{}?table={}",
254            self.config.connection.host,
255            self.config.connection.port,
256            self.config.connection.database,
257            table
258        )
259    }
260
261    async fn write_batch(&self, records: &[Value]) -> Result<usize, FaucetError> {
262        if records.is_empty() {
263            return Ok(0);
264        }
265        let chunks: Vec<&[Value]> = if self.config.batch_size == 0 {
266            vec![records]
267        } else {
268            records.chunks(self.config.batch_size).collect()
269        };
270
271        let mut total = 0;
272        for chunk in chunks {
273            total += match self.config.write_strategy {
274                RedshiftWriteStrategy::Copy => self.copy_chunk(chunk).await?,
275                RedshiftWriteStrategy::Insert => self.insert_chunk(chunk).await?,
276            };
277        }
278
279        tracing::info!(
280            table = %self.config.table_name,
281            rows = total,
282            strategy = self.config.write_strategy.as_str(),
283            "Redshift write complete"
284        );
285        Ok(total)
286    }
287
288    /// Preflight connectivity probe (`faucet doctor`): acquire a connection and
289    /// run `SELECT 1`. Non-mutating and idempotent.
290    async fn check(
291        &self,
292        ctx: &faucet_core::check::CheckContext,
293    ) -> Result<faucet_core::check::CheckReport, FaucetError> {
294        use faucet_core::check::{CheckReport, Probe};
295
296        let started = std::time::Instant::now();
297        let probe =
298            match tokio::time::timeout(ctx.timeout, sqlx::query("SELECT 1").execute(&self.pool))
299                .await
300            {
301                Ok(Ok(_)) => Probe::pass("auth", started.elapsed()),
302                Ok(Err(e)) => Probe::fail_hint(
303                    "auth",
304                    started.elapsed(),
305                    e.to_string(),
306                    "check host/port/database/user/credentials and that the cluster is reachable",
307                ),
308                Err(_) => Probe::fail_hint(
309                    "auth",
310                    started.elapsed(),
311                    "timed out",
312                    "check host/port/database/user/credentials and that the cluster is reachable",
313                ),
314            };
315        Ok(CheckReport::single(probe))
316    }
317}
318
319#[cfg(test)]
320mod tests {
321    use super::*;
322    use crate::config::{RedshiftCopyFormat, RedshiftWriteStrategy};
323    use faucet_common_redshift::RedshiftConnection;
324    use faucet_core::Sink as _;
325    use serde_json::json;
326
327    fn insert_config() -> RedshiftSinkConfig {
328        RedshiftSinkConfig {
329            connection: RedshiftConnection::new("host", "db", "user", "pw"),
330            table_name: "events".into(),
331            schema: Some("public".into()),
332            write_strategy: RedshiftWriteStrategy::Insert,
333            copy_format: RedshiftCopyFormat::Jsonl,
334            staging_bucket: None,
335            staging_prefix: String::new(),
336            iam_role: None,
337            region: None,
338            endpoint_url: None,
339            batch_size: 1000,
340            max_connections: 5,
341        }
342    }
343
344    fn copy_config() -> RedshiftSinkConfig {
345        RedshiftSinkConfig {
346            write_strategy: RedshiftWriteStrategy::Copy,
347            staging_bucket: Some("stage".into()),
348            staging_prefix: "rs/".into(),
349            iam_role: Some("arn:aws:iam::1:role/r".into()),
350            // Explicit region so building the S3 client resolves without the
351            // default region provider probing IMDS (hermetic, fast tests).
352            region: Some("us-east-1".into()),
353            ..insert_config()
354        }
355    }
356
357    async fn sink(c: RedshiftSinkConfig) -> RedshiftSink {
358        RedshiftSink::new(c).await.unwrap()
359    }
360
361    #[tokio::test]
362    async fn new_insert_has_no_s3_client() {
363        let s = sink(insert_config()).await;
364        assert!(s.s3.is_none());
365    }
366
367    #[tokio::test]
368    async fn new_copy_builds_s3_client() {
369        let s = sink(copy_config()).await;
370        assert!(s.s3.is_some());
371    }
372
373    #[tokio::test]
374    async fn new_rejects_copy_without_bucket() {
375        let mut c = copy_config();
376        c.staging_bucket = None;
377        assert!(matches!(
378            RedshiftSink::new(c).await,
379            Err(FaucetError::Config(_))
380        ));
381    }
382
383    #[tokio::test]
384    async fn new_surfaces_unsupported_credentials() {
385        let mut c = insert_config();
386        c.connection.credentials = faucet_common_redshift::RedshiftCredentials::RedshiftDataApi {
387            region: None,
388            cluster_identifier: None,
389            workgroup_name: None,
390            secret_arn: None,
391            db_user: None,
392        };
393        assert!(matches!(
394            RedshiftSink::new(c).await,
395            Err(FaucetError::Config(_))
396        ));
397    }
398
399    #[tokio::test]
400    async fn connector_name_is_redshift() {
401        assert_eq!(sink(insert_config()).await.connector_name(), "redshift");
402    }
403
404    #[tokio::test]
405    async fn supported_write_modes_is_append_only() {
406        let s = sink(insert_config()).await;
407        assert_eq!(
408            s.supported_write_modes(),
409            [faucet_core::WriteMode::Append].as_slice()
410        );
411    }
412
413    #[tokio::test]
414    async fn dataset_uri_schema_qualified() {
415        let s = sink(insert_config()).await;
416        assert_eq!(
417            s.dataset_uri(),
418            "redshift://host:5439/db?table=public.events"
419        );
420    }
421
422    #[tokio::test]
423    async fn config_schema_reports_required_fields() {
424        let s = sink(insert_config()).await;
425        let schema = s.config_schema();
426        assert!(schema["properties"]["table_name"].is_object());
427        let required = schema["required"].as_array().expect("required array");
428        assert!(required.iter().any(|v| v == "table_name"));
429    }
430
431    #[tokio::test]
432    async fn write_batch_empty_is_zero() {
433        let s = sink(insert_config()).await;
434        assert_eq!(s.write_batch(&[]).await.unwrap(), 0);
435    }
436
437    #[tokio::test]
438    async fn table_ref_and_staging_key() {
439        let s = sink(copy_config()).await;
440        assert_eq!(s.table_ref(), "\"public\".\"events\"");
441        let key = s.staging_key("jsonl");
442        assert!(key.starts_with("rs/"));
443        assert!(key.ends_with(".jsonl"));
444    }
445
446    #[test]
447    fn bind_json_covers_all_scalar_kinds() {
448        // Smoke: binding must not panic for every JSON scalar kind. The actual
449        // wire encoding is exercised by the live integration test.
450        let q = sqlx::query("SELECT $1, $2, $3, $4, $5, $6");
451        let q = bind_json(q, Some(&json!("s")));
452        let q = bind_json(q, Some(&json!(7)));
453        let q = bind_json(q, Some(&json!(7.5)));
454        let q = bind_json(q, Some(&json!(true)));
455        let q = bind_json(q, Some(&Value::Null));
456        let _q = bind_json(q, None);
457    }
458}