reddb_server/
pager_zone_migration.rs1use std::fs::{self, File, OpenOptions};
28use std::io::{Read, Seek, SeekFrom, Write};
29use std::path::{Path, PathBuf};
30
31use reddb_file::layout::retired;
32
33const PAGE_SIZE: usize = reddb_file::PAGED_PAGE_SIZE;
34const SLOT_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_SLOT_SIZE;
35const ZONE_SIZE: usize = reddb_file::PAGED_SUPERBLOCK_ZONE_SIZE;
36const SUPERBLOCK_TRAILER_OFFSET: usize = reddb_file::PAGED_SUPERBLOCK_TRAILER_OFFSET;
37
38const BACKUP_SUFFIX: &str = "pre-migration";
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct ZoneMigrationReport {
44 pub data_path: PathBuf,
46 pub backup_path: PathBuf,
48 pub removed_sidecars: Vec<PathBuf>,
50 pub header_recovered_from_shadow: bool,
52 pub manifest_recovered_from_shadow: bool,
55}
56
57#[derive(Debug)]
58pub enum ZoneMigrationError {
59 MissingStore(PathBuf),
61 NotALegacyStore(PathBuf),
63 AlreadyZoned(PathBuf),
65 HeaderUnrecoverable(PathBuf),
67 Io(std::io::Error),
68}
69
70impl std::fmt::Display for ZoneMigrationError {
71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72 match self {
73 Self::MissingStore(path) => write!(f, "no store at {}", path.display()),
74 Self::NotALegacyStore(path) => write!(
75 f,
76 "{} carries no retired rdb-hdr/rdb-meta sidecar, so there is nothing to \
77 migrate; a zoned store opens directly",
78 path.display()
79 ),
80 Self::AlreadyZoned(path) => write!(
81 f,
82 "{} already has a valid superblock zone; migrating again would discard it",
83 path.display()
84 ),
85 Self::HeaderUnrecoverable(path) => write!(
86 f,
87 "neither page 0 of {} nor its rdb-hdr shadow holds a readable database \
88 header, so no superblock can be seeded from this store. This is a damaged \
89 store. Preserve the database and its recovery files; restore from a \
90 verified backup",
91 path.display()
92 ),
93 Self::Io(err) => write!(f, "io error: {err}"),
94 }
95 }
96}
97
98impl std::error::Error for ZoneMigrationError {}
99
100impl From<std::io::Error> for ZoneMigrationError {
101 fn from(err: std::io::Error) -> Self {
102 Self::Io(err)
103 }
104}
105
106type Result<T> = std::result::Result<T, ZoneMigrationError>;
107
108pub fn backup_path_for(data_path: &Path) -> PathBuf {
110 let mut path = data_path.as_os_str().to_os_string();
111 path.push(".");
112 path.push(BACKUP_SUFFIX);
113 PathBuf::from(path)
114}
115
116pub fn migrate_to_zoned(data_path: &Path) -> Result<ZoneMigrationReport> {
123 if !data_path.exists() {
124 return Err(ZoneMigrationError::MissingStore(data_path.to_path_buf()));
125 }
126 let sidecars = present_sidecars(data_path);
127 if sidecars.is_empty() {
128 return Err(ZoneMigrationError::NotALegacyStore(data_path.to_path_buf()));
129 }
130 if has_valid_superblock_zone(data_path)? {
131 return Err(ZoneMigrationError::AlreadyZoned(data_path.to_path_buf()));
132 }
133
134 let backup_path = backup_path_for(data_path);
135 fs::copy(data_path, &backup_path)?;
136
137 let page_zero = read_page(data_path, 0)?;
138 let (header_image, header_recovered_from_shadow) =
141 if reddb_file::database_header_magic_matches(&page_zero) {
142 (page_zero, false)
143 } else {
144 let shadow = read_sidecar_page(&retired::pager_header_shadow_path_v0(data_path))?
145 .filter(|page| reddb_file::database_header_magic_matches(page))
146 .ok_or_else(|| ZoneMigrationError::HeaderUnrecoverable(data_path.to_path_buf()))?;
147 (shadow, true)
148 };
149
150 let manifest_recovered_from_shadow = restore_manifest_page_if_torn(data_path)?;
151
152 let mut slot = [0u8; SLOT_SIZE];
155 slot.copy_from_slice(&header_image[..SLOT_SIZE]);
156 let mut file = OpenOptions::new().read(true).write(true).open(data_path)?;
157 for (copy_index, generation) in [(0usize, 1u64), (1usize, 2u64)] {
158 reddb_file::seal_paged_superblock_slot(&mut slot, copy_index, generation)
159 .map_err(|err| std::io::Error::other(err.to_string()))?;
160 write_at(&mut file, superblock_offset(copy_index), &slot)?;
161 }
162 file.sync_all()?;
163 drop(file);
164
165 for sidecar in &sidecars {
168 fs::remove_file(sidecar)?;
169 }
170
171 Ok(ZoneMigrationReport {
172 data_path: data_path.to_path_buf(),
173 backup_path,
174 removed_sidecars: sidecars,
175 header_recovered_from_shadow,
176 manifest_recovered_from_shadow,
177 })
178}
179
180pub fn revert_to_sidecars(data_path: &Path) -> Result<ZoneMigrationReport> {
189 if !data_path.exists() {
190 return Err(ZoneMigrationError::MissingStore(data_path.to_path_buf()));
191 }
192
193 let image = newest_superblock_image(data_path)?
194 .ok_or_else(|| ZoneMigrationError::HeaderUnrecoverable(data_path.to_path_buf()))?;
195
196 let mut header_page = [0u8; PAGE_SIZE];
199 header_page[..SLOT_SIZE].copy_from_slice(&image);
200 header_page[SUPERBLOCK_TRAILER_OFFSET..SLOT_SIZE].fill(0);
201 reddb_file::clear_paged_page_checksum(&mut header_page);
202 let checksum = crate::storage::engine::crc32::crc32(&header_page);
203 reddb_file::set_paged_page_checksum(&mut header_page, checksum);
204
205 let manifest_page = read_page(data_path, 1)?;
206
207 let mut file = OpenOptions::new().read(true).write(true).open(data_path)?;
208 write_at(&mut file, 0, &header_page)?;
209 file.sync_all()?;
210 drop(file);
211
212 write_sidecar_page(
213 &retired::pager_header_shadow_path_v0(data_path),
214 &header_page,
215 )?;
216 write_sidecar_page(
217 &retired::pager_meta_shadow_path_v0(data_path),
218 &manifest_page,
219 )?;
220
221 let backup_path = backup_path_for(data_path);
222 if backup_path.exists() {
223 fs::remove_file(&backup_path)?;
224 }
225
226 Ok(ZoneMigrationReport {
227 data_path: data_path.to_path_buf(),
228 backup_path,
229 removed_sidecars: Vec::new(),
230 header_recovered_from_shadow: false,
231 manifest_recovered_from_shadow: false,
232 })
233}
234
235fn newest_superblock_image(data_path: &Path) -> Result<Option<[u8; SLOT_SIZE]>> {
238 let zone = read_superblock_zone(data_path)?;
239 let Some(selection) = reddb_file::select_paged_superblock(&zone) else {
240 return Ok(None);
241 };
242 let start = selection.copy_index * SLOT_SIZE;
243 let mut image = [0u8; SLOT_SIZE];
244 image.copy_from_slice(&zone[start..start + SLOT_SIZE]);
245 Ok(Some(image))
246}
247
248fn read_superblock_zone(data_path: &Path) -> Result<[u8; ZONE_SIZE]> {
249 let mut zone = [0u8; ZONE_SIZE];
250 let mut file = File::open(data_path)?;
251 let len = file.metadata()?.len().min(ZONE_SIZE as u64) as usize;
252 if len > 0 {
253 file.read_exact(&mut zone[..len])?;
254 }
255 Ok(zone)
256}
257
258fn present_sidecars(data_path: &Path) -> Vec<PathBuf> {
259 let mut seen: Vec<PathBuf> = Vec::new();
260 for candidate in retired::phase1_sidecar_paths(data_path) {
261 if candidate.exists() && !seen.contains(&candidate) {
262 seen.push(candidate);
263 }
264 }
265 seen
266}
267
268fn has_valid_superblock_zone(data_path: &Path) -> Result<bool> {
269 let zone = read_superblock_zone(data_path)?;
270 Ok(reddb_file::select_paged_superblock(&zone).is_some())
271}
272
273fn restore_manifest_page_if_torn(data_path: &Path) -> Result<bool> {
276 let page_one = read_page(data_path, 1)?;
277 if page_checksum_valid(&page_one) {
278 return Ok(false);
279 }
280 let Some(shadow) = read_sidecar_page(&retired::pager_meta_shadow_path_v0(data_path))? else {
281 return Ok(false);
282 };
283 if !page_checksum_valid(&shadow) {
284 return Ok(false);
285 }
286 let mut file = OpenOptions::new().read(true).write(true).open(data_path)?;
287 write_at(&mut file, PAGE_SIZE as u64, &shadow)?;
288 file.sync_all()?;
289 Ok(true)
290}
291
292fn page_checksum_valid(page: &[u8; PAGE_SIZE]) -> bool {
295 let stored = reddb_file::paged_page_checksum(page);
296 let mut scratch = *page;
297 reddb_file::clear_paged_page_checksum(&mut scratch);
298 stored == crate::storage::engine::crc32::crc32(&scratch)
299}
300
301fn superblock_offset(copy_index: usize) -> u64 {
302 reddb_file::paged_superblock_slot_offset(copy_index)
303}
304
305fn read_page(path: &Path, page_id: u64) -> Result<[u8; PAGE_SIZE]> {
306 let mut file = File::open(path)?;
307 let mut page = [0u8; PAGE_SIZE];
308 file.seek(SeekFrom::Start(page_id * PAGE_SIZE as u64))?;
309 file.read_exact(&mut page)?;
310 Ok(page)
311}
312
313fn read_sidecar_page(path: &Path) -> Result<Option<[u8; PAGE_SIZE]>> {
314 if !path.exists() {
315 return Ok(None);
316 }
317 let mut file = File::open(path)?;
318 let mut page = [0u8; PAGE_SIZE];
319 match file.read_exact(&mut page) {
320 Ok(()) => Ok(Some(page)),
321 Err(err) if err.kind() == std::io::ErrorKind::UnexpectedEof => Ok(None),
323 Err(err) => Err(err.into()),
324 }
325}
326
327fn write_sidecar_page(path: &Path, page: &[u8; PAGE_SIZE]) -> Result<()> {
328 let mut file = File::create(path)?;
329 file.write_all(page)?;
330 file.sync_all()?;
331 Ok(())
332}
333
334fn write_at(file: &mut File, offset: u64, bytes: &[u8]) -> Result<()> {
335 file.seek(SeekFrom::Start(offset))?;
336 file.write_all(bytes)?;
337 Ok(())
338}