Skip to main content

risingwave_object_store/object/
mem.rs

1// Copyright 2022 RisingWave Labs
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//     http://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
15use std::collections::{HashMap, VecDeque};
16use std::pin::Pin;
17use std::sync::{Arc, LazyLock};
18use std::task::{Context, Poll};
19use std::time::{SystemTime, UNIX_EPOCH};
20
21use bytes::{BufMut, Bytes, BytesMut};
22use fail::fail_point;
23use futures::Stream;
24use itertools::Itertools;
25use risingwave_common::range::RangeBoundsExt;
26use thiserror::Error;
27use tokio::sync::Mutex;
28
29use super::{
30    ObjectError, ObjectMetadata, ObjectRangeBounds, ObjectResult, ObjectStore, StreamingUploader,
31};
32use crate::object::{ObjectDataStream, ObjectMetadataIter};
33
34#[derive(Error, Debug)]
35pub enum Error {
36    #[error("NotFound error: {0}")]
37    NotFound(String),
38    #[error("Other error: {0}")]
39    Other(String),
40}
41
42impl Error {
43    pub fn is_object_not_found_error(&self) -> bool {
44        matches!(self, Error::NotFound(_))
45    }
46}
47
48impl Error {
49    fn not_found(msg: impl ToString) -> Self {
50        Error::NotFound(msg.to_string())
51    }
52
53    fn other(msg: impl ToString) -> Self {
54        Error::Other(msg.to_string())
55    }
56}
57
58/// Store multiple parts in a map, and concatenate them on finish.
59pub struct InMemStreamingUploader {
60    path: String,
61    buf: BytesMut,
62    objects: Arc<Mutex<HashMap<String, (ObjectMetadata, Bytes)>>>,
63}
64
65impl StreamingUploader for InMemStreamingUploader {
66    async fn write_bytes(&mut self, data: Bytes) -> ObjectResult<()> {
67        fail_point!("mem_write_bytes_err", |_| Err(ObjectError::internal(
68            "mem write bytes error"
69        )));
70        self.buf.put(data);
71        Ok(())
72    }
73
74    async fn finish(self) -> ObjectResult<()> {
75        fail_point!("mem_finish_streaming_upload_err", |_| Err(
76            ObjectError::internal("mem finish streaming upload error")
77        ));
78        let obj = self.buf.freeze();
79        if obj.is_empty() {
80            Err(Error::other("upload empty object").into())
81        } else {
82            let metadata = get_obj_meta(&self.path, &obj)?;
83            self.objects.lock().await.insert(self.path, (metadata, obj));
84            Ok(())
85        }
86    }
87
88    fn get_memory_usage(&self) -> u64 {
89        self.buf.capacity() as u64
90    }
91}
92
93/// In-memory object storage, useful for testing.
94#[derive(Default, Clone)]
95pub struct InMemObjectStore {
96    objects: Arc<Mutex<HashMap<String, (ObjectMetadata, Bytes)>>>,
97}
98
99#[async_trait::async_trait]
100impl ObjectStore for InMemObjectStore {
101    type StreamingUploader = InMemStreamingUploader;
102
103    fn get_object_prefix(&self, _obj_id: u64, _use_new_object_prefix_strategy: bool) -> String {
104        String::default()
105    }
106
107    async fn upload(&self, path: &str, obj: Bytes) -> ObjectResult<()> {
108        fail_point!("mem_upload_err", |_| Err(ObjectError::internal(
109            "mem upload error"
110        )));
111        if obj.is_empty() {
112            Err(Error::other("upload empty object").into())
113        } else {
114            let metadata = get_obj_meta(path, &obj)?;
115            self.objects
116                .lock()
117                .await
118                .insert(path.into(), (metadata, obj));
119            Ok(())
120        }
121    }
122
123    async fn streaming_upload(&self, path: &str) -> ObjectResult<Self::StreamingUploader> {
124        Ok(InMemStreamingUploader {
125            path: path.to_owned(),
126            buf: BytesMut::new(),
127            objects: self.objects.clone(),
128        })
129    }
130
131    async fn read(&self, path: &str, range: impl ObjectRangeBounds) -> ObjectResult<Bytes> {
132        fail_point!("mem_read_err", |_| Err(ObjectError::internal(
133            "mem read error"
134        )));
135        self.get_object(path, range).await
136    }
137
138    /// Returns a stream reading the object specified in `path`. If given, the stream starts at the
139    /// byte with index `start_pos` (0-based). As far as possible, the stream only loads the amount
140    /// of data into memory that is read from the stream.
141    async fn streaming_read(
142        &self,
143        path: &str,
144        read_range: impl ObjectRangeBounds,
145    ) -> ObjectResult<ObjectDataStream> {
146        fail_point!("mem_streaming_read_err", |_| Err(ObjectError::internal(
147            "mem streaming read error"
148        )));
149        let bytes = self.get_object(path, read_range).await?;
150
151        Ok(Box::pin(InMemDataIterator::new(bytes)))
152    }
153
154    async fn metadata(&self, path: &str) -> ObjectResult<ObjectMetadata> {
155        self.objects
156            .lock()
157            .await
158            .get(path)
159            .map(|(metadata, _)| metadata)
160            .cloned()
161            .ok_or_else(|| Error::not_found(format!("no object at path '{}'", path)).into())
162    }
163
164    async fn delete(&self, path: &str) -> ObjectResult<()> {
165        fail_point!("mem_delete_err", |_| Err(ObjectError::internal(
166            "mem delete error"
167        )));
168        self.objects.lock().await.remove(path);
169        Ok(())
170    }
171
172    /// Deletes the objects with the given paths permanently from the storage. If an object
173    /// specified in the request is not found, it will be considered as successfully deleted.
174    async fn delete_objects(&self, paths: &[String]) -> ObjectResult<()> {
175        let mut guard = self.objects.lock().await;
176
177        for path in paths {
178            guard.remove(path);
179        }
180
181        Ok(())
182    }
183
184    async fn list(&self, prefix: &str) -> ObjectResult<ObjectMetadataIter> {
185        let list_result = self
186            .objects
187            .lock()
188            .await
189            .iter()
190            .filter_map(|(path, (metadata, _))| {
191                if path.starts_with(prefix) {
192                    return Some(metadata.clone());
193                }
194                None
195            })
196            .sorted_by(|a, b| Ord::cmp(&a.key, &b.key))
197            .collect_vec();
198        Ok(Box::pin(InMemObjectIter::new(list_result)))
199    }
200
201    fn store_media_type(&self) -> &'static str {
202        "mem"
203    }
204}
205
206pub struct InMemDataIterator {
207    data: Bytes,
208    offset: usize,
209}
210
211impl InMemDataIterator {
212    pub fn new(data: Bytes) -> Self {
213        Self { data, offset: 0 }
214    }
215}
216
217impl Stream for InMemDataIterator {
218    type Item = ObjectResult<Bytes>;
219
220    fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
221        const MAX_PACKET_SIZE: usize = 128 * 1024;
222        if self.offset >= self.data.len() {
223            return Poll::Ready(None);
224        }
225        let read_len = std::cmp::min(self.data.len() - self.offset, MAX_PACKET_SIZE);
226        let data = self.data.slice(self.offset..(self.offset + read_len));
227        self.offset += read_len;
228        Poll::Ready(Some(Ok(data)))
229    }
230}
231
232static SHARED: LazyLock<spin::Mutex<InMemObjectStore>> =
233    LazyLock::new(|| spin::Mutex::new(InMemObjectStore::new()));
234
235impl InMemObjectStore {
236    fn new() -> Self {
237        Self {
238            objects: Arc::new(Mutex::new(HashMap::new())),
239        }
240    }
241
242    /// Create a new in-memory object store for testing, isolated with others.
243    pub fn for_test() -> Self {
244        Self::new()
245    }
246
247    /// Get a reference to the in-memory object store shared in this process.
248    ///
249    /// Note: Should only be used for `risedev playground`, when there're multiple compute-nodes or
250    /// compactors in the same process.
251    pub(super) fn shared() -> Self {
252        SHARED.lock().clone()
253    }
254
255    /// Reset the shared in-memory object store.
256    pub fn reset_shared() {
257        *SHARED.lock() = InMemObjectStore::new();
258    }
259
260    async fn get_object(&self, path: &str, range: impl ObjectRangeBounds) -> ObjectResult<Bytes> {
261        let objects = self.objects.lock().await;
262
263        let obj = objects
264            .get(path)
265            .map(|(_, obj)| obj)
266            .ok_or_else(|| Error::not_found(format!("no object at path '{}'", path)))?;
267
268        if let Some(end) = range.end()
269            && end > obj.len()
270        {
271            return Err(Error::other("bad block offset and size").into());
272        }
273
274        Ok(obj.slice(range))
275    }
276}
277
278fn get_obj_meta(path: &str, obj: &Bytes) -> ObjectResult<ObjectMetadata> {
279    Ok(ObjectMetadata {
280        key: path.to_owned(),
281        last_modified: SystemTime::now()
282            .duration_since(UNIX_EPOCH)
283            .map_err(ObjectError::internal)?
284            .as_secs_f64(),
285        total_size: obj.len(),
286    })
287}
288
289struct InMemObjectIter {
290    list_result: VecDeque<ObjectMetadata>,
291}
292
293impl InMemObjectIter {
294    fn new(list_result: Vec<ObjectMetadata>) -> Self {
295        Self {
296            list_result: list_result.into(),
297        }
298    }
299}
300
301impl Stream for InMemObjectIter {
302    type Item = ObjectResult<ObjectMetadata>;
303
304    fn poll_next(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
305        if let Some(i) = self.list_result.pop_front() {
306            return Poll::Ready(Some(Ok(i)));
307        }
308        Poll::Ready(None)
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use futures::TryStreamExt;
315    use itertools::enumerate;
316
317    use super::*;
318
319    #[tokio::test]
320    async fn test_upload() {
321        let block = Bytes::from("123456");
322
323        let s3 = InMemObjectStore::for_test();
324        s3.upload("/abc", block).await.unwrap();
325
326        // No such object.
327        let err = s3.read("/ab", 0..3).await.unwrap_err();
328        assert!(err.is_object_not_found_error());
329
330        let bytes = s3.read("/abc", 4..6).await.unwrap();
331        assert_eq!(String::from_utf8(bytes.to_vec()).unwrap(), "56".to_owned());
332
333        // Overflow.
334        s3.read("/abc", 4..8).await.unwrap_err();
335
336        s3.delete("/abc").await.unwrap();
337
338        // No such object.
339        s3.read("/abc", 0..3).await.unwrap_err();
340    }
341
342    #[tokio::test]
343    async fn test_streaming_upload() {
344        let blocks = vec![Bytes::from("123"), Bytes::from("456"), Bytes::from("789")];
345        let obj = Bytes::from("123456789");
346
347        let store = InMemObjectStore::for_test();
348        let mut uploader = store.streaming_upload("/abc").await.unwrap();
349
350        for block in blocks {
351            uploader.write_bytes(block).await.unwrap();
352        }
353        uploader.finish().await.unwrap();
354
355        // Read whole object.
356        let read_obj = store.read("/abc", ..).await.unwrap();
357        assert!(read_obj.eq(&obj));
358
359        // Read part of the object.
360        let read_obj = store.read("/abc", 4..6).await.unwrap();
361        assert_eq!(
362            String::from_utf8(read_obj.to_vec()).unwrap(),
363            "56".to_owned()
364        );
365    }
366
367    #[tokio::test]
368    async fn test_metadata() {
369        let block = Bytes::from("123456");
370
371        let obj_store = InMemObjectStore::for_test();
372        obj_store.upload("/abc", block).await.unwrap();
373
374        let err = obj_store.metadata("/not_exist").await.unwrap_err();
375        assert!(err.is_object_not_found_error());
376
377        let metadata = obj_store.metadata("/abc").await.unwrap();
378        assert_eq!(metadata.total_size, 6);
379    }
380
381    async fn list_all(prefix: &str, store: &InMemObjectStore) -> Vec<ObjectMetadata> {
382        store
383            .list(prefix)
384            .await
385            .unwrap()
386            .try_collect::<Vec<_>>()
387            .await
388            .unwrap()
389    }
390
391    #[tokio::test]
392    async fn test_list() {
393        let payload = Bytes::from("123456");
394        let store = InMemObjectStore::for_test();
395        assert!(list_all("", &store).await.is_empty());
396
397        let paths = vec!["001/002/test.obj", "001/003/test.obj"];
398        for (i, path) in enumerate(paths.clone()) {
399            assert_eq!(list_all("", &store).await.len(), i);
400            store.upload(path, payload.clone()).await.unwrap();
401            assert_eq!(list_all("", &store).await.len(), i + 1);
402        }
403
404        let list_path = list_all("", &store)
405            .await
406            .iter()
407            .map(|p| p.key.clone())
408            .collect_vec();
409        assert_eq!(list_path, paths);
410
411        for i in 0..=5 {
412            assert_eq!(list_all(&paths[0][0..=i], &store).await.len(), 2);
413        }
414        for i in 6..=paths[0].len() - 1 {
415            assert_eq!(list_all(&paths[0][0..=i], &store).await.len(), 1)
416        }
417        assert!(list_all("003", &store).await.is_empty());
418
419        for (i, path) in enumerate(paths.clone()) {
420            assert_eq!(list_all("", &store).await.len(), paths.len() - i);
421            store.delete(path).await.unwrap();
422            assert_eq!(list_all("", &store).await.len(), paths.len() - i - 1);
423        }
424    }
425
426    #[tokio::test]
427    async fn test_delete_objects() {
428        let block1 = Bytes::from("123456");
429        let block2 = Bytes::from("987654");
430
431        let store = InMemObjectStore::for_test();
432        store.upload("/abc", block1).await.unwrap();
433        store.upload("/klm", block2).await.unwrap();
434
435        assert_eq!(list_all("", &store).await.len(), 2);
436
437        let str_list = [
438            String::from("/abc"),
439            String::from("/klm"),
440            String::from("/xyz"),
441        ];
442
443        store.delete_objects(&str_list).await.unwrap();
444
445        assert_eq!(list_all("", &store).await.len(), 0);
446    }
447}