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/// Iceberg table transaction mode.
52///
53/// Determines how the connector breaks up its input into Feldera transactions.
54///
55/// * `none` - the connector does not group its input into transactions.
56/// * `snapshot` - ingest the initial snapshot in one or more transactions (see below). Changes
57///   ingested afterward, in the follow phase, are not grouped into transactions.
58/// * `catchup` - ingest the initial snapshot like `snapshot`. In the follow phase, the connector
59///   batches all currently available table commits into a single transaction. Once that transaction
60///   completes, it checks for commits added since the transaction began, ingests them in the next
61///   transaction, and repeats continuously. Most efficient for backfill and steady-state following.
62/// * `always` - ingest the initial snapshot like `snapshot`. In the follow phase, each table commit
63///   is ingested in its own transaction.
64///
65/// # How the table snapshot is ingested using transactions
66///
67/// For the initial snapshot (`snapshot`, `catchup`, and `always` all behave the same), the
68/// connector ingests the snapshot in one or several transactions, depending on `timestamp_column`.
69/// If `timestamp_column` is not set, the whole snapshot is ingested in a single Feldera
70/// transaction. If `timestamp_column` is set, the connector ingests the snapshot in a series of
71/// timestamp ranges of width equal to the `LATENESS` attribute of the column, each range in a
72/// separate transaction.
73#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
74pub enum IcebergTransactionMode {
75    #[default]
76    #[serde(rename = "none")]
77    None,
78    #[serde(rename = "snapshot")]
79    Snapshot,
80    #[serde(rename = "catchup")]
81    Catchup,
82    #[serde(rename = "always")]
83    Always,
84}
85
86/// AWS Glue catalog config.
87#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
88pub struct GlueCatalogConfig {
89    /// Location for table metadata.
90    ///
91    /// Example: `"s3://my-data-warehouse/tables/"`
92    #[serde(rename = "glue.warehouse")]
93    pub warehouse: Option<String>,
94
95    /// Configure an alternative endpoint of the Glue service for Glue catalog to access.
96    ///
97    /// Example: `"https://glue.us-east-1.amazonaws.com"`
98    #[serde(rename = "glue.endpoint")]
99    pub endpoint: Option<String>,
100
101    /// Access key id used to access the Glue catalog.
102    #[serde(rename = "glue.access-key-id")]
103    pub access_key_id: Option<String>,
104
105    /// Secret access key used to access the Glue catalog.
106    #[serde(rename = "glue.secret-access-key")]
107    pub secret_access_key: Option<String>,
108
109    /// Profile used to access the Glue catalog.
110    #[serde(rename = "glue.profile-name")]
111    pub profile_name: Option<String>,
112
113    /// Region of the Glue catalog.
114    #[serde(rename = "glue.region")]
115    pub region: Option<String>,
116
117    // Static session token used to access the Glue catalog.
118    #[serde(rename = "glue.session-token")]
119    pub session_token: Option<String>,
120
121    /// The 12-digit ID of the Glue catalog.
122    #[serde(rename = "glue.id")]
123    pub id: Option<String>,
124}
125
126/// Iceberg REST catalog config.
127#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
128pub struct RestCatalogConfig {
129    /// URI identifying the REST catalog server.
130    #[serde(rename = "rest.uri")]
131    pub uri: Option<String>,
132
133    /// The default location for managed tables created by the catalog.
134    #[serde(rename = "rest.warehouse")]
135    pub warehouse: Option<String>,
136
137    /// Authentication URL to use for client credentials authentication (default: uri + 'v1/oauth/tokens')
138    #[serde(rename = "rest.oauth2-server-uri")]
139    pub oauth2_server_uri: Option<String>,
140
141    /// Credential to use for OAuth2 credential flow when initializing the catalog.
142    ///
143    /// A key and secret pair separated by ":" (key is optional).
144    #[serde(rename = "rest.credential")]
145    pub credential: Option<String>,
146
147    /// Bearer token value to use for `Authorization` header.
148    #[serde(rename = "rest.token")]
149    pub token: Option<String>,
150
151    // Desired scope of the requested security token (default: catalog).
152    #[serde(rename = "rest.scope")]
153    pub scope: Option<String>,
154
155    /// Customize table storage paths.
156    ///
157    /// When combined with the `warehouse` property, the prefix determines
158    /// how table data is organized within the storage.
159    #[serde(rename = "rest.prefix")]
160    pub prefix: Option<String>,
161
162    /// Additional HTTP request headers added to each catalog REST API call.
163    #[serde(default)]
164    #[serde(rename = "rest.headers")]
165    pub headers: Option<Vec<(String, String)>>,
166
167    /// Logical name of target resource or service.
168    #[serde(rename = "rest.audience")]
169    pub audience: Option<String>,
170
171    /// URI for the target resource or service.
172    #[serde(rename = "rest.resource")]
173    pub resource: Option<String>,
174}
175
176/// Amazon S3 Tables catalog config.
177#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
178pub struct S3TablesCatalogConfig {
179    /// ARN of the S3 table bucket that contains the table.
180    ///
181    /// Note that this is the ARN of the table *bucket*, not of an individual table,
182    /// e.g., `"arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket"`.
183    #[serde(rename = "s3tables.table-bucket-arn")]
184    pub table_bucket_arn: Option<String>,
185
186    /// Custom endpoint URL for the S3 Tables service.
187    ///
188    /// Primarily used to target a local or mock S3 Tables implementation for testing.
189    /// When omitted, the default regional endpoint is used.
190    #[serde(rename = "s3tables.endpoint")]
191    pub endpoint: Option<String>,
192
193    /// Access key id used to access the S3 Tables catalog.
194    #[serde(rename = "s3tables.access-key-id")]
195    pub access_key_id: Option<String>,
196
197    /// Secret access key used to access the S3 Tables catalog.
198    #[serde(rename = "s3tables.secret-access-key")]
199    pub secret_access_key: Option<String>,
200
201    /// Static session token used to access the S3 Tables catalog.
202    #[serde(rename = "s3tables.session-token")]
203    pub session_token: Option<String>,
204
205    /// Profile used to access the S3 Tables catalog.
206    #[serde(rename = "s3tables.profile-name")]
207    pub profile_name: Option<String>,
208
209    /// Region of the S3 Tables catalog.
210    #[serde(rename = "s3tables.region")]
211    pub region: Option<String>,
212}
213
214fn default_num_parsers() -> u32 {
215    4
216}
217
218/// Iceberg input connector configuration.
219#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
220pub struct IcebergReaderConfig {
221    /// Table read mode.
222    pub mode: IcebergIngestMode,
223
224    /// Transaction mode.
225    ///
226    /// Determines how the connector breaks up its input into Feldera transactions.
227    /// See [`IcebergTransactionMode`]. Defaults to [`IcebergTransactionMode::None`].
228    #[serde(default)]
229    pub transaction_mode: IcebergTransactionMode,
230
231    /// Table column that serves as an event timestamp.
232    ///
233    /// When this option is specified, and `mode` is one of `snapshot` or `snapshot_and_follow`,
234    /// table rows are ingested in the timestamp order, respecting the
235    /// [`LATENESS`](https://docs.feldera.com/sql/streaming#lateness-expressions)
236    /// property of the column: each ingested row has a timestamp no more than `LATENESS`
237    /// time units earlier than the most recent timestamp of any previously ingested row.
238    /// The ingestion is performed by partitioning the table into timestamp ranges of width
239    /// `LATENESS`. Each range is processed sequentially, in increasing timestamp order.
240    ///
241    /// # Example
242    ///
243    /// Consider a table with timestamp column of type `TIMESTAMP` and lateness attribute
244    /// `INTERVAL 1 DAY`. Assuming that the oldest timestamp in the table is
245    /// `2024-01-01T00:00:00``, the connector will fetch all records with timestamps
246    /// from `2024-01-01`, then all records for `2024-01-02`, `2024-01-03`, etc., until all records
247    /// in the table have been ingested.
248    ///
249    /// # Requirements
250    ///
251    /// * The timestamp column must be of a supported type: integer, `DATE`, or `TIMESTAMP`.
252    /// * The timestamp column must be declared with non-zero `LATENESS`.
253    /// * For efficient ingest, the table must be optimized for timestamp-based
254    ///   queries using partitioning, Z-ordering, or liquid clustering.
255    pub timestamp_column: Option<String>,
256
257    /// Optional row filter.
258    ///
259    /// This option is only valid when `mode` is set to `snapshot` or `snapshot_and_follow`.
260    ///
261    /// When specified, only rows that satisfy the filter condition are included in the
262    /// snapshot.  The condition must be a valid SQL Boolean expression that can be used in
263    /// the `where` clause of the `select * from snapshot where ...` query.
264    ///
265    /// This option can be used to specify the range of event times to include in the snapshot,
266    /// e.g.: `ts BETWEEN '2005-01-01 00:00:00' AND '2010-12-31 23:59:59'`.
267    pub snapshot_filter: Option<String>,
268
269    /// Optional snapshot id.
270    ///
271    /// When this option is set, the connector finds the specified snapshot of the table.
272    /// In `snapshot` and `snapshot_and_follow` modes, it loads this snapshot.
273    /// In `follow` and `snapshot_and_follow` modes, it follows table updates
274    /// **after** this snapshot.
275    ///
276    /// Note: at most one of `snapshot_id` and `datetime` options can be specified.
277    /// When neither of the two options is specified, the latest committed version of the table
278    /// is used.
279    pub snapshot_id: Option<i64>,
280
281    /// Optional timestamp for the snapshot in the ISO-8601/RFC-3339 format, e.g.,
282    /// "2024-12-09T16:09:53+00:00".
283    ///
284    /// When this option is set, the connector finds and opens the snapshot of the table as of the
285    /// specified point in time (based on the server time recorded in the transaction
286    /// log, not the event time encoded in the data).  In `snapshot` and `snapshot_and_follow`
287    /// modes, it retrieves this snapshot.  In `follow` and `snapshot_and_follow` modes, it
288    /// follows transaction log records **after** this snapshot.
289    ///
290    /// Note: at most one of `snapshot_id` and `datetime` options can be specified.
291    /// When neither of the two options is specified, the latest committed version of the table
292    /// is used.
293    pub datetime: Option<String>,
294
295    /// Optional final snapshot id.
296    ///
297    /// Valid only in `follow` and `snapshot_and_follow` modes.
298    ///
299    /// When set, the connector stops after fully ingesting the snapshot with
300    /// this id, signaling end-of-input. Iceberg snapshot ids are not ordered, so
301    /// the bound is an exact match: the id must name a snapshot committed after
302    /// the starting snapshot and already present in the table's current history.
303    /// The connector rejects any other value at startup, including a
304    /// not-yet-committed id, rather than follow forever.
305    pub end_snapshot_id: Option<i64>,
306
307    /// Location of the table metadata JSON file.
308    ///
309    /// This propery is used to access an Iceberg table without a catalog. It is mutually
310    /// exclusive with the `catalog_type` property.
311    pub metadata_location: Option<String>,
312
313    /// Specifies the Iceberg table name in the "namespace.table" format.
314    ///
315    /// This option is applicable when an Iceberg catalog is configured using the `catalog_type` property.
316    pub table_name: Option<String>,
317
318    /// Specifies the catalog type used to access the Iceberg table.
319    ///
320    /// Supported options include "rest", "glue", and "s3tables". This property is mutually
321    /// exclusive with `metadata_location`.
322    pub catalog_type: Option<IcebergCatalogType>,
323
324    /// The number of parallel parsing tasks the connector uses to process data read from the
325    /// table. Increasing this value can enhance performance by allowing more concurrent processing.
326    /// Recommended range: 1-10. The default is 4.
327    #[serde(default = "default_num_parsers")]
328    #[schema(minimum = 1)]
329    pub num_parsers: u32,
330
331    /// Maximum number of retries for reading the table snapshot.
332    ///
333    /// When reading the snapshot fails partway through, for example because an
334    /// object-store read times out or is throttled, the connector retries the
335    /// entire read with exponential backoff. This is in addition to the
336    /// lower-level retries performed by the object-store client.
337    ///
338    /// Defaults to unlimited retries. Set to 0 to disable retries.
339    #[serde(default, skip_serializing_if = "Option::is_none")]
340    pub max_retries: Option<u32>,
341
342    #[serde(flatten)]
343    pub glue_catalog_config: GlueCatalogConfig,
344
345    #[serde(flatten)]
346    pub rest_catalog_config: RestCatalogConfig,
347
348    #[serde(flatten)]
349    pub s3tables_catalog_config: S3TablesCatalogConfig,
350
351    /// Storage options for configuring backend object store.
352    ///
353    /// See the [list of available options in PyIceberg documentation](https://py.iceberg.apache.org/configuration/#fileio).
354    #[serde(flatten)]
355    pub fileio_config: HashMap<String, String>,
356}
357
358impl IcebergReaderConfig {
359    pub fn validate_catalog_config(&self) -> Result<(), String> {
360        self.validate_metadata_location()?;
361        self.validate_table_name()?;
362        self.validate_glue_catalog_config()?;
363        self.validate_rest_catalog_config()?;
364        self.validate_s3tables_catalog_config()?;
365
366        Ok(())
367    }
368
369    /// Reject Glue catalog config properties when 'catalog_type' isn't set to 'glue'.
370    pub fn validate_glue_catalog_config(&self) -> Result<(), String> {
371        if self.catalog_type == Some(IcebergCatalogType::Glue) {
372            if self.glue_catalog_config.warehouse.is_none() {
373                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());
374            }
375        } else {
376            ensure_glue_property_not_set(&self.glue_catalog_config.warehouse, "warehouse")?;
377            ensure_glue_property_not_set(&self.glue_catalog_config.endpoint, "uri")?;
378            ensure_glue_property_not_set(&self.glue_catalog_config.access_key_id, "access-key-id")?;
379            ensure_glue_property_not_set(
380                &self.glue_catalog_config.secret_access_key,
381                "secret-access-key",
382            )?;
383            ensure_glue_property_not_set(&self.glue_catalog_config.profile_name, "profile-name")?;
384            ensure_glue_property_not_set(&self.glue_catalog_config.region, "region")?;
385            ensure_glue_property_not_set(&self.glue_catalog_config.session_token, "session-token")?;
386            ensure_glue_property_not_set(&self.glue_catalog_config.id, "id")?;
387        }
388
389        Ok(())
390    }
391
392    /// Reject Rest catalog config when 'catalog_type' isn't set to 'rest'.
393    pub fn validate_rest_catalog_config(&self) -> Result<(), String> {
394        if self.catalog_type == Some(IcebergCatalogType::Rest) {
395            if self.rest_catalog_config.uri.is_none() {
396                return Err(r#"missing Iceberg Rest catalog URI—set the 'rest.uri' property when using "catalog_type" = "rest""#.to_string());
397            }
398        } else {
399            ensure_rest_property_not_set(&self.rest_catalog_config.uri, "uri")?;
400            ensure_rest_property_not_set(&self.rest_catalog_config.warehouse, "warehouse")?;
401            ensure_rest_property_not_set(
402                &self.rest_catalog_config.oauth2_server_uri,
403                "oauth2_server_uri",
404            )?;
405            ensure_rest_property_not_set(&self.rest_catalog_config.credential, "credential")?;
406            ensure_rest_property_not_set(&self.rest_catalog_config.token, "token")?;
407            ensure_rest_property_not_set(&self.rest_catalog_config.scope, "scope")?;
408            ensure_rest_property_not_set(&self.rest_catalog_config.prefix, "prefix")?;
409            ensure_rest_property_not_set(&self.rest_catalog_config.headers, "headers")?;
410            ensure_rest_property_not_set(&self.rest_catalog_config.audience, "audience")?;
411            ensure_rest_property_not_set(&self.rest_catalog_config.resource, "resource")?;
412        }
413
414        Ok(())
415    }
416
417    /// Reject S3 Tables catalog config when 'catalog_type' isn't set to 's3tables'.
418    pub fn validate_s3tables_catalog_config(&self) -> Result<(), String> {
419        if self.catalog_type == Some(IcebergCatalogType::S3Tables) {
420            if self.s3tables_catalog_config.table_bucket_arn.is_none() {
421                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());
422            }
423        } else {
424            ensure_s3tables_property_not_set(
425                &self.s3tables_catalog_config.table_bucket_arn,
426                "table-bucket-arn",
427            )?;
428            ensure_s3tables_property_not_set(&self.s3tables_catalog_config.endpoint, "endpoint")?;
429            ensure_s3tables_property_not_set(
430                &self.s3tables_catalog_config.access_key_id,
431                "access-key-id",
432            )?;
433            ensure_s3tables_property_not_set(
434                &self.s3tables_catalog_config.secret_access_key,
435                "secret-access-key",
436            )?;
437            ensure_s3tables_property_not_set(
438                &self.s3tables_catalog_config.session_token,
439                "session-token",
440            )?;
441            ensure_s3tables_property_not_set(
442                &self.s3tables_catalog_config.profile_name,
443                "profile-name",
444            )?;
445            ensure_s3tables_property_not_set(&self.s3tables_catalog_config.region, "region")?;
446        }
447
448        Ok(())
449    }
450
451    /// Table name must be configured iff 'catalog_type' is set.
452    pub fn validate_table_name(&self) -> Result<(), String> {
453        if self.catalog_type.is_none() && self.table_name.is_some() {
454            Err("unexpected 'table_name' property: the 'table_name' property is valid only when an Iceberg catalog is configured using 'catalog_type'".to_string())
455        } else if self.catalog_type.is_some() && self.table_name.is_none() {
456            Err("missing 'table_name' property—'table_name' must be specified when Iceberg catalog is configured using 'catalog_type'".to_string())
457        } else {
458            Ok(())
459        }
460    }
461
462    /// 'metadata_location' must be configured iff 'catalog_type' is set.
463    pub fn validate_metadata_location(&self) -> Result<(), String> {
464        if self.catalog_type.is_none() && self.metadata_location.is_none() {
465            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())
466        } else if self.catalog_type.is_some() && self.metadata_location.is_some() {
467            Err("unexpected 'metadata_location' property: the 'metadata_location' property is not supported when an Iceberg catalog is configured using 'catalog_type'".to_string())
468        } else {
469            Ok(())
470        }
471    }
472}
473
474fn ensure_glue_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
475    if property.is_some() {
476        Err(format!(
477            r#"unexpected 'glue.{name}' property—Glue catalog configuration properties are only valid when "catalog_type" = "glue""#
478        ))
479    } else {
480        Ok(())
481    }
482}
483
484fn ensure_rest_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
485    if property.is_some() {
486        Err(format!(
487            r#"unexpected 'rest.{name}' property—Rest catalog configuration properties are only valid when "catalog_type" = "rest""#
488        ))
489    } else {
490        Ok(())
491    }
492}
493
494fn ensure_s3tables_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
495    if property.is_some() {
496        Err(format!(
497            r#"unexpected 's3tables.{name}' property—S3 Tables catalog configuration properties are only valid when "catalog_type" = "s3tables""#
498        ))
499    } else {
500        Ok(())
501    }
502}
503
504impl IcebergReaderConfig {
505    /// Maximum number of high-level operation retries. Defaults to unlimited.
506    pub fn max_retries(&self) -> u32 {
507        self.max_retries.unwrap_or(u32::MAX)
508    }
509
510    /// `true` if the configuration requires taking an initial snapshot of the table.
511    pub fn snapshot(&self) -> bool {
512        matches!(
513            &self.mode,
514            IcebergIngestMode::Snapshot | IcebergIngestMode::SnapshotAndFollow
515        )
516    }
517
518    /// `true` if the configuration requires following the transaction log of the table
519    /// (possibly after taking an initial snapshot).s
520    pub fn follow(&self) -> bool {
521        matches!(
522            &self.mode,
523            IcebergIngestMode::SnapshotAndFollow | IcebergIngestMode::Follow
524        )
525    }
526}
527
528#[cfg(test)]
529mod test {
530    use super::*;
531    use serde_json::json;
532
533    fn config(value: serde_json::Value) -> IcebergReaderConfig {
534        serde_json::from_value(value).unwrap()
535    }
536
537    #[test]
538    fn s3tables_config_deserializes() {
539        let config = config(json!({
540            "mode": "snapshot",
541            "catalog_type": "s3tables",
542            "table_name": "namespace.table",
543            "s3tables.table-bucket-arn": "arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket",
544            "s3tables.region": "us-east-2",
545            "s3tables.access-key-id": "key",
546            "s3tables.secret-access-key": "secret",
547            "s3tables.session-token": "token",
548            "s3tables.profile-name": "profile",
549            "s3tables.endpoint": "http://localhost:4566",
550        }));
551
552        // Each prefixed key must land on its struct field, not in the catch-all
553        // `fileio_config` map (which is what happens on a rename mismatch).
554        let s3tables = &config.s3tables_catalog_config;
555        assert_eq!(
556            s3tables.table_bucket_arn.as_deref(),
557            Some("arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket")
558        );
559        assert_eq!(s3tables.region.as_deref(), Some("us-east-2"));
560        assert_eq!(s3tables.access_key_id.as_deref(), Some("key"));
561        assert_eq!(s3tables.secret_access_key.as_deref(), Some("secret"));
562        assert_eq!(s3tables.session_token.as_deref(), Some("token"));
563        assert_eq!(s3tables.profile_name.as_deref(), Some("profile"));
564        assert_eq!(s3tables.endpoint.as_deref(), Some("http://localhost:4566"));
565        assert!(config.fileio_config.is_empty());
566
567        config.validate_catalog_config().unwrap();
568    }
569
570    #[test]
571    fn s3tables_requires_table_bucket_arn() {
572        let err = config(json!({
573            "mode": "snapshot",
574            "catalog_type": "s3tables",
575            "table_name": "namespace.table",
576        }))
577        .validate_catalog_config()
578        .unwrap_err();
579        assert!(err.contains("s3tables.table-bucket-arn"), "{err}");
580    }
581
582    #[test]
583    fn s3tables_props_rejected_for_other_catalog() {
584        let err = config(json!({
585            "mode": "snapshot",
586            "catalog_type": "glue",
587            "table_name": "namespace.table",
588            "glue.warehouse": "s3://warehouse/",
589            "s3tables.region": "us-east-2",
590        }))
591        .validate_catalog_config()
592        .unwrap_err();
593        assert!(err.contains("s3tables.region"), "{err}");
594    }
595
596    #[test]
597    fn s3tables_props_rejected_without_catalog() {
598        let err = config(json!({
599            "mode": "snapshot",
600            "metadata_location": "s3://warehouse/metadata.json",
601            "s3tables.table-bucket-arn": "arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket",
602        }))
603        .validate_catalog_config()
604        .unwrap_err();
605        assert!(err.contains("s3tables.table-bucket-arn"), "{err}");
606    }
607
608    #[test]
609    fn num_parsers_and_max_retries_defaults() {
610        // With neither field set, num_parsers defaults to 4 and retries are unlimited.
611        let config: IcebergReaderConfig = serde_json::from_str(
612            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json"}"#,
613        )
614        .unwrap();
615        assert_eq!(config.num_parsers, 4);
616        assert_eq!(config.max_retries, None);
617        assert_eq!(config.max_retries(), u32::MAX);
618    }
619
620    #[test]
621    fn num_parsers_and_max_retries_explicit() {
622        let config: IcebergReaderConfig = serde_json::from_str(
623            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json","num_parsers":8,"max_retries":0}"#,
624        )
625        .unwrap();
626        assert_eq!(config.num_parsers, 8);
627        assert_eq!(config.max_retries, Some(0));
628        // 0 disables retries: the first attempt is the last.
629        assert_eq!(config.max_retries(), 0);
630    }
631
632    #[test]
633    fn transaction_mode_defaults_to_none() {
634        let config: IcebergReaderConfig = serde_json::from_str(
635            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json"}"#,
636        )
637        .unwrap();
638        assert_eq!(config.transaction_mode, IcebergTransactionMode::None);
639    }
640
641    #[test]
642    fn transaction_mode_snapshot_parses() {
643        let config: IcebergReaderConfig = serde_json::from_str(
644            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json","transaction_mode":"snapshot"}"#,
645        )
646        .unwrap();
647        assert_eq!(config.transaction_mode, IcebergTransactionMode::Snapshot);
648    }
649
650    #[test]
651    fn reader_config_roundtrips() {
652        let config: IcebergReaderConfig = serde_json::from_str(
653            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json","num_parsers":2}"#,
654        )
655        .unwrap();
656        let serialized = serde_json::to_string(&config).unwrap();
657        let reparsed: IcebergReaderConfig = serde_json::from_str(&serialized).unwrap();
658        assert_eq!(config, reparsed);
659        assert_eq!(reparsed.num_parsers, 2);
660    }
661}