Skip to main content

object_store_opendal/service/
reader.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use std::sync::Arc;
19
20use bytes::Bytes;
21use futures::TryStreamExt;
22use futures::stream::BoxStream;
23use object_store::ObjectStore;
24use object_store::path::Path as ObjectStorePath;
25
26use opendal::raw::*;
27use opendal::*;
28
29use super::core::format_metadata;
30use super::core::parse_op_read;
31use super::error::parse_error;
32
33/// ObjectStore reader
34pub struct ObjectStoreReader {
35    store: Arc<dyn ObjectStore + 'static>,
36    path: String,
37    args: OpRead,
38}
39
40impl ObjectStoreReader {
41    pub(crate) fn new(store: Arc<dyn ObjectStore + 'static>, path: &str, args: OpRead) -> Self {
42        Self {
43            store,
44            path: path.to_string(),
45            args,
46        }
47    }
48}
49
50impl oio::StreamRead for ObjectStoreReader {
51    async fn open(&self, range: BytesRange) -> Result<(RpRead, Box<dyn oio::ReadStreamDyn>)> {
52        let path = ObjectStorePath::from(self.path.as_str());
53        let opts = parse_op_read(&self.args, range)?;
54        let result = self
55            .store
56            .get_opts(&path, opts)
57            .await
58            .map_err(parse_error)?;
59        let rp = RpRead::new(format_metadata(&result.meta));
60        let stream = ObjectStoreReadStream::new(result.into_stream());
61
62        Ok((rp, Box::new(stream) as Box<dyn oio::ReadStreamDyn>))
63    }
64}
65
66/// ObjectStore read stream
67pub struct ObjectStoreReadStream {
68    bytes_stream: BoxStream<'static, object_store::Result<Bytes>>,
69}
70
71impl ObjectStoreReadStream {
72    fn new(bytes_stream: BoxStream<'static, object_store::Result<Bytes>>) -> Self {
73        Self { bytes_stream }
74    }
75}
76
77// ObjectStoreReadStream is safe to share between threads, because the `read()` method requires
78// `&mut self`.
79unsafe impl Sync for ObjectStoreReadStream {}
80
81impl oio::ReadStream for ObjectStoreReadStream {
82    async fn read(&mut self) -> Result<Buffer> {
83        let bs = self.bytes_stream.try_next().await.map_err(parse_error)?;
84        Ok(bs.map(Buffer::from).unwrap_or_default())
85    }
86}