1#![expect(
16 unexpected_cfgs,
17 reason = "feature(hdfs-backend) is banned https://github.com/risingwavelabs/risingwave/pull/7875"
18)]
19
20pub mod sim;
21use std::io;
22use std::ops::RangeBounds;
23use std::pin::Pin;
24use std::sync::Arc;
25use std::task::{Context, Poll, ready};
26use std::time::Duration;
27
28use bytes::{Buf, Bytes};
29
30pub mod mem;
31pub use mem::*;
32
33pub mod opendal_engine;
34pub use opendal_engine::*;
35
36pub mod s3;
37use await_tree::{InstrumentAwait, SpanExt};
38use futures::stream::BoxStream;
39use futures::{Future, Stream, StreamExt};
40use futures_async_stream::try_stream;
41use pin_project_lite::pin_project;
42pub use risingwave_common::config::ObjectStoreConfig;
43pub use s3::*;
44
45pub mod error;
46pub mod object_metrics;
47
48pub mod prefix;
49
50pub use error::*;
51use object_metrics::ObjectStoreMetrics;
52use risingwave_common::util::retry::exponential_backoff;
53use thiserror_ext::AsReport;
54use tokio::io::{AsyncRead, ReadBuf};
55use tokio_retry::strategy::jitter;
56
57#[cfg(madsim)]
58use self::sim::SimObjectStore;
59
60pub type ObjectStoreRef = Arc<ObjectStoreImpl>;
61pub type ObjectStreamingUploader = StreamingUploaderImpl;
62
63pub trait ObjectRangeBounds = RangeBounds<usize> + Clone + Send + Sync + std::fmt::Debug + 'static;
64
65#[derive(Debug, Clone, PartialEq)]
66pub struct ObjectMetadata {
67 pub key: String,
69 pub last_modified: f64,
71 pub total_size: usize,
72}
73
74pub trait StreamingUploader: Send {
75 #[expect(async_fn_in_trait)]
76 async fn write_bytes(&mut self, data: Bytes) -> ObjectResult<()>;
77
78 #[expect(async_fn_in_trait)]
79 async fn finish(self) -> ObjectResult<()>;
80
81 fn get_memory_usage(&self) -> u64;
82}
83
84#[async_trait::async_trait]
86pub trait ObjectStore: Send + Sync {
87 type StreamingUploader: StreamingUploader;
88 fn get_object_prefix(&self, obj_id: u64, use_new_object_prefix_strategy: bool) -> String;
90
91 async fn upload(&self, path: &str, obj: Bytes) -> ObjectResult<()>;
93
94 async fn streaming_upload(&self, path: &str) -> ObjectResult<Self::StreamingUploader>;
95
96 async fn read(&self, path: &str, range: impl ObjectRangeBounds) -> ObjectResult<Bytes>;
100
101 async fn streaming_read(
105 &self,
106 path: &str,
107 read_range: impl ObjectRangeBounds,
108 ) -> ObjectResult<ObjectDataStream>;
109
110 async fn metadata(&self, path: &str) -> ObjectResult<ObjectMetadata>;
112
113 async fn delete(&self, path: &str) -> ObjectResult<()>;
115
116 async fn delete_objects(&self, paths: &[String]) -> ObjectResult<()>;
119
120 fn monitored(
121 self,
122 metrics: Arc<ObjectStoreMetrics>,
123 config: Arc<ObjectStoreConfig>,
124 ) -> MonitoredObjectStore<Self>
125 where
126 Self: Sized,
127 {
128 MonitoredObjectStore::new(self, metrics, config)
129 }
130
131 async fn list(&self, prefix: &str) -> ObjectResult<ObjectMetadataIter>;
134
135 fn store_media_type(&self) -> &'static str;
136}
137
138#[cfg(not(madsim))]
139macro_rules! for_all_object_store {
140 ($macro:ident $($args:tt)*) => {
141 $macro! {
142 {
143 { InMem, InMemObjectStore },
144 { Opendal, OpendalObjectStore },
145 { S3, S3ObjectStore }
146 }
147 $($args)*
148 }
149 }
150}
151
152#[cfg(madsim)]
153macro_rules! for_all_object_store {
154 ($macro:ident $($args:tt)*) => {
155 $macro! {
156 {
157 { InMem, InMemObjectStore },
158 { Opendal, OpendalObjectStore },
159 { S3, S3ObjectStore },
160 { Sim, SimObjectStore }
161 }
162 $($args)*
163 }
164 }
165}
166
167macro_rules! enum_map {
168 (
169 {
170 $(
171 {$variant:ident, $_type_name:ty}
172 ),*
173 },
174 $object_store:expr,
175 $var_name:ident,
176 $func:expr
177 ) => {
178 match $object_store {
179 $(
180 ObjectStoreEnum::$variant($var_name) => ObjectStoreEnum::$variant({
181 $func
182 }),
183 )*
184 }
185 };
186 ($object_store:expr, |$var_name:ident| $func:expr) => {
187 for_all_object_store! {
188 enum_map, $object_store, $var_name, $func
189 }
190 };
191}
192
193macro_rules! dispatch_object_store_enum {
194 (
195 {
196 $(
197 {$variant:ident, $_type_name:ty}
198 ),*
199 },
200 $object_store:expr,
201 $var_name:ident,
202 $func:expr
203 ) => {
204 match $object_store {
205 $(
206 ObjectStoreEnum::$variant($var_name) => {
207 $func
208 },
209 )*
210 }
211 };
212 ($object_store:expr, |$var_name:ident| $func:expr) => {
213 for_all_object_store! {
214 dispatch_object_store_enum, $object_store, $var_name, $func
215 }
216 };
217}
218
219macro_rules! define_object_store_impl {
220 () => {
221 for_all_object_store! {
222 define_object_store_impl
223 }
224 };
225 (
226 {$(
227 {$variant:ident, $type_name:ty}
228 ),*}
229 ) => {
230 pub enum ObjectStoreEnum<
231 $($variant),*
232 > {
233 $(
234 $variant($variant),
235 )*
236 }
237
238 pub type ObjectStoreImpl = ObjectStoreEnum<
239 $(
240 MonitoredObjectStore<$type_name>,
241 )*
242 >;
243
244 pub type StreamingUploaderImpl = ObjectStoreEnum<
245 $(
246 MonitoredStreamingUploader<<$type_name as ObjectStore>::StreamingUploader>
247 ),*
248 >;
249 };
250}
251
252define_object_store_impl!();
253
254macro_rules! object_store_impl_method_body {
259 ($object_store:expr, $method_name:ident ($($args:expr),*).await) => {
261 {
262 dispatch_object_store_enum! {$object_store, |os| {
263 os.$method_name($($args),*).await
264 }}
265 }
266 };
267 ($object_store:expr, $method_name:ident ($(, $args:expr)*)) => {
269 {
270 dispatch_object_store_enum! {$object_store, |os| {
271 os.$method_name($($args),*)
272 }}
273 }
274 };
275}
276
277impl StreamingUploaderImpl {
278 pub async fn write_bytes(&mut self, data: Bytes) -> ObjectResult<()> {
279 object_store_impl_method_body!(self, write_bytes(data).await)
280 }
281
282 pub async fn finish(self) -> ObjectResult<()> {
283 object_store_impl_method_body!(self, finish().await)
284 }
285
286 pub fn get_memory_usage(&self) -> u64 {
287 object_store_impl_method_body!(self, get_memory_usage())
288 }
289}
290
291impl ObjectStoreImpl {
292 pub async fn upload(&self, path: &str, obj: Bytes) -> ObjectResult<()> {
293 object_store_impl_method_body!(self, upload(path, obj).await)
294 }
295
296 pub async fn streaming_upload(&self, path: &str) -> ObjectResult<ObjectStreamingUploader> {
297 Ok(enum_map!(self, |store| {
298 store.streaming_upload(path).await?
299 }))
300 }
301
302 pub async fn read(&self, path: &str, range: impl ObjectRangeBounds) -> ObjectResult<Bytes> {
303 object_store_impl_method_body!(self, read(path, range).await)
304 }
305
306 pub async fn metadata(&self, path: &str) -> ObjectResult<ObjectMetadata> {
307 object_store_impl_method_body!(self, metadata(path).await)
308 }
309
310 pub async fn streaming_read(
314 &self,
315 path: &str,
316 start_loc: impl ObjectRangeBounds,
317 ) -> ObjectResult<MonitoredStreamingReader> {
318 object_store_impl_method_body!(self, streaming_read(path, start_loc).await)
319 }
320
321 pub async fn delete(&self, path: &str) -> ObjectResult<()> {
322 object_store_impl_method_body!(self, delete(path).await)
323 }
324
325 pub async fn delete_objects(&self, paths: &[String]) -> ObjectResult<()> {
331 object_store_impl_method_body!(self, delete_objects(paths).await)
332 }
333
334 pub async fn list(&self, prefix: &str) -> ObjectResult<ObjectMetadataIter> {
335 object_store_impl_method_body!(self, list(prefix).await)
336 }
337
338 pub fn get_object_prefix(&self, obj_id: u64, use_new_object_prefix_strategy: bool) -> String {
339 dispatch_object_store_enum!(self, |store| store
340 .inner
341 .get_object_prefix(obj_id, use_new_object_prefix_strategy))
342 }
343
344 pub fn media_type(&self) -> &'static str {
345 object_store_impl_method_body!(self, media_type())
346 }
347}
348
349fn try_update_failure_metric<T>(
350 metrics: &Arc<ObjectStoreMetrics>,
351 result: &ObjectResult<T>,
352 operation_type: &'static str,
353) {
354 if let Err(e) = &result {
355 tracing::error!(error = %e.as_report(), "{} failed", operation_type);
356 metrics
357 .failure_count
358 .with_label_values(&[operation_type])
359 .inc();
360 }
361}
362
363pub struct MonitoredStreamingUploader<U: StreamingUploader> {
375 inner: U,
376 object_store_metrics: Arc<ObjectStoreMetrics>,
377 operation_size: usize,
379}
380
381impl<U: StreamingUploader> MonitoredStreamingUploader<U> {
382 pub fn new(handle: U, object_store_metrics: Arc<ObjectStoreMetrics>) -> Self {
383 Self {
384 inner: handle,
385 object_store_metrics,
386 operation_size: 0,
387 }
388 }
389}
390
391impl<U: StreamingUploader> MonitoredStreamingUploader<U> {
394 async fn write_bytes(&mut self, data: Bytes) -> ObjectResult<()> {
395 let operation_type = OperationType::StreamingUpload;
396 let operation_type_str = operation_type.as_str();
397 let data_len = data.len();
398
399 let res = self
400 .inner
401 .write_bytes(data)
402 .instrument_await(operation_type_str.verbose())
403 .await;
404
405 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
406
407 self.object_store_metrics
409 .write_bytes
410 .inc_by(data_len as u64);
411 self.object_store_metrics
412 .operation_size
413 .with_label_values(&[operation_type_str])
414 .observe(data_len as f64);
415 self.operation_size += data_len;
416
417 res
418 }
419
420 async fn finish(self) -> ObjectResult<()> {
421 let operation_type = OperationType::StreamingUploadFinish;
422 let operation_type_str = operation_type.as_str();
423
424 let res =
425 self.inner
427 .finish()
428 .instrument_await(operation_type_str.verbose())
429 .await;
430
431 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
432
433 self.object_store_metrics
435 .operation_size
436 .with_label_values(&[operation_type_str])
437 .observe(self.operation_size as f64);
438 res
439 }
440
441 fn get_memory_usage(&self) -> u64 {
442 self.inner.get_memory_usage()
443 }
444}
445
446pub struct MonitoredStreamingReader {
447 inner: ObjectDataStream,
448 object_store_metrics: Arc<ObjectStoreMetrics>,
449 operation_size: usize,
450 media_type: &'static str,
451 streaming_read_timeout: Option<Duration>,
452 operation_type_str: &'static str,
453}
454
455impl MonitoredStreamingReader {
456 pub fn new(
457 media_type: &'static str,
458 handle: ObjectDataStream,
459 object_store_metrics: Arc<ObjectStoreMetrics>,
460 streaming_read_timeout: Option<Duration>,
461 ) -> Self {
462 Self {
463 inner: handle,
464 object_store_metrics,
465 operation_size: 0,
466 media_type,
467 streaming_read_timeout,
468 operation_type_str: OperationType::StreamingRead.as_str(),
469 }
470 }
471
472 pub async fn read_bytes(&mut self) -> Option<ObjectResult<Bytes>> {
473 let _timer = self
474 .object_store_metrics
475 .operation_latency
476 .with_label_values(&[self.media_type, self.operation_type_str])
477 .start_timer();
478 let future = async {
479 self.inner
480 .next()
481 .instrument_await(self.operation_type_str.verbose())
482 .await
483 };
484 let res = match self.streaming_read_timeout.as_ref() {
485 None => future.await,
486 Some(timeout_duration) => tokio::time::timeout(*timeout_duration, future)
487 .await
488 .unwrap_or_else(|_| {
489 Some(Err(ObjectError::timeout(format!(
490 "Retry attempts exhausted for {}. Please modify {}_attempt_timeout_ms (current={:?}) under [storage.object_store.retry] in the config accordingly if needed.",
491 self.operation_type_str, self.operation_type_str, timeout_duration.as_millis()
492 ))))
493 }),
494 };
495
496 if let Some(ret) = &res {
497 try_update_failure_metric(&self.object_store_metrics, ret, self.operation_type_str);
498 }
499 if let Some(Ok(data)) = &res {
500 let data_len = data.len();
501 self.object_store_metrics.read_bytes.inc_by(data_len as u64);
502 self.object_store_metrics
503 .operation_size
504 .with_label_values(&[self.operation_type_str])
505 .observe(data_len as f64);
506 self.operation_size += data_len;
507 }
508 res
509 }
510
511 pub fn into_stream(self) -> ObjectDataStream {
512 Self::into_stream_inner(self).boxed()
513 }
514
515 #[try_stream(ok = Bytes, error = ObjectError)]
516 async fn into_stream_inner(mut self) {
517 while let Some(bytes) = self.read_bytes().await.transpose()? {
518 yield bytes;
519 }
520 }
521}
522
523impl Drop for MonitoredStreamingReader {
524 fn drop(&mut self) {
525 self.object_store_metrics
526 .operation_size
527 .with_label_values(&[self.operation_type_str])
528 .observe(self.operation_size as f64);
529 }
530}
531
532pub struct MonitoredObjectStore<OS: ObjectStore> {
533 inner: OS,
534 object_store_metrics: Arc<ObjectStoreMetrics>,
535 config: Arc<ObjectStoreConfig>,
536}
537
538impl<OS: ObjectStore> MonitoredObjectStore<OS> {
555 pub fn new(
556 store: OS,
557 object_store_metrics: Arc<ObjectStoreMetrics>,
558 config: Arc<ObjectStoreConfig>,
559 ) -> Self {
560 Self {
561 object_store_metrics,
562 inner: store,
563 config,
564 }
565 }
566
567 fn media_type(&self) -> &'static str {
568 self.inner.store_media_type()
569 }
570
571 pub fn inner(&self) -> &OS {
572 &self.inner
573 }
574
575 pub fn mut_inner(&mut self) -> &mut OS {
576 &mut self.inner
577 }
578
579 pub async fn upload(&self, path: &str, obj: Bytes) -> ObjectResult<()> {
580 let operation_type = OperationType::Upload;
581 let operation_type_str = operation_type.as_str();
582 let media_type = self.media_type();
583
584 self.object_store_metrics
585 .write_bytes
586 .inc_by(obj.len() as u64);
587 self.object_store_metrics
588 .operation_size
589 .with_label_values(&[operation_type_str])
590 .observe(obj.len() as f64);
591 let _timer = self
592 .object_store_metrics
593 .operation_latency
594 .with_label_values(&[media_type, operation_type_str])
595 .start_timer();
596
597 let builder = || async {
598 self.inner
599 .upload(path, obj.clone())
600 .instrument_await(operation_type_str.verbose())
601 .await
602 };
603
604 let res = retry_request(
605 builder,
606 &self.config,
607 operation_type,
608 self.object_store_metrics.clone(),
609 media_type,
610 )
611 .await;
612
613 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
614 res
615 }
616
617 pub async fn streaming_upload(
618 &self,
619 path: &str,
620 ) -> ObjectResult<MonitoredStreamingUploader<OS::StreamingUploader>> {
621 let operation_type = OperationType::StreamingUploadInit;
622 let operation_type_str = operation_type.as_str();
623 let media_type = self.media_type();
624 let _timer = self
625 .object_store_metrics
626 .operation_latency
627 .with_label_values(&[media_type, operation_type_str])
628 .start_timer();
629
630 let res = self
631 .inner
632 .streaming_upload(path)
633 .instrument_await(operation_type_str.verbose())
634 .await;
635
636 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
637
638 Ok(MonitoredStreamingUploader::new(
639 res?,
640 self.object_store_metrics.clone(),
641 ))
642 }
643
644 pub async fn read(&self, path: &str, range: impl ObjectRangeBounds) -> ObjectResult<Bytes> {
645 let operation_type = OperationType::Read;
646 let operation_type_str = operation_type.as_str();
647 let media_type = self.media_type();
648
649 let _timer = self
650 .object_store_metrics
651 .operation_latency
652 .with_label_values(&[media_type, operation_type_str])
653 .start_timer();
654
655 let builder = || async {
656 self.inner
657 .read(path, range.clone())
658 .instrument_await(operation_type_str.verbose())
659 .await
660 };
661
662 let res = retry_request(
663 builder,
664 &self.config,
665 operation_type,
666 self.object_store_metrics.clone(),
667 media_type,
668 )
669 .await;
670
671 if let Err(e) = &res
672 && e.is_object_not_found_error()
673 && !path.ends_with(".data")
674 {
675 } else {
678 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
679 }
680
681 let data = res?;
682 self.object_store_metrics
683 .read_bytes
684 .inc_by(data.len() as u64);
685 self.object_store_metrics
686 .operation_size
687 .with_label_values(&[operation_type_str])
688 .observe(data.len() as f64);
689 Ok(data)
690 }
691
692 async fn streaming_read(
696 &self,
697 path: &str,
698 range: impl ObjectRangeBounds,
699 ) -> ObjectResult<MonitoredStreamingReader> {
700 let operation_type = OperationType::StreamingReadInit;
701 let operation_type_str = operation_type.as_str();
702 let media_type = self.media_type();
703 let _timer = self
704 .object_store_metrics
705 .operation_latency
706 .with_label_values(&[media_type, operation_type_str])
707 .start_timer();
708
709 let builder = || async {
710 self.inner
711 .streaming_read(path, range.clone())
712 .instrument_await(operation_type_str.verbose())
713 .await
714 };
715
716 let res = retry_request(
717 builder,
718 &self.config,
719 operation_type,
720 self.object_store_metrics.clone(),
721 media_type,
722 )
723 .await;
724
725 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
726
727 Ok(MonitoredStreamingReader::new(
728 media_type,
729 res?,
730 self.object_store_metrics.clone(),
731 Some(Duration::from_millis(
732 self.config.retry.streaming_read_attempt_timeout_ms,
733 )),
734 ))
735 }
736
737 pub async fn metadata(&self, path: &str) -> ObjectResult<ObjectMetadata> {
738 let operation_type = OperationType::Metadata;
739 let operation_type_str = operation_type.as_str();
740 let media_type = self.media_type();
741 let _timer = self
742 .object_store_metrics
743 .operation_latency
744 .with_label_values(&[media_type, operation_type_str])
745 .start_timer();
746
747 let builder = || async {
748 self.inner
749 .metadata(path)
750 .instrument_await(operation_type_str.verbose())
751 .await
752 };
753
754 let res = retry_request(
755 builder,
756 &self.config,
757 operation_type,
758 self.object_store_metrics.clone(),
759 media_type,
760 )
761 .await;
762
763 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
764 res
765 }
766
767 pub async fn delete(&self, path: &str) -> ObjectResult<()> {
768 let operation_type = OperationType::Delete;
769 let operation_type_str = operation_type.as_str();
770 let media_type = self.media_type();
771
772 let _timer = self
773 .object_store_metrics
774 .operation_latency
775 .with_label_values(&[media_type, operation_type_str])
776 .start_timer();
777
778 let builder = || async {
779 self.inner
780 .delete(path)
781 .instrument_await(operation_type_str.verbose())
782 .await
783 };
784
785 let res = retry_request(
786 builder,
787 &self.config,
788 operation_type,
789 self.object_store_metrics.clone(),
790 media_type,
791 )
792 .await;
793
794 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
795 res
796 }
797
798 async fn delete_objects(&self, paths: &[String]) -> ObjectResult<()> {
799 let operation_type = OperationType::DeleteObjects;
800 let operation_type_str = operation_type.as_str();
801 let media_type = self.media_type();
802
803 let _timer = self
804 .object_store_metrics
805 .operation_latency
806 .with_label_values(&[self.media_type(), operation_type_str])
807 .start_timer();
808
809 let builder = || async {
810 self.inner
811 .delete_objects(paths)
812 .instrument_await(operation_type_str.verbose())
813 .await
814 };
815
816 let res = retry_request(
817 builder,
818 &self.config,
819 operation_type,
820 self.object_store_metrics.clone(),
821 media_type,
822 )
823 .await;
824
825 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
826 res
827 }
828
829 pub async fn list(&self, prefix: &str) -> ObjectResult<ObjectMetadataIter> {
830 let operation_type = OperationType::List;
831 let operation_type_str = operation_type.as_str();
832 let media_type = self.media_type();
833
834 let _timer = self
835 .object_store_metrics
836 .operation_latency
837 .with_label_values(&[media_type, operation_type_str])
838 .start_timer();
839
840 let builder = || async {
841 self.inner
842 .list(prefix)
843 .instrument_await(operation_type_str.verbose())
844 .await
845 };
846
847 let res = retry_request(
848 builder,
849 &self.config,
850 operation_type,
851 self.object_store_metrics.clone(),
852 media_type,
853 )
854 .await;
855
856 try_update_failure_metric(&self.object_store_metrics, &res, operation_type_str);
857 res
858 }
859}
860
861pub async fn build_remote_object_store(
867 url: &str,
868 metrics: Arc<ObjectStoreMetrics>,
869 ident: &str,
870 config: Arc<ObjectStoreConfig>,
871) -> ObjectStoreImpl {
872 tracing::debug!(config=?config, "object store {ident}");
873 match url {
874 s3 if s3.starts_with("s3://") => {
875 if config.s3.developer.use_opendal {
876 let bucket = s3.strip_prefix("s3://").unwrap();
877 tracing::info!("Using OpenDAL to access s3, bucket is {}", bucket);
878 ObjectStoreImpl::Opendal(
879 OpendalObjectStore::new_s3_engine(
880 bucket.to_owned(),
881 config.clone(),
882 metrics.clone(),
883 )
884 .unwrap()
885 .monitored(metrics, config),
886 )
887 } else {
888 ObjectStoreImpl::S3(
889 S3ObjectStore::new_with_config(
890 s3.strip_prefix("s3://").unwrap().to_owned(),
891 metrics.clone(),
892 config.clone(),
893 )
894 .await
895 .monitored(metrics, config),
896 )
897 }
898 }
899 #[cfg(feature = "hdfs-backend")]
900 hdfs if hdfs.starts_with("hdfs://") => {
901 let hdfs = hdfs.strip_prefix("hdfs://").unwrap();
902 let (namenode, root) = hdfs.split_once('@').unwrap_or((hdfs, ""));
903 ObjectStoreImpl::Opendal(
904 OpendalObjectStore::new_hdfs_engine(
905 namenode.to_string(),
906 root.to_string(),
907 config.clone(),
908 metrics.clone(),
909 )
910 .unwrap()
911 .monitored(metrics, config),
912 )
913 }
914 gcs if gcs.starts_with("gcs://") => {
915 let gcs = gcs.strip_prefix("gcs://").unwrap();
916 let (bucket, root) = gcs.split_once('@').unwrap_or((gcs, ""));
917 ObjectStoreImpl::Opendal(
918 OpendalObjectStore::new_gcs_engine(
919 bucket.to_owned(),
920 root.to_owned(),
921 config.clone(),
922 metrics.clone(),
923 )
924 .unwrap()
925 .monitored(metrics, config),
926 )
927 }
928 obs if obs.starts_with("obs://") => {
929 let obs = obs.strip_prefix("obs://").unwrap();
930 let (bucket, root) = obs.split_once('@').unwrap_or((obs, ""));
931 ObjectStoreImpl::Opendal(
932 OpendalObjectStore::new_obs_engine(
933 bucket.to_owned(),
934 root.to_owned(),
935 config.clone(),
936 metrics.clone(),
937 )
938 .unwrap()
939 .monitored(metrics, config),
940 )
941 }
942
943 oss if oss.starts_with("oss://") => {
944 let oss = oss.strip_prefix("oss://").unwrap();
945 let (bucket, root) = oss.split_once('@').unwrap_or((oss, ""));
946 ObjectStoreImpl::Opendal(
947 OpendalObjectStore::new_oss_engine(
948 bucket.to_owned(),
949 root.to_owned(),
950 config.clone(),
951 metrics.clone(),
952 )
953 .unwrap()
954 .monitored(metrics, config),
955 )
956 }
957 webhdfs if webhdfs.starts_with("webhdfs://") => {
958 let webhdfs = webhdfs.strip_prefix("webhdfs://").unwrap();
959 let (namenode, root) = webhdfs.split_once('@').unwrap_or((webhdfs, ""));
960 ObjectStoreImpl::Opendal(
961 OpendalObjectStore::new_webhdfs_engine(
962 namenode.to_owned(),
963 root.to_owned(),
964 config.clone(),
965 metrics.clone(),
966 )
967 .unwrap()
968 .monitored(metrics, config),
969 )
970 }
971 azblob if azblob.starts_with("azblob://") => {
972 let azblob = azblob.strip_prefix("azblob://").unwrap();
973 let (container_name, root) = azblob.split_once('@').unwrap_or((azblob, ""));
974 ObjectStoreImpl::Opendal(
975 OpendalObjectStore::new_azblob_engine(
976 container_name.to_owned(),
977 root.to_owned(),
978 config.clone(),
979 metrics.clone(),
980 )
981 .unwrap()
982 .monitored(metrics, config),
983 )
984 }
985 fs if fs.starts_with("fs://") => {
986 let fs = fs.strip_prefix("fs://").unwrap();
987 ObjectStoreImpl::Opendal(
988 OpendalObjectStore::new_fs_engine(fs.to_owned(), config.clone(), metrics.clone())
989 .unwrap()
990 .monitored(metrics, config),
991 )
992 }
993
994 s3_compatible if s3_compatible.starts_with("s3-compatible://") => {
995 tracing::error!("The s3 compatible mode has been unified with s3.");
996 tracing::error!("If you want to use s3 compatible storage, please set your access_key, secret_key and region to the environment variable AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION,
997 set your endpoint to the environment variable RW_S3_ENDPOINT.");
998 panic!(
999 "Passing s3-compatible is not supported, please modify the environment variable and pass in s3."
1000 );
1001 }
1002 minio if minio.starts_with("minio://") => {
1003 if config.s3.developer.use_opendal {
1004 tracing::info!("Using OpenDAL to access minio.");
1005 ObjectStoreImpl::Opendal(
1006 OpendalObjectStore::new_minio_engine(minio, config.clone(), metrics.clone())
1007 .unwrap()
1008 .monitored(metrics, config),
1009 )
1010 } else {
1011 ObjectStoreImpl::S3(
1012 S3ObjectStore::new_minio_engine(minio, metrics.clone(), config.clone())
1013 .await
1014 .monitored(metrics, config),
1015 )
1016 }
1017 }
1018 "memory" | "memory-shared" => {
1019 if ident == "Meta Backup" {
1020 tracing::warn!(
1021 "You're using in-memory remote object store for {}. This is not recommended for production environment.",
1022 ident
1023 );
1024 } else {
1025 tracing::warn!(
1026 "You're using in-memory remote object store for {}. This should never be used in benchmarks and production environment.",
1027 ident
1028 );
1029 }
1030 ObjectStoreImpl::InMem(InMemObjectStore::shared().monitored(metrics, config))
1031 }
1032 #[cfg(debug_assertions)]
1033 "memory-isolated-for-test" => {
1034 ObjectStoreImpl::InMem(InMemObjectStore::for_test().monitored(metrics, config))
1035 }
1036 #[cfg(madsim)]
1037 sim if sim.starts_with("sim://") => {
1038 ObjectStoreImpl::Sim(SimObjectStore::new(url).monitored(metrics, config))
1039 }
1040 other => {
1041 unimplemented!(
1042 "{} remote object store only supports s3, minio, gcs, oss, cos, azure blob, hdfs, disk, memory.",
1043 other
1044 )
1045 }
1046 }
1047}
1048
1049#[inline(always)]
1050fn get_retry_strategy(
1051 config: &ObjectStoreConfig,
1052 operation_type: OperationType,
1053) -> impl Iterator<Item = Duration> + use<> {
1054 let attempts = get_retry_attempts_by_type(config, operation_type);
1055 exponential_backoff(
1056 Duration::from_millis(config.retry.req_backoff_interval_ms),
1057 config.retry.req_backoff_factor,
1058 Duration::from_millis(config.retry.req_backoff_max_delay_ms),
1059 )
1060 .take(attempts)
1061 .map(jitter)
1062}
1063
1064pub type ObjectMetadataIter = BoxStream<'static, ObjectResult<ObjectMetadata>>;
1065pub type ObjectDataStream = BoxStream<'static, ObjectResult<Bytes>>;
1066
1067pin_project! {
1068 pub struct ObjectDataStreamReader<S> {
1069 #[pin]
1070 stream: S,
1071 pending: Bytes,
1072 }
1073}
1074
1075impl<S> ObjectDataStreamReader<S>
1076where
1077 S: Stream<Item = ObjectResult<Bytes>>,
1078{
1079 pub fn new(stream: S) -> Self {
1080 Self {
1081 stream,
1082 pending: Bytes::new(),
1083 }
1084 }
1085}
1086
1087impl ObjectDataStreamReader<ObjectDataStream> {
1088 pub fn into_bytes_stream(self) -> ObjectDataStream {
1089 Self::into_bytes_stream_inner(self).boxed()
1090 }
1091
1092 #[try_stream(ok = Bytes, error = ObjectError)]
1093 async fn into_bytes_stream_inner(mut self) {
1094 if self.pending.has_remaining() {
1095 yield std::mem::take(&mut self.pending);
1096 }
1097 while let Some(bytes) = self.stream.next().await.transpose()? {
1098 yield bytes;
1099 }
1100 }
1101}
1102
1103impl<S> AsyncRead for ObjectDataStreamReader<S>
1104where
1105 S: Stream<Item = ObjectResult<Bytes>>,
1106{
1107 fn poll_read(
1108 self: Pin<&mut Self>,
1109 cx: &mut Context<'_>,
1110 buf: &mut ReadBuf<'_>,
1111 ) -> Poll<io::Result<()>> {
1112 if buf.remaining() == 0 {
1113 return Poll::Ready(Ok(()));
1114 }
1115
1116 let mut this = self.project();
1117 loop {
1118 if this.pending.has_remaining() {
1119 let len = this.pending.remaining().min(buf.remaining());
1120 buf.put_slice(&this.pending[..len]);
1121 this.pending.advance(len);
1122 return Poll::Ready(Ok(()));
1123 }
1124
1125 match ready!(this.stream.as_mut().poll_next(cx)) {
1126 Some(Ok(bytes)) => {
1127 *this.pending = bytes;
1128 }
1129 Some(Err(err)) => return Poll::Ready(Err(io::Error::other(err))),
1130 None => return Poll::Ready(Ok(())),
1131 }
1132 }
1133 }
1134}
1135
1136#[cfg(test)]
1137mod tests {
1138 use futures::stream;
1139 use tokio::io::AsyncReadExt;
1140
1141 use super::{Bytes, ObjectDataStreamReader, ObjectError};
1142
1143 #[tokio::test]
1144 async fn test_object_data_stream_reader_reads_across_chunks() {
1145 let stream = stream::iter([
1146 Ok(Bytes::from_static(b"ab")),
1147 Ok(Bytes::from_static(b"cdef")),
1148 Ok(Bytes::from_static(b"g")),
1149 ]);
1150 let mut reader = ObjectDataStreamReader::new(stream);
1151
1152 let mut first = [0; 3];
1153 reader.read_exact(&mut first).await.unwrap();
1154 assert_eq!(&first, b"abc");
1155
1156 let mut rest = vec![];
1157 reader.read_to_end(&mut rest).await.unwrap();
1158 assert_eq!(&rest, b"defg");
1159 }
1160
1161 #[tokio::test]
1162 async fn test_object_data_stream_reader_returns_stream_error() {
1163 let stream = stream::iter([
1164 Ok(Bytes::from_static(b"ab")),
1165 Err(ObjectError::internal("injected stream error")),
1166 ]);
1167 let mut reader = ObjectDataStreamReader::new(stream);
1168
1169 let mut output = vec![];
1170 let err = reader.read_to_end(&mut output).await.unwrap_err();
1171 assert!(err.to_string().contains("injected stream error"));
1172 }
1173}
1174
1175#[derive(Debug, Clone, Copy)]
1176enum OperationType {
1177 Upload,
1178 StreamingUploadInit,
1179 StreamingUpload,
1180 StreamingUploadFinish,
1181 Read,
1182 StreamingReadInit,
1183 StreamingRead,
1184 Metadata,
1185 Delete,
1186 DeleteObjects,
1187 List,
1188}
1189
1190impl OperationType {
1191 fn as_str(&self) -> &'static str {
1192 match self {
1193 Self::Upload => "upload",
1194 Self::StreamingUploadInit => "streaming_upload_init",
1195 Self::StreamingUpload => "streaming_upload",
1196 Self::StreamingUploadFinish => "streaming_upload_finish",
1197 Self::Read => "read",
1198 Self::StreamingReadInit => "streaming_read_init",
1199 Self::StreamingRead => "streaming_read",
1200 Self::Metadata => "metadata",
1201 Self::Delete => "delete",
1202 Self::DeleteObjects => "delete_objects",
1203 Self::List => "list",
1204 }
1205 }
1206}
1207
1208fn get_retry_attempts_by_type(config: &ObjectStoreConfig, operation_type: OperationType) -> usize {
1209 match operation_type {
1210 OperationType::Upload => config.retry.upload_retry_attempts,
1211 OperationType::StreamingUploadInit
1212 | OperationType::StreamingUpload
1213 | OperationType::StreamingUploadFinish => config.retry.streaming_upload_retry_attempts,
1214 OperationType::Read => config.retry.read_retry_attempts,
1215 OperationType::StreamingReadInit | OperationType::StreamingRead => {
1216 config.retry.streaming_read_retry_attempts
1217 }
1218 OperationType::Metadata => config.retry.metadata_retry_attempts,
1219 OperationType::Delete => config.retry.delete_retry_attempts,
1220 OperationType::DeleteObjects => config.retry.delete_objects_retry_attempts,
1221 OperationType::List => config.retry.list_retry_attempts,
1222 }
1223}
1224
1225fn get_attempt_timeout_by_type(config: &ObjectStoreConfig, operation_type: OperationType) -> u64 {
1226 match operation_type {
1227 OperationType::Upload => config.retry.upload_attempt_timeout_ms,
1228 OperationType::StreamingUploadInit
1229 | OperationType::StreamingUpload
1230 | OperationType::StreamingUploadFinish => config.retry.streaming_upload_attempt_timeout_ms,
1231 OperationType::Read => config.retry.read_attempt_timeout_ms,
1232 OperationType::StreamingReadInit | OperationType::StreamingRead => {
1233 config.retry.streaming_read_attempt_timeout_ms
1234 }
1235 OperationType::Metadata => config.retry.metadata_attempt_timeout_ms,
1236 OperationType::Delete => config.retry.delete_attempt_timeout_ms,
1237 OperationType::DeleteObjects => config.retry.delete_objects_attempt_timeout_ms,
1238 OperationType::List => config.retry.list_attempt_timeout_ms,
1239 }
1240}
1241
1242struct RetryCondition {
1243 operation_type: OperationType,
1244 retry_count: usize,
1245 metrics: Arc<ObjectStoreMetrics>,
1246 retry_opendal_s3_unknown_error: bool,
1247}
1248
1249impl RetryCondition {
1250 fn new(
1251 operation_type: OperationType,
1252 metrics: Arc<ObjectStoreMetrics>,
1253 retry_opendal_s3_unknown_error: bool,
1254 ) -> Self {
1255 Self {
1256 operation_type,
1257 retry_count: 0,
1258 metrics,
1259 retry_opendal_s3_unknown_error,
1260 }
1261 }
1262
1263 #[inline(always)]
1264 fn should_retry_inner(&mut self, err: &ObjectError) -> bool {
1265 let should_retry = err.should_retry(self.retry_opendal_s3_unknown_error);
1266 if should_retry {
1267 self.retry_count += 1;
1268 }
1269
1270 should_retry
1271 }
1272}
1273
1274impl tokio_retry::Condition<ObjectError> for RetryCondition {
1275 fn should_retry(&mut self, err: &ObjectError) -> bool {
1276 self.should_retry_inner(err)
1277 }
1278}
1279
1280impl Drop for RetryCondition {
1281 fn drop(&mut self) {
1282 if self.retry_count > 0 {
1283 self.metrics
1284 .request_retry_count
1285 .with_label_values(&[self.operation_type.as_str()])
1286 .inc_by(self.retry_count as _);
1287 }
1288 }
1289}
1290
1291async fn retry_request<F, T, B>(
1292 builder: B,
1293 config: &ObjectStoreConfig,
1294 operation_type: OperationType,
1295 object_store_metrics: Arc<ObjectStoreMetrics>,
1296 media_type: &'static str,
1297) -> ObjectResult<T>
1298where
1299 B: Fn() -> F,
1300 F: Future<Output = ObjectResult<T>>,
1301{
1302 let backoff = get_retry_strategy(config, operation_type);
1303 let timeout_duration =
1304 Duration::from_millis(get_attempt_timeout_by_type(config, operation_type));
1305 let operation_type_str = operation_type.as_str();
1306
1307 let retry_condition = RetryCondition::new(
1308 operation_type,
1309 object_store_metrics,
1310 (config.s3.developer.retry_unknown_service_error || config.s3.retry_unknown_service_error)
1311 && (media_type == opendal_engine::MediaType::S3.as_str()
1312 || media_type == opendal_engine::MediaType::Minio.as_str()),
1313 );
1314
1315 let f = || async {
1316 let future = builder();
1317 if timeout_duration.is_zero() {
1318 future.await
1319 } else {
1320 tokio::time::timeout(timeout_duration, future)
1321 .await
1322 .unwrap_or_else(|_| {
1323 Err(ObjectError::timeout(format!(
1324 "Retry attempts exhausted for {}. Please modify {}_attempt_timeout_ms (current={:?}) and {}_retry_attempts (current={}) under [storage.object_store.retry] in the config accordingly if needed.",
1325 operation_type_str, operation_type_str, timeout_duration.as_millis(), operation_type_str, get_retry_attempts_by_type(config, operation_type)
1326 )))
1327 })
1328 }
1329 };
1330
1331 tokio_retry::RetryIf::spawn(backoff, f, retry_condition).await
1332}