Skip to main content

coven_foundation/files/
device_reset.rs

1//! Swapping a loaded replacement into a store's directory (§19.3).
2//!
3//! `reset_device` and `restore_device` load the new installation in its own
4//! directory inside the store's, then move it into place. The durable record
5//! names the old and new device ids and the call that began the replacement:
6//! written before the fresh device registers, it makes ordinary opens refuse
7//! the store, naming that call, and every later call finishes the same
8//! replacement (§19.3). It says, too, whether the swap has begun.
9//! The bootstrap marker separates the swap's two moves. Without it, the old
10//! local state is still moving into its archive; with it, the new installation
11//! is moving in. The settings change last. Each step is idempotent, so a retry
12//! after any interruption continues forward where it stopped.
13
14use std::fs;
15use std::path::{Path, PathBuf};
16
17use serde::{Deserialize, Serialize};
18
19use super::{
20    atomic_file, bootstrap, set_aside, settings, DirectoryCreationError, FileError, SettingsError,
21    StoreFile,
22};
23use crate::id_source::{DeviceId, StoreId};
24
25pub(crate) const RECORD: &str = "device-reset.json";
26const ARCHIVE_PREFIX: &str = "discarded-device-";
27/// The folder each archive moves into as its removal begins, so the archive
28/// leaves the store's directory in one rename while coven deletes the files
29/// under it (§19.3).
30const REMOVING: &str = "removing-discarded-devices";
31/// The directory inside a store's directory where its replacement loads.
32pub(super) const AREA: &str = ".coven-replacement";
33/// Files describing the store's location and this installation's custody,
34/// which the replacement keeps in place. Everything else is local state.
35const KEPT: [StoreFile; 3] =
36    [StoreFile::StorageSettings, StoreFile::StoreKeys, StoreFile::MemberKeys];
37
38/// A replacement of this installation, not a membership removal (E5).
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
40pub struct DeviceReset {
41    /// The id whose local copy was discarded.
42    pub old_device: DeviceId,
43    /// The fresh id the replacement registers.
44    pub new_device: DeviceId,
45}
46
47/// The call that began a replacement, and so the only call that finishes it
48/// (§19.3). The other call would load under different keys, or keep or remove
49/// a different copy, so it is refused before anything changes.
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
51pub enum ReplacedBy {
52    /// `CovenBuilder::reset_device`, which keeps the old copy for inspection.
53    Reset,
54    /// `CovenBuilder::restore_device`, which commits the restore code's member
55    /// keys and removes the old copy (§13.1).
56    Restore,
57}
58
59impl std::fmt::Display for ReplacedBy {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        f.write_str(match self {
62            Self::Reset => "reset_device",
63            Self::Restore => "restore_device",
64        })
65    }
66}
67
68/// What the fresh device's registration does to the old id (§19.3).
69#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
70pub enum Registration {
71    /// The fresh device replaces the old id: nothing else uses it.
72    ReplacesOld,
73    /// The fresh device joins its member beside the old id, which another
74    /// installation still uses and keeps (a copy that found its id in use).
75    NewDevice,
76}
77
78/// How far a recorded replacement has come (§19.3).
79#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
80pub enum ReplacementPhase {
81    /// Recorded before the fresh device registers. The new installation is
82    /// in its hidden directory and the old one in the store's place.
83    Registering,
84    /// The swap has begun: the installations are moving, or have moved.
85    Swapping,
86}
87
88/// The durable record of a replacement past its point of no return: from
89/// just before the fresh device registers until it is published (§19.3).
90#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(deny_unknown_fields)]
92pub struct ReplacementRecord {
93    /// The installation being replaced and its fresh successor.
94    pub reset: DeviceReset,
95    /// The call that began the replacement and finishes it.
96    pub by: ReplacedBy,
97    /// What the registration does to the old id, kept so a resumed
98    /// replacement registers the same entry.
99    pub registration: Registration,
100    /// The store's name in the new installation's loaded database. While the
101    /// replacement is unfinished the store doesn't open, so listings show this.
102    pub name: String,
103    /// How far it has come.
104    pub phase: ReplacementPhase,
105}
106
107pub(super) fn read(directory: &Path) -> Result<Option<ReplacementRecord>, FileError> {
108    atomic_file::read_json(&directory.join(RECORD), "read replacement record")
109}
110
111/// The record of a replacement that has not finished: one still
112/// registering, one whose marker is still present, or one whose settings do
113/// not yet name the new device. A record that outlived publication is not
114/// returned.
115pub(super) fn unfinished(
116    directory: &Path,
117    id: StoreId,
118) -> Result<Option<ReplacementRecord>, SettingsError> {
119    let Some(record) = read(directory)? else {
120        return Ok(None);
121    };
122    if record.phase == ReplacementPhase::Swapping
123        && !bootstrap::is_pending(directory)?
124        && settings::read(directory, id)?.device_id == record.reset.new_device
125    {
126        return Ok(None);
127    }
128    Ok(Some(record))
129}
130
131/// Keep the first decision: a resumed replacement never changes the chosen
132/// fresh id. A record already there is returned as it is.
133pub(super) fn record(
134    directory: &Path,
135    record: &ReplacementRecord,
136) -> Result<ReplacementRecord, FileError> {
137    if let Some(recorded) = read(directory)? {
138        return Ok(recorded);
139    }
140    if record.reset.old_device == record.reset.new_device {
141        return Err(FileError::at(
142            "record device reset",
143            &directory.join(RECORD),
144            std::io::Error::new(
145                std::io::ErrorKind::InvalidInput,
146                "a reset needs a fresh device id",
147            ),
148        ));
149    }
150    let bytes = serde_json::to_vec(record).expect("replacement record encodes");
151    atomic_file::replace(&directory.join(RECORD), &bytes)?;
152    Ok(record.clone())
153}
154
155/// Mark the recorded replacement's swap as begun, before anything moves.
156pub(super) fn swapping(directory: &Path, recorded: &ReplacementRecord) -> Result<(), FileError> {
157    if recorded.phase == ReplacementPhase::Swapping {
158        return Ok(());
159    }
160    let record = ReplacementRecord { phase: ReplacementPhase::Swapping, ..recorded.clone() };
161    let bytes = serde_json::to_vec(&record).expect("replacement record encodes");
162    atomic_file::replace(&directory.join(RECORD), &bytes)
163}
164
165/// The directory where the replacement of the store at `directory` loads.
166pub(super) fn loading(directory: &Path, id: StoreId) -> PathBuf {
167    directory.join(AREA).join(id.to_string())
168}
169
170/// The discarded installation's local state, kept for inspection after a reset.
171fn archive(directory: &Path, old_device: DeviceId) -> PathBuf {
172    directory.join(archive_name(old_device))
173}
174
175/// Under the writer, bootstrap and excluded reader locks, move the old local
176/// state into its archive and the loaded installation into its place, then
177/// name the new device in the settings. Resumes any interrupted swap.
178pub(super) fn forward(
179    directory: &Path,
180    id: StoreId,
181    reset: DeviceReset,
182) -> Result<(), DirectoryCreationError> {
183    let marker = bootstrap::marker(directory);
184    if !atomic_file::exists("inspect bootstrap marker", &marker)? {
185        let archive = archive(directory, reset.old_device);
186        if !atomic_file::exists("inspect discarded device archive", &archive)? {
187            fs::create_dir(&archive).map_err(|source| {
188                FileError::at("create discarded device archive", &archive, source)
189            })?;
190        }
191        // The archive stays for inspection, so what unfinished saves left,
192        // sealed keys among it, doesn't go in. The writer lock is held.
193        atomic_file::remove_temporaries(directory)?;
194        move_local_state(directory, &archive)?;
195        atomic_file::replace(&marker, b"")?;
196    }
197    let loaded = loading(directory, id);
198    if atomic_file::exists("inspect loaded replacement", &loaded)? {
199        move_local_state(&loaded, directory)?;
200    }
201    name_device(directory, id, reset.new_device)
202}
203
204/// The name of the archive a swap keeps of `old_device`'s installation.
205pub(super) fn archive_name(old_device: DeviceId) -> String {
206    format!("{ARCHIVE_PREFIX}{}", old_device.0)
207}
208
209/// The name of every archive in the store's directory, in order.
210pub(super) fn discarded_devices(directory: &Path) -> Result<Vec<String>, FileError> {
211    Ok(archives(directory)?
212        .iter()
213        .map(|archive| {
214            archive
215                .file_name()
216                .and_then(|name| name.to_str())
217                .expect("`archives` lists only UTF-8 names")
218                .to_owned()
219        })
220        .collect())
221}
222
223/// The size of everything in the archive `name`.
224pub(super) fn discarded_device_size(directory: &Path, name: &str) -> Result<u64, FileError> {
225    tree_size(&named_archive(directory, name)?)
226}
227
228/// The path of the archive `name`, refusing a name that is not one.
229fn named_archive(directory: &Path, name: &str) -> Result<PathBuf, FileError> {
230    if !name.starts_with(ARCHIVE_PREFIX) || name.contains(['/', '\\']) || name.contains("..") {
231        return Err(FileError::at(
232            "name a discarded device archive",
233            &directory.join(name),
234            std::io::Error::new(std::io::ErrorKind::InvalidInput, "not an archive's name"),
235        ));
236    }
237    Ok(directory.join(name))
238}
239
240/// Move the archive `name` into the removal folder, in one rename, so it
241/// leaves the store's directory in one step. Returns whether it was there
242/// to move.
243pub(super) fn retire(directory: &Path, name: &str) -> Result<bool, FileError> {
244    set_aside::move_aside(&named_archive(directory, name)?, &directory.join(REMOVING).join(name))
245}
246
247/// Move the archive `name` back from the removal folder, as `retire` found it.
248pub(super) fn unretire(directory: &Path, name: &str) -> Result<(), FileError> {
249    set_aside::move_back(&named_archive(directory, name)?, &directory.join(REMOVING).join(name))
250}
251
252/// Delete the removal folder and everything in it, then sync the store's
253/// directory. No row in the database names the archives in it, so a
254/// deletion that stops partway leaves the rest for the next call. When the folder is absent, the call
255/// does nothing and succeeds.
256pub(super) fn remove_retired(directory: &Path) -> Result<(), FileError> {
257    set_aside::delete(&directory.join(REMOVING))
258}
259
260/// The size of a file, or of everything under a folder. The function does
261/// not follow links, and counts nothing for what disappears while it walks.
262pub(super) fn tree_size(path: &Path) -> Result<u64, FileError> {
263    let metadata = match fs::symlink_metadata(path) {
264        Ok(metadata) => metadata,
265        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(0),
266        Err(source) => return Err(FileError::at("measure a store file", path, source)),
267    };
268    if metadata.is_file() {
269        return Ok(metadata.len());
270    }
271    if !metadata.is_dir() {
272        return Ok(0);
273    }
274    let entries = match fs::read_dir(path) {
275        Ok(entries) => entries,
276        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(0),
277        Err(source) => return Err(FileError::at("list a store folder", path, source)),
278    };
279    let mut total = 0u64;
280    for entry in entries {
281        let entry = entry.map_err(|source| FileError::at("list a store folder", path, source))?;
282        total = total.saturating_add(tree_size(&entry.path())?);
283    }
284    Ok(total)
285}
286
287/// The archives of earlier resets in the store's directory, by name. Nothing
288/// reads one once its reset's notice is in the database (§19.3).
289pub(super) fn archives(directory: &Path) -> Result<Vec<PathBuf>, FileError> {
290    let entries = fs::read_dir(directory)
291        .map_err(|source| FileError::at("list discarded device archives", directory, source))?;
292    let mut found = Vec::new();
293    for entry in entries {
294        let entry = entry
295            .map_err(|source| FileError::at("list discarded device archives", directory, source))?;
296        if entry.file_name().to_str().is_some_and(|name| name.starts_with(ARCHIVE_PREFIX)) {
297            found.push(entry.path());
298        }
299    }
300    found.sort();
301    Ok(found)
302}
303
304/// Whether an entry stays where it is while installations swap: the custody
305/// files the replacement keeps, the settings, which change last, the swap's
306/// own record and marker, the replacement's area, earlier archives and the
307/// folder where coven deletes archives.
308fn stays(name: &str) -> bool {
309    KEPT.iter().any(|file| file.name() == name)
310        || name == settings::SETTINGS_FILE
311        || name == RECORD
312        || name == bootstrap::MARKER
313        || name == AREA
314        || name == REMOVING
315        || name.starts_with(ARCHIVE_PREFIX)
316}
317
318/// Move every local entry of `from` into `to`, then sync both directories.
319fn move_local_state(from: &Path, to: &Path) -> Result<(), FileError> {
320    let entries = fs::read_dir(from)
321        .map_err(|source| FileError::at("list installation files", from, source))?;
322    for entry in entries {
323        let entry =
324            entry.map_err(|source| FileError::at("list installation files", from, source))?;
325        let name = entry.file_name();
326        if name.to_str().is_some_and(stays) {
327            continue;
328        }
329        let source = entry.path();
330        atomic_file::rename_new(&source, &to.join(&name))
331            .map_err(|error| FileError::at("move installation file", &source, error))?;
332    }
333    #[cfg(unix)]
334    for path in [from, to] {
335        atomic_file::sync_directory(path)
336            .map_err(|source| FileError::at("sync installation files", path, source))?;
337    }
338    Ok(())
339}
340
341fn name_device(
342    directory: &Path,
343    id: StoreId,
344    device: DeviceId,
345) -> Result<(), DirectoryCreationError> {
346    let mut current = settings::read(directory, id)?;
347    if current.device_id != device {
348        current.device_id = device;
349        settings::write(directory, &current)?;
350    }
351    Ok(())
352}
353
354/// The database a swap moved aside, in its discarded-device archive.
355pub(super) fn discarded_database(directory: &Path, old_device: DeviceId) -> PathBuf {
356    archive(directory, old_device).join(super::directory::DATABASE)
357}
358
359/// Remove the record once the replacement is published, its database
360/// keeping the notice, or once the facts end a replacement before its swap.
361pub(super) fn finish(directory: &Path) -> Result<(), FileError> {
362    atomic_file::remove(&directory.join(RECORD))
363}