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
214/// The number of CPU cores, at most 16. Each parsing task holds a record batch.
215fn default_num_parsers() -> u32 {
216    std::thread::available_parallelism().map_or(4, |n| n.get().min(16) as u32)
217}
218
219/// Iceberg input connector configuration.
220#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
221pub struct IcebergReaderConfig {
222    /// Table read mode.
223    pub mode: IcebergIngestMode,
224
225    /// Transaction mode.
226    ///
227    /// Determines how the connector breaks up its input into Feldera transactions.
228    /// See [`IcebergTransactionMode`]. Defaults to [`IcebergTransactionMode::None`].
229    #[serde(default)]
230    pub transaction_mode: IcebergTransactionMode,
231
232    /// Table column that serves as an event timestamp.
233    ///
234    /// When this option is specified, and `mode` is one of `snapshot` or `snapshot_and_follow`,
235    /// table rows are ingested in the timestamp order, respecting the
236    /// [`LATENESS`](https://docs.feldera.com/sql/streaming#lateness-expressions)
237    /// property of the column: each ingested row has a timestamp no more than `LATENESS`
238    /// time units earlier than the most recent timestamp of any previously ingested row.
239    /// The ingestion is performed by partitioning the table into timestamp ranges of width
240    /// `LATENESS`. Each range is processed sequentially, in increasing timestamp order.
241    ///
242    /// # Example
243    ///
244    /// Consider a table with timestamp column of type `TIMESTAMP` and lateness attribute
245    /// `INTERVAL 1 DAY`. Assuming that the oldest timestamp in the table is
246    /// `2024-01-01T00:00:00``, the connector will fetch all records with timestamps
247    /// from `2024-01-01`, then all records for `2024-01-02`, `2024-01-03`, etc., until all records
248    /// in the table have been ingested.
249    ///
250    /// # Requirements
251    ///
252    /// * The timestamp column must be of a supported type: integer, `DATE`, or `TIMESTAMP`.
253    /// * The timestamp column must be declared with non-zero `LATENESS`.
254    /// * For efficient ingest, the table must be optimized for timestamp-based
255    ///   queries using partitioning, Z-ordering, or liquid clustering.
256    pub timestamp_column: Option<String>,
257
258    /// Optional row filter.
259    ///
260    /// This option is only valid when `mode` is set to `snapshot` or `snapshot_and_follow`.
261    ///
262    /// When specified, only rows that satisfy the filter condition are included in the
263    /// snapshot.  The condition must be a valid SQL Boolean expression that can be used in
264    /// the `where` clause of the `select * from snapshot where ...` query.
265    ///
266    /// This option can be used to specify the range of event times to include in the snapshot,
267    /// e.g.: `ts BETWEEN '2005-01-01 00:00:00' AND '2010-12-31 23:59:59'`.
268    pub snapshot_filter: Option<String>,
269
270    /// Optional snapshot id.
271    ///
272    /// When this option is set, the connector finds the specified snapshot of the table.
273    /// In `snapshot` and `snapshot_and_follow` modes, it loads this snapshot.
274    /// In `follow` and `snapshot_and_follow` modes, it follows table updates
275    /// **after** this snapshot.
276    ///
277    /// Note: at most one of `snapshot_id` and `datetime` options can be specified.
278    /// When neither of the two options is specified, the latest committed version of the table
279    /// is used.
280    pub snapshot_id: Option<i64>,
281
282    /// Optional timestamp for the snapshot in the ISO-8601/RFC-3339 format, e.g.,
283    /// "2024-12-09T16:09:53+00:00".
284    ///
285    /// When this option is set, the connector finds and opens the snapshot of the table as of the
286    /// specified point in time (based on the server time recorded in the transaction
287    /// log, not the event time encoded in the data).  In `snapshot` and `snapshot_and_follow`
288    /// modes, it retrieves this snapshot.  In `follow` and `snapshot_and_follow` modes, it
289    /// follows transaction log records **after** this snapshot.
290    ///
291    /// Note: at most one of `snapshot_id` and `datetime` options can be specified.
292    /// When neither of the two options is specified, the latest committed version of the table
293    /// is used.
294    pub datetime: Option<String>,
295
296    /// Optional final snapshot id.
297    ///
298    /// Valid only in `follow` and `snapshot_and_follow` modes.
299    ///
300    /// When set, the connector stops after fully ingesting the snapshot with
301    /// this id, signaling end-of-input. Iceberg snapshot ids are not ordered, so
302    /// the bound is an exact match: the id must name a snapshot committed after
303    /// the starting snapshot and already present in the table's current history.
304    /// The connector rejects any other value at startup, including a
305    /// not-yet-committed id, rather than follow forever.
306    pub end_snapshot_id: Option<i64>,
307
308    /// Location of the table metadata JSON file.
309    ///
310    /// This propery is used to access an Iceberg table without a catalog. It is mutually
311    /// exclusive with the `catalog_type` property.
312    pub metadata_location: Option<String>,
313
314    /// Specifies the Iceberg table name in the "namespace.table" format.
315    ///
316    /// This option is applicable when an Iceberg catalog is configured using the `catalog_type` property.
317    pub table_name: Option<String>,
318
319    /// Specifies the catalog type used to access the Iceberg table.
320    ///
321    /// Supported options include "rest", "glue", and "s3tables". This property is mutually
322    /// exclusive with `metadata_location`.
323    pub catalog_type: Option<IcebergCatalogType>,
324
325    /// The number of record batches the connector parses at the same time. Parsing runs on a
326    /// pool with one thread per CPU core, which all connectors share, so a larger value only
327    /// helps while the pool has idle threads. Each batch in flight holds memory.
328    /// All connectors together keep at most two batches per CPU core in flight.
329    /// The default is the number of CPU cores available to the pipeline, at most 16.
330    ///
331    /// When set, this is also the number of files the connector reads at the same time,
332    /// which is 4 otherwise.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    #[schema(minimum = 1)]
335    pub num_parsers: Option<u32>,
336
337    /// Maximum number of retries for reading the table snapshot.
338    ///
339    /// When reading the snapshot fails partway through, for example because an
340    /// object-store read times out or is throttled, the connector retries the
341    /// entire read with exponential backoff. This is in addition to the
342    /// lower-level retries performed by the object-store client.
343    ///
344    /// Defaults to unlimited retries. Set to 0 to disable retries.
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    pub max_retries: Option<u32>,
347
348    #[serde(flatten)]
349    pub glue_catalog_config: GlueCatalogConfig,
350
351    #[serde(flatten)]
352    pub rest_catalog_config: RestCatalogConfig,
353
354    #[serde(flatten)]
355    pub s3tables_catalog_config: S3TablesCatalogConfig,
356
357    /// Storage options for configuring backend object store.
358    ///
359    /// See the [list of available options in PyIceberg documentation](https://py.iceberg.apache.org/configuration/#fileio).
360    #[serde(flatten)]
361    pub fileio_config: HashMap<String, String>,
362}
363
364impl IcebergReaderConfig {
365    pub fn validate_catalog_config(&self) -> Result<(), String> {
366        self.validate_metadata_location()?;
367        self.validate_table_name()?;
368        self.validate_glue_catalog_config()?;
369        self.validate_rest_catalog_config()?;
370        self.validate_s3tables_catalog_config()?;
371
372        Ok(())
373    }
374
375    /// Reject Glue catalog config properties when 'catalog_type' isn't set to 'glue'.
376    pub fn validate_glue_catalog_config(&self) -> Result<(), String> {
377        if self.catalog_type == Some(IcebergCatalogType::Glue) {
378            if self.glue_catalog_config.warehouse.is_none() {
379                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());
380            }
381        } else {
382            ensure_glue_property_not_set(&self.glue_catalog_config.warehouse, "warehouse")?;
383            ensure_glue_property_not_set(&self.glue_catalog_config.endpoint, "uri")?;
384            ensure_glue_property_not_set(&self.glue_catalog_config.access_key_id, "access-key-id")?;
385            ensure_glue_property_not_set(
386                &self.glue_catalog_config.secret_access_key,
387                "secret-access-key",
388            )?;
389            ensure_glue_property_not_set(&self.glue_catalog_config.profile_name, "profile-name")?;
390            ensure_glue_property_not_set(&self.glue_catalog_config.region, "region")?;
391            ensure_glue_property_not_set(&self.glue_catalog_config.session_token, "session-token")?;
392            ensure_glue_property_not_set(&self.glue_catalog_config.id, "id")?;
393        }
394
395        Ok(())
396    }
397
398    /// Reject Rest catalog config when 'catalog_type' isn't set to 'rest'.
399    pub fn validate_rest_catalog_config(&self) -> Result<(), String> {
400        if self.catalog_type == Some(IcebergCatalogType::Rest) {
401            if self.rest_catalog_config.uri.is_none() {
402                return Err(r#"missing Iceberg Rest catalog URI—set the 'rest.uri' property when using "catalog_type" = "rest""#.to_string());
403            }
404        } else {
405            ensure_rest_property_not_set(&self.rest_catalog_config.uri, "uri")?;
406            ensure_rest_property_not_set(&self.rest_catalog_config.warehouse, "warehouse")?;
407            ensure_rest_property_not_set(
408                &self.rest_catalog_config.oauth2_server_uri,
409                "oauth2_server_uri",
410            )?;
411            ensure_rest_property_not_set(&self.rest_catalog_config.credential, "credential")?;
412            ensure_rest_property_not_set(&self.rest_catalog_config.token, "token")?;
413            ensure_rest_property_not_set(&self.rest_catalog_config.scope, "scope")?;
414            ensure_rest_property_not_set(&self.rest_catalog_config.prefix, "prefix")?;
415            ensure_rest_property_not_set(&self.rest_catalog_config.headers, "headers")?;
416            ensure_rest_property_not_set(&self.rest_catalog_config.audience, "audience")?;
417            ensure_rest_property_not_set(&self.rest_catalog_config.resource, "resource")?;
418        }
419
420        Ok(())
421    }
422
423    /// Reject S3 Tables catalog config when 'catalog_type' isn't set to 's3tables'.
424    pub fn validate_s3tables_catalog_config(&self) -> Result<(), String> {
425        if self.catalog_type == Some(IcebergCatalogType::S3Tables) {
426            if self.s3tables_catalog_config.table_bucket_arn.is_none() {
427                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());
428            }
429        } else {
430            ensure_s3tables_property_not_set(
431                &self.s3tables_catalog_config.table_bucket_arn,
432                "table-bucket-arn",
433            )?;
434            ensure_s3tables_property_not_set(&self.s3tables_catalog_config.endpoint, "endpoint")?;
435            ensure_s3tables_property_not_set(
436                &self.s3tables_catalog_config.access_key_id,
437                "access-key-id",
438            )?;
439            ensure_s3tables_property_not_set(
440                &self.s3tables_catalog_config.secret_access_key,
441                "secret-access-key",
442            )?;
443            ensure_s3tables_property_not_set(
444                &self.s3tables_catalog_config.session_token,
445                "session-token",
446            )?;
447            ensure_s3tables_property_not_set(
448                &self.s3tables_catalog_config.profile_name,
449                "profile-name",
450            )?;
451            ensure_s3tables_property_not_set(&self.s3tables_catalog_config.region, "region")?;
452        }
453
454        Ok(())
455    }
456
457    /// Table name must be configured iff 'catalog_type' is set.
458    pub fn validate_table_name(&self) -> Result<(), String> {
459        if self.catalog_type.is_none() && self.table_name.is_some() {
460            Err("unexpected 'table_name' property: the 'table_name' property is valid only when an Iceberg catalog is configured using 'catalog_type'".to_string())
461        } else if self.catalog_type.is_some() && self.table_name.is_none() {
462            Err("missing 'table_name' property—'table_name' must be specified when Iceberg catalog is configured using 'catalog_type'".to_string())
463        } else {
464            Ok(())
465        }
466    }
467
468    /// 'metadata_location' must be configured iff 'catalog_type' is set.
469    pub fn validate_metadata_location(&self) -> Result<(), String> {
470        if self.catalog_type.is_none() && self.metadata_location.is_none() {
471            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())
472        } else if self.catalog_type.is_some() && self.metadata_location.is_some() {
473            Err("unexpected 'metadata_location' property: the 'metadata_location' property is not supported when an Iceberg catalog is configured using 'catalog_type'".to_string())
474        } else {
475            Ok(())
476        }
477    }
478}
479
480fn ensure_glue_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
481    if property.is_some() {
482        Err(format!(
483            r#"unexpected 'glue.{name}' property—Glue catalog configuration properties are only valid when "catalog_type" = "glue""#
484        ))
485    } else {
486        Ok(())
487    }
488}
489
490fn ensure_rest_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
491    if property.is_some() {
492        Err(format!(
493            r#"unexpected 'rest.{name}' property—Rest catalog configuration properties are only valid when "catalog_type" = "rest""#
494        ))
495    } else {
496        Ok(())
497    }
498}
499
500fn ensure_s3tables_property_not_set<T>(property: &Option<T>, name: &str) -> Result<(), String> {
501    if property.is_some() {
502        Err(format!(
503            r#"unexpected 's3tables.{name}' property—S3 Tables catalog configuration properties are only valid when "catalog_type" = "s3tables""#
504        ))
505    } else {
506        Ok(())
507    }
508}
509
510impl IcebergReaderConfig {
511    /// Maximum number of high-level operation retries. Defaults to unlimited.
512    pub fn max_retries(&self) -> u32 {
513        self.max_retries.unwrap_or(u32::MAX)
514    }
515
516    /// The number of record batches to parse at the same time.
517    ///
518    /// The default depends on the host, so the pipeline computes it, not the
519    /// service that stores the configuration.
520    pub fn num_parsers(&self) -> u32 {
521        self.num_parsers.unwrap_or_else(default_num_parsers)
522    }
523
524    /// The number of data files, delete files, and manifests to read at the
525    /// same time: `num_parsers` when set, otherwise 4. Each read holds decoded
526    /// data, so this does not follow the CPU count.
527    pub fn read_concurrency(&self) -> usize {
528        self.num_parsers.unwrap_or(4) as usize
529    }
530
531    /// `true` if the configuration requires taking an initial snapshot of the table.
532    pub fn snapshot(&self) -> bool {
533        matches!(
534            &self.mode,
535            IcebergIngestMode::Snapshot | IcebergIngestMode::SnapshotAndFollow
536        )
537    }
538
539    /// `true` if the configuration requires following the transaction log of the table
540    /// (possibly after taking an initial snapshot).s
541    pub fn follow(&self) -> bool {
542        matches!(
543            &self.mode,
544            IcebergIngestMode::SnapshotAndFollow | IcebergIngestMode::Follow
545        )
546    }
547}
548
549impl crate::sensitive::SensitiveValues for IcebergReaderConfig {
550    fn visit_sensitive_values(&self, visit: &mut dyn FnMut(&str, &str)) {
551        use crate::sensitive::{credential_header, visit_optional, visit_url};
552        visit_optional(
553            "glue.secret-access-key",
554            self.glue_catalog_config.secret_access_key.as_deref(),
555            visit,
556        );
557        visit_optional(
558            "glue.session-token",
559            self.glue_catalog_config.session_token.as_deref(),
560            visit,
561        );
562        visit_optional(
563            "s3tables.secret-access-key",
564            self.s3tables_catalog_config.secret_access_key.as_deref(),
565            visit,
566        );
567        visit_optional(
568            "s3tables.session-token",
569            self.s3tables_catalog_config.session_token.as_deref(),
570            visit,
571        );
572        visit_optional(
573            "rest.credential",
574            self.rest_catalog_config.credential.as_deref(),
575            visit,
576        );
577        visit_optional(
578            "rest.token",
579            self.rest_catalog_config.token.as_deref(),
580            visit,
581        );
582        if let Some(uri) = &self.rest_catalog_config.uri {
583            visit_url("rest.uri", uri, visit);
584        }
585        if let Some(headers) = &self.rest_catalog_config.headers {
586            for (name, value) in headers {
587                if credential_header(name) {
588                    visit(
589                        &format!("rest.headers.{}", name.to_ascii_lowercase()),
590                        value,
591                    );
592                }
593            }
594        }
595        // Iceberg FileIO uses dotted keys, independently of object_store's
596        // keys. These are the keys of the PyIceberg FileIO list (see
597        // `fileio_config`) that hold a secret key, a token or a connection
598        // string. A key that is not here is not registered; connector errors
599        // still leave its value out.
600        for (key, value) in &self.fileio_config {
601            if matches!(
602                key.as_str(),
603                "s3.secret-access-key"
604                    | "s3.session-token"
605                    | "s3.sse.key"
606                    | "gcs.credentials-json"
607                    | "gcs.oauth2.token"
608                    | "oss.access-key-secret"
609                    | "adls.connection-string"
610                    | "adls.account-key"
611                    | "adls.sas-token"
612                    | "adls.client-secret"
613            ) {
614                visit(key, value);
615            }
616        }
617    }
618}
619
620#[cfg(test)]
621mod test {
622    use super::*;
623    use serde_json::json;
624
625    fn config(value: serde_json::Value) -> IcebergReaderConfig {
626        serde_json::from_value(value).unwrap()
627    }
628
629    #[test]
630    fn s3tables_config_deserializes() {
631        let config = config(json!({
632            "mode": "snapshot",
633            "catalog_type": "s3tables",
634            "table_name": "namespace.table",
635            "s3tables.table-bucket-arn": "arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket",
636            "s3tables.region": "us-east-2",
637            "s3tables.access-key-id": "key",
638            "s3tables.secret-access-key": "secret",
639            "s3tables.session-token": "token",
640            "s3tables.profile-name": "profile",
641            "s3tables.endpoint": "http://localhost:4566",
642        }));
643
644        // Each prefixed key must land on its struct field, not in the catch-all
645        // `fileio_config` map (which is what happens on a rename mismatch).
646        let s3tables = &config.s3tables_catalog_config;
647        assert_eq!(
648            s3tables.table_bucket_arn.as_deref(),
649            Some("arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket")
650        );
651        assert_eq!(s3tables.region.as_deref(), Some("us-east-2"));
652        assert_eq!(s3tables.access_key_id.as_deref(), Some("key"));
653        assert_eq!(s3tables.secret_access_key.as_deref(), Some("secret"));
654        assert_eq!(s3tables.session_token.as_deref(), Some("token"));
655        assert_eq!(s3tables.profile_name.as_deref(), Some("profile"));
656        assert_eq!(s3tables.endpoint.as_deref(), Some("http://localhost:4566"));
657        assert!(config.fileio_config.is_empty());
658
659        config.validate_catalog_config().unwrap();
660    }
661
662    #[test]
663    fn s3tables_requires_table_bucket_arn() {
664        let err = config(json!({
665            "mode": "snapshot",
666            "catalog_type": "s3tables",
667            "table_name": "namespace.table",
668        }))
669        .validate_catalog_config()
670        .unwrap_err();
671        assert!(err.contains("s3tables.table-bucket-arn"), "{err}");
672    }
673
674    #[test]
675    fn s3tables_props_rejected_for_other_catalog() {
676        let err = config(json!({
677            "mode": "snapshot",
678            "catalog_type": "glue",
679            "table_name": "namespace.table",
680            "glue.warehouse": "s3://warehouse/",
681            "s3tables.region": "us-east-2",
682        }))
683        .validate_catalog_config()
684        .unwrap_err();
685        assert!(err.contains("s3tables.region"), "{err}");
686    }
687
688    #[test]
689    fn s3tables_props_rejected_without_catalog() {
690        let err = config(json!({
691            "mode": "snapshot",
692            "metadata_location": "s3://warehouse/metadata.json",
693            "s3tables.table-bucket-arn": "arn:aws:s3tables:us-east-2:123456789012:bucket/my-bucket",
694        }))
695        .validate_catalog_config()
696        .unwrap_err();
697        assert!(err.contains("s3tables.table-bucket-arn"), "{err}");
698    }
699
700    #[test]
701    fn num_parsers_and_max_retries_defaults() {
702        // With neither field set, num_parsers takes its default and retries are unlimited.
703        let config: IcebergReaderConfig = serde_json::from_str(
704            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json"}"#,
705        )
706        .unwrap();
707        assert_eq!(config.num_parsers(), default_num_parsers());
708        assert_eq!(config.read_concurrency(), 4);
709        // An unset `num_parsers` stays unset: the pipeline computes the default.
710        assert!(
711            !serde_json::to_string(&config)
712                .unwrap()
713                .contains("num_parsers")
714        );
715        assert_eq!(config.max_retries, None);
716        assert_eq!(config.max_retries(), u32::MAX);
717    }
718
719    #[test]
720    fn num_parsers_and_max_retries_explicit() {
721        let config: IcebergReaderConfig = serde_json::from_str(
722            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json","num_parsers":8,"max_retries":0}"#,
723        )
724        .unwrap();
725        assert_eq!(config.num_parsers(), 8);
726        assert_eq!(config.read_concurrency(), 8);
727        assert_eq!(config.max_retries, Some(0));
728        // 0 disables retries: the first attempt is the last.
729        assert_eq!(config.max_retries(), 0);
730    }
731
732    #[test]
733    fn transaction_mode_defaults_to_none() {
734        let config: IcebergReaderConfig = serde_json::from_str(
735            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json"}"#,
736        )
737        .unwrap();
738        assert_eq!(config.transaction_mode, IcebergTransactionMode::None);
739    }
740
741    #[test]
742    fn transaction_mode_snapshot_parses() {
743        let config: IcebergReaderConfig = serde_json::from_str(
744            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json","transaction_mode":"snapshot"}"#,
745        )
746        .unwrap();
747        assert_eq!(config.transaction_mode, IcebergTransactionMode::Snapshot);
748    }
749
750    #[test]
751    fn reader_config_roundtrips() {
752        let config: IcebergReaderConfig = serde_json::from_str(
753            r#"{"mode":"snapshot","metadata_location":"file:///tmp/t/metadata.json","num_parsers":2}"#,
754        )
755        .unwrap();
756        let serialized = serde_json::to_string(&config).unwrap();
757        let reparsed: IcebergReaderConfig = serde_json::from_str(&serialized).unwrap();
758        assert_eq!(config, reparsed);
759        assert_eq!(reparsed.num_parsers(), 2);
760    }
761}