1use std::collections::BTreeSet;
21use std::path::Component;
22
23use async_trait::async_trait;
24use futures::TryStreamExt;
25use object_store::services::{Azblob, Fs, Gcs, Oss, S3};
26use object_store::util::{with_instrument_layers, with_retry_layers};
27use object_store::{
28 AzblobConnection, ErrorKind, GcsConnection, ObjectStore, OssConnection, S3Connection,
29};
30use snafu::ResultExt;
31use url::Url;
32
33use crate::common::ObjectStoreConfig;
34use crate::data::export_v2::error::{
35 BuildObjectStoreSnafu, InvalidUriSnafu, ManifestParseSnafu, ManifestSerializeSnafu, Result,
36 SnapshotNotFoundSnafu, StorageOperationSnafu, TextDecodeSnafu, UnsupportedSchemeSnafu,
37 UrlParseSnafu,
38};
39use crate::data::export_v2::manifest::{MANIFEST_FILE, Manifest};
40#[cfg(test)]
41use crate::data::export_v2::schema::SchemaDefinition;
42use crate::data::export_v2::schema::{SCHEMA_DIR, SCHEMAS_FILE, SchemaSnapshot};
43
44struct RemoteLocation {
45 bucket_or_container: String,
46 root: String,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum StorageScheme {
52 S3,
54 Oss,
56 Gcs,
58 Azblob,
60 File,
62}
63
64impl StorageScheme {
65 pub fn from_uri(uri: &str) -> Result<Self> {
67 let url = Url::parse(uri).context(UrlParseSnafu)?;
68
69 match url.scheme() {
70 "s3" => Ok(Self::S3),
71 "oss" => Ok(Self::Oss),
72 "gs" | "gcs" => Ok(Self::Gcs),
73 "azblob" => Ok(Self::Azblob),
74 "file" => Ok(Self::File),
75 scheme => UnsupportedSchemeSnafu { scheme }.fail(),
76 }
77 }
78}
79
80fn extract_remote_location_with_root_policy(
82 uri: &str,
83 allow_empty_root: bool,
84) -> Result<RemoteLocation> {
85 let url = Url::parse(uri).context(UrlParseSnafu)?;
86 let bucket_or_container = url.host_str().unwrap_or("").to_string();
87 if bucket_or_container.is_empty() {
88 return InvalidUriSnafu {
89 uri,
90 reason: "URI must include bucket/container in host",
91 }
92 .fail();
93 }
94
95 let root = url.path().trim_start_matches('/').to_string();
96 if root.is_empty() && !allow_empty_root {
97 return InvalidUriSnafu {
98 uri,
99 reason: "snapshot URI must include a non-empty path after the bucket/container",
100 }
101 .fail();
102 }
103
104 Ok(RemoteLocation {
105 bucket_or_container,
106 root,
107 })
108}
109
110pub fn validate_uri(uri: &str) -> Result<StorageScheme> {
123 if !uri.contains("://") {
125 return InvalidUriSnafu {
126 uri,
127 reason: "URI must have a scheme (e.g., s3://, file://). Bare paths are not supported.",
128 }
129 .fail();
130 }
131
132 StorageScheme::from_uri(uri)
133}
134
135pub fn validate_snapshot_uri(uri: &str) -> Result<StorageScheme> {
143 let scheme = validate_uri(uri)?;
144 reject_query_or_fragment(uri)?;
145 match scheme {
146 StorageScheme::File => validate_file_snapshot_uri(uri)?,
147 StorageScheme::S3 | StorageScheme::Oss | StorageScheme::Gcs | StorageScheme::Azblob => {
148 extract_remote_location_with_root_policy(uri, false)?;
149 }
150 }
151 Ok(scheme)
152}
153
154fn reject_query_or_fragment(uri: &str) -> Result<()> {
155 let url = Url::parse(uri).context(UrlParseSnafu)?;
156 if url.query().is_some() || url.fragment().is_some() {
157 return InvalidUriSnafu {
158 uri,
159 reason: "snapshot URI must not include query or fragment",
160 }
161 .fail();
162 }
163
164 Ok(())
165}
166
167fn validate_file_snapshot_uri(uri: &str) -> Result<()> {
168 if has_explicit_dot_segment(uri) {
169 return InvalidUriSnafu {
170 uri,
171 reason: "file snapshot URI must not contain '.' or '..' path segments",
172 }
173 .fail();
174 }
175
176 let path = extract_file_path_from_uri(uri)?;
177 let mut normal_component_count = 0;
178
179 for component in std::path::Path::new(&path).components() {
184 match component {
185 Component::Normal(_) => normal_component_count += 1,
186 Component::CurDir | Component::ParentDir => {
187 return InvalidUriSnafu {
188 uri,
189 reason: "file snapshot URI must not contain '.' or '..' path segments",
190 }
191 .fail();
192 }
193 Component::Prefix(_) | Component::RootDir => {}
194 }
195 }
196
197 if normal_component_count < 2 {
198 return InvalidUriSnafu {
199 uri,
200 reason: "file snapshot URI must point to a directory at least two levels deep",
201 }
202 .fail();
203 }
204
205 Ok(())
206}
207
208fn has_explicit_dot_segment(uri: &str) -> bool {
209 let without_fragment = uri.split_once('#').map_or(uri, |(path, _)| path);
213 let path = without_fragment
214 .split_once('?')
215 .map_or(without_fragment, |(path, _)| path);
216
217 path.split('/')
218 .any(|segment| segment == "." || segment == "..")
219}
220
221fn schema_index_path() -> String {
222 format!("{}/{}", SCHEMA_DIR, SCHEMAS_FILE)
223}
224
225fn extract_file_path_from_uri(uri: &str) -> Result<String> {
227 let url = Url::parse(uri).context(UrlParseSnafu)?;
228
229 match url.host_str() {
230 Some(host) if !host.is_empty() && host != "localhost" => InvalidUriSnafu {
231 uri,
232 reason: "file:// URI must use an absolute path like file:///tmp/backup",
233 }
234 .fail(),
235 _ => url
236 .to_file_path()
237 .map_err(|_| {
238 InvalidUriSnafu {
239 uri,
240 reason: "file:// URI must use an absolute path like file:///tmp/backup",
241 }
242 .build()
243 })
244 .map(|path| path.to_string_lossy().into_owned()),
245 }
246}
247
248async fn ensure_snapshot_exists(storage: &OpenDalStorage) -> Result<()> {
249 if storage.exists().await? {
250 Ok(())
251 } else {
252 SnapshotNotFoundSnafu {
253 uri: storage.target_uri.as_str(),
254 }
255 .fail()
256 }
257}
258
259#[async_trait]
263pub trait SnapshotStorage: Send + Sync {
264 async fn exists(&self) -> Result<bool>;
266
267 async fn read_manifest(&self) -> Result<Manifest>;
269
270 async fn write_manifest(&self, manifest: &Manifest) -> Result<()>;
272
273 async fn write_schema(&self, schema: &SchemaSnapshot) -> Result<()>;
275
276 async fn write_text(&self, path: &str, content: &str) -> Result<()>;
278
279 async fn read_text(&self, path: &str) -> Result<String>;
281
282 async fn create_dir_all(&self, path: &str) -> Result<()>;
284
285 async fn list_files_recursive(&self, prefix: &str) -> Result<Vec<String>>;
287
288 async fn delete_snapshot(&self) -> Result<()>;
290}
291
292pub struct OpenDalStorage {
294 object_store: ObjectStore,
295 target_uri: String,
296}
297
298impl OpenDalStorage {
299 fn new_operator_rooted(object_store: ObjectStore, target_uri: &str) -> Self {
300 Self {
301 object_store,
302 target_uri: target_uri.to_string(),
303 }
304 }
305
306 fn finish_local_store(object_store: ObjectStore) -> ObjectStore {
307 with_instrument_layers(object_store, false)
308 }
309
310 fn finish_remote_store(object_store: ObjectStore) -> ObjectStore {
311 with_instrument_layers(with_retry_layers(object_store), false)
312 }
313
314 fn ensure_backend_enabled(uri: &str, enabled: bool, reason: &'static str) -> Result<()> {
315 if enabled {
316 Ok(())
317 } else {
318 InvalidUriSnafu { uri, reason }.fail()
319 }
320 }
321
322 fn validate_remote_config<E: std::fmt::Display>(
323 uri: &str,
324 backend: &str,
325 result: std::result::Result<(), E>,
326 ) -> Result<()> {
327 result.map_err(|error| {
328 InvalidUriSnafu {
329 uri,
330 reason: format!("invalid {} config: {}", backend, error),
331 }
332 .build()
333 })
334 }
335
336 pub fn from_file_uri(uri: &str) -> Result<Self> {
338 let path = extract_file_path_from_uri(uri)?;
339
340 let builder = Fs::default().root(&path);
341 let object_store = ObjectStore::new(builder)
342 .context(BuildObjectStoreSnafu)?
343 .finish();
344 Ok(Self::new_operator_rooted(
345 Self::finish_local_store(object_store),
346 uri,
347 ))
348 }
349
350 fn from_file_uri_with_config(uri: &str, storage: &ObjectStoreConfig) -> Result<Self> {
351 if storage.enable_s3 || storage.enable_oss || storage.enable_gcs || storage.enable_azblob {
352 return InvalidUriSnafu {
353 uri,
354 reason: "file:// cannot be used with remote storage flags",
355 }
356 .fail();
357 }
358
359 Self::from_file_uri(uri)
360 }
361
362 fn from_s3_uri(uri: &str, storage: &ObjectStoreConfig) -> Result<Self> {
363 Self::from_s3_uri_with_root_policy(uri, storage, false)
364 }
365
366 fn from_s3_uri_with_root_policy(
367 uri: &str,
368 storage: &ObjectStoreConfig,
369 allow_empty_root: bool,
370 ) -> Result<Self> {
371 Self::ensure_backend_enabled(
372 uri,
373 storage.enable_s3,
374 "s3:// requires --s3 and related options",
375 )?;
376
377 let location = extract_remote_location_with_root_policy(uri, allow_empty_root)?;
378 let mut config = storage.s3.clone();
379 config.s3_bucket = location.bucket_or_container;
380 config.s3_root = location.root;
381 Self::validate_remote_config(uri, "s3", config.validate())?;
382
383 let conn: S3Connection = config.into();
384 let object_store = ObjectStore::new(S3::from(&conn))
385 .context(BuildObjectStoreSnafu)?
386 .finish();
387 Ok(Self::new_operator_rooted(
388 Self::finish_remote_store(object_store),
389 uri,
390 ))
391 }
392
393 fn from_oss_uri(uri: &str, storage: &ObjectStoreConfig) -> Result<Self> {
394 Self::from_oss_uri_with_root_policy(uri, storage, false)
395 }
396
397 fn from_oss_uri_with_root_policy(
398 uri: &str,
399 storage: &ObjectStoreConfig,
400 allow_empty_root: bool,
401 ) -> Result<Self> {
402 Self::ensure_backend_enabled(
403 uri,
404 storage.enable_oss,
405 "oss:// requires --oss and related options",
406 )?;
407
408 let location = extract_remote_location_with_root_policy(uri, allow_empty_root)?;
409 let mut config = storage.oss.clone();
410 config.oss_bucket = location.bucket_or_container;
411 config.oss_root = location.root;
412 Self::validate_remote_config(uri, "oss", config.validate())?;
413
414 let conn: OssConnection = config.into();
415 let object_store = ObjectStore::new(Oss::from(&conn))
416 .context(BuildObjectStoreSnafu)?
417 .finish();
418 Ok(Self::new_operator_rooted(
419 Self::finish_remote_store(object_store),
420 uri,
421 ))
422 }
423
424 fn from_gcs_uri(uri: &str, storage: &ObjectStoreConfig) -> Result<Self> {
425 Self::from_gcs_uri_with_root_policy(uri, storage, false)
426 }
427
428 fn from_gcs_uri_with_root_policy(
429 uri: &str,
430 storage: &ObjectStoreConfig,
431 allow_empty_root: bool,
432 ) -> Result<Self> {
433 Self::ensure_backend_enabled(
434 uri,
435 storage.enable_gcs,
436 "gs:// or gcs:// requires --gcs and related options",
437 )?;
438
439 let location = extract_remote_location_with_root_policy(uri, allow_empty_root)?;
440 let mut config = storage.gcs.clone();
441 config.gcs_bucket = location.bucket_or_container;
442 config.gcs_root = location.root;
443 if allow_empty_root && config.gcs_root.is_empty() {
445 Self::validate_gcs_parent_config(uri, &config)?;
446 } else {
447 Self::validate_remote_config(uri, "gcs", config.validate())?;
448 }
449
450 let conn: GcsConnection = config.into();
451 let object_store = ObjectStore::new(Gcs::from(&conn))
452 .context(BuildObjectStoreSnafu)?
453 .finish();
454 Ok(Self::new_operator_rooted(
455 Self::finish_remote_store(object_store),
456 uri,
457 ))
458 }
459
460 fn validate_gcs_parent_config(
461 uri: &str,
462 config: &crate::common::PrefixedGcsConnection,
463 ) -> Result<()> {
464 if config.gcs_bucket.is_empty() {
465 return InvalidUriSnafu {
466 uri,
467 reason: "invalid gcs config: GCS bucket must be set when --gcs is enabled.",
468 }
469 .fail();
470 }
471 if config.gcs_scope.is_empty() {
472 return InvalidUriSnafu {
473 uri,
474 reason: "invalid gcs config: GCS scope must be set when --gcs is enabled.",
475 }
476 .fail();
477 }
478 Ok(())
479 }
480
481 fn from_azblob_uri(uri: &str, storage: &ObjectStoreConfig) -> Result<Self> {
482 Self::from_azblob_uri_with_root_policy(uri, storage, false)
483 }
484
485 fn from_azblob_uri_with_root_policy(
486 uri: &str,
487 storage: &ObjectStoreConfig,
488 allow_empty_root: bool,
489 ) -> Result<Self> {
490 Self::ensure_backend_enabled(
491 uri,
492 storage.enable_azblob,
493 "azblob:// requires --azblob and related options",
494 )?;
495
496 let location = extract_remote_location_with_root_policy(uri, allow_empty_root)?;
497 let mut config = storage.azblob.clone();
498 config.azblob_container = location.bucket_or_container;
499 config.azblob_root = location.root;
500 Self::validate_remote_config(uri, "azblob", config.validate())?;
501
502 let conn: AzblobConnection = config.into();
503 let object_store = ObjectStore::new(Azblob::from(&conn))
504 .context(BuildObjectStoreSnafu)?
505 .finish();
506 Ok(Self::new_operator_rooted(
507 Self::finish_remote_store(object_store),
508 uri,
509 ))
510 }
511
512 pub fn from_uri(uri: &str, storage: &ObjectStoreConfig) -> Result<Self> {
514 match StorageScheme::from_uri(uri)? {
515 StorageScheme::File => Self::from_file_uri_with_config(uri, storage),
516 StorageScheme::S3 => Self::from_s3_uri(uri, storage),
517 StorageScheme::Oss => Self::from_oss_uri(uri, storage),
518 StorageScheme::Gcs => Self::from_gcs_uri(uri, storage),
519 StorageScheme::Azblob => Self::from_azblob_uri(uri, storage),
520 }
521 }
522
523 pub fn from_parent_uri(uri: &str, storage: &ObjectStoreConfig) -> Result<Self> {
529 match StorageScheme::from_uri(uri)? {
530 StorageScheme::File => Self::from_file_uri_with_config(uri, storage),
531 StorageScheme::S3 => Self::from_s3_uri_with_root_policy(uri, storage, true),
532 StorageScheme::Oss => Self::from_oss_uri_with_root_policy(uri, storage, true),
533 StorageScheme::Gcs => Self::from_gcs_uri_with_root_policy(uri, storage, true),
534 StorageScheme::Azblob => Self::from_azblob_uri_with_root_policy(uri, storage, true),
535 }
536 }
537
538 async fn read_file(&self, path: &str) -> Result<Vec<u8>> {
540 let data = self
541 .object_store
542 .read(path)
543 .await
544 .context(StorageOperationSnafu {
545 operation: format!("read {}", path),
546 })?;
547 Ok(data.to_vec())
548 }
549
550 pub(crate) async fn read_file_if_exists(&self, path: &str) -> Result<Option<Vec<u8>>> {
552 match self.object_store.read(path).await {
553 Ok(data) => Ok(Some(data.to_vec())),
554 Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
555 Err(error) => Err(error).context(StorageOperationSnafu {
556 operation: format!("read {}", path),
557 }),
558 }
559 }
560
561 async fn write_file(&self, path: &str, data: Vec<u8>) -> Result<()> {
563 self.object_store
564 .write(path, data)
565 .await
566 .map(|_| ())
567 .context(StorageOperationSnafu {
568 operation: format!("write {}", path),
569 })
570 }
571
572 pub(crate) async fn file_exists(&self, path: &str) -> Result<bool> {
574 match self.object_store.stat(path).await {
575 Ok(metadata) => Ok(!metadata.is_dir()),
576 Err(e) if e.kind() == object_store::ErrorKind::NotFound => Ok(false),
577 Err(e) => Err(e).context(StorageOperationSnafu {
578 operation: format!("check exists {}", path),
579 }),
580 }
581 }
582
583 pub(crate) async fn list_direct_child_dirs(&self) -> Result<Vec<String>> {
585 let mut lister = match self.object_store.lister_with("/").recursive(false).await {
586 Ok(lister) => lister,
587 Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
588 Err(error) => {
589 return Err(error).context(StorageOperationSnafu {
590 operation: "list /",
591 });
592 }
593 };
594
595 let mut dirs = BTreeSet::new();
596 while let Some(entry) = lister.try_next().await.context(StorageOperationSnafu {
597 operation: "list /",
598 })? {
599 let path = entry.path().trim_matches('/');
600 if path.is_empty() {
601 continue;
602 }
603
604 if entry.metadata().is_dir()
605 && let Some(name) = path.split('/').next()
606 {
607 dirs.insert(name.to_string());
608 }
609 }
610
611 Ok(dirs.into_iter().collect())
612 }
613
614 #[cfg(test)]
615 pub async fn read_schema(&self) -> Result<SchemaSnapshot> {
616 let schemas_path = schema_index_path();
617 let schemas: Vec<SchemaDefinition> = if self.file_exists(&schemas_path).await? {
618 let data = self.read_file(&schemas_path).await?;
619 serde_json::from_slice(&data).context(ManifestParseSnafu)?
620 } else {
621 vec![]
622 };
623
624 Ok(SchemaSnapshot { schemas })
625 }
626}
627
628#[async_trait]
629impl SnapshotStorage for OpenDalStorage {
630 async fn exists(&self) -> Result<bool> {
631 self.file_exists(MANIFEST_FILE).await
632 }
633
634 async fn read_manifest(&self) -> Result<Manifest> {
635 ensure_snapshot_exists(self).await?;
636
637 let data = self.read_file(MANIFEST_FILE).await?;
638 serde_json::from_slice(&data).context(ManifestParseSnafu)
639 }
640
641 async fn write_manifest(&self, manifest: &Manifest) -> Result<()> {
642 let data = serde_json::to_vec_pretty(manifest).context(ManifestSerializeSnafu)?;
643 self.write_file(MANIFEST_FILE, data).await
644 }
645
646 async fn write_schema(&self, schema: &SchemaSnapshot) -> Result<()> {
647 let schemas_path = schema_index_path();
648 let schemas_data =
649 serde_json::to_vec_pretty(&schema.schemas).context(ManifestSerializeSnafu)?;
650 self.write_file(&schemas_path, schemas_data).await
651 }
652
653 async fn write_text(&self, path: &str, content: &str) -> Result<()> {
654 self.write_file(path, content.as_bytes().to_vec()).await
655 }
656
657 async fn read_text(&self, path: &str) -> Result<String> {
658 let data = self.read_file(path).await?;
659 String::from_utf8(data).context(TextDecodeSnafu)
660 }
661
662 async fn create_dir_all(&self, path: &str) -> Result<()> {
663 self.object_store
664 .create_dir(path)
665 .await
666 .context(StorageOperationSnafu {
667 operation: format!("create dir {}", path),
668 })
669 }
670
671 async fn list_files_recursive(&self, prefix: &str) -> Result<Vec<String>> {
672 let mut lister = match self.object_store.lister_with(prefix).recursive(true).await {
673 Ok(lister) => lister,
674 Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
675 Err(error) => {
676 return Err(error).context(StorageOperationSnafu {
677 operation: format!("list {}", prefix),
678 });
679 }
680 };
681
682 let mut files = Vec::new();
683 while let Some(entry) = lister.try_next().await.context(StorageOperationSnafu {
684 operation: format!("list {}", prefix),
685 })? {
686 if entry.metadata().is_dir() {
687 continue;
688 }
689 files.push(entry.path().to_string());
690 }
691 Ok(files)
692 }
693
694 async fn delete_snapshot(&self) -> Result<()> {
695 self.object_store
696 .delete_with("/")
697 .recursive(true)
698 .await
699 .context(StorageOperationSnafu {
700 operation: "delete snapshot",
701 })
702 }
703}
704
705#[cfg(test)]
706mod tests {
707 use std::collections::HashMap;
708 use std::path::Path;
709
710 use object_store::ObjectStore;
711 use object_store::services::Fs;
712 use tempfile::tempdir;
713 use url::Url;
714
715 use super::*;
716 use crate::data::export_v2::manifest::{DataFormat, TimeRange};
717 use crate::data::export_v2::schema::SchemaDefinition;
718
719 fn make_storage_with_rooted_fs(dir: &std::path::Path) -> OpenDalStorage {
720 let object_store = ObjectStore::new(Fs::default().root(dir.to_str().unwrap()))
721 .unwrap()
722 .finish();
723 OpenDalStorage::new_operator_rooted(
724 OpenDalStorage::finish_local_store(object_store),
725 Url::from_directory_path(dir).unwrap().as_ref(),
726 )
727 }
728
729 #[test]
730 fn test_validate_uri_valid() {
731 assert_eq!(validate_uri("s3://bucket/path").unwrap(), StorageScheme::S3);
732 assert_eq!(
733 validate_uri("oss://bucket/path").unwrap(),
734 StorageScheme::Oss
735 );
736 assert_eq!(
737 validate_uri("gs://bucket/path").unwrap(),
738 StorageScheme::Gcs
739 );
740 assert_eq!(
741 validate_uri("gcs://bucket/path").unwrap(),
742 StorageScheme::Gcs
743 );
744 assert_eq!(
745 validate_uri("azblob://container/path").unwrap(),
746 StorageScheme::Azblob
747 );
748 assert_eq!(
749 validate_uri("file:///tmp/backup").unwrap(),
750 StorageScheme::File
751 );
752 }
753
754 #[test]
755 fn test_validate_uri_invalid() {
756 assert!(validate_uri("/tmp/backup").is_err());
758 assert!(validate_uri("./backup").is_err());
759 assert!(validate_uri("backup").is_err());
760
761 assert!(validate_uri("ftp://server/path").is_err());
763 }
764
765 #[test]
766 fn test_extract_remote_location_requires_non_empty_root() {
767 assert!(extract_remote_location_with_root_policy("s3://bucket", false).is_err());
768 assert!(extract_remote_location_with_root_policy("s3://bucket/", false).is_err());
769 assert!(extract_remote_location_with_root_policy("oss://bucket", false).is_err());
770 assert!(extract_remote_location_with_root_policy("gs://bucket", false).is_err());
771 assert!(extract_remote_location_with_root_policy("azblob://container", false).is_err());
772 }
773
774 #[test]
775 fn test_extract_remote_location_allows_empty_root_when_permitted() {
776 let location = extract_remote_location_with_root_policy("s3://bucket", true).unwrap();
777 assert_eq!(location.bucket_or_container, "bucket");
778 assert_eq!(location.root, "");
779
780 let location =
781 extract_remote_location_with_root_policy("azblob://container/", true).unwrap();
782 assert_eq!(location.bucket_or_container, "container");
783 assert_eq!(location.root, "");
784 }
785
786 #[test]
787 fn test_parent_storage_allows_s3_bucket_root() {
788 let mut storage = ObjectStoreConfig {
789 enable_s3: true,
790 ..Default::default()
791 };
792 storage.s3.s3_region = Some("us-east-1".to_string());
793
794 assert!(OpenDalStorage::from_uri("s3://bucket", &storage).is_err());
795 assert!(OpenDalStorage::from_parent_uri("s3://bucket", &storage).is_ok());
796 }
797
798 #[test]
799 fn test_validate_snapshot_uri_rejects_dangerous_roots() {
800 assert!(validate_snapshot_uri("s3://bucket").is_err());
801 assert!(validate_snapshot_uri("s3://bucket/").is_err());
802 assert!(validate_snapshot_uri("oss://bucket").is_err());
803 assert!(validate_snapshot_uri("gs://bucket").is_err());
804 assert!(validate_snapshot_uri("azblob://container").is_err());
805 assert!(validate_snapshot_uri("s3://bucket/snapshot?version=1").is_err());
806 assert!(validate_snapshot_uri("file:///tmp/backup#fragment").is_err());
807 assert!(validate_snapshot_uri("file:///").is_err());
808 assert!(validate_snapshot_uri("file:///tmp").is_err());
809 assert!(validate_snapshot_uri("file:///tmp/backup/.").is_err());
810 assert!(validate_snapshot_uri("file:///tmp/backup/..").is_err());
811 }
812
813 #[test]
814 fn test_validate_snapshot_uri_accepts_snapshot_paths() {
815 assert_eq!(
816 validate_snapshot_uri("s3://bucket/snapshots/prod").unwrap(),
817 StorageScheme::S3
818 );
819
820 let dir = tempdir().unwrap();
821 let snapshot = dir.path().join("snapshot");
822 std::fs::create_dir_all(&snapshot).unwrap();
823 let uri = Url::from_directory_path(snapshot).unwrap().to_string();
824 assert_eq!(validate_snapshot_uri(&uri).unwrap(), StorageScheme::File);
825 }
826
827 #[cfg(windows)]
828 #[test]
829 fn test_validate_snapshot_uri_windows_drive_prefix_depth() {
830 assert!(validate_snapshot_uri("file:///C:/").is_err());
831 assert!(validate_snapshot_uri("file:///C:/Users").is_err());
832 assert!(validate_snapshot_uri("file:///C:/Users/snapshot").is_ok());
833 }
834
835 #[cfg(not(windows))]
836 #[test]
837 fn test_extract_path_from_uri_unix_examples() {
838 assert_eq!(
839 extract_file_path_from_uri("file:///tmp/backup").unwrap(),
840 "/tmp/backup"
841 );
842 assert_eq!(
843 extract_file_path_from_uri("file://localhost/tmp/backup").unwrap(),
844 "/tmp/backup"
845 );
846 assert_eq!(
847 extract_file_path_from_uri("file:///tmp/my%20backup").unwrap(),
848 "/tmp/my backup"
849 );
850 assert_eq!(
851 extract_file_path_from_uri("file://localhost/tmp/my%20backup").unwrap(),
852 "/tmp/my backup"
853 );
854 }
855
856 #[test]
857 fn test_extract_file_path_from_uri_rejects_file_host() {
858 assert!(extract_file_path_from_uri("file://tmp/backup").is_err());
859 }
860
861 #[test]
862 fn test_extract_file_path_from_uri_round_trips_directory_url() {
863 let dir = tempdir().unwrap();
864 let uri = Url::from_directory_path(dir.path()).unwrap().to_string();
865 let path = extract_file_path_from_uri(&uri).unwrap();
866
867 assert_eq!(Path::new(&path), dir.path());
868 }
869
870 #[tokio::test]
871 async fn test_read_manifest_reports_requested_uri() {
872 let dir = tempdir().unwrap();
873 let uri = Url::from_directory_path(dir.path()).unwrap().to_string();
874 let storage = OpenDalStorage::from_file_uri(&uri).unwrap();
875
876 let error = storage.read_manifest().await.unwrap_err().to_string();
877
878 assert!(error.contains(uri.as_str()));
879 }
880
881 #[tokio::test]
882 async fn test_manifest_round_trip() {
883 let dir = tempdir().unwrap();
884 let storage = make_storage_with_rooted_fs(dir.path());
885
886 let manifest = Manifest::new_full(
887 "greptime".to_string(),
888 vec!["public".to_string()],
889 TimeRange::unbounded(),
890 DataFormat::Parquet,
891 );
892
893 storage.write_manifest(&manifest).await.unwrap();
894 let loaded = storage.read_manifest().await.unwrap();
895
896 assert_eq!(loaded.catalog, manifest.catalog);
897 assert_eq!(loaded.schemas, manifest.schemas);
898 assert_eq!(loaded.schema_only, manifest.schema_only);
899 assert_eq!(loaded.format, manifest.format);
900 assert_eq!(loaded.snapshot_id, manifest.snapshot_id);
901 }
902
903 #[tokio::test]
904 async fn test_schema_round_trip() {
905 let dir = tempdir().unwrap();
906 let storage = make_storage_with_rooted_fs(dir.path());
907
908 let mut snapshot = SchemaSnapshot::new();
909 snapshot.add_schema(SchemaDefinition {
910 catalog: "greptime".to_string(),
911 name: "test_db".to_string(),
912 options: HashMap::from([("ttl".to_string(), "7d".to_string())]),
913 });
914
915 storage.write_schema(&snapshot).await.unwrap();
916 let loaded = storage.read_schema().await.unwrap();
917
918 assert_eq!(loaded, snapshot);
919 }
920
921 #[tokio::test]
922 async fn test_text_round_trip() {
923 let dir = tempdir().unwrap();
924 let storage = make_storage_with_rooted_fs(dir.path());
925 let content = "CREATE TABLE metrics (ts TIMESTAMP TIME INDEX);";
926
927 storage
928 .write_text("schema/ddl/public.sql", content)
929 .await
930 .unwrap();
931 let loaded = storage.read_text("schema/ddl/public.sql").await.unwrap();
932
933 assert_eq!(loaded, content);
934 }
935
936 #[tokio::test]
937 async fn test_read_text_rejects_invalid_utf8() {
938 let dir = tempdir().unwrap();
939 let storage = make_storage_with_rooted_fs(dir.path());
940
941 storage
942 .write_file("schema/ddl/public.sql", vec![0xff, 0xfe, 0xfd])
943 .await
944 .unwrap();
945
946 let error = storage
947 .read_text("schema/ddl/public.sql")
948 .await
949 .unwrap_err();
950 assert!(error.to_string().contains("UTF-8"));
951 }
952
953 #[tokio::test]
954 async fn test_exists_follows_manifest_presence() {
955 let dir = tempdir().unwrap();
956 let storage = make_storage_with_rooted_fs(dir.path());
957
958 assert!(!storage.exists().await.unwrap());
959
960 storage
961 .write_manifest(&Manifest::new_schema_only(
962 "greptime".to_string(),
963 vec!["public".to_string()],
964 ))
965 .await
966 .unwrap();
967
968 assert!(storage.exists().await.unwrap());
969 }
970
971 #[tokio::test]
972 async fn test_delete_snapshot_only_removes_rooted_contents() {
973 let parent = tempdir().unwrap();
974 let snapshot_root = parent.path().join("snapshot");
975 let sibling = parent.path().join("sibling");
976 std::fs::create_dir_all(&snapshot_root).unwrap();
977 std::fs::create_dir_all(&sibling).unwrap();
978 std::fs::write(snapshot_root.join("manifest.json"), b"{}").unwrap();
979 std::fs::write(sibling.join("keep.txt"), b"keep").unwrap();
980
981 let storage = make_storage_with_rooted_fs(&snapshot_root);
982 storage.delete_snapshot().await.unwrap();
983
984 assert!(!snapshot_root.join("manifest.json").exists());
985 assert!(sibling.join("keep.txt").exists());
986 }
987}