Skip to main content

google_cloud_storage/
object_descriptor.rs

1// Copyright 2025 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Defines the return type for [Storage::open_object][crate::client::Storage::open_object].
16
17use crate::http::HeaderMap;
18use crate::model::Object;
19use crate::model_ext::ReadRange;
20use crate::read_object::ReadObjectResponse;
21use crate::storage::bidi::stub::dynamic::ObjectDescriptor as ObjectDescriptorStub;
22use std::sync::Arc;
23
24/// An open object ready to read one or more ranges.
25///
26/// # Example
27/// ```
28/// # use google_cloud_storage::object_descriptor::ObjectDescriptor;
29/// use google_cloud_storage::{client::Storage, model_ext::ReadRange};
30/// # async fn sample() -> anyhow::Result<()> {
31/// let client = Storage::builder().build().await?;
32/// let open: ObjectDescriptor = client
33///     .open_object("projects/_/buckets/my-bucket", "my-object")
34///     .send().await?;
35/// println!("metadata = {:?}", open.object());
36/// // Read 2000 bytes starting at offset 1000.
37/// let mut reader = open.read_range(ReadRange::segment(1000, 2000)).await;
38/// while let Some(data) = reader.next().await.transpose()? {
39///   println!("received {} bytes", data.len());
40/// }
41/// # Ok(()) }
42/// ```
43///
44/// This is analogous to a "file descriptor". It represents an object in Cloud
45/// Storage that has been "opened" and is ready for more read operations. An
46/// object descriptor can have multiple concurrent read operations at a time.
47/// You may call `read_range()` even if previous reads have not completed.
48///
49/// There are no guarantees about the order of the responses. All the data for
50/// a `read_range()` may be returned before any data of earlier `read_range()`
51/// calls, or the data may arrive in any interleaved order. Naturally, the data
52/// for a single ranged read arrives in order.
53///
54/// You should actively read from all concurrent reads: the client library uses
55/// separate buffers for each `read_range()` call, but once a buffer is full the
56/// library will stop delivering data to **all** the concurrent reads.
57///
58/// The client library can automatically resume reads interrupted by transient
59/// errors. If the underlying stream closes unexpectedly or fails with an
60/// unrecoverable error, the reads in progress and any later reads return an
61/// error with [ReadError::UnrecoverableBidiReadInterrupt] as its source. Open a
62/// new `ObjectDescriptor` to continue reading.
63///
64/// [ReadError::UnrecoverableBidiReadInterrupt]: crate::error::ReadError::UnrecoverableBidiReadInterrupt
65#[derive(Debug, Clone)]
66pub struct ObjectDescriptor {
67    inner: Arc<dyn ObjectDescriptorStub>,
68}
69
70impl ObjectDescriptor {
71    /// Returns the metadata for the open object.
72    ///
73    /// # Example
74    /// ```
75    /// # use google_cloud_storage::object_descriptor::ObjectDescriptor;
76    /// # async fn sample() -> anyhow::Result<()> {
77    /// let descriptor = open();
78    /// println!("object generation = {}", descriptor.object().generation);
79    ///
80    /// fn open() -> ObjectDescriptor {
81    /// # panic!()
82    /// // ... details omitted ...
83    /// }
84    /// # Ok(()) }
85    /// ```
86    ///
87    pub fn object(&self) -> Object {
88        self.inner.object()
89    }
90
91    /// Start reading a range.
92    ///
93    /// # Example
94    /// ```
95    /// # use google_cloud_storage::object_descriptor::ObjectDescriptor;
96    /// use google_cloud_storage::{model_ext::ReadRange, read_object::ReadObjectResponse};
97    /// # async fn sample() -> anyhow::Result<()> {
98    /// const MIB: u64 = 1024 * 1024;
99    /// let descriptor = open();
100    /// println!("object generation = {}", descriptor.object().generation);
101    ///
102    /// // Read 2 MiB starting at offset 0.
103    /// let read1 = descriptor.read_range(ReadRange::segment(0, 2 * MIB)).await;
104    /// // Concurrently read 2 MiB starting at offset 4 MiB.
105    /// let read2 = descriptor.read_range(ReadRange::segment(4 * MIB, 2 * MIB)).await;
106    ///
107    /// let t1 = tokio::spawn(async move { do_read(read1) });
108    /// let t2 = tokio::spawn(async move { do_read(read2) });
109    ///
110    /// async fn do_read(mut reader: ReadObjectResponse) {
111    /// # panic!()
112    /// // ... details omitted ...
113    /// }
114    /// fn open() -> ObjectDescriptor {
115    /// # panic!()
116    /// // ... details omitted ...
117    /// }
118    /// # Ok(()) }
119    /// ```
120    pub async fn read_range(&self, range: ReadRange) -> ReadObjectResponse {
121        self.inner.read_range(range).await
122    }
123
124    /// Returns metadata about the original `open_object()` request.
125    ///
126    /// # Example
127    /// ```
128    /// # use google_cloud_storage::object_descriptor::ObjectDescriptor;
129    /// # async fn sample() -> anyhow::Result<()> {
130    /// let descriptor = open();
131    /// // Often useful when troubleshooting problems with Google Support.
132    /// let headers = descriptor.headers();
133    /// println!("debugging header = {:?}", headers.get("x-guploader-uploadid"));
134    ///
135    /// fn open() -> ObjectDescriptor {
136    /// # panic!()
137    /// // ... details omitted ...
138    /// }
139    /// # Ok(()) }
140    /// ```
141    pub fn headers(&self) -> HeaderMap {
142        self.inner.headers()
143    }
144
145    /// Create a new instance.
146    ///
147    /// Application developers should only need to create an `ObjectDescriptor`
148    /// in unit tests.
149    pub fn new<T>(inner: T) -> Self
150    where
151        T: crate::stub::ObjectDescriptor + 'static,
152    {
153        Self {
154            inner: Arc::new(inner),
155        }
156    }
157
158    pub(crate) fn into_parts(self) -> Arc<dyn ObjectDescriptorStub> {
159        self.inner
160    }
161}
162
163#[cfg(test)]
164pub(crate) mod tests {
165    use super::*;
166    use crate::model_ext::ObjectHighlights;
167    use crate::read_object::ReadObjectResponse;
168    use http::{HeaderName, HeaderValue};
169    use mockall::mock;
170    use static_assertions::assert_impl_all;
171
172    #[test]
173    fn impls() {
174        assert_impl_all!(ObjectDescriptor: Clone, std::fmt::Debug);
175    }
176
177    // Verify this can be mocked inside the crate.
178    // TODO(#3838) - support mocking outside the crate too.
179    #[tokio::test]
180    async fn can_be_mocked() -> anyhow::Result<()> {
181        let object = Object::new().set_name("test-object").set_generation(123456);
182        let headers = HeaderMap::from_iter(
183            [
184                ("content-type", "application/octet-stream"),
185                ("x-guploader-uploadid", "abc-123"),
186            ]
187            .map(|(k, v)| (HeaderName::from_static(k), HeaderValue::from_static(v))),
188        );
189        let mut mock = MockDescriptor::new();
190        mock.expect_object().times(1).return_const(object.clone());
191        mock.expect_read_range()
192            .times(1)
193            .withf(|range| range.0 == ReadRange::segment(100, 200).0)
194            .returning(|_| ReadObjectResponse::new(Box::new(MockResponse::new())));
195        mock.expect_headers().times(1).return_const(headers.clone());
196
197        let descriptor = ObjectDescriptor::new(mock);
198        assert_eq!(descriptor.object(), object);
199        assert_eq!(descriptor.headers(), headers);
200
201        let _reader = descriptor.read_range(ReadRange::segment(100, 200)).await;
202        Ok(())
203    }
204
205    mock! {
206        #[derive(Debug)]
207        pub Descriptor {}
208
209        impl crate::stub::ObjectDescriptor for Descriptor {
210            fn object(&self) -> Object;
211            async fn read_range(&self, range: ReadRange) -> ReadObjectResponse;
212            fn headers(&self) -> HeaderMap;
213        }
214    }
215
216    mock! {
217        #[derive(Debug)]
218        pub Response {}
219
220        #[async_trait::async_trait]
221        impl crate::read_object::dynamic::ReadObjectResponse for Response {
222            fn object(&self) -> ObjectHighlights;
223            async fn next(&mut self) -> Option<crate::Result<bytes::Bytes>>;
224        }
225    }
226}