mito2/manifest/storage/
staging.rs1use common_telemetry::debug;
16use object_store::{ObjectStore, util};
17use snafu::ResultExt;
18
19use crate::error::{OpenDalSnafu, Result};
20use crate::manifest::storage::utils::write_and_put_cache;
21
22#[derive(Debug, Clone)]
28pub(crate) struct StagingBlobStorage {
29 object_store: ObjectStore,
30 path: String,
31}
32
33pub fn staging_blob_path(manifest_path: &str) -> String {
39 let parent_dir = manifest_path
40 .trim_end_matches("manifest/")
41 .trim_end_matches('/');
42 util::normalize_dir(&format!("{}/staging/blob", parent_dir))
43}
44
45impl StagingBlobStorage {
46 pub fn new(path: String, object_store: ObjectStore) -> Self {
47 let path = util::normalize_dir(&path);
48 common_telemetry::debug!(
49 "Staging blob storage path: {}, root: {}",
50 path,
51 object_store.info().root()
52 );
53 Self { object_store, path }
54 }
55
56 pub fn path(&self) -> &str {
58 &self.path
59 }
60
61 pub fn object_store(&self) -> &ObjectStore {
63 &self.object_store
64 }
65
66 pub async fn put(&self, path: &str, bytes: Vec<u8>) -> Result<()> {
68 let path = format!("{}{}", self.path, path);
69 common_telemetry::debug!(
70 "Putting blob to staging blob storage, path: {}, root: {}, bytes: {}",
71 path,
72 self.object_store.info().root(),
73 bytes.len()
74 );
75 write_and_put_cache(&self.object_store, None, &path, bytes).await?;
76 Ok(())
77 }
78
79 pub async fn get(&self, path: &str) -> Result<Vec<u8>> {
81 let path = format!("{}{}", self.path, path);
82 common_telemetry::debug!(
83 "Reading blob from staging blob storage, path: {}, root: {}",
84 path,
85 self.object_store.info().root()
86 );
87 let bytes = self.object_store.read(&path).await.context(OpenDalSnafu)?;
88
89 Ok(bytes.to_vec())
90 }
91}
92
93#[derive(Debug, Clone)]
100pub(crate) struct StagingStorage {
101 object_store: ObjectStore,
102 manifest_path: String,
103 blob_storage: StagingBlobStorage,
104}
105
106pub fn staging_manifest_path(manifest_path: &str) -> String {
112 let parent_dir = manifest_path
113 .trim_end_matches("manifest/")
114 .trim_end_matches('/');
115 util::normalize_dir(&format!("{}/staging/manifest", parent_dir))
116}
117
118impl StagingStorage {
119 pub fn new(path: String, object_store: ObjectStore) -> Self {
120 let blob_storage = StagingBlobStorage::new(staging_blob_path(&path), object_store.clone());
121
122 Self {
123 object_store,
124 manifest_path: staging_manifest_path(&path),
125 blob_storage,
126 }
127 }
128
129 pub(crate) fn blob_storage(&self) -> &StagingBlobStorage {
131 &self.blob_storage
132 }
133
134 pub(crate) async fn clear(&self) -> Result<()> {
136 self.object_store
137 .delete_with(&self.manifest_path)
138 .recursive(true)
139 .await
140 .context(OpenDalSnafu)?;
141
142 self.blob_storage
143 .object_store()
144 .delete_with(self.blob_storage.path())
145 .recursive(true)
146 .await
147 .context(OpenDalSnafu)?;
148
149 debug!(
150 "Cleared all staging manifest files from {}, blob directory: {}",
151 self.manifest_path,
152 self.blob_storage.path()
153 );
154
155 Ok(())
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use std::sync::{Arc, Mutex};
162
163 use common_test_util::temp_dir::create_temp_dir;
164 use futures::TryStreamExt;
165 use object_store::layers::mock::{MockLayerBuilder, ObservedWriter, WriterObservations, oio};
166 use object_store::services::Fs;
167 use object_store::{ErrorKind, ObjectStore};
168
169 use super::{StagingBlobStorage, StagingStorage, staging_blob_path, staging_manifest_path};
170
171 const WRITE_LIMIT: usize = 64 * 1024 * 1024;
173
174 struct LimitedWriter {
175 inner: oio::Writer,
176 }
177
178 impl oio::Write for LimitedWriter {
179 async fn write(&mut self, bytes: object_store::Buffer) -> object_store::Result<()> {
180 if bytes.len() > WRITE_LIMIT {
181 return Err(object_store::Error::new(
182 ErrorKind::Unexpected,
183 "test write size limit exceeded",
184 ));
185 }
186 self.inner.write(bytes).await
187 }
188
189 async fn close(&mut self) -> object_store::Result<object_store::layers::mock::Metadata> {
190 self.inner.close().await
191 }
192
193 async fn abort(&mut self) -> object_store::Result<()> {
194 self.inner.abort().await
195 }
196 }
197
198 #[tokio::test]
199 async fn test_staging_blob_put_chunked() {
200 let tmp_dir = create_temp_dir("test_staging_blob_put_chunked");
201 let observations = Arc::new(Mutex::new(WriterObservations::default()));
202 let captured = observations.clone();
203 let layer = MockLayerBuilder::default()
204 .writer_factory(Arc::new(move |_, _, inner| {
205 Box::new(ObservedWriter::new(
206 Box::new(LimitedWriter { inner }),
207 captured.clone(),
208 ))
209 }))
210 .build()
211 .unwrap();
212 let store = ObjectStore::new(Fs::default().root(&tmp_dir.path().to_string_lossy()))
213 .unwrap()
214 .layer(layer);
215 let storage = StagingBlobStorage::new("staging/blob/".to_string(), store);
216
217 for size in [17, WRITE_LIMIT, WRITE_LIMIT + 17] {
218 let bytes = (0..size).map(|i| (i % 251) as u8).collect::<Vec<_>>();
219 *observations.lock().unwrap() = WriterObservations::default();
220 storage.put("manifest", bytes.clone()).await.unwrap();
221 assert_eq!(storage.get("manifest").await.unwrap(), bytes);
222 let observed = observations.lock().unwrap();
223 assert_eq!(observed.write_sizes.iter().sum::<usize>(), size);
224 assert!(observed.write_sizes.iter().all(|size| *size <= WRITE_LIMIT));
225 assert_eq!(observed.write_sizes.len(), size.div_ceil(WRITE_LIMIT));
226 assert_eq!(observed.close_calls, 1);
227 }
228 }
229
230 #[test]
231 fn test_staging_path() {
232 let path = "/data/table/region_0001/manifest/";
233 let expected = "/data/table/region_0001/staging/manifest/";
234 assert_eq!(staging_manifest_path(path), expected);
235 }
236
237 #[test]
238 fn test_staging_blob_path() {
239 let path = "/data/table/region_0001/manifest/";
240 let expected = "/data/table/region_0001/staging/blob/";
241 assert_eq!(staging_blob_path(path), expected);
242 }
243
244 async fn count_entries(object_store: &ObjectStore, path: &str) -> usize {
245 match object_store.lister_with(path).await {
246 Ok(lister) => lister.try_collect::<Vec<_>>().await.unwrap().len(),
247 Err(err) if err.kind() == ErrorKind::NotFound => 0,
248 Err(err) => panic!("failed to list {path}: {err}"),
249 }
250 }
251
252 #[tokio::test]
253 async fn test_staging_clear_removes_blobs() {
254 common_telemetry::init_default_ut_logging();
255
256 let tmp_dir = create_temp_dir("test_staging_storage_clear");
257 let builder = Fs::default().root(&tmp_dir.path().to_string_lossy());
258 let object_store = ObjectStore::new(builder).unwrap();
259 let manifest_path = "/data/table/region_0001/manifest/";
260 let storage = StagingStorage::new(manifest_path.to_string(), object_store.clone());
261 let manifest_dir = staging_manifest_path(manifest_path);
262 let blob_dir = staging_blob_path(manifest_path);
263
264 object_store
266 .write(
267 &format!("{manifest_dir}00000000000000000000.json"),
268 b"manifest".to_vec(),
269 )
270 .await
271 .unwrap();
272 storage
273 .blob_storage()
274 .put("region_0002_manifest", b"blob".to_vec())
275 .await
276 .unwrap();
277
278 assert!(count_entries(&object_store, &manifest_dir).await > 0);
279 assert!(count_entries(&object_store, &blob_dir).await > 0);
280
281 storage.clear().await.unwrap();
282
283 assert_eq!(count_entries(&object_store, &manifest_dir).await, 0);
284 assert_eq!(count_entries(&object_store, &blob_dir).await, 0);
285 }
286}