Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
828 lines (761 loc) · 28.4 KB
/
Copy pathlib.rs
File metadata and controls
828 lines (761 loc) · 28.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! OpenDAL-based storage implementation for Apache Iceberg.
//!
//! This crate provides [`OpenDalStorage`] and [`OpenDalStorageFactory`],
//! which implement the [`Storage`] and
//! [`StorageFactory`] traits from the `iceberg` crate
//! using [OpenDAL](https://opendal.apache.org/) as the backend.
mod utils;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::sync::Arc;
use async_trait::async_trait;
use bytes::Bytes;
use cfg_if::cfg_if;
use futures::StreamExt;
use futures::stream::BoxStream;
use iceberg::io::{
FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig,
StorageFactory,
};
use iceberg::{Error, ErrorKind, Result};
use opendal::Operator;
use opendal::layers::{RetryLayer, TimeoutLayer};
use serde::{Deserialize, Serialize};
use utils::from_opendal_error;
cfg_if! {
if #[cfg(feature = "opendal-azdls")] {
mod azdls;
use azdls::*;
use opendal::services::AzdlsConfig;
}
}
cfg_if! {
if #[cfg(feature = "opendal-hf")] {
mod hf;
use hf::*;
use opendal::services::HfConfig;
}
}
cfg_if! {
if #[cfg(feature = "opendal-fs")] {
mod fs;
use fs::*;
}
}
cfg_if! {
if #[cfg(feature = "opendal-gcs")] {
mod gcs;
use gcs::*;
use opendal::services::GcsConfig;
}
}
cfg_if! {
if #[cfg(feature = "opendal-memory")] {
mod memory;
use memory::*;
}
}
cfg_if! {
if #[cfg(feature = "opendal-oss")] {
mod oss;
use opendal::services::OssConfig;
use oss::*;
}
}
cfg_if! {
if #[cfg(feature = "opendal-s3")] {
mod s3;
use opendal::services::S3Config;
pub use s3::*;
}
}
mod resolving;
pub use resolving::{OpenDalResolvingStorage, OpenDalResolvingStorageFactory};
/// OpenDAL-based storage factory.
///
/// Maps scheme to the corresponding OpenDalStorage storage variant.
/// Use this factory with `FileIOBuilder::new(factory)` to create FileIO instances.
///
/// # Serialization
///
/// The receiving binary must enable the feature corresponding to the serialized backend variant.
/// For example, deserializing `OpenDalStorageFactory::S3` requires the `opendal-s3` feature.
///
/// Serialization fails when the `OpenDalStorageFactory::S3` variant contains a custom AWS
/// credential loader because the loader holds process-local state that cannot be reconstructed in
/// another process. Construct the factory without a custom loader before serializing it.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OpenDalStorageFactory {
/// Memory storage factory.
#[cfg(feature = "opendal-memory")]
Memory,
/// Local filesystem storage factory.
#[cfg(feature = "opendal-fs")]
Fs,
/// S3 storage factory.
#[cfg(feature = "opendal-s3")]
S3 {
/// Custom AWS credential loader.
#[serde(
skip_deserializing,
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_custom_credential_loader"
)]
customized_credential_load: Option<CustomAwsCredentialLoader>,
},
/// GCS storage factory.
#[cfg(feature = "opendal-gcs")]
Gcs,
/// OSS storage factory.
#[cfg(feature = "opendal-oss")]
Oss,
/// Azure Data Lake Storage factory.
#[cfg(feature = "opendal-azdls")]
Azdls,
/// HuggingFace Hub storage factory.
#[cfg(feature = "opendal-hf")]
Hf,
}
#[cfg(feature = "opendal-s3")]
pub(crate) fn serialize_custom_credential_loader<S>(
_loader: &Option<CustomAwsCredentialLoader>,
_serializer: S,
) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
Err(serde::ser::Error::custom(
"custom AWS credential loaders cannot be serialized",
))
}
#[typetag::serde(name = "OpenDalStorageFactory")]
impl StorageFactory for OpenDalStorageFactory {
#[allow(unused_variables)]
fn build(&self, config: &StorageConfig) -> Result<Arc<dyn Storage>> {
match self {
#[cfg(feature = "opendal-memory")]
OpenDalStorageFactory::Memory => {
Ok(Arc::new(OpenDalStorage::Memory(memory_config_build()?)))
}
#[cfg(feature = "opendal-fs")]
OpenDalStorageFactory::Fs => Ok(Arc::new(OpenDalStorage::LocalFs)),
#[cfg(feature = "opendal-s3")]
OpenDalStorageFactory::S3 {
customized_credential_load,
} => Ok(Arc::new(OpenDalStorage::S3 {
config: s3_config_parse(config.props().clone())?.into(),
customized_credential_load: customized_credential_load.clone(),
})),
#[cfg(feature = "opendal-gcs")]
OpenDalStorageFactory::Gcs => Ok(Arc::new(OpenDalStorage::Gcs {
config: gcs_config_parse(config.props().clone())?.into(),
})),
#[cfg(feature = "opendal-oss")]
OpenDalStorageFactory::Oss => Ok(Arc::new(OpenDalStorage::Oss {
config: oss_config_parse(config.props().clone())?.into(),
})),
#[cfg(feature = "opendal-azdls")]
OpenDalStorageFactory::Azdls => Ok(Arc::new(OpenDalStorage::Azdls {
config: azdls_config_parse(config.props().clone())?.into(),
})),
#[cfg(feature = "opendal-hf")]
OpenDalStorageFactory::Hf => Ok(Arc::new(OpenDalStorage::Hf {
config: hf_config_parse(config.props().clone())?.into(),
})),
#[cfg(all(
not(feature = "opendal-memory"),
not(feature = "opendal-fs"),
not(feature = "opendal-s3"),
not(feature = "opendal-gcs"),
not(feature = "opendal-oss"),
not(feature = "opendal-azdls"),
not(feature = "opendal-hf"),
))]
_ => Err(Error::new(
ErrorKind::FeatureUnsupported,
"No storage service has been enabled",
)),
}
}
}
/// Default memory operator for serde deserialization.
#[cfg(feature = "opendal-memory")]
fn default_memory_operator() -> Operator {
memory_config_build().expect("Failed to create default memory operator")
}
/// OpenDAL-based storage implementation.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum OpenDalStorage {
/// Memory storage variant.
#[cfg(feature = "opendal-memory")]
Memory(#[serde(skip, default = "self::default_memory_operator")] Operator),
/// Local filesystem storage variant.
#[cfg(feature = "opendal-fs")]
LocalFs,
/// S3 storage variant.
///
/// Accepts any S3-family URL (`s3://`, `s3a://`, `s3n://`); the scheme is
/// derived from the path at call time.
#[cfg(feature = "opendal-s3")]
S3 {
/// S3 configuration.
config: Arc<S3Config>,
/// Custom AWS credential loader.
#[serde(skip)]
customized_credential_load: Option<CustomAwsCredentialLoader>,
},
/// GCS storage variant.
#[cfg(feature = "opendal-gcs")]
Gcs {
/// GCS configuration.
config: Arc<GcsConfig>,
},
/// OSS storage variant.
#[cfg(feature = "opendal-oss")]
Oss {
/// OSS configuration.
config: Arc<OssConfig>,
},
/// Azure Data Lake Storage variant.
///
/// Accepts paths of the form
/// `abfs[s]://<filesystem>@<account>.dfs.<endpoint-suffix>/<path>` or
/// `wasb[s]://<container>@<account>.blob.<endpoint-suffix>/<path>`.
/// The scheme is derived from the path at call time.
#[cfg(feature = "opendal-azdls")]
Azdls {
/// Azure DLS configuration.
config: Arc<AzdlsConfig>,
},
/// HuggingFace Hub storage variant.
///
/// Accepts paths of the form
/// `hf://<repo_type>/<owner>/<repo>[@<revision>]/<path_in_repo>`,
/// where `<repo_type>` must be one of `models`, `datasets`, `spaces`, or `buckets`.
#[cfg(feature = "opendal-hf")]
Hf {
/// HuggingFace Hub configuration (token + endpoint).
config: Arc<HfConfig>,
},
}
impl OpenDalStorage {
/// Creates operator from path.
///
/// # Arguments
///
/// * path: It should be *absolute* path starting with scheme string used to construct [`FileIO`](iceberg::io::FileIO).
///
/// # Returns
///
/// The return value consists of two parts:
///
/// * An [`opendal::Operator`] instance used to operate on file.
/// * Relative path to the root uri of [`opendal::Operator`].
#[allow(unreachable_code, unused_variables)]
pub(crate) fn create_operator<'a>(
&self,
path: &'a impl AsRef<str>,
) -> Result<(Operator, &'a str)> {
let path = path.as_ref();
let (operator, relative_path): (Operator, &str) = match self {
#[cfg(feature = "opendal-memory")]
OpenDalStorage::Memory(op) => {
if let Some(stripped) = path.strip_prefix("memory:/") {
(op.clone(), stripped)
} else {
(op.clone(), &path[1..])
}
}
#[cfg(feature = "opendal-fs")]
OpenDalStorage::LocalFs => {
let op = fs_config_build()?;
if let Some(stripped) = path.strip_prefix("file:/") {
(op, stripped)
} else {
(op, &path[1..])
}
}
#[cfg(feature = "opendal-s3")]
OpenDalStorage::S3 {
config,
customized_credential_load,
} => {
let op = s3_config_build(config, customized_credential_load, path)?;
let op_info = op.info();
// Use the URL scheme in the path for prefix matching. This enables
// use of S3-compatible storage backends using custom schemes (e.g., `minio://`, `r2://`).
let url = url::Url::parse(path).map_err(|e| {
Error::new(
ErrorKind::DataInvalid,
format!("Invalid s3 url: {path}: {e}"),
)
})?;
let prefix = format!("{}://{}/", url.scheme(), op_info.name());
if path.starts_with(&prefix) {
(op, &path[prefix.len()..])
} else {
return Err(Error::new(
ErrorKind::DataInvalid,
format!("Invalid s3 url: {path}, should start with {prefix}"),
));
}
}
#[cfg(feature = "opendal-gcs")]
OpenDalStorage::Gcs { config } => {
let operator = gcs_config_build(config, path)?;
let prefix = format!("gs://{}/", operator.info().name());
if path.starts_with(&prefix) {
(operator, &path[prefix.len()..])
} else {
return Err(Error::new(
ErrorKind::DataInvalid,
format!("Invalid gcs url: {path}, should start with {prefix}"),
));
}
}
#[cfg(feature = "opendal-oss")]
OpenDalStorage::Oss { config } => {
let op = oss_config_build(config, path)?;
let prefix = format!("oss://{}/", op.info().name());
if path.starts_with(&prefix) {
(op, &path[prefix.len()..])
} else {
return Err(Error::new(
ErrorKind::DataInvalid,
format!("Invalid oss url: {path}, should start with {prefix}"),
));
}
}
#[cfg(feature = "opendal-azdls")]
OpenDalStorage::Azdls { config } => azdls_create_operator(path, config)?,
#[cfg(feature = "opendal-hf")]
OpenDalStorage::Hf { config } => hf_config_build(config, path)?,
#[cfg(all(
not(feature = "opendal-s3"),
not(feature = "opendal-fs"),
not(feature = "opendal-gcs"),
not(feature = "opendal-oss"),
not(feature = "opendal-azdls"),
not(feature = "opendal-hf"),
))]
_ => {
return Err(Error::new(
ErrorKind::FeatureUnsupported,
"No storage service has been enabled",
));
}
};
// Apply observability/resilience layers. TimeoutLayer must be
// inside RetryLayer so each retry attempt is independently
// bounded — without a per-attempt timeout, a future parked on a
// silently dropped TCP connection never produces an `Err` and
// RetryLayer cannot retry, leaving the caller hung indefinitely.
// See: https://opendal.apache.org/docs/rust/opendal/layers/struct.TimeoutLayer.html
//
// Transient errors are common for object stores; we retry temporary
// failures with exponential backoff. The retry behavior also
// benefits non-object-store backends.
let operator = operator.layer(TimeoutLayer::new()).layer(RetryLayer::new());
Ok((operator, relative_path))
}
/// Returns a cache key used by `delete_stream` to group paths by storage operator.
///
/// For most backends the URL host (bucket name) is sufficient. For HF the host
/// encodes the repo type, not the repo identity, so a more specific key is used.
fn batch_key_for_path(&self, path: &str) -> String {
match self {
#[cfg(feature = "opendal-hf")]
OpenDalStorage::Hf { .. } => hf_batch_key(path),
_ => url::Url::parse(path)
.ok()
.and_then(|u| u.host_str().map(|s| s.to_string()))
.unwrap_or_default(),
}
}
/// Extracts the relative path from an absolute path without building an operator.
///
/// This is a lightweight alternative to [`create_operator`](Self::create_operator) for cases
/// where only the relative path is needed (e.g. bulk deletes where the operator is already
/// available).
#[allow(unreachable_code, unused_variables)]
pub(crate) fn relativize_path<'a>(&self, path: &'a str) -> Result<&'a str> {
match self {
#[cfg(feature = "opendal-memory")]
OpenDalStorage::Memory(_) => Ok(path.strip_prefix("memory:/").unwrap_or(&path[1..])),
#[cfg(feature = "opendal-fs")]
OpenDalStorage::LocalFs => Ok(path.strip_prefix("file:/").unwrap_or(&path[1..])),
#[cfg(feature = "opendal-s3")]
OpenDalStorage::S3 { .. } => {
let url = url::Url::parse(path)?;
let bucket = url.host_str().ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
format!("Invalid s3 url: {path}, missing bucket"),
)
})?;
let prefix = format!("{}://{}/", url.scheme(), bucket);
if path.starts_with(&prefix) {
Ok(&path[prefix.len()..])
} else {
Err(Error::new(
ErrorKind::DataInvalid,
format!("Invalid s3 url: {path}, should start with {prefix}"),
))
}
}
#[cfg(feature = "opendal-gcs")]
OpenDalStorage::Gcs { .. } => {
let url = url::Url::parse(path)?;
let bucket = url.host_str().ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
format!("Invalid gcs url: {path}, missing bucket"),
)
})?;
let prefix = format!("gs://{}/", bucket);
if path.starts_with(&prefix) {
Ok(&path[prefix.len()..])
} else {
Err(Error::new(
ErrorKind::DataInvalid,
format!("Invalid gcs url: {path}, should start with {prefix}"),
))
}
}
#[cfg(feature = "opendal-oss")]
OpenDalStorage::Oss { .. } => {
let url = url::Url::parse(path)?;
let bucket = url.host_str().ok_or_else(|| {
Error::new(
ErrorKind::DataInvalid,
format!("Invalid oss url: {path}, missing bucket"),
)
})?;
let prefix = format!("oss://{}/", bucket);
if path.starts_with(&prefix) {
Ok(&path[prefix.len()..])
} else {
Err(Error::new(
ErrorKind::DataInvalid,
format!("Invalid oss url: {path}, should start with {prefix}"),
))
}
}
#[cfg(feature = "opendal-azdls")]
OpenDalStorage::Azdls { config } => {
let azure_path = path.parse::<AzureStoragePath>()?;
match_path_with_config(&azure_path, config)?;
let relative_path_len = azure_path.path.len();
Ok(&path[path.len() - relative_path_len..])
}
#[cfg(feature = "opendal-hf")]
OpenDalStorage::Hf { .. } => {
let parsed = HfUri::parse(path).ok_or_else(|| {
Error::new(ErrorKind::DataInvalid, format!("Invalid hf url: {path}"))
})?;
Ok(&path[path.len() - parsed.path.len()..])
}
#[cfg(all(
not(feature = "opendal-s3"),
not(feature = "opendal-fs"),
not(feature = "opendal-gcs"),
not(feature = "opendal-oss"),
not(feature = "opendal-azdls"),
not(feature = "opendal-hf"),
))]
_ => Err(Error::new(
ErrorKind::FeatureUnsupported,
"No storage service has been enabled",
)),
}
}
}
#[typetag::serde(name = "OpenDalStorage")]
#[async_trait]
impl Storage for OpenDalStorage {
async fn exists(&self, path: &str) -> Result<bool> {
let (op, relative_path) = self.create_operator(&path)?;
Ok(op.exists(relative_path).await.map_err(from_opendal_error)?)
}
async fn metadata(&self, path: &str) -> Result<FileMetadata> {
let (op, relative_path) = self.create_operator(&path)?;
let meta = op.stat(relative_path).await.map_err(from_opendal_error)?;
Ok(FileMetadata {
size: meta.content_length(),
})
}
async fn read(&self, path: &str) -> Result<Bytes> {
let (op, relative_path) = self.create_operator(&path)?;
Ok(op
.read(relative_path)
.await
.map_err(from_opendal_error)?
.to_bytes())
}
async fn reader(&self, path: &str) -> Result<Box<dyn FileRead>> {
let (op, relative_path) = self.create_operator(&path)?;
Ok(Box::new(OpenDalReader(
op.reader(relative_path).await.map_err(from_opendal_error)?,
)))
}
async fn write(&self, path: &str, bs: Bytes) -> Result<()> {
let (op, relative_path) = self.create_operator(&path)?;
op.write(relative_path, bs)
.await
.map_err(from_opendal_error)?;
Ok(())
}
async fn writer(&self, path: &str) -> Result<Box<dyn FileWrite>> {
let (op, relative_path) = self.create_operator(&path)?;
Ok(Box::new(OpenDalWriter(
op.writer(relative_path).await.map_err(from_opendal_error)?,
)))
}
async fn delete(&self, path: &str) -> Result<()> {
let (op, relative_path) = self.create_operator(&path)?;
Ok(op.delete(relative_path).await.map_err(from_opendal_error)?)
}
async fn delete_prefix(&self, path: &str) -> Result<()> {
let (op, relative_path) = self.create_operator(&path)?;
let path = if relative_path.ends_with('/') {
relative_path.to_string()
} else {
format!("{relative_path}/")
};
Ok(op
.delete_with(&path)
.recursive(true)
.await
.map_err(from_opendal_error)?)
}
async fn delete_stream(&self, mut paths: BoxStream<'static, String>) -> Result<()> {
let mut deleters: HashMap<String, opendal::Deleter> = HashMap::new();
while let Some(path) = paths.next().await {
let bucket = self.batch_key_for_path(&path);
let (relative_path, deleter) = match deleters.entry(bucket) {
Entry::Occupied(entry) => {
(self.relativize_path(&path)?.to_string(), entry.into_mut())
}
Entry::Vacant(entry) => {
let (op, rel) = self.create_operator(&path)?;
let rel = rel.to_string();
let deleter = op.deleter().await.map_err(from_opendal_error)?;
(rel, entry.insert(deleter))
}
};
deleter
.delete(relative_path)
.await
.map_err(from_opendal_error)?;
}
for (_, mut deleter) in deleters {
deleter.close().await.map_err(from_opendal_error)?;
}
Ok(())
}
#[allow(unreachable_code, unused_variables)]
fn new_input(&self, path: &str) -> Result<InputFile> {
Ok(InputFile::new(Arc::new(self.clone()), path.to_string()))
}
#[allow(unreachable_code, unused_variables)]
fn new_output(&self, path: &str) -> Result<OutputFile> {
Ok(OutputFile::new(Arc::new(self.clone()), path.to_string()))
}
}
// Newtype wrappers for opendal types to satisfy orphan rules.
// We can't implement iceberg's FileRead/FileWrite traits directly on opendal's
// Reader/Writer since neither trait nor type is defined in this crate.
/// Wrapper around `opendal::Reader` that implements `FileRead`.
pub(crate) struct OpenDalReader(pub(crate) opendal::Reader);
#[async_trait]
impl FileRead for OpenDalReader {
async fn read(&self, range: std::ops::Range<u64>) -> Result<Bytes> {
Ok(opendal::Reader::read(&self.0, range)
.await
.map_err(from_opendal_error)?
.to_bytes())
}
}
/// Wrapper around `opendal::Writer` that implements `FileWrite`.
pub(crate) struct OpenDalWriter(pub(crate) opendal::Writer);
#[async_trait]
impl FileWrite for OpenDalWriter {
async fn write(&mut self, bs: Bytes) -> Result<()> {
Ok(opendal::Writer::write(&mut self.0, bs)
.await
.map_err(from_opendal_error)?)
}
async fn close(&mut self) -> Result<()> {
let _ = opendal::Writer::close(&mut self.0)
.await
.map_err(from_opendal_error)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(feature = "opendal-s3")]
#[derive(Debug)]
struct EmptyCredentialLoader;
#[cfg(feature = "opendal-s3")]
impl ProvideCredential for EmptyCredentialLoader {
type Credential = AwsCredential;
async fn provide_credential(
&self,
_ctx: &reqsign_core::Context,
) -> reqsign_core::Result<Option<AwsCredential>> {
Ok(None)
}
}
#[cfg(feature = "opendal-s3")]
#[test]
fn test_s3_factory_custom_credential_loader_serialization_fails() {
let file_io = iceberg::io::FileIOBuilder::new(Arc::new(OpenDalStorageFactory::S3 {
customized_credential_load: Some(CustomAwsCredentialLoader::new(EmptyCredentialLoader)),
}))
.build();
let err = file_io.serialize_all().unwrap_err();
assert!(
err.to_string()
.contains("custom AWS credential loaders cannot be serialized")
);
}
#[cfg(feature = "opendal-memory")]
#[test]
fn test_default_memory_operator() {
let op = default_memory_operator();
assert_eq!(op.info().scheme().to_string(), "memory");
}
#[cfg(feature = "opendal-memory")]
#[test]
fn test_relativize_path_memory() {
let storage = OpenDalStorage::Memory(default_memory_operator());
assert_eq!(
storage.relativize_path("memory:/path/to/file").unwrap(),
"path/to/file"
);
// Without the scheme prefix, falls back to stripping the leading slash
assert_eq!(
storage.relativize_path("/path/to/file").unwrap(),
"path/to/file"
);
}
#[cfg(feature = "opendal-fs")]
#[test]
fn test_relativize_path_fs() {
let storage = OpenDalStorage::LocalFs;
assert_eq!(
storage
.relativize_path("file:/tmp/data/file.parquet")
.unwrap(),
"tmp/data/file.parquet"
);
assert_eq!(
storage.relativize_path("/tmp/data/file.parquet").unwrap(),
"tmp/data/file.parquet"
);
}
#[cfg(feature = "opendal-s3")]
#[test]
fn test_relativize_path_s3() {
let storage = OpenDalStorage::S3 {
config: Arc::new(S3Config::default()),
customized_credential_load: None,
};
// All S3-family schemes are accepted by the same storage instance.
// Custom schemes for S3-compatible stores (e.g., `minio://`) are also
// accepted because the path's scheme is used as-is for prefix matching.
for scheme in ["s3", "s3a", "s3n", "minio"] {
assert_eq!(
storage
.relativize_path(&format!("{scheme}://my-bucket/path/to/file.parquet"))
.unwrap(),
"path/to/file.parquet"
);
}
}
#[cfg(feature = "opendal-gcs")]
#[test]
fn test_relativize_path_gcs() {
let storage = OpenDalStorage::Gcs {
config: Arc::new(GcsConfig::default()),
};
assert_eq!(
storage
.relativize_path("gs://my-bucket/path/to/file.parquet")
.unwrap(),
"path/to/file.parquet"
);
}
#[cfg(feature = "opendal-gcs")]
#[test]
fn test_relativize_path_gcs_invalid_scheme() {
let storage = OpenDalStorage::Gcs {
config: Arc::new(GcsConfig::default()),
};
assert!(
storage
.relativize_path("s3://my-bucket/path/to/file.parquet")
.is_err()
);
}
#[cfg(feature = "opendal-oss")]
#[test]
fn test_relativize_path_oss() {
let storage = OpenDalStorage::Oss {
config: Arc::new(OssConfig::default()),
};
assert_eq!(
storage
.relativize_path("oss://my-bucket/path/to/file.parquet")
.unwrap(),
"path/to/file.parquet"
);
}
#[cfg(feature = "opendal-oss")]
#[test]
fn test_relativize_path_oss_invalid_scheme() {
let storage = OpenDalStorage::Oss {
config: Arc::new(OssConfig::default()),
};
assert!(
storage
.relativize_path("s3://my-bucket/path/to/file.parquet")
.is_err()
);
}
#[cfg(feature = "opendal-azdls")]
#[test]
fn test_relativize_path_azdls() {
let storage = OpenDalStorage::Azdls {
config: Arc::new(AzdlsConfig {
account_name: Some("myaccount".to_string()),
endpoint: Some("https://myaccount.dfs.core.windows.net".to_string()),
..Default::default()
}),
};
assert_eq!(
storage
.relativize_path("abfss://[email protected]/path/to/file.parquet")
.unwrap(),
"/path/to/file.parquet"
);
}
}