Skip to main content

rocketmq_store_api/
checkpoint_artifact.rs

1// Copyright 2023 The RocketMQ Rust Authors
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
15//! Backend-neutral checkpoint artifact utilities.
16
17use std::fs;
18use std::fs::File;
19use std::io::BufReader;
20use std::io::Read;
21use std::path::Path;
22use std::path::PathBuf;
23
24use rocketmq_error::STORAGE_IO_FAILED;
25use rocketmq_error::STORAGE_REQUEST_INVALID;
26use sha2::Digest;
27use sha2::Sha256;
28use thiserror::Error;
29
30/// Manifest stored beside a checkpoint payload.
31pub const RELEASE_CHECKPOINT_MANIFEST_FILE: &str = ".rocketmq-release-checkpoint.json";
32
33/// Deterministic digest and payload length for one checkpoint directory.
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct CheckpointDirectoryDigest {
36    /// Number of payload bytes covered by the digest.
37    pub length_bytes: u64,
38    /// Lowercase SHA-256 over stable path and file content ordering.
39    pub sha256: String,
40}
41
42use crate::StoreContractViolation;
43use crate::StoreError;
44use crate::StoreOperation;
45
46/// Private filesystem failure while reading a checkpoint artifact.
47#[derive(Debug, Error)]
48#[error("{operation} failed for {path}: {source}")]
49struct CheckpointArtifactIoError {
50    operation: &'static str,
51    path: PathBuf,
52    #[source]
53    source: std::io::Error,
54}
55
56/// Hashes all regular files in stable relative-path order.
57///
58/// The embedded manifest is excluded because it contains the digest itself.
59/// Symlinks and special files are rejected, and the byte budget is enforced
60/// while reading.
61///
62/// # Errors
63///
64/// Returns [`StoreError`] when the artifact cannot be traversed safely, read,
65/// or kept within `max_checkpoint_bytes`. Deterministic shape violations are
66/// preserved as a typed [`StoreContractViolation`] source; filesystem failures
67/// retain their private typed source and underlying [`std::io::Error`].
68pub fn hash_checkpoint_directory(
69    checkpoint_root: &Path,
70    max_checkpoint_bytes: u64,
71) -> Result<CheckpointDirectoryDigest, StoreError> {
72    let checkpoint_root = checkpoint_root
73        .canonicalize()
74        .map_err(|source| io_error("canonicalize checkpoint", checkpoint_root, source))?;
75    let files = collect_regular_files(&checkpoint_root)?;
76    let mut hasher = Sha256::new();
77    let mut length_bytes = 0_u64;
78    let mut buffer = vec![0_u8; 64 * 1024];
79
80    for (relative, path) in files {
81        if relative == Path::new(RELEASE_CHECKPOINT_MANIFEST_FILE) {
82            continue;
83        }
84        hash_relative_path(&mut hasher, &relative);
85        let mut input =
86            BufReader::new(File::open(&path).map_err(|source| io_error("open checkpoint file", &path, source))?);
87        loop {
88            let read = input
89                .read(&mut buffer)
90                .map_err(|source| io_error("read checkpoint file", &path, source))?;
91            if read == 0 {
92                break;
93            }
94            length_bytes = length_bytes.checked_add(read as u64).ok_or_else(|| {
95                artifact_contract(StoreContractViolation::CheckpointArtifactTooLarge {
96                    actual: u64::MAX,
97                    maximum: max_checkpoint_bytes,
98                })
99            })?;
100            if length_bytes > max_checkpoint_bytes {
101                return Err(artifact_contract(StoreContractViolation::CheckpointArtifactTooLarge {
102                    actual: length_bytes,
103                    maximum: max_checkpoint_bytes,
104                }));
105            }
106            hasher.update(&buffer[..read]);
107        }
108    }
109
110    if length_bytes == 0 {
111        return Err(artifact_contract(StoreContractViolation::CheckpointArtifactEmpty));
112    }
113    Ok(CheckpointDirectoryDigest {
114        length_bytes,
115        sha256: hex::encode(hasher.finalize()),
116    })
117}
118
119/// Converts a local path to the file URI emitted in checkpoint manifests.
120pub fn path_to_file_uri(path: &Path) -> String {
121    let raw = path.to_string_lossy();
122    #[cfg(windows)]
123    let raw = raw.strip_prefix(r"\\?\").map_or_else(|| raw.to_string(), str::to_owned);
124    #[cfg(not(windows))]
125    let raw = raw.into_owned();
126    let portable = raw.replace('\\', "/");
127    if portable.starts_with('/') {
128        format!("file://{portable}")
129    } else {
130        format!("file:///{portable}")
131    }
132}
133
134/// Resolves a checkpoint URI created by [`path_to_file_uri`].
135///
136/// # Errors
137///
138/// Returns [`StoreContractViolation::CheckpointArtifactUnsupportedUri`] when
139/// `uri` is not a local file URI.
140pub fn file_uri_to_path(uri: &str) -> Result<PathBuf, StoreContractViolation> {
141    let raw = uri
142        .strip_prefix("file:///")
143        .ok_or_else(|| StoreContractViolation::CheckpointArtifactUnsupportedUri(uri.to_string()))?;
144    #[cfg(windows)]
145    let path = PathBuf::from(raw.replace('/', "\\"));
146    #[cfg(not(windows))]
147    let path = PathBuf::from(format!("/{raw}"));
148    Ok(path)
149}
150
151fn collect_regular_files(root: &Path) -> Result<Vec<(PathBuf, PathBuf)>, StoreError> {
152    let mut pending = vec![root.to_path_buf()];
153    let mut files = Vec::new();
154    while let Some(directory) = pending.pop() {
155        let entries =
156            fs::read_dir(&directory).map_err(|source| io_error("read checkpoint directory", &directory, source))?;
157        for entry in entries {
158            let entry = entry.map_err(|source| io_error("read checkpoint entry", &directory, source))?;
159            let path = entry.path();
160            let metadata =
161                fs::symlink_metadata(&path).map_err(|source| io_error("inspect checkpoint entry", &path, source))?;
162            if metadata.file_type().is_symlink() {
163                return Err(artifact_contract(
164                    StoreContractViolation::CheckpointArtifactSymbolicLink(path),
165                ));
166            }
167            if metadata.is_dir() {
168                pending.push(path);
169            } else if metadata.is_file() {
170                let relative = path
171                    .strip_prefix(root)
172                    .map_err(|_| {
173                        artifact_contract(StoreContractViolation::CheckpointArtifactPathEscaped(path.clone()))
174                    })?
175                    .to_path_buf();
176                files.push((relative, path));
177            } else {
178                return Err(artifact_contract(
179                    StoreContractViolation::CheckpointArtifactUnsupportedFileType(path),
180                ));
181            }
182        }
183    }
184    files.sort_by_cached_key(|entry| portable_relative_path(&entry.0));
185    Ok(files)
186}
187
188fn hash_relative_path(hasher: &mut Sha256, relative: &Path) {
189    let portable = portable_relative_path(relative);
190    hasher.update((portable.len() as u64).to_le_bytes());
191    hasher.update(portable.as_bytes());
192}
193
194fn portable_relative_path(path: &Path) -> String {
195    path.components()
196        .map(|component| component.as_os_str().to_string_lossy())
197        .collect::<Vec<_>>()
198        .join("/")
199}
200
201fn artifact_contract(source: StoreContractViolation) -> StoreError {
202    StoreError::new(&STORAGE_REQUEST_INVALID, StoreOperation::Read).with_source(source)
203}
204
205fn io_error(operation: &'static str, path: &Path, source: std::io::Error) -> StoreError {
206    StoreError::new(&STORAGE_IO_FAILED, StoreOperation::Read).with_source(CheckpointArtifactIoError {
207        operation,
208        path: path.to_path_buf(),
209        source,
210    })
211}