Skip to main content

notedthat_core/
storage.rs

1//! `Storage` trait โ€” object store abstraction.
2
3use crate::conditional::ConditionalHeaders;
4use crate::error::StorageError;
5use crate::kb::{KbManifest, ObjectMeta};
6use crate::object_path::ObjectPath;
7use crate::range::ByteRange;
8use crate::slug::KbSlug;
9use async_trait::async_trait;
10use bytes::Bytes;
11use futures::Stream;
12use std::pin::Pin;
13
14use crate::staging::StagedBody;
15
16/// Ordered chunks returned by a streaming object read.
17pub type ObjectChunkStream = Pin<Box<dyn Stream<Item = Result<Bytes, StorageError>> + Send>>;
18
19/// Metadata and ordered chunks returned without materializing the object.
20pub struct ObjectStream {
21    /// Ordered object body chunks.
22    pub chunks: ObjectChunkStream,
23    /// Associated metadata.
24    pub meta: ObjectMeta,
25    /// Backend `Content-Range` value for range reads.
26    pub content_range: Option<String>,
27}
28
29/// Preconditions and metadata for a server-side object copy.
30#[derive(Clone, Debug, Default, PartialEq, Eq)]
31pub struct CopyObjectOptions {
32    /// Required source `ETag` match when present.
33    pub source_if_match: Option<String>,
34    /// Required destination non-match condition when present.
35    pub destination_if_none_match: Option<String>,
36    /// Content type stored on the destination.
37    pub content_type: Option<String>,
38}
39
40/// The bytes and metadata returned by a GET or HEAD operation.
41pub struct ObjectRead {
42    /// The raw object bytes.
43    pub bytes: Bytes,
44    /// Associated metadata (size, content-type, last-modified).
45    pub meta: ObjectMeta,
46    /// `Content-Range: bytes start-end/total` header value from the backend
47    /// when responding to a range request, or `None` for full-body reads.
48    /// Passed through to HTTP clients on 206 responses.
49    pub content_range: Option<String>,
50}
51
52/// The result of a LIST operation.
53///
54/// # Invariant
55///
56/// `truncated == next_cursor.is_some()`. A response where `truncated=true` MUST supply a
57/// `next_cursor`; a response where `next_cursor=Some(_)` MUST also set `truncated=true`.
58#[derive(Debug)]
59pub struct ListResponse {
60    /// The matching objects, up to the requested `limit`.
61    pub objects: Vec<ObjectMeta>,
62    /// `true` if the backend indicated more objects exist beyond `limit`.
63    pub truncated: bool,
64    /// Opaque backend continuation token. Present exactly when `truncated=true`.
65    ///
66    /// Pass this value unchanged as `cursor` on the next `list_objects` call to retrieve the
67    /// next page. Clients MUST NOT parse, validate, or store this value beyond the immediate
68    /// next request.
69    ///
70    /// What an *invalid* token does is backend-defined and must not be relied on. A backend
71    /// that detects one returns `StorageError::BackendUnavailable`; some S3 implementations
72    /// accept an unrecognised token and answer with a page instead. Since the token is
73    /// opaque and backend-issued, a client has no legitimate reason to send one that did
74    /// not come from this API.
75    pub next_cursor: Option<String>,
76}
77
78/// Return value from [`Storage::put_object`]. Carries the `ETag` of the stored object.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct PutOutcome {
81    /// `ETag` from the backend (opaque, quoted per RFC 7232 ยง2.3), or `None` if not returned.
82    pub etag: Option<String>,
83}
84
85/// The storage abstraction shared by all `NotedThat` components.
86///
87/// Implementations include `notedthat_storage_s3::S3Storage` (production)
88/// and `notedthat_api_http::testing::InMemoryStorage` (tests).
89///
90/// # Object safety
91///
92/// This trait is designed to be used as `Arc<dyn Storage>` from axum handlers.
93/// All methods take `&self` (not `&mut self`) to allow sharing across threads.
94#[async_trait]
95pub trait Storage: Send + Sync {
96    /// Idempotently create the S3 bucket for the given KB.
97    ///
98    /// Returns `Ok(())` if the bucket already exists (owned by this account).
99    async fn ensure_bucket(&self, kb: &KbSlug) -> Result<(), StorageError>;
100
101    /// Read the KB manifest from `.notedthat/manifest.json` in the KB's bucket.
102    ///
103    /// Returns `Err(StorageError::NotFound)` if no manifest exists yet.
104    async fn read_manifest(&self, kb: &KbSlug) -> Result<KbManifest, StorageError>;
105
106    /// Write (overwrite) the KB manifest in the KB's bucket.
107    async fn write_manifest(&self, kb: &KbSlug, manifest: &KbManifest) -> Result<(), StorageError>;
108
109    /// Return metadata for an object without fetching its body.
110    ///
111    /// `conditionals` carries raw HTTP conditional headers for the backend to evaluate.
112    /// Returns `Err(StorageError::NotFound)` if the object does not exist.
113    async fn head_object(
114        &self,
115        kb: &KbSlug,
116        path: &ObjectPath,
117        conditionals: ConditionalHeaders,
118    ) -> Result<ObjectMeta, StorageError>;
119
120    /// Fetch an object's bytes and metadata.
121    ///
122    /// `range` carries parsed byte ranges for the backend, and `conditionals`
123    /// carries raw HTTP conditional headers for the backend to evaluate.
124    /// Returns `Err(StorageError::NotFound)` if the object does not exist.
125    async fn get_object(
126        &self,
127        kb: &KbSlug,
128        path: &ObjectPath,
129        range: Option<Vec<ByteRange>>,
130        conditionals: ConditionalHeaders,
131    ) -> Result<ObjectRead, StorageError>;
132
133    /// Fetch metadata and an ordered body stream without whole-object buffering.
134    async fn get_object_stream(
135        &self,
136        kb: &KbSlug,
137        path: &ObjectPath,
138        range: Option<Vec<ByteRange>>,
139        conditionals: ConditionalHeaders,
140    ) -> Result<ObjectStream, StorageError>;
141
142    /// Store an object, overwriting any existing object at the same path.
143    ///
144    /// The `content_type` is stored with the object and echoed on GET/HEAD.
145    /// `conditionals` carries raw HTTP conditional headers for the backend to evaluate.
146    async fn put_object(
147        &self,
148        kb: &KbSlug,
149        path: &ObjectPath,
150        bytes: Bytes,
151        content_type: Option<&str>,
152        conditionals: ConditionalHeaders,
153    ) -> Result<PutOutcome, StorageError>;
154
155    /// Store an owned staged body without loading file-backed bodies into memory.
156    async fn put_staged_object(
157        &self,
158        kb: &KbSlug,
159        path: &ObjectPath,
160        body: StagedBody,
161        content_type: Option<&str>,
162        conditionals: ConditionalHeaders,
163    ) -> Result<PutOutcome, StorageError>;
164
165    /// Copy an object within one KB using backend-native conditional copy.
166    async fn copy_object(
167        &self,
168        kb: &KbSlug,
169        source: &ObjectPath,
170        destination: &ObjectPath,
171        options: CopyObjectOptions,
172    ) -> Result<PutOutcome, StorageError>;
173
174    /// Delete an object.
175    ///
176    /// `conditionals` carries raw HTTP conditional headers for the backend to evaluate.
177    /// This operation is **idempotent** โ€” deleting a non-existent object returns
178    /// `Ok(())` (matching S3 semantics per Metis directive).
179    async fn delete_object(
180        &self,
181        kb: &KbSlug,
182        path: &ObjectPath,
183        conditionals: ConditionalHeaders,
184    ) -> Result<(), StorageError>;
185
186    /// List objects in the KB, optionally filtered by a prefix.
187    ///
188    /// Results are capped at `limit` (default 100, max 1000).
189    ///
190    /// Pass `cursor = None` on the first call. On subsequent calls, pass the opaque
191    /// `next_cursor` value from the previous [`ListResponse`] unchanged. What an invalid
192    /// cursor does is backend-defined โ€” see [`ListResponse::next_cursor`].
193    ///
194    /// # Invariant
195    ///
196    /// Every returned `ListResponse` satisfies `truncated == next_cursor.is_some()`.
197    async fn list_objects(
198        &self,
199        kb: &KbSlug,
200        prefix: Option<&str>,
201        limit: u32,
202        cursor: Option<&str>,
203    ) -> Result<ListResponse, StorageError>;
204}
205
206#[cfg(test)]
207mod tests {
208    fn assert_send_sync<T: Send + Sync + ?Sized>() {}
209
210    #[test]
211    fn storage_is_dyn_compatible_and_send_sync() {
212        assert_send_sync::<dyn crate::storage::Storage>();
213    }
214}