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}
48
49/// AWS Glue catalog config.
50#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
51pub struct GlueCatalogConfig {
52    /// Location for table metadata.
53    ///
54    /// Example: `"s3://my-data-warehouse/tables/"`
55    #[serde(rename = "glue.warehouse")]
56    pub warehouse: Option<String>,
57
58    /// Configure an alternative endpoint of the Glue service for Glue catalog to access.
59    ///
60    /// Example: `"https://glue.us-east-1.amazonaws.com"`
61    #[serde(rename = "glue.endpoint")]
62    pub endpoint: Option<String>,
63
64    /// Access key id used to access the Glue catalog.
65    #[serde(rename = "glue.access-key-id")]
66    pub access_key_id: Option<String>,
67
68    /// Secret access key used to access the Glue catalog.
69    #[serde(rename = "glue.secret-access-key")]
70    pub secret_access_key: Option<String>,
71
72    /// Profile used to access the Glue catalog.
73    #[serde(rename = "glue.profile-name")]
74    pub profile_name: Option<String>,
75
76    /// Region of the Glue catalog.
77    #[serde(rename = "glue.region")]
78    pub region: Option<String>,
79
80    // Static session token used to access the Glue catalog.
81    #[serde(rename = "glue.session-token")]
82    pub session_token: Option<String>,
83
84    /// The 12-digit ID of the Glue catalog.
85    #[serde(rename = "glue.id")]
86    pub id: Option<String>,
87}
88
89/// Iceberg REST catalog config.
90#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
91pub struct RestCatalogConfig {
92    /// URI identifying the REST catalog server.
93    #[serde(rename = "rest.uri")]
94    pub uri: Option<String>,
95
96    /// The default location for managed tables created by the catalog.
97    #[serde(rename = "rest.warehouse")]
98    pub warehouse: Option<String>,
99
100    /// Authentication URL to use for client credentials authentication (default: uri + 'v1/oauth/tokens')
101    #[serde(rename = "rest.oauth2-server-uri")]
102    pub oauth2_server_uri: Option<String>,
103
104    /// Credential to use for OAuth2 credential flow when initializing the catalog.
105    ///
106    /// A key and secret pair separated by ":" (key is optional).
107    #[serde(rename = "rest.credential")]
108    pub credential: Option<String>,
109
110    /// Bearer token value to use for `Authorization` header.
111    #[serde(rename = "rest.token")]
112    pub token: Option<String>,
113
114    // Desired scope of the requested security token (default: catalog).
115    #[serde(rename = "rest.scope")]
116    pub scope: Option<String>,
117
118    /// Customize table storage paths.
119    ///
120    /// When combined with the `warehouse` property, the prefix determines
121    /// how table data is organized within the storage.
122    #[serde(rename = "rest.prefix")]
123    pub prefix: Option<String>,
124
125    /// Additional HTTP request headers added to each catalog REST API call.
126    #[serde(default)]
127    #[serde(rename = "rest.headers")]
128    pub headers: Option<Vec<(String, String)>>,
129
130    /// Logical name of target resource or service.
131    #[serde(rename = "rest.audience")]
132    pub audience: Option<String>,
133
134    /// URI for the target resource or service.
135    #[serde(rename = "rest.resource")]
136    pub resource: Option<String>,
137}
138
139/// Iceberg input connector configuration.
140#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
141pub struct IcebergReaderConfig {
142    /// Table read mode.
143    pub mode: IcebergIngestMode,
144
145    /// Table column that serves as an event timestamp.
146    ///
147    /// When this option is specified, and `mode` is one of `snapshot` or `snapshot_and_follow`,
148    /// table rows are ingested in the timestamp order, respecting the
149    /// [`LATENESS`](https://docs.feldera.com/sql/streaming#lateness-expressions)
150    /// property of the column: each ingested row has a timestamp no more than `LATENESS`
151    /// time units earlier than the most recent timestamp of any previously ingested row.
152    /// The ingestion is performed by partitioning the table into timestamp ranges of width
153    /// `LATENESS`. Each range is processed sequentially, in increasing timestamp order.
154    ///
155    /// # Example
156    ///
157    /// Consider a table with timestamp column of type `TIMESTAMP` and lateness attribute
158    /// `INTERVAL 1 DAY`. Assuming that the oldest timestamp in the table is
159    /// `2024-01-01T00:00:00``, the connector will fetch all records with timestamps
160    /// from `2024-01-01`, then all records for `2024-01-02`, `2024-01-03`, etc., until all records
161    /// in the table have been ingested.
162    ///
163    /// # Requirements
164    ///
165    /// * The timestamp column must be of a supported type: integer, `DATE`, or `TIMESTAMP`.
166    /// * The timestamp column must be declared with non-zero `LATENESS`.
167    /// * For efficient ingest, the table must be optimized for timestamp-based
168    ///   queries using partitioning, Z-ordering, or liquid clustering.
169    pub timestamp_column: Option<String>,
170
171    /// Optional row filter.
172    ///
173    /// This option is only valid when `mode` is set to `snapshot` or `snapshot_and_follow`.
174    ///
175    /// When specified, only rows that satisfy the filter condition are included in the
176    /// snapshot.  The condition must be a valid SQL Boolean expression that can be used in
177    /// the `where` clause of the `select * from snapshot where ...` query.
178    ///
179    /// This option can be used to specify the range of event times to include in the snapshot,
180    /// e.g.: `ts BETWEEN '2005-01-01 00:00:00' AND '2010-12-31 23:59:59'`.
181    pub snapshot_filter: Option<String>,
182
183    /// Optional snapshot id.
184    ///
185    /// When this option is set, the connector finds the specified snapshot of the table.
186    /// In `snapshot` and `snapshot_and_follow` modes, it loads this snapshot.
187    /// In `follow` and `snapshot_and_follow` modes, it follows table updates
188    /// **after** this snapshot.
189    ///
190    /// Note: at most one of `snapshot_id` and `datetime` options can be specified.
191    /// When neither of the two options is specified, the latest committed version of the table
192    /// is used.
193    pub snapshot_id: Option<i64>,
194
195    /// Optional timestamp for the snapshot in the ISO-8601/RFC-3339 format, e.g.,
196    /// "2024-12-09T16:09:53+00:00".
197    ///
198    /// When this option is set, the connector finds and opens the snapshot of the table as of the
199    /// specified point in time (based on the server time recorded in the transaction
200    /// log, not the event time encoded in the data).  In `snapshot` and `snapshot_and_follow`
201    /// modes, it retrieves this snapshot.  In `follow` and `snapshot_and_follow` modes, it
202    /// follows transaction log records **after** this snapshot.
203    ///
204    /// Note: at most one of `snapshot_id` and `datetime` options can be specified.
205    /// When neither of the two options is specified, the latest committed version of the table
206    /// is used.
207    pub datetime: Option<String>,
208
209    /// Location of the table metadata JSON file.
210    ///
211    /// This propery is used to access an Iceberg table without a catalog. It is mutually
212    /// exclusive with the `catalog_type` property.
213    pub metadata_location: Option<String>,
214
215    /// Specifies the Iceberg table name in the "namespace.table" format.
216    ///
217    /// This option is applicable when an Iceberg catalog is configured using the `catalog_type` property.
218    pub table_name: Option<String>,
219
220    /// Specifies the catalog type used to access the Iceberg table.
221    ///
222    /// Supported options include "rest" and "glue". This property is mutually exclusive with `metadata_location`.
223    pub catalog_type: Option<IcebergCatalogType>,
224
225    #[serde(flatten)]
226    pub glue_catalog_config: GlueCatalogConfig,
227
228    #[serde(flatten)]
229    pub rest_catalog_config: RestCatalogConfig,
230
231    /// Storage options for configuring backend object store.
232    ///
233    /// See the [list of available options in PyIceberg documentation](https://py.iceberg.apache.org/configuration/#fileio).
234    #[serde(flatten)]
235    pub fileio_config: HashMap<String, String>,
236}
237
238impl IcebergReaderConfig {
239    pub fn validate_catalog_config(&self) -> Result<(), String> {
240        self.validate_metadata_location()?;
241        self.validate_table_name()?;
242        self.validate_glue_catalog_config()?;
243        self.validate_rest_catalog_config()?;
244
245        Ok(())
246    }
247
248    /// Reject Glue catalog config properties when 'catalog_type' isn't set to 'glue'.
249    pub fn validate_glue_catalog_config(&self) -> Result<(), String> {
250        if self.catalog_type == Some(IcebergCatalogType::Glue) {
251            if self.glue_catalog_config.warehouse.is_none() {
252                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());
253            }
254        } else {
255            ensure_glue_property_not_set(&self.glue_catalog_config.warehouse, "warehouse")?;
256            ensure_glue_property_not_set(&self.glue_catalog_config.endpoint, "uri")?;
257            ensure_glue_property_not_set(&self.glue_catalog_config.access_key_id, "access-key-id")?;
258            ensure_glue_property_not_set(
259                &self.glue_catalog_config.secret_access_key,
260                "secret-access-key",
261            )?;
262            ensure_glue_property_not_set(&self.glue_catalog_config.profile_name, "profile-name")?;
263            ensure_glue_property_not_set(&self.glue_catalog_config.region, "region")?;
264            ensure_glue_property_not_set(&self.glue_catalog_config.session_token, "session-token")?;
265            ensure_glue_property_not_set(&self.glue_catalog_config.id, "id")?;
266        }
267
268        Ok(())
269    }
270
271    /// Reject Rest catalog config when 'catalog_type' isn't set to 'rest'.
272    pub fn validate_rest_catalog_config(&self) -> Result<(), String> {
273        if self.catalog_type == Some(IcebergCatalogType::Rest) {
274            if self.rest_catalog_config.uri.is_none() {
275                return Err(r#"missing Iceberg Rest catalog URI—set the 'rest.uri' property when using "catalog_type" = "rest""#.to_string());
276            }
277        } else {
278            ensure_rest_property_not_set(&self.rest_catalog_config.uri, "uri")?;
279            ensure_rest_property_not_set(&self.rest_catalog_config.warehouse, "warehouse")?;
280            ensure_rest_property_not_set(
281                &self.rest_catalog_config.oauth2_server_uri,
282                "oauth2_server_uri",
283            )?;
284            ensure_rest_property_not_set(&self.rest_catalog_config.credential, "credential")?;
285            ensure_rest_property_not_set(&self.rest_catalog_config.token, "token")?;
286            ensure_rest_property_not_set(&self.rest_catalog_config.scope, "scope")?;
287            ensure_rest_property_not_set(&self.rest_catalog_config.prefix, "prefix")?;
288            ensure_rest_property_not_set(&self.rest_catalog_config.headers, "headers")?;
289            ensure_rest_property_not_set(&self.rest_catalog_config.audience, "audience")?;
290            ensure_rest_property_not_set(&self.rest_catalog_config.resource, "resource")?;
291        }
292
293        Ok(())
294    }
295
296    /// Table name must be configured iff 'catalog_type' is set.
297    pub fn validate_table_name(&self) -> Result<(), String> {
298        if self.catalog_type.is_none() && self.table_name.is_some() {
299            Err("unexpected 'table_name' property: the 'table_name' property is valid only when an Iceberg catalog is configured using 'catalog_type'".to_string())
300        } else if self.catalog_type.is_some() && self.table_name.is_none() {
301            Err("missing 'table_name' property—'table_name' must be specified when Iceberg catalog is configured using 'catalog_type'".to_string())
302        } else {
303            Ok(())
304        }
305    }
306
307    /// 'metadata_location' must be configured iff 'catalog_type' is set.
308    pub fn validate_metadata_location(&self) -> Result<(), String> {
309        if self.catalog_type.is_none() && self.metadata_location.is_none() {
310            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())
311        } else if self.catalog_type.is_some() && self.metadata_location.is_some() {
312            Err("unexpected 'metadata_location' property: the 'metadata_location' property is not supported when an Iceberg catalog is configured using 'catalog_type'".to_string())
313        } else {
314            Ok(())
315        }
316    }
317}
318
319fn ensure_glue_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
320    if property.is_some() {
321        Err(format!(
322            r#"unexpected 'glue.{name}' property—Glue catalog configuration properties are only valid when "catalog_type" = "glue""#
323        ))
324    } else {
325        Ok(())
326    }
327}
328
329fn ensure_rest_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
330    if property.is_some() {
331        Err(format!(
332            r#"unexpected 'rest.{name}' property—Rest catalog configuration properties are only valid when "catalog_type" = "rest""#
333        ))
334    } else {
335        Ok(())
336    }
337}
338
339impl IcebergReaderConfig {
340    /// `true` if the configuration requires taking an initial snapshot of the table.
341    pub fn snapshot(&self) -> bool {
342        matches!(
343            &self.mode,
344            IcebergIngestMode::Snapshot | IcebergIngestMode::SnapshotAndFollow
345        )
346    }
347
348    /// `true` if the configuration requires following the transaction log of the table
349    /// (possibly after taking an initial snapshot).s
350    pub fn follow(&self) -> bool {
351        matches!(
352            &self.mode,
353            IcebergIngestMode::SnapshotAndFollow | IcebergIngestMode::Follow
354        )
355    }
356}