Skip to main content

qubit_fs/read/
async_random_access_reader.rs

1// =============================================================================
2//    Copyright (c) 2025 - 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8
9//! Application-facing asynchronous handle for bounded offset reads.
10use std::fmt::Debug;
11use std::fmt::Formatter;
12use std::fmt::Result as FmtResult;
13use std::pin::Pin;
14
15use crate::error::FsError;
16use crate::error::FsErrorKind;
17use crate::error::FsOperation;
18use crate::error::FsResult;
19use crate::metadata::FileSystemLimit;
20use crate::metadata::OpenedFileInfo;
21use crate::read::RandomAccessReadPolicy;
22use crate::spi::AsyncRandomAccessReadSession;
23
24/// An async random-access session bound to one opened object.
25///
26/// # Examples
27///
28/// This small example assumes each requested window fits the configured
29/// `max_read_range_bytes`; a larger single `read_at` request returns
30/// `ResourceLimitExceeded`. See the user guide for a fixture-backed helper
31/// that splits a larger sample across bounded reads.
32///
33/// ```rust
34/// use qubit_fs::{AsyncFileSystem, Path};
35/// use qubit_fs::read::ReadOptions;
36///
37/// async fn sample(filesystem: &AsyncFileSystem, path: &Path) -> Result<Vec<u8>, qubit_fs::FsError> {
38///     let mut reader = filesystem.open_random_access_reader(path, ReadOptions::default()).await?;
39///     let mut bytes = [0; 16];
40///     let mut filled = 0;
41///     while filled < bytes.len() {
42///         match reader.read_at(filled as u64, &mut bytes[filled..]).await? {
43///             0 => break,
44///             count => filled += count,
45///         }
46///     }
47///     Ok(bytes[..filled].to_vec())
48/// }
49/// ```
50///
51/// A short read is allowed. If a call returns `Err` or its future is dropped,
52/// the output may contain partial bytes; discard the incomplete sample. The
53/// cached length is not a content snapshot.
54pub struct AsyncRandomAccessReader {
55    /// Identity and metadata captured when the object was opened.
56    info: OpenedFileInfo,
57    /// Open-time readable upper bound; this is not a content snapshot.
58    len: u64,
59    /// Maximum size of one request after clipping to `len`.
60    limit: FileSystemLimit,
61    /// Provider identifier added to read errors for context.
62    provider_id: String,
63    /// Pinned session retaining ownership of the already opened object.
64    session: Pin<Box<dyn AsyncRandomAccessReadSession>>,
65}
66impl AsyncRandomAccessReader {
67    /// Builds a reader from the validated result of a provider open and pins
68    /// its session for the lifetime of the reader.
69    ///
70    /// # Parameters
71    /// - `info`: File identity and metadata captured at open time.
72    /// - `len`: Readable upper bound captured at open time.
73    /// - `limit`: Maximum size of each clipped provider request.
74    /// - `provider_id`: Provider identity included in read errors.
75    /// - `session`: Provider session owning the already-open object; it is
76    ///   pinned for the lifetime of the reader.
77    ///
78    /// # Returns
79    /// A reader that retains the open object and applies the supplied bound
80    /// and request limit.
81    pub(crate) fn new(
82        info: OpenedFileInfo,
83        len: u64,
84        limit: FileSystemLimit,
85        provider_id: String,
86        session: Box<dyn AsyncRandomAccessReadSession>,
87    ) -> Self {
88        Self {
89            info,
90            len,
91            limit,
92            provider_id,
93            session: Box::into_pin(session),
94        }
95    }
96    /// Returns the identity and metadata captured at open time.
97    #[inline]
98    #[must_use]
99    pub fn info(&self) -> &OpenedFileInfo {
100        &self.info
101    }
102    /// Returns the open-time readable upper bound.
103    ///
104    /// This bound does not change if the object grows and does not make the
105    /// object's contents a snapshot.
106    #[inline]
107    #[must_use]
108    pub fn len(&self) -> u64 {
109        self.len
110    }
111    /// Returns whether the open-time length is zero.
112    #[inline]
113    #[must_use]
114    pub fn is_empty(&self) -> bool {
115        self.len == 0
116    }
117    /// Reads into caller storage at an explicit offset; cancellation does not
118    /// change session identity.
119    ///
120    /// # Parameters
121    /// - `offset`: Byte offset from the beginning of the opened object.
122    /// - `output`: Caller-owned destination buffer borrowed until the future
123    ///   completes or is dropped.
124    ///
125    /// # Returns
126    /// Returns the number of bytes read. An empty output buffer returns zero
127    /// without observing EOF. A non-overflowing request at or beyond the
128    /// open-time length also returns zero without provider I/O. For a non-empty
129    /// request within that bound, a provider result of zero indicates EOF
130    /// observed by that request. A positive count may be shorter than the
131    /// clipped request.
132    ///
133    /// # Errors
134    /// Returns `InvalidOptions` for an overflowing offset range,
135    /// `ResourceLimitExceeded` when the clipped request exceeds the provider
136    /// limit, a provider error with path/provider/source context, or
137    /// `ProviderContractViolation` when the provider over-reports bytes. The
138    /// buffer may contain partial bytes after an error or cancellation and
139    /// must be discarded. Provider-supplied path and provider context is
140    /// preserved; missing fields are filled from this session. The operation
141    /// is reported as `Read`.
142    pub async fn read_at(&mut self, offset: u64, output: &mut [u8]) -> FsResult<usize> {
143        let count = RandomAccessReadPolicy::validate_read(offset, output.len(), self.len, self.limit)
144            .map_err(|e| e.with_path(self.info.path().clone()).with_provider(&self.provider_id))?;
145        if count == 0 {
146            return Ok(0);
147        }
148        let n = self
149            .session
150            .as_mut()
151            .read_at_async(offset, &mut output[..count])
152            .await
153            .map_err(|e| {
154                e.with_missing_context(self.info.path(), None, &self.provider_id)
155                    .with_operation(FsOperation::Read)
156            })?;
157        if n > count {
158            return Err(FsError::new(
159                FsErrorKind::ProviderContractViolation,
160                FsOperation::Read,
161                "provider returned more bytes than supplied buffer",
162            )
163            .with_path(self.info.path().clone())
164            .with_provider(&self.provider_id));
165        }
166        Ok(n)
167    }
168}
169impl Debug for AsyncRandomAccessReader {
170    /// Formats the open-time information and length without exposing the
171    /// provider session.
172    ///
173    /// # Parameters
174    /// - `f`: Destination for the debug representation.
175    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
176        f.debug_struct("AsyncRandomAccessReader")
177            .field("info", &self.info)
178            .field("len", &self.len)
179            .finish_non_exhaustive()
180    }
181}