Skip to main content

iota_data_ingestion_core/
util.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{str::FromStr, time::Duration};
6
7use backoff::{ExponentialBackoff, backoff::Backoff};
8use object_store::{
9    ClientOptions, ObjectStore, RetryConfig, aws::AmazonS3ConfigKey, gcp::GoogleConfigKey,
10};
11use url::Url;
12
13use crate::IngestionResult;
14
15/// Creates a remote store client *without* any retry mechanism.
16///
17/// This function constructs a remote store client configured to *not* retry
18/// failed requests. All requests will fail immediately if the underlying
19/// operation encounters an error.  This is a convenience wrapper around
20/// `create_remote_store_client_with_ops` that sets the retry configuration
21/// to disable retries.
22///
23/// # Arguments
24///
25/// * `url`: The URL of the remote store. The scheme of the URL determines the storage provider:
26///     * `http://` or `https://`: HTTP-based store.
27///     * `gs://`: Google Cloud Storage.
28///     * `s3://` or other AWS S3-compatible URL: Amazon S3.
29/// * `remote_store_options`: A vector of key-value pairs representing provider-specific options.
30///     * For GCS: See [`object_store::gcp::GoogleConfigKey`] for valid keys.
31///     * For S3: See [`object_store::aws::AmazonS3ConfigKey`] for valid keys.
32///     * For HTTP: No options are currently supported. This parameter should be empty.
33/// * `request_timeout_secs`: The timeout duration (in seconds) for individual requests. This
34///   timeout is used to set a slightly longer retry timeout (request_timeout_secs + 1) internally,
35///   even though retries are disabled. This is done to ensure that the overall operation doesn't
36///   hang indefinitely.
37///
38/// # Examples
39///
40/// Creating an S3 client without retries:
41///
42/// ```rust,no_run
43/// # use iota_data_ingestion_core::create_remote_store_client;
44/// use object_store::aws::AmazonS3ConfigKey;
45///
46/// let url = "s3://my-bucket";
47/// let options = vec![(
48///     AmazonS3ConfigKey::Region.as_ref().to_owned(),
49///     "us-east-1".to_string(),
50/// )];
51/// let client = create_remote_store_client(url.to_string(), options, 30).unwrap();
52/// ```
53///
54/// Creating a GCS client without retries:
55///
56/// ```rust,no_run
57/// # use iota_data_ingestion_core::create_remote_store_client;
58/// use object_store::gcp::GoogleConfigKey;
59///
60/// let url = "gs://my-bucket";
61/// let options = vec![(
62///     GoogleConfigKey::ServiceAccount.as_ref().to_owned(),
63///     "my-service-account".to_string(),
64/// )];
65/// let client = create_remote_store_client(url.to_string(), options, 30).unwrap();
66/// ```
67///
68/// Creating an HTTP client without retries (no options supported):
69///
70/// ```rust,no_run
71/// # use iota_data_ingestion_core::create_remote_store_client;
72///
73/// let url = "http://example.bucket.com";
74/// let options = vec![]; // No options for HTTP
75/// let client = create_remote_store_client(url.to_string(), options, 30).unwrap();
76/// ```
77pub fn create_remote_store_client(
78    url: String,
79    remote_store_options: Vec<(String, String)>,
80    request_timeout_secs: u64,
81) -> IngestionResult<Box<dyn ObjectStore>> {
82    let retry_config = RetryConfig {
83        max_retries: 0,
84        retry_timeout: Duration::from_secs(request_timeout_secs + 1),
85        ..Default::default()
86    };
87
88    create_remote_store_client_with_ops(
89        url,
90        remote_store_options,
91        request_timeout_secs,
92        retry_config,
93    )
94}
95
96/// Creates a remote store client with configurable retry behavior and options.
97///
98/// This function constructs a remote store client for various cloud storage
99/// providers (HTTP, Google Cloud Storage, Amazon S3) based on the provided URL
100/// and options. It allows configuring retry behavior through the `retry_config`
101/// argument.
102///
103/// The function sets `ring` as the default crypto provider for `rustls`, if it has not been already
104/// set. Users that want to install another provider are thus advised to do so before calling this
105/// function.
106///
107/// # Arguments
108///
109/// * `url`: The URL of the remote store.  The scheme of the URL determines the storage provider:
110///     * `http://` or `https://`:  HTTP-based store.
111///     * `gs://`: Google Cloud Storage.
112///     * `s3://` or other AWS S3-compatible URL: Amazon S3.
113/// * `remote_store_options`: A vector of key-value pairs representing provider-specific options.
114///     * For GCS:  See [`object_store::gcp::GoogleConfigKey`] for valid keys.
115///     * For S3: See [`object_store::aws::AmazonS3ConfigKey`] for valid keys.
116///     * For HTTP: No options are currently supported. This parameter should be empty.
117/// * `request_timeout_secs`: The timeout duration (in seconds) for individual requests.
118/// * `retry_config`: A [`RetryConfig`] struct defining the retry strategy. This allows fine-grained
119///   control over the number of retries, backoff behavior, and retry timeouts.  See the
120///   documentation for [`object_store::RetryConfig`] for details.
121///
122/// # Examples
123///
124/// Creating an S3 client with specific options and a retry configuration:
125///
126/// ```text
127/// # use iota_data_ingestion_core::create_remote_store_client_with_ops;
128/// use object_store::{RetryConfig, aws::AmazonS3ConfigKey};
129///
130/// let url = "s3://my-bucket";
131/// let options = vec![(
132///     AmazonS3ConfigKey::Region.as_ref().to_owned(),
133///     "us-east-1".to_string(),
134/// )];
135/// let retry_config = RetryConfig::default(); // Use default retry settings
136/// let client =
137///     create_remote_store_client_with_ops(url.to_string(), options, 30, retry_config).unwrap();
138/// ```
139///
140/// Creating a GCS client:
141///
142/// ```text
143/// # use iota_data_ingestion_core::create_remote_store_client_with_ops;
144/// use object_store::{RetryConfig, gcp::GoogleConfigKey};
145///
146/// let url = "gs://my-bucket";
147/// let options = vec![(
148///     GoogleConfigKey::ServiceAccount.as_ref().to_owned(),
149///     "my-service-account".to_string(),
150/// )];
151/// let retry_config = RetryConfig::default();
152/// let client =
153///     create_remote_store_client_with_ops(url.to_string(), options, 30, retry_config).unwrap();
154/// ```
155///
156/// Creating an HTTP client (no options supported):
157///
158/// ```text
159/// # use iota_data_ingestion_core::create_remote_store_client_with_ops;
160/// use object_store::RetryConfig;
161///
162/// let url = "http://example.bucket.com";
163/// let options = vec![]; // No options for HTTP
164/// let retry_config = RetryConfig::default();
165/// let client =
166///     create_remote_store_client_with_ops(url.to_string(), options, 30, retry_config).unwrap();
167/// ```
168pub fn create_remote_store_client_with_ops(
169    url: String,
170    remote_store_options: Vec<(String, String)>,
171    request_timeout_secs: u64,
172    retry_config: RetryConfig,
173) -> IngestionResult<Box<dyn ObjectStore>> {
174    // Every store below builds a reqwest client, which panics if no rustls
175    // crypto provider is installed.
176    let _ = rustls::crypto::ring::default_provider().install_default();
177    let client_options = ClientOptions::new()
178        .with_timeout(Duration::from_secs(request_timeout_secs))
179        .with_allow_http(true);
180    if remote_store_options.is_empty() {
181        let http_store = object_store::http::HttpBuilder::new()
182            .with_url(url)
183            .with_client_options(client_options)
184            .with_retry(retry_config)
185            .build()?;
186        Ok(Box::new(http_store))
187    } else if Url::parse(&url)?.scheme() == "gs" {
188        let url = Url::parse(&url)?;
189        let mut builder = object_store::gcp::GoogleCloudStorageBuilder::new()
190            .with_url(url.as_str())
191            .with_retry(retry_config)
192            .with_client_options(client_options);
193        for (key, value) in remote_store_options {
194            builder = builder.with_config(GoogleConfigKey::from_str(&key)?, value);
195        }
196        Ok(Box::new(builder.build()?))
197    } else {
198        let url = Url::parse(&url)?;
199        let mut builder = object_store::aws::AmazonS3Builder::new()
200            .with_url(url.as_str())
201            .with_retry(retry_config)
202            .with_client_options(client_options);
203        for (key, value) in remote_store_options {
204            builder = builder.with_config(AmazonS3ConfigKey::from_str(&key)?, value);
205        }
206        Ok(Box::new(builder.build()?))
207    }
208}
209
210/// Creates a new [`ExponentialBackoff`] instance based on the configured
211/// template.
212///
213/// Returns a fresh backoff instance that has been reset to its initial
214/// state, ensuring consistent retry behavior for each new operation.
215pub(crate) fn reset_backoff(backoff: &ExponentialBackoff) -> ExponentialBackoff {
216    let mut backoff = backoff.clone();
217    backoff.reset();
218    backoff
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    fn make(url: &str, options: Vec<(String, String)>) {
226        create_remote_store_client_with_ops(url.to_string(), options, 30, RetryConfig::default())
227            .unwrap();
228    }
229
230    #[test]
231    fn http_store() {
232        make("http://localhost:1/", vec![]);
233    }
234
235    #[test]
236    fn gcs_store() {
237        make(
238            "gs://bucket",
239            vec![("google_skip_signature".to_string(), "true".to_string())],
240        );
241    }
242
243    #[test]
244    fn s3_store() {
245        make(
246            "s3://bucket",
247            vec![("aws_region".to_string(), "us-east-1".to_string())],
248        );
249    }
250}