1#![forbid(unsafe_code)]
8
9use std::{fmt, sync::Arc};
10
11use bytes::Bytes;
12use futures_util::TryStreamExt;
13use object_store::{ObjectStore, PutMode, PutOptions, gcp::GoogleCloudStorageBuilder, path::Path};
14use thiserror::Error;
15
16#[derive(Clone, Debug, Eq, Error, PartialEq)]
17pub enum BucketError {
18 #[error("record path must be relative, non-empty, and contain no empty, '.' or '..' segments")]
19 InvalidPath,
20 #[error("record already exists at {path}")]
21 AlreadyExists { path: String },
22 #[error("object store {operation} failed: {message}")]
23 Store {
24 operation: &'static str,
25 message: String,
26 },
27}
28
29#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
30pub struct RecordPath(String);
31
32impl RecordPath {
33 pub fn new(value: impl Into<String>) -> Result<Self, BucketError> {
34 let value = value.into();
35 if value.is_empty()
36 || value.starts_with('/')
37 || value.ends_with('/')
38 || value
39 .split('/')
40 .any(|segment| segment.is_empty() || segment == "." || segment == "..")
41 {
42 return Err(BucketError::InvalidPath);
43 }
44 Ok(Self(value))
45 }
46
47 #[must_use]
48 pub fn as_str(&self) -> &str {
49 &self.0
50 }
51
52 fn object_path(&self) -> Path {
53 Path::from(self.0.clone())
54 }
55}
56
57impl fmt::Display for RecordPath {
58 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
59 formatter.write_str(&self.0)
60 }
61}
62
63#[derive(Clone, Debug)]
64pub struct BucketClient {
65 store: Arc<dyn ObjectStore>,
66}
67
68impl BucketClient {
69 #[must_use]
70 pub fn from_store(store: Arc<dyn ObjectStore>) -> Self {
71 Self { store }
72 }
73
74 pub async fn create(&self, path: &RecordPath, content: Bytes) -> Result<(), BucketError> {
75 let options = PutOptions {
76 mode: PutMode::Create,
77 ..PutOptions::default()
78 };
79 self.store
80 .put_opts(&path.object_path(), content.into(), options)
81 .await
82 .map(drop)
83 .map_err(|error| match error {
84 object_store::Error::AlreadyExists { .. } => BucketError::AlreadyExists {
85 path: path.to_string(),
86 },
87 other => store_error("create", other),
88 })
89 }
90
91 pub async fn get(&self, path: &RecordPath) -> Result<Bytes, BucketError> {
92 self.store
93 .get(&path.object_path())
94 .await
95 .map_err(|error| store_error("get", error))?
96 .bytes()
97 .await
98 .map_err(|error| store_error("read", error))
99 }
100
101 pub async fn list(&self, prefix: &RecordPath) -> Result<Vec<RecordPath>, BucketError> {
102 let mut entries = self
103 .store
104 .list(Some(&prefix.object_path()))
105 .map_ok(|metadata| metadata.location.to_string())
106 .try_collect::<Vec<_>>()
107 .await
108 .map_err(|error| store_error("list", error))?;
109 entries.sort();
110 entries
111 .into_iter()
112 .map(RecordPath::new)
113 .collect::<Result<Vec<_>, _>>()
114 }
115}
116
117pub fn from_gcs_env(bucket_name: &str) -> Result<BucketClient, BucketError> {
118 let store = GoogleCloudStorageBuilder::from_env()
119 .with_bucket_name(bucket_name)
120 .build()
121 .map_err(|error| store_error("construct Google Cloud Storage client", error))?;
122 Ok(BucketClient::from_store(Arc::new(store)))
123}
124
125fn store_error(operation: &'static str, error: impl fmt::Display) -> BucketError {
126 BucketError::Store {
127 operation,
128 message: error.to_string(),
129 }
130}
131
132#[cfg(test)]
133mod tests {
134 use std::sync::Arc;
135
136 use bytes::Bytes;
137 use object_store::memory::InMemory;
138
139 use super::{BucketClient, BucketError, RecordPath};
140
141 #[test]
142 fn path_refuses_addresses_that_are_not_prefix_safe() {
143 assert_eq!(RecordPath::new("../record"), Err(BucketError::InvalidPath));
144 assert_eq!(RecordPath::new("/record"), Err(BucketError::InvalidPath));
145 assert_eq!(RecordPath::new("record/"), Err(BucketError::InvalidPath));
146 }
147
148 #[tokio::test]
149 async fn records_are_create_only_and_read_through_the_same_path() {
150 let client = BucketClient::from_store(Arc::new(InMemory::new()));
151 let path = RecordPath::new("sessions/2026/08/24/session.v1.json").expect("path");
152 client
153 .create(&path, Bytes::from_static(b"first"))
154 .await
155 .expect("create");
156 assert_eq!(
157 client.get(&path).await.expect("get"),
158 Bytes::from_static(b"first")
159 );
160 assert_eq!(
161 client.create(&path, Bytes::from_static(b"second")).await,
162 Err(BucketError::AlreadyExists {
163 path: path.to_string()
164 })
165 );
166 }
167
168 #[tokio::test]
169 async fn listing_is_sorted_and_limited_to_the_requested_prefix() {
170 let client = BucketClient::from_store(Arc::new(InMemory::new()));
171 for path in [
172 "sessions/2026/08/24/b.v1.json",
173 "sessions/2026/08/24/a.v1.json",
174 "sessions/2026/08/25/c.v1.json",
175 ] {
176 client
177 .create(&RecordPath::new(path).expect("path"), Bytes::new())
178 .await
179 .expect("create");
180 }
181 let prefix = RecordPath::new("sessions/2026/08/24").expect("prefix");
182 let listed = client.list(&prefix).await.expect("list");
183 assert_eq!(
184 listed.iter().map(RecordPath::as_str).collect::<Vec<_>>(),
185 [
186 "sessions/2026/08/24/a.v1.json",
187 "sessions/2026/08/24/b.v1.json"
188 ]
189 );
190 }
191}