Skip to main content

mito2/manifest/storage/
delta.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 common_datasource::compression::CompressionType;
18use common_telemetry::{debug, warn};
19use futures::TryStreamExt;
20use futures::future::try_join_all;
21use object_store::{Buffer, Entry, ErrorKind, Lister, ObjectStore};
22use snafu::{ResultExt, ensure};
23use store_api::ManifestVersion;
24use store_api::storage::RegionId;
25use tokio::sync::Semaphore;
26
27use crate::cache::manifest_cache::ManifestCache;
28use crate::error::{
29    CompressObjectSnafu, DecompressObjectSnafu, InvalidScanIndexSnafu, ManifestDeltaNotFoundSnafu,
30    ManifestVersionConflictSnafu, OpenDalSnafu, Result,
31};
32use crate::manifest::storage::size_tracker::Tracker;
33use crate::manifest::storage::utils::{
34    get_from_cache_decoded, sort_manifests, write_and_put_cache,
35};
36use crate::manifest::storage::{
37    FETCH_MANIFEST_PARALLELISM, delta_file, file_compress_type, file_version, gen_path,
38    is_delta_file, list_start_after,
39};
40
41#[derive(Debug, Clone)]
42pub(crate) struct DeltaStorage<T: Tracker> {
43    object_store: ObjectStore,
44    compress_type: CompressionType,
45    path: String,
46    delta_tracker: Arc<T>,
47    manifest_cache: Option<ManifestCache>,
48}
49
50impl<T: Tracker> DeltaStorage<T> {
51    pub(crate) fn new(
52        path: String,
53        object_store: ObjectStore,
54        compress_type: CompressionType,
55        manifest_cache: Option<ManifestCache>,
56        delta_tracker: Arc<T>,
57    ) -> Self {
58        Self {
59            object_store,
60            compress_type,
61            path,
62            delta_tracker,
63            manifest_cache,
64        }
65    }
66
67    fn delta_file_path(&self, version: ManifestVersion) -> String {
68        gen_path(&self.path, &delta_file(version), self.compress_type)
69    }
70
71    /// Returns an iterator of manifests from path directory.
72    ///
73    /// If `start_after` is `Some`, the lister will skip entries whose name is
74    /// lexicographically less than or equal to it (see OpenDAL's `start_after`).
75    pub(crate) async fn manifest_lister(
76        &self,
77        start_after: Option<&str>,
78    ) -> Result<Option<Lister>> {
79        let mut builder = self.object_store.lister_with(&self.path);
80        if let Some(s) = start_after {
81            builder = builder.start_after(s);
82        }
83        match builder.await {
84            Ok(streamer) => Ok(Some(streamer)),
85            Err(e) if e.kind() == ErrorKind::NotFound => {
86                debug!("Manifest directory does not exist: {}", self.path);
87                Ok(None)
88            }
89            Err(e) => Err(e).context(OpenDalSnafu)?,
90        }
91    }
92
93    /// Return all `R`s in the directory that meet the `filter` conditions (that is, the `filter` closure returns `Some(R)`),
94    /// and discard `R` that does not meet the conditions (that is, the `filter` closure returns `None`)
95    /// Return an empty vector when directory is not found.
96    ///
97    /// `start_after` is forwarded to the underlying lister to skip entries
98    /// whose name is lexicographically less than or equal to it.
99    pub async fn get_paths<F, R>(&self, start_after: Option<&str>, mut filter: F) -> Result<Vec<R>>
100    where
101        F: FnMut(Entry) -> Option<R>,
102    {
103        let Some(streamer) = self.manifest_lister(start_after).await? else {
104            return Ok(vec![]);
105        };
106
107        streamer
108            .try_filter_map(|e| {
109                let result = filter(e);
110                async { Ok(result) }
111            })
112            .try_collect::<Vec<_>>()
113            .await
114            .context(OpenDalSnafu)
115    }
116
117    /// Scans the manifest files in the range of [start, end) and return all manifest entries.
118    pub async fn scan(
119        &self,
120        start: ManifestVersion,
121        end: ManifestVersion,
122    ) -> Result<Vec<(ManifestVersion, Entry)>> {
123        ensure!(start <= end, InvalidScanIndexSnafu { start, end });
124
125        // Push the version lower bound into the list request via
126        // `list_start_after`; skip the hint when `start == 0` (nothing to skip).
127        let start_after = (start > 0).then(|| list_start_after(&self.path, start));
128        let mut total_paths = 0;
129        let mut entries: Vec<(ManifestVersion, Entry)> = self
130            .get_paths(start_after.as_deref(), |entry| {
131                total_paths += 1;
132                let file_name = entry.name();
133                if is_delta_file(file_name) {
134                    let version = file_version(file_name);
135                    if start <= version && version < end {
136                        return Some((version, entry));
137                    }
138                }
139                None
140            })
141            .await?;
142
143        sort_manifests(&mut entries);
144
145        common_telemetry::debug!(
146            "DeltaStorage get paths for {}, start: {}, end: {}, start_after: {:?}, total_paths: {}, entries: {}",
147            self.path,
148            start,
149            end,
150            start_after,
151            total_paths,
152            entries.len()
153        );
154
155        Ok(entries)
156    }
157
158    /// Fetches manifests in range [start_version, end_version).
159    ///
160    /// This functions is guaranteed to return manifests from the `start_version` strictly (must contain `start_version`).
161    pub async fn fetch_manifests_strict_from(
162        &self,
163        start_version: ManifestVersion,
164        end_version: ManifestVersion,
165        region_id: RegionId,
166    ) -> Result<Vec<(ManifestVersion, Vec<u8>)>> {
167        let mut manifests = self.fetch_manifests(start_version, end_version).await?;
168        let start_index = manifests.iter().position(|(v, _)| *v == start_version);
169        debug!(
170            "Fetches manifests in range [{},{}), start_index: {:?}, region_id: {}, manifests: {:?}",
171            start_version,
172            end_version,
173            start_index,
174            region_id,
175            manifests.iter().map(|(v, _)| *v).collect::<Vec<_>>()
176        );
177        if let Some(start_index) = start_index {
178            Ok(manifests.split_off(start_index))
179        } else {
180            Ok(vec![])
181        }
182    }
183
184    /// Common implementation for fetching manifests from entries in parallel.
185    pub(crate) async fn fetch_manifests_from_entries(
186        &self,
187        entries: &[(ManifestVersion, Entry)],
188    ) -> Result<Vec<(ManifestVersion, Vec<u8>)>> {
189        if entries.is_empty() {
190            return Ok(vec![]);
191        }
192
193        // TODO(weny): Make it configurable.
194        let semaphore = Semaphore::new(FETCH_MANIFEST_PARALLELISM);
195
196        let tasks = entries.iter().map(|(v, entry)| async {
197            // Safety: semaphore must exist.
198            let _permit = semaphore.acquire().await.unwrap();
199
200            let cache_key = entry.path();
201            let compress_type = file_compress_type(entry.name());
202            // Try to get from cache first
203            if let Some(data) = get_from_cache_decoded(self.manifest_cache.as_ref(), cache_key, compress_type).await {
204                let size = entry.metadata().content_length();
205                if size > 0 {
206                    self.delta_tracker.record(*v, size);
207                } else {
208                    match self.object_store.stat(entry.path()).await {
209                        Ok(metadata) => self.delta_tracker.record(*v, metadata.content_length()),
210                        Err(error) => warn!(error; "Failed to account for cached manifest delta {}", entry.path()),
211                    }
212                }
213                return Ok((*v, data));
214            }
215
216            // Fetch from remote object store
217            let bytes = match self.object_store.read(entry.path()).await {
218                Ok(bytes) => bytes,
219                Err(error) if error.kind() == ErrorKind::NotFound => {
220                    return Err(error).context(ManifestDeltaNotFoundSnafu {
221                        version: *v,
222                        path: entry.path(),
223                    });
224                }
225                Err(error) => return Err(error).context(OpenDalSnafu),
226            };
227            self.delta_tracker.record(*v, bytes.len() as u64);
228            let data = compress_type
229                .decode(bytes.clone())
230                .await
231                .context(DecompressObjectSnafu {
232                    compress_type,
233                    path: entry.path(),
234                })?;
235
236            // Add to cache
237            if let Some(cache) = &self.manifest_cache {
238                cache.put_file(cache_key.to_string(), bytes.to_vec()).await;
239            }
240
241            Ok((*v, data))
242        });
243
244        try_join_all(tasks).await
245    }
246
247    /// Fetch all manifests in concurrent, and return the manifests in range [start_version, end_version)
248    ///
249    /// **Notes**: This function is no guarantee to return manifests from the `start_version` strictly.
250    /// Uses [fetch_manifests_strict_from](DeltaStorage::fetch_manifests_strict_from) to get manifests from the `start_version`.
251    pub async fn fetch_manifests(
252        &self,
253        start_version: ManifestVersion,
254        end_version: ManifestVersion,
255    ) -> Result<Vec<(ManifestVersion, Vec<u8>)>> {
256        let manifests = self.scan(start_version, end_version).await?;
257        self.fetch_manifests_from_entries(&manifests).await
258    }
259
260    /// Save the delta manifest file.
261    pub async fn save(&mut self, version: ManifestVersion, bytes: &[u8]) -> Result<()> {
262        let path = self.delta_file_path(version);
263        debug!("Save log to manifest storage, version: {}", version);
264        let data = self
265            .compress_type
266            .encode(bytes)
267            .await
268            .context(CompressObjectSnafu {
269                compress_type: self.compress_type,
270                path: &path,
271            })?;
272        let delta_size = data.len();
273
274        write_and_put_cache(
275            &self.object_store,
276            self.manifest_cache.as_ref(),
277            &path,
278            data,
279        )
280        .await?;
281        self.delta_tracker.record(version, delta_size as u64);
282
283        Ok(())
284    }
285
286    /// Creates the delta of `version` under its fixed `.json.gz` name, so that only one writer can
287    /// commit the version.
288    ///
289    /// An existing object with the same decoded content is a retry of an earlier write that
290    /// landed. Any other existing object fails with a version conflict.
291    pub(crate) async fn save_conditional(
292        &mut self,
293        version: ManifestVersion,
294        bytes: &[u8],
295    ) -> Result<()> {
296        let path = gen_path(&self.path, &delta_file(version), CompressionType::Gzip);
297        // Every writer has to use one object name, so `compress_manifest = false` is honoured
298        // with gzip level 0, which stores the bytes without compressing them.
299        let data = if self.compress_type.is_compressed() {
300            CompressionType::Gzip.encode(bytes).await
301        } else {
302            CompressionType::encode_gzip_stored(bytes).await
303        }
304        .context(CompressObjectSnafu {
305            compress_type: CompressionType::Gzip,
306            path: &path,
307        })?;
308        let data = Buffer::from(data);
309
310        let stored_size = match self
311            .object_store
312            .write_with(&path, data.clone())
313            .if_not_exists(true)
314            .await
315        {
316            Ok(_) => data.len(),
317            Err(error)
318                if matches!(
319                    error.kind(),
320                    ErrorKind::AlreadyExists | ErrorKind::ConditionNotMatch
321                ) =>
322            {
323                self.ensure_same_delta(version, &path, bytes).await?
324            }
325            Err(error) => return Err(error).context(OpenDalSnafu),
326        };
327
328        self.delta_tracker.record(version, stored_size as u64);
329        if let Some(cache) = &self.manifest_cache {
330            cache.put_file(path, data.to_vec()).await;
331        }
332
333        Ok(())
334    }
335
336    /// Checks that the object at `path` decodes to `bytes`, reading it directly from storage.
337    /// Returns the size of the stored object.
338    async fn ensure_same_delta(
339        &self,
340        version: ManifestVersion,
341        path: &str,
342        bytes: &[u8],
343    ) -> Result<usize> {
344        let conflict = |reason: String| {
345            ManifestVersionConflictSnafu {
346                version,
347                manifest_dir: &self.path,
348                reason,
349            }
350            .build()
351        };
352        let existing = self
353            .object_store
354            .read(path)
355            .await
356            .map_err(|e| conflict(format!("cannot read the existing delta: {e}")))?;
357        let stored_size = existing.len();
358        let existing = CompressionType::Gzip
359            .decode(existing)
360            .await
361            .map_err(|e| conflict(format!("cannot decode the existing delta: {e}")))?;
362        if existing != bytes {
363            return Err(conflict(
364                "the existing delta has different content".to_string(),
365            ));
366        }
367        Ok(stored_size)
368    }
369}
370
371#[cfg(test)]
372impl<T: Tracker> DeltaStorage<T> {
373    pub fn set_compress_type(&mut self, compress_type: CompressionType) {
374        self.compress_type = compress_type;
375    }
376}