Skip to main content

mito2/wal/
raw_entry_reader.rs

1// Copyright 2023 Greptime Team
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::sync::Arc;
16
17use async_stream::try_stream;
18use common_error::ext::BoxedError;
19use futures::future::BoxFuture;
20use futures::stream::BoxStream;
21use snafu::ResultExt;
22use store_api::logstore::LogStore;
23use store_api::logstore::entry::Entry;
24use store_api::logstore::provider::Provider;
25use store_api::storage::RegionId;
26use tokio_stream::StreamExt;
27
28use crate::error::{self, Result};
29use crate::wal::EntryId;
30
31/// A stream that yields [Entry].
32pub type EntryStream<'a> = BoxStream<'a, Result<Entry>>;
33
34/// [RawEntryReader] reads [Entry] from the underlying [LogStore] and lists the WAL of another
35/// node for a bound.
36pub(crate) trait RawEntryReader: Send + Sync {
37    fn read(&self, provider: &Provider, start_id: EntryId) -> Result<EntryStream<'static>>;
38
39    /// Returns a bound at or above every entry, of any region, in the listed objects of the WAL
40    /// of node `node_id`, see [LogStore::list_upper_bound], or None if the log store cannot list
41    /// that WAL. `region_id` only names the request in errors.
42    fn list_upper_bound(
43        &self,
44        _node_id: u64,
45        _region_id: RegionId,
46    ) -> BoxFuture<'_, std::result::Result<Option<EntryId>, BoxedError>> {
47        Box::pin(async { Ok(None) })
48    }
49}
50
51/// Implement the [RawEntryReader] for the [LogStore].
52pub struct LogStoreRawEntryReader<S> {
53    store: Arc<S>,
54}
55
56impl<S> LogStoreRawEntryReader<S> {
57    pub fn new(store: Arc<S>) -> Self {
58        Self { store }
59    }
60}
61
62impl<S: LogStore> RawEntryReader for LogStoreRawEntryReader<S> {
63    fn list_upper_bound(
64        &self,
65        node_id: u64,
66        region_id: RegionId,
67    ) -> BoxFuture<'_, std::result::Result<Option<EntryId>, BoxedError>> {
68        Box::pin(async move {
69            self.store
70                .list_upper_bound(node_id, region_id)
71                .await
72                .map_err(BoxedError::new)
73        })
74    }
75
76    fn read(&self, provider: &Provider, start_id: EntryId) -> Result<EntryStream<'static>> {
77        let store = self.store.clone();
78        let provider = provider.clone();
79        let stream = try_stream!({
80            let mut stream = store
81                .read(&provider, start_id)
82                .await
83                .map_err(BoxedError::new)
84                .with_context(|_| error::ReadWalSnafu {
85                    provider: provider.clone(),
86                })?;
87
88            while let Some(entries) = stream.next().await {
89                let entries =
90                    entries
91                        .map_err(BoxedError::new)
92                        .with_context(|_| error::ReadWalSnafu {
93                            provider: provider.clone(),
94                        })?;
95
96                for entry in entries {
97                    yield entry
98                }
99            }
100        });
101
102        Ok(Box::pin(stream))
103    }
104}
105
106/// A [RawEntryReader] reads [RawEntry] belongs to a specific region.
107pub struct RegionRawEntryReader<R> {
108    reader: R,
109    region_id: RegionId,
110}
111
112impl<R> RegionRawEntryReader<R>
113where
114    R: RawEntryReader,
115{
116    pub fn new(reader: R, region_id: RegionId) -> Self {
117        Self { reader, region_id }
118    }
119}
120
121impl<R> RawEntryReader for RegionRawEntryReader<R>
122where
123    R: RawEntryReader,
124{
125    fn read(&self, ctx: &Provider, start_id: EntryId) -> Result<EntryStream<'static>> {
126        let mut stream = self.reader.read(ctx, start_id)?;
127        let region_id = self.region_id;
128
129        let stream = try_stream!({
130            while let Some(entry) = stream.next().await {
131                let entry = entry?;
132                if entry.region_id() == region_id {
133                    yield entry
134                }
135            }
136        });
137
138        Ok(Box::pin(stream))
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use std::sync::Arc;
145
146    use futures::{TryStreamExt, stream};
147    use store_api::logstore::entry::{Entry, NaiveEntry};
148    use store_api::logstore::{AppendBatchResponse, EntryId, LogStore, SendableEntryStream};
149    use store_api::storage::RegionId;
150
151    use super::*;
152    use crate::error;
153
154    #[derive(Debug)]
155    struct MockLogStore {
156        entries: Vec<Entry>,
157    }
158
159    #[async_trait::async_trait]
160    impl LogStore for MockLogStore {
161        type Error = error::Error;
162
163        async fn stop(&self) -> Result<(), Self::Error> {
164            unreachable!()
165        }
166
167        async fn append_batch(
168            &self,
169            _entries: Vec<Entry>,
170        ) -> Result<AppendBatchResponse, Self::Error> {
171            unreachable!()
172        }
173
174        async fn read(
175            &self,
176            _provider: &Provider,
177            _id: EntryId,
178        ) -> Result<SendableEntryStream<'static, Entry, Self::Error>, Self::Error> {
179            Ok(Box::pin(stream::iter(vec![Ok(self.entries.clone())])))
180        }
181
182        async fn create_namespace(&self, _ns: &Provider) -> Result<(), Self::Error> {
183            unreachable!()
184        }
185
186        async fn delete_namespace(&self, _ns: &Provider) -> Result<(), Self::Error> {
187            unreachable!()
188        }
189
190        async fn list_namespaces(&self) -> Result<Vec<Provider>, Self::Error> {
191            unreachable!()
192        }
193
194        async fn obsolete(
195            &self,
196            _provider: &Provider,
197            _region_id: RegionId,
198            _entry_id: EntryId,
199        ) -> Result<(), Self::Error> {
200            unreachable!()
201        }
202
203        async fn obsolete_all(
204            &self,
205            _provider: &Provider,
206            _region_id: RegionId,
207        ) -> Result<(), Self::Error> {
208            unreachable!()
209        }
210
211        fn entry(
212            &self,
213            _data: Vec<u8>,
214            _entry_id: EntryId,
215            _region_id: RegionId,
216            _provider: &Provider,
217        ) -> Result<Entry, Self::Error> {
218            unreachable!()
219        }
220
221        fn latest_entry_id(&self, _provider: &Provider) -> Result<EntryId, Self::Error> {
222            unreachable!()
223        }
224    }
225
226    #[tokio::test]
227    async fn test_raw_entry_reader() {
228        let provider = Provider::raft_engine_provider(RegionId::new(1024, 1).as_u64());
229        let expected_entries = vec![Entry::Naive(NaiveEntry {
230            provider: provider.clone(),
231            region_id: RegionId::new(1024, 1),
232            entry_id: 1,
233            data: vec![1],
234        })];
235        let store = MockLogStore {
236            entries: expected_entries.clone(),
237        };
238
239        let reader = LogStoreRawEntryReader::new(Arc::new(store));
240        let entries = reader
241            .read(&provider, 0)
242            .unwrap()
243            .try_collect::<Vec<_>>()
244            .await
245            .unwrap();
246        assert_eq!(expected_entries, entries);
247    }
248
249    #[tokio::test]
250    async fn test_raw_entry_reader_filter() {
251        let provider = Provider::raft_engine_provider(RegionId::new(1024, 1).as_u64());
252        let all_entries = vec![
253            Entry::Naive(NaiveEntry {
254                provider: provider.clone(),
255                region_id: RegionId::new(1024, 1),
256                entry_id: 1,
257                data: vec![1],
258            }),
259            Entry::Naive(NaiveEntry {
260                provider: provider.clone(),
261                region_id: RegionId::new(1024, 2),
262                entry_id: 2,
263                data: vec![2],
264            }),
265            Entry::Naive(NaiveEntry {
266                provider: provider.clone(),
267                region_id: RegionId::new(1024, 3),
268                entry_id: 3,
269                data: vec![3],
270            }),
271        ];
272        let store = MockLogStore {
273            entries: all_entries.clone(),
274        };
275
276        let expected_region_id = RegionId::new(1024, 3);
277        let reader = RegionRawEntryReader::new(
278            LogStoreRawEntryReader::new(Arc::new(store)),
279            expected_region_id,
280        );
281        let entries = reader
282            .read(&provider, 0)
283            .unwrap()
284            .try_collect::<Vec<_>>()
285            .await
286            .unwrap();
287        assert_eq!(
288            all_entries
289                .into_iter()
290                .filter(|entry| entry.region_id() == expected_region_id)
291                .collect::<Vec<_>>(),
292            entries
293        );
294    }
295}