Skip to main content

feldera_types/transport/
dynamodb.rs

1use crate::size::{ConfigSize, LegacySizeUnit};
2use serde::{Deserialize, Serialize};
3use utoipa::ToSchema;
4
5/// Connectors by default start with 1 worker thread.
6/// Increasing the number of threads helps scale the encoding process; however, for
7/// DynamoDB, encoding is often not the bottleneck, writing to DynamoDB is.
8fn default_threads() -> usize {
9    1
10}
11
12/// Ten retries with the ~13s backoff ceiling retry for roughly one minute:
13/// enough to ride out transient throttling, bounded enough not to stall the
14/// pipeline forever. Set `max_retries` to `null` for unbounded.
15fn default_max_retries() -> Option<u8> {
16    Some(10)
17}
18
19fn default_max_buffer_size() -> ConfigSize {
20    ConfigSize::from_mib(1)
21}
22fn schema_default_max_buffer_size() -> String {
23    default_max_buffer_size().to_string()
24}
25crate::required_size_setting!(
26    size_max_buffer_size,
27    "max_buffer_size",
28    LegacySizeUnit::Bytes
29);
30
31/// Number of concurrent requests made to DynamoDB at any time.
32/// Increasing this may improve the throughput, but may also cause
33/// throttling and increase retries.
34///
35/// 64 concurrent requests mean at any time, we submit a maximum of:
36/// - 64 * 25 Batch items
37/// - 64 * 100 Transactional items
38fn default_max_concurrent_requests() -> usize {
39    64
40}
41
42/// Batch mode allows for higher throughput than transactional mode.
43fn default_write_mode() -> DynamoDBWriteMode {
44    DynamoDBWriteMode::Batch
45}
46
47/// DynamoDB write API used by the output connector.
48#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
49#[serde(rename_all = "snake_case")]
50pub enum DynamoDBWriteMode {
51    /// Use DynamoDB [`BatchWriteItem`].
52    ///
53    /// This is the high-throughput path. Each request writes up to 25 items,
54    /// and each item costs one write capacity unit (WCU). Writes are flushed at
55    /// batch end, but DynamoDB does not make the whole batch atomic: some items
56    /// in a request may succeed while others fail (and are retried).
57    ///
58    /// [`BatchWriteItem`]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_BatchWriteItem.html
59    Batch,
60
61    /// Use DynamoDB [`TransactWriteItems`].
62    ///
63    /// This provides atomicity for each transaction chunk: either all items in
64    /// the request are written or none are. It is substantially slower than
65    /// `Batch` and is limited to 100 writes per request.
66    ///
67    /// [`TransactWriteItems`]: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TransactWriteItems.html
68    Transactional,
69}
70
71/// DynamoDB output connector configuration.
72#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
73pub struct DynamoDBWriterConfig {
74    /// Name of the DynamoDB table to write to.
75    pub table: String,
76
77    /// AWS region.
78    pub region: String,
79
80    /// Optional endpoint URL, for example when using a local
81    /// DynamoDB-compatible service.
82    pub endpoint_url: Option<String>,
83
84    /// AWS access key ID.
85    ///
86    /// If both `aws_access_key_id` and `aws_secret_access_key` are specified,
87    /// the connector uses these static credentials. Otherwise it uses the
88    /// default AWS credential provider chain, including IAM Roles for Service
89    /// Accounts (IRSA) in EKS.
90    ///
91    /// Static credentials are treated as long-lived IAM keys: no session token
92    /// is sent, so STS-issued temporary credentials are not supported via these
93    /// fields. To use temporary credentials, rely on the default provider chain
94    /// instead (leave these unset).
95    pub aws_access_key_id: Option<String>,
96
97    /// AWS secret access key.
98    pub aws_secret_access_key: Option<String>,
99
100    /// Maximum number of write requests in one DynamoDB write call.
101    ///
102    /// DynamoDB supports at most 100 for `TransactWriteItems` and at most 25
103    /// for `BatchWriteItem`. If omitted, the connector uses the maximum for
104    /// the selected `write_mode`.
105    #[serde(default)]
106    pub batch_size: Option<usize>,
107
108    /// Write API to use when flushing records at batch end.
109    ///
110    /// The default is `batch`, where each worker bulk-writes its own split
111    /// using DynamoDB `BatchWriteItem`.
112    #[serde(default = "default_write_mode")]
113    #[schema(default = default_write_mode)]
114    pub write_mode: DynamoDBWriteMode,
115
116    /// Maximum size of the data buffered by each worker before flushing
117    /// writes, such as `"1Mi"`.
118    ///
119    /// This is an approximate size based on encoded DynamoDB attributes.
120    ///
121    /// Before release 0.367.0 this setting was `max_buffer_size_bytes`, a
122    /// number of bytes. That name is deprecated but still read.
123    #[serde(
124        default = "default_max_buffer_size",
125        alias = "max_buffer_size_bytes",
126        deserialize_with = "size_max_buffer_size"
127    )]
128    #[schema(value_type = String, default = schema_default_max_buffer_size)]
129    pub max_buffer_size: ConfigSize,
130
131    /// Maximum number of DynamoDB write requests in flight per worker thread.
132    ///
133    /// The total in-flight request count across the connector is
134    /// `threads × max_concurrent_requests`. Size this accordingly when
135    /// tuning against a provisioned-throughput table to avoid excessive
136    /// throttling.
137    #[serde(default = "default_max_concurrent_requests")]
138    #[schema(default = default_max_concurrent_requests)]
139    pub max_concurrent_requests: usize,
140
141    /// Number of worker threads used to encode and write disjoint key ranges.
142    #[serde(default = "default_threads")]
143    #[schema(default = default_threads)]
144    pub threads: usize,
145
146    /// Maximum number of retries of a DynamoDB write chunk after its first request.
147    ///
148    /// One budget covers every reason a chunk is sent again: items that a successful
149    /// `BatchWriteItem` response returns as unprocessed, a `TransactWriteItems` call cancelled by
150    /// transient contention, and a request that fails with a retryable error, such as
151    /// throttling, a timeout, a network failure, a server error, or a temporary failure to
152    /// obtain credentials. The AWS SDK makes its own few attempts first; only a retry that this
153    /// connector starts after the SDK gave up counts here. Each retry waits longer than the
154    /// previous one (exponential backoff with random jitter), up to a ceiling of roughly 13
155    /// seconds.
156    ///
157    /// `0` permits no retry. Set to `null` to retry indefinitely: the connector keeps retrying
158    /// at the ceiling interval, and the pipeline waits behind it, until DynamoDB recovers or
159    /// the pipeline stops. When a bounded budget runs out, the chunk's remaining records are
160    /// discarded and counted in `dynamodb_output_failed_items_total`.
161    ///
162    /// An error that a retry cannot fix, such as a validation error, a missing table, denied
163    /// access, or an invalid credential configuration, discards the chunk at once, whatever
164    /// the budget. Items of a transaction that fail their condition expression are dropped
165    /// without a retry, which costs nothing here.
166    ///
167    /// Once a chunk has retried for ten seconds, the connector reports itself unhealthy in
168    /// the pipeline's statistics, with the cause; it reports healthy again once no chunk
169    /// retries and a chunk has landed. Defaults to `10`.
170    #[serde(default = "default_max_retries")]
171    #[schema(default = default_max_retries)]
172    pub max_retries: Option<u8>,
173
174    /// [Condition expression] evaluated before each put (insert or upsert).
175    ///
176    /// When the condition is false, the record is skipped without failing the
177    /// connector. This option requires `transactional` [`write_mode`].
178    ///
179    /// The condition gates every value write, and the connector cannot tell a
180    /// replayed insert from a legitimate update: both arrive as puts. A guard
181    /// such as `attribute_not_exists(id)` therefore also suppresses updates to
182    /// existing keys, not just replayed duplicates. Choose the expression
183    /// accordingly.
184    ///
185    /// The connector does not currently support `ExpressionAttributeNames` or
186    /// `ExpressionAttributeValues`, so the expression cannot use placeholders.
187    ///
188    /// [Condition expression]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html
189    /// [`write_mode`]: Self::write_mode
190    #[serde(default)]
191    pub put_condition_expression: Option<String>,
192
193    /// [Condition expression] evaluated before each delete.
194    ///
195    /// When the condition is false, the delete is skipped without failing the
196    /// connector. This option requires `transactional` [`write_mode`]. The
197    /// expression cannot use `ExpressionAttributeNames` or
198    /// `ExpressionAttributeValues` placeholders.
199    ///
200    /// [Condition expression]: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html
201    /// [`write_mode`]: Self::write_mode
202    #[serde(default)]
203    pub delete_condition_expression: Option<String>,
204}
205
206impl DynamoDBWriterConfig {
207    pub fn effective_batch_size(&self) -> usize {
208        self.batch_size
209            .unwrap_or_else(|| self.write_mode.max_batch_size())
210    }
211
212    pub fn validate(&self) -> Result<(), String> {
213        if self.table.trim().is_empty() {
214            return Err("table cannot be empty".to_string());
215        }
216        if self.table.len() < 3 || self.table.len() > 255 {
217            return Err(format!(
218                "table name '{}' is {} character(s); DynamoDB requires 3–255 characters",
219                self.table,
220                self.table.len()
221            ));
222        }
223        if !self
224            .table
225            .chars()
226            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.')
227        {
228            return Err(format!(
229                "table name '{}' contains invalid characters; DynamoDB requires [a-zA-Z0-9_.-]",
230                self.table
231            ));
232        }
233        if self.region.trim().is_empty() {
234            return Err("region cannot be empty".to_string());
235        }
236        if let Some(batch_size) = self.batch_size {
237            let max_batch_size = self.write_mode.max_batch_size();
238            if batch_size == 0 || batch_size > max_batch_size {
239                return Err(format!(
240                    "batch_size must be between 1 and {max_batch_size} for {:?} write mode",
241                    self.write_mode
242                ));
243            }
244        }
245        if self.threads == 0 {
246            return Err("threads must be at least 1".to_string());
247        }
248        if self.max_buffer_size.is_zero() {
249            return Err("max_buffer_size must be greater than 0".to_string());
250        }
251        if self.max_concurrent_requests == 0 {
252            return Err("max_concurrent_requests must be greater than 0".to_string());
253        }
254        match (&self.aws_access_key_id, &self.aws_secret_access_key) {
255            (Some(_), Some(_)) | (None, None) => {}
256            _ => {
257                return Err(
258                    "aws_access_key_id and aws_secret_access_key must be specified together"
259                        .to_string(),
260                );
261            }
262        }
263        for (field, expression) in [
264            ("put_condition_expression", &self.put_condition_expression),
265            (
266                "delete_condition_expression",
267                &self.delete_condition_expression,
268            ),
269        ] {
270            if let Some(expression) = expression {
271                if expression.trim().is_empty() {
272                    return Err(format!("{field} cannot be empty"));
273                }
274                if self.write_mode != DynamoDBWriteMode::Transactional {
275                    return Err(format!(
276                        "{field} requires the 'transactional' write mode; conditional writes \
277                         are not supported for 'batch' writes"
278                    ));
279                }
280            }
281        }
282        Ok(())
283    }
284}
285
286impl DynamoDBWriteMode {
287    pub fn max_batch_size(self) -> usize {
288        match self {
289            Self::Batch => 25,
290            Self::Transactional => 100,
291        }
292    }
293}
294
295impl crate::sensitive::SensitiveValues for DynamoDBWriterConfig {
296    fn visit_sensitive_values(&self, visit: &mut dyn FnMut(&str, &str)) {
297        crate::sensitive::visit_optional(
298            "aws_secret_access_key",
299            self.aws_secret_access_key.as_deref(),
300            visit,
301        );
302        if let Some(url) = &self.endpoint_url {
303            crate::sensitive::visit_url("endpoint_url", url, visit);
304        }
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    fn config(write_mode: DynamoDBWriteMode, batch_size: Option<usize>) -> DynamoDBWriterConfig {
313        DynamoDBWriterConfig {
314            table: "test_table".to_string(),
315            region: "us-east-1".to_string(),
316            endpoint_url: None,
317            aws_access_key_id: None,
318            aws_secret_access_key: None,
319            batch_size,
320            write_mode,
321            max_buffer_size: ConfigSize::from_mib(1),
322            max_concurrent_requests: 16,
323            threads: 1,
324            max_retries: Some(10u8),
325            put_condition_expression: None,
326            delete_condition_expression: None,
327        }
328    }
329
330    #[test]
331    fn default_batch_size_is_mode_specific() {
332        assert_eq!(
333            config(DynamoDBWriteMode::Batch, None).effective_batch_size(),
334            25
335        );
336        assert_eq!(
337            config(DynamoDBWriteMode::Transactional, None).effective_batch_size(),
338            100
339        );
340    }
341
342    #[test]
343    fn explicit_batch_size_is_validated_against_mode_limit() {
344        assert!(
345            config(DynamoDBWriteMode::Batch, Some(25))
346                .validate()
347                .is_ok()
348        );
349        assert!(
350            config(DynamoDBWriteMode::Batch, Some(26))
351                .validate()
352                .is_err()
353        );
354        assert!(
355            config(DynamoDBWriteMode::Transactional, Some(100))
356                .validate()
357                .is_ok()
358        );
359        assert!(
360            config(DynamoDBWriteMode::Transactional, Some(101))
361                .validate()
362                .is_err()
363        );
364    }
365
366    #[test]
367    fn table_name_validation() {
368        let base = config(DynamoDBWriteMode::Batch, None);
369
370        // too short
371        assert!(
372            DynamoDBWriterConfig {
373                table: "ab".to_string(),
374                ..base.clone()
375            }
376            .validate()
377            .is_err()
378        );
379        // minimum length
380        assert!(
381            DynamoDBWriterConfig {
382                table: "abc".to_string(),
383                ..base.clone()
384            }
385            .validate()
386            .is_ok()
387        );
388        // too long
389        assert!(
390            DynamoDBWriterConfig {
391                table: "a".repeat(256),
392                ..base.clone()
393            }
394            .validate()
395            .is_err()
396        );
397        // maximum length
398        assert!(
399            DynamoDBWriterConfig {
400                table: "a".repeat(255),
401                ..base.clone()
402            }
403            .validate()
404            .is_ok()
405        );
406        // invalid characters
407        assert!(
408            DynamoDBWriterConfig {
409                table: "my/table".to_string(),
410                ..base.clone()
411            }
412            .validate()
413            .is_err()
414        );
415        assert!(
416            DynamoDBWriterConfig {
417                table: "my table".to_string(),
418                ..base.clone()
419            }
420            .validate()
421            .is_err()
422        );
423        // valid characters
424        assert!(
425            DynamoDBWriterConfig {
426                table: "my.table-name_1".to_string(),
427                ..base.clone()
428            }
429            .validate()
430            .is_ok()
431        );
432    }
433
434    #[test]
435    fn condition_requires_transactional_write_mode() {
436        // A put condition in batch mode is rejected.
437        let batch = DynamoDBWriterConfig {
438            put_condition_expression: Some("attribute_not_exists(id)".to_string()),
439            ..config(DynamoDBWriteMode::Batch, None)
440        };
441        assert!(batch.validate().is_err());
442
443        // The same condition is accepted in transactional mode.
444        let transactional = DynamoDBWriterConfig {
445            put_condition_expression: Some("attribute_not_exists(id)".to_string()),
446            ..config(DynamoDBWriteMode::Transactional, None)
447        };
448        assert!(transactional.validate().is_ok());
449
450        // A delete condition in batch mode is rejected as well.
451        let batch_delete = DynamoDBWriterConfig {
452            delete_condition_expression: Some("attribute_exists(id)".to_string()),
453            ..config(DynamoDBWriteMode::Batch, None)
454        };
455        assert!(batch_delete.validate().is_err());
456    }
457
458    #[test]
459    fn blank_condition_is_rejected() {
460        let cfg = DynamoDBWriterConfig {
461            put_condition_expression: Some("   ".to_string()),
462            ..config(DynamoDBWriteMode::Transactional, None)
463        };
464        assert!(cfg.validate().is_err());
465    }
466
467    #[test]
468    fn null_max_retries_deserializes_as_unbounded() {
469        let json = r#"{"table":"t","region":"us-east-1","max_retries":null}"#;
470        let cfg: DynamoDBWriterConfig = serde_json::from_str(json).unwrap();
471        assert_eq!(cfg.max_retries, None);
472    }
473
474    #[test]
475    fn omitted_max_retries_deserializes_as_default() {
476        let json = r#"{"table":"t","region":"us-east-1"}"#;
477        let cfg: DynamoDBWriterConfig = serde_json::from_str(json).unwrap();
478        assert_eq!(cfg.max_retries, Some(10u8));
479    }
480}