Skip to main content

feldera_types/transport/
iceberg.rs

1use serde::{Deserialize, Serialize};
2use std::{collections::HashMap, fmt::Display};
3use utoipa::ToSchema;
4
5/// Iceberg table read mode.
6///
7/// Three options are available:
8///
9/// * `snapshot` - read a snapshot of the table and stop.
10///
11/// * `follow` - continuously ingest changes to the table, starting from a specified snapshot
12///   or timestamp.
13///
14/// * `snapshot_and_follow` - read a snapshot of the table before switching to continuous ingestion
15///   mode.
16#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
17pub enum IcebergIngestMode {
18    /// Read a snapshot of the table and stop.
19    #[serde(rename = "snapshot")]
20    Snapshot,
21
22    /// Follow the changelog of the table, only ingesting changes (new and deleted rows).
23    #[serde(rename = "follow")]
24    Follow,
25
26    /// Take a snapshot of the table before switching to the `follow` mode.
27    #[serde(rename = "snapshot_and_follow")]
28    SnapshotAndFollow,
29}
30
31impl Display for IcebergIngestMode {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        match self {
34            IcebergIngestMode::Snapshot => f.write_str("snapshot"),
35            IcebergIngestMode::Follow => f.write_str("follow"),
36            IcebergIngestMode::SnapshotAndFollow => f.write_str("snapshot_and_follow"),
37        }
38    }
39}
40
41#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
42pub enum IcebergCatalogType {
43    #[serde(rename = "rest")]
44    Rest,
45    #[serde(rename = "glue")]
46    Glue,
47    #[serde(rename = "s3tables")]
48    S3Tables,
49}
50
51/// AWS Glue catalog config.
52#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
53pub struct GlueCatalogConfig {
54    /// Location for table metadata.
55    ///
56    /// Example: `"s3://my-data-warehouse/tables/"`
57    #[serde(rename = "glue.warehouse")]
58    pub warehouse: Option<String>,
59
60    /// Configure an alternative endpoint of the Glue service for Glue catalog to access.
61    ///
62    /// Example: `"https://glue.us-east-1.amazonaws.com"`
63    #[serde(rename = "glue.endpoint")]
64    pub endpoint: Option<String>,
65
66    /// Access key id used to access the Glue catalog.
67    #[serde(rename = "glue.access-key-id")]
68    pub access_key_id: Option<String>,
69
70    /// Secret access key used to access the Glue catalog.
71    #[serde(rename = "glue.secret-access-key")]
72    pub secret_access_key: Option<String>,
73
74    /// Profile used to access the Glue catalog.
75    #[serde(rename = "glue.profile-name")]
76    pub profile_name: Option<String>,
77
78    /// Region of the Glue catalog.
79    #[serde(rename = "glue.region")]
80    pub region: Option<String>,
81
82    // Static session token used to access the Glue catalog.
83    #[serde(rename = "glue.session-token")]
84    pub session_token: Option<String>,
85
86    /// The 12-digit ID of the Glue catalog.
87    #[serde(rename = "glue.id")]
88    pub id: Option<String>,
89}
90
91/// Iceberg REST catalog config.
92#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
93pub struct RestCatalogConfig {
94    /// URI identifying the REST catalog server.
95    #[serde(rename = "rest.uri")]
96    pub uri: Option<String>,
97
98    /// The default location for managed tables created by the catalog.
99    #[serde(rename = "rest.warehouse")]
100    pub warehouse: Option<String>,
101
102    /// Authentication URL to use for client credentials authentication (default: uri + 'v1/oauth/tokens')
103    #[serde(rename = "rest.oauth2-server-uri")]
104    pub oauth2_server_uri: Option<String>,
105
106    /// Credential to use for OAuth2 credential flow when initializing the catalog.
107    ///
108    /// A key and secret pair separated by ":" (key is optional).
109    #[serde(rename = "rest.credential")]
110    pub credential: Option<String>,
111
112    /// Bearer token value to use for `Authorization` header.
113    #[serde(rename = "rest.token")]
114    pub token: Option<String>,
115
116    // Desired scope of the requested security token (default: catalog).
117    #[serde(rename = "rest.scope")]
118    pub scope: Option<String>,
119
120    /// Customize table storage paths.
121    ///
122    /// When combined with the `warehouse` property, the prefix determines
123    /// how table data is organized within the storage.
124    #[serde(rename = "rest.prefix")]
125    pub prefix: Option<String>,
126
127    /// Additional HTTP request headers added to each catalog REST API call.
128    #[serde(default)]
129    #[serde(rename = "rest.headers")]
130    pub headers: Option<Vec<(String, String)>>,
131
132    /// Logical name of target resource or service.
133    #[serde(rename = "rest.audience")]
134    pub audience: Option<String>,
135
136    /// URI for the target resource or service.
137    #[serde(rename = "rest.resource")]
138    pub resource: Option<String>,
139}
140
141/// Amazon S3 Tables catalog config.
142#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
143pub struct S3TablesCatalogConfig {
144    /// ARN of the S3 table bucket that contains the table.
145    ///
146    /// Note that this is the ARN of the table *bucket*, not of an individual table,
147    /// e.g., `"arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket"`.
148    #[serde(rename = "s3tables.table-bucket-arn")]
149    pub table_bucket_arn: Option<String>,
150
151    /// Custom endpoint URL for the S3 Tables service.
152    ///
153    /// Primarily used to target a local or mock S3 Tables implementation for testing.
154    /// When omitted, the default regional endpoint is used.
155    #[serde(rename = "s3tables.endpoint")]
156    pub endpoint: Option<String>,
157
158    /// Access key id used to access the S3 Tables catalog.
159    #[serde(rename = "s3tables.access-key-id")]
160    pub access_key_id: Option<String>,
161
162    /// Secret access key used to access the S3 Tables catalog.
163    #[serde(rename = "s3tables.secret-access-key")]
164    pub secret_access_key: Option<String>,
165
166    /// Static session token used to access the S3 Tables catalog.
167    #[serde(rename = "s3tables.session-token")]
168    pub session_token: Option<String>,
169
170    /// Profile used to access the S3 Tables catalog.
171    #[serde(rename = "s3tables.profile-name")]
172    pub profile_name: Option<String>,
173
174    /// Region of the S3 Tables catalog.
175    #[serde(rename = "s3tables.region")]
176    pub region: Option<String>,
177}
178
179/// Iceberg input connector configuration.
180#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
181pub struct IcebergReaderConfig {
182    /// Table read mode.
183    pub mode: IcebergIngestMode,
184
185    /// Table column that serves as an event timestamp.
186    ///
187    /// When this option is specified, and `mode` is one of `snapshot` or `snapshot_and_follow`,
188    /// table rows are ingested in the timestamp order, respecting the
189    /// [`LATENESS`](https://docs.feldera.com/sql/streaming#lateness-expressions)
190    /// property of the column: each ingested row has a timestamp no more than `LATENESS`
191    /// time units earlier than the most recent timestamp of any previously ingested row.
192    /// The ingestion is performed by partitioning the table into timestamp ranges of width
193    /// `LATENESS`. Each range is processed sequentially, in increasing timestamp order.
194    ///
195    /// # Example
196    ///
197    /// Consider a table with timestamp column of type `TIMESTAMP` and lateness attribute
198    /// `INTERVAL 1 DAY`. Assuming that the oldest timestamp in the table is
199    /// `2024-01-01T00:00:00``, the connector will fetch all records with timestamps
200    /// from `2024-01-01`, then all records for `2024-01-02`, `2024-01-03`, etc., until all records
201    /// in the table have been ingested.
202    ///
203    /// # Requirements
204    ///
205    /// * The timestamp column must be of a supported type: integer, `DATE`, or `TIMESTAMP`.
206    /// * The timestamp column must be declared with non-zero `LATENESS`.
207    /// * For efficient ingest, the table must be optimized for timestamp-based
208    ///   queries using partitioning, Z-ordering, or liquid clustering.
209    pub timestamp_column: Option<String>,
210
211    /// Optional row filter.
212    ///
213    /// This option is only valid when `mode` is set to `snapshot` or `snapshot_and_follow`.
214    ///
215    /// When specified, only rows that satisfy the filter condition are included in the
216    /// snapshot.  The condition must be a valid SQL Boolean expression that can be used in
217    /// the `where` clause of the `select * from snapshot where ...` query.
218    ///
219    /// This option can be used to specify the range of event times to include in the snapshot,
220    /// e.g.: `ts BETWEEN '2005-01-01 00:00:00' AND '2010-12-31 23:59:59'`.
221    pub snapshot_filter: Option<String>,
222
223    /// Optional snapshot id.
224    ///
225    /// When this option is set, the connector finds the specified snapshot of the table.
226    /// In `snapshot` and `snapshot_and_follow` modes, it loads this snapshot.
227    /// In `follow` and `snapshot_and_follow` modes, it follows table updates
228    /// **after** this snapshot.
229    ///
230    /// Note: at most one of `snapshot_id` and `datetime` options can be specified.
231    /// When neither of the two options is specified, the latest committed version of the table
232    /// is used.
233    pub snapshot_id: Option<i64>,
234
235    /// Optional timestamp for the snapshot in the ISO-8601/RFC-3339 format, e.g.,
236    /// "2024-12-09T16:09:53+00:00".
237    ///
238    /// When this option is set, the connector finds and opens the snapshot of the table as of the
239    /// specified point in time (based on the server time recorded in the transaction
240    /// log, not the event time encoded in the data).  In `snapshot` and `snapshot_and_follow`
241    /// modes, it retrieves this snapshot.  In `follow` and `snapshot_and_follow` modes, it
242    /// follows transaction log records **after** this snapshot.
243    ///
244    /// Note: at most one of `snapshot_id` and `datetime` options can be specified.
245    /// When neither of the two options is specified, the latest committed version of the table
246    /// is used.
247    pub datetime: Option<String>,
248
249    /// Location of the table metadata JSON file.
250    ///
251    /// This propery is used to access an Iceberg table without a catalog. It is mutually
252    /// exclusive with the `catalog_type` property.
253    pub metadata_location: Option<String>,
254
255    /// Specifies the Iceberg table name in the "namespace.table" format.
256    ///
257    /// This option is applicable when an Iceberg catalog is configured using the `catalog_type` property.
258    pub table_name: Option<String>,
259
260    /// Specifies the catalog type used to access the Iceberg table.
261    ///
262    /// Supported options include "rest", "glue", and "s3tables". This property is mutually
263    /// exclusive with `metadata_location`.
264    pub catalog_type: Option<IcebergCatalogType>,
265
266    #[serde(flatten)]
267    pub glue_catalog_config: GlueCatalogConfig,
268
269    #[serde(flatten)]
270    pub rest_catalog_config: RestCatalogConfig,
271
272    #[serde(flatten)]
273    pub s3tables_catalog_config: S3TablesCatalogConfig,
274
275    /// Storage options for configuring backend object store.
276    ///
277    /// See the [list of available options in PyIceberg documentation](https://py.iceberg.apache.org/configuration/#fileio).
278    #[serde(flatten)]
279    pub fileio_config: HashMap<String, String>,
280}
281
282impl IcebergReaderConfig {
283    pub fn validate_catalog_config(&self) -> Result<(), String> {
284        self.validate_metadata_location()?;
285        self.validate_table_name()?;
286        self.validate_glue_catalog_config()?;
287        self.validate_rest_catalog_config()?;
288        self.validate_s3tables_catalog_config()?;
289
290        Ok(())
291    }
292
293    /// Reject Glue catalog config properties when 'catalog_type' isn't set to 'glue'.
294    pub fn validate_glue_catalog_config(&self) -> Result<(), String> {
295        if self.catalog_type == Some(IcebergCatalogType::Glue) {
296            if self.glue_catalog_config.warehouse.is_none() {
297                return Err(r#"missing Iceberg warehouse location—set the 'glue.warehouse' property to the location of the Iceberg tables managed by the catalog (e.g., 's3://my-data-warehouse/tables/') when using "catalog_type" = "glue""#.to_string());
298            }
299        } else {
300            ensure_glue_property_not_set(&self.glue_catalog_config.warehouse, "warehouse")?;
301            ensure_glue_property_not_set(&self.glue_catalog_config.endpoint, "uri")?;
302            ensure_glue_property_not_set(&self.glue_catalog_config.access_key_id, "access-key-id")?;
303            ensure_glue_property_not_set(
304                &self.glue_catalog_config.secret_access_key,
305                "secret-access-key",
306            )?;
307            ensure_glue_property_not_set(&self.glue_catalog_config.profile_name, "profile-name")?;
308            ensure_glue_property_not_set(&self.glue_catalog_config.region, "region")?;
309            ensure_glue_property_not_set(&self.glue_catalog_config.session_token, "session-token")?;
310            ensure_glue_property_not_set(&self.glue_catalog_config.id, "id")?;
311        }
312
313        Ok(())
314    }
315
316    /// Reject Rest catalog config when 'catalog_type' isn't set to 'rest'.
317    pub fn validate_rest_catalog_config(&self) -> Result<(), String> {
318        if self.catalog_type == Some(IcebergCatalogType::Rest) {
319            if self.rest_catalog_config.uri.is_none() {
320                return Err(r#"missing Iceberg Rest catalog URI—set the 'rest.uri' property when using "catalog_type" = "rest""#.to_string());
321            }
322        } else {
323            ensure_rest_property_not_set(&self.rest_catalog_config.uri, "uri")?;
324            ensure_rest_property_not_set(&self.rest_catalog_config.warehouse, "warehouse")?;
325            ensure_rest_property_not_set(
326                &self.rest_catalog_config.oauth2_server_uri,
327                "oauth2_server_uri",
328            )?;
329            ensure_rest_property_not_set(&self.rest_catalog_config.credential, "credential")?;
330            ensure_rest_property_not_set(&self.rest_catalog_config.token, "token")?;
331            ensure_rest_property_not_set(&self.rest_catalog_config.scope, "scope")?;
332            ensure_rest_property_not_set(&self.rest_catalog_config.prefix, "prefix")?;
333            ensure_rest_property_not_set(&self.rest_catalog_config.headers, "headers")?;
334            ensure_rest_property_not_set(&self.rest_catalog_config.audience, "audience")?;
335            ensure_rest_property_not_set(&self.rest_catalog_config.resource, "resource")?;
336        }
337
338        Ok(())
339    }
340
341    /// Reject S3 Tables catalog config when 'catalog_type' isn't set to 's3tables'.
342    pub fn validate_s3tables_catalog_config(&self) -> Result<(), String> {
343        if self.catalog_type == Some(IcebergCatalogType::S3Tables) {
344            if self.s3tables_catalog_config.table_bucket_arn.is_none() {
345                return Err(r#"missing S3 table bucket ARN; set the 's3tables.table-bucket-arn' property to the ARN of the S3 table bucket (e.g., 'arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket') when using "catalog_type" = "s3tables""#.to_string());
346            }
347        } else {
348            ensure_s3tables_property_not_set(
349                &self.s3tables_catalog_config.table_bucket_arn,
350                "table-bucket-arn",
351            )?;
352            ensure_s3tables_property_not_set(&self.s3tables_catalog_config.endpoint, "endpoint")?;
353            ensure_s3tables_property_not_set(
354                &self.s3tables_catalog_config.access_key_id,
355                "access-key-id",
356            )?;
357            ensure_s3tables_property_not_set(
358                &self.s3tables_catalog_config.secret_access_key,
359                "secret-access-key",
360            )?;
361            ensure_s3tables_property_not_set(
362                &self.s3tables_catalog_config.session_token,
363                "session-token",
364            )?;
365            ensure_s3tables_property_not_set(
366                &self.s3tables_catalog_config.profile_name,
367                "profile-name",
368            )?;
369            ensure_s3tables_property_not_set(&self.s3tables_catalog_config.region, "region")?;
370        }
371
372        Ok(())
373    }
374
375    /// Table name must be configured iff 'catalog_type' is set.
376    pub fn validate_table_name(&self) -> Result<(), String> {
377        if self.catalog_type.is_none() && self.table_name.is_some() {
378            Err("unexpected 'table_name' property: the 'table_name' property is valid only when an Iceberg catalog is configured using 'catalog_type'".to_string())
379        } else if self.catalog_type.is_some() && self.table_name.is_none() {
380            Err("missing 'table_name' property—'table_name' must be specified when Iceberg catalog is configured using 'catalog_type'".to_string())
381        } else {
382            Ok(())
383        }
384    }
385
386    /// 'metadata_location' must be configured iff 'catalog_type' is set.
387    pub fn validate_metadata_location(&self) -> Result<(), String> {
388        if self.catalog_type.is_none() && self.metadata_location.is_none() {
389            Err("missing metadata location: you must either specify an Iceberg catalog configuration by setting the 'catalog_type' property or provide a table metadata location directly via the 'metadata_location' property".to_string())
390        } else if self.catalog_type.is_some() && self.metadata_location.is_some() {
391            Err("unexpected 'metadata_location' property: the 'metadata_location' property is not supported when an Iceberg catalog is configured using 'catalog_type'".to_string())
392        } else {
393            Ok(())
394        }
395    }
396}
397
398fn ensure_glue_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
399    if property.is_some() {
400        Err(format!(
401            r#"unexpected 'glue.{name}' property—Glue catalog configuration properties are only valid when "catalog_type" = "glue""#
402        ))
403    } else {
404        Ok(())
405    }
406}
407
408fn ensure_rest_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
409    if property.is_some() {
410        Err(format!(
411            r#"unexpected 'rest.{name}' property—Rest catalog configuration properties are only valid when "catalog_type" = "rest""#
412        ))
413    } else {
414        Ok(())
415    }
416}
417
418fn ensure_s3tables_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
419    if property.is_some() {
420        Err(format!(
421            r#"unexpected 's3tables.{name}' property—S3 Tables catalog configuration properties are only valid when "catalog_type" = "s3tables""#
422        ))
423    } else {
424        Ok(())
425    }
426}
427
428impl IcebergReaderConfig {
429    /// `true` if the configuration requires taking an initial snapshot of the table.
430    pub fn snapshot(&self) -> bool {
431        matches!(
432            &self.mode,
433            IcebergIngestMode::Snapshot | IcebergIngestMode::SnapshotAndFollow
434        )
435    }
436
437    /// `true` if the configuration requires following the transaction log of the table
438    /// (possibly after taking an initial snapshot).s
439    pub fn follow(&self) -> bool {
440        matches!(
441            &self.mode,
442            IcebergIngestMode::SnapshotAndFollow | IcebergIngestMode::Follow
443        )
444    }
445}
446
447#[cfg(test)]
448mod test {
449    use super::*;
450    use serde_json::json;
451
452    fn config(value: serde_json::Value) -> IcebergReaderConfig {
453        serde_json::from_value(value).unwrap()
454    }
455
456    #[test]
457    fn s3tables_config_deserializes() {
458        let config = config(json!({
459            "mode": "snapshot",
460            "catalog_type": "s3tables",
461            "table_name": "namespace.table",
462            "s3tables.table-bucket-arn": "arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket",
463            "s3tables.region": "us-east-2",
464            "s3tables.access-key-id": "key",
465            "s3tables.secret-access-key": "secret",
466            "s3tables.session-token": "token",
467            "s3tables.profile-name": "profile",
468            "s3tables.endpoint": "http://localhost:4566",
469        }));
470
471        // Each prefixed key must land on its struct field, not in the catch-all
472        // `fileio_config` map (which is what happens on a rename mismatch).
473        let s3tables = &config.s3tables_catalog_config;
474        assert_eq!(
475            s3tables.table_bucket_arn.as_deref(),
476            Some("arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket")
477        );
478        assert_eq!(s3tables.region.as_deref(), Some("us-east-2"));
479        assert_eq!(s3tables.access_key_id.as_deref(), Some("key"));
480        assert_eq!(s3tables.secret_access_key.as_deref(), Some("secret"));
481        assert_eq!(s3tables.session_token.as_deref(), Some("token"));
482        assert_eq!(s3tables.profile_name.as_deref(), Some("profile"));
483        assert_eq!(s3tables.endpoint.as_deref(), Some("http://localhost:4566"));
484        assert!(config.fileio_config.is_empty());
485
486        config.validate_catalog_config().unwrap();
487    }
488
489    #[test]
490    fn s3tables_requires_table_bucket_arn() {
491        let err = config(json!({
492            "mode": "snapshot",
493            "catalog_type": "s3tables",
494            "table_name": "namespace.table",
495        }))
496        .validate_catalog_config()
497        .unwrap_err();
498        assert!(err.contains("s3tables.table-bucket-arn"), "{err}");
499    }
500
501    #[test]
502    fn s3tables_props_rejected_for_other_catalog() {
503        let err = config(json!({
504            "mode": "snapshot",
505            "catalog_type": "glue",
506            "table_name": "namespace.table",
507            "glue.warehouse": "s3://warehouse/",
508            "s3tables.region": "us-east-2",
509        }))
510        .validate_catalog_config()
511        .unwrap_err();
512        assert!(err.contains("s3tables.region"), "{err}");
513    }
514
515    #[test]
516    fn s3tables_props_rejected_without_catalog() {
517        let err = config(json!({
518            "mode": "snapshot",
519            "metadata_location": "s3://warehouse/metadata.json",
520            "s3tables.table-bucket-arn": "arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket",
521        }))
522        .validate_catalog_config()
523        .unwrap_err();
524        assert!(err.contains("s3tables.table-bucket-arn"), "{err}");
525    }
526}