Skip to main content

coven_foundation/files/
replacement.rs

1//! A new installation of a published store, loaded beside the store's own
2//! files before it takes their place (§19.3).
3//!
4//! `reset_device` and `restore_device` load the replacement in a hidden
5//! directory inside the store's directory, while the store stays as it was
6//! and its writer lock stays held. Before the fresh device registers, the
7//! replacement records itself: from then on the store refuses opens and the
8//! replacement only moves forward, unless the facts end it before the swap.
9//! Once the registration applied, the swap moves the old local state into an
10//! archive and the new installation into place; a restore then removes the
11//! archive. A failure before the record leaves the store untouched. A
12//! replacement recorded or swapping is finished by the next call of the same
13//! kind, and the other kind is refused.
14
15use super::{
16    atomic_file::{self, exists},
17    bootstrap::{self, BootstrapLease},
18    creation, device_reset,
19    file_lock::FileLock,
20    lock,
21    protection::Protection,
22    settings, BootstrapDirectoryError, BootstrapStore, DeviceReset, DirectoryCreationError,
23    FileError, Registration, ReplacedBy, ReplacementPhase, ReplacementRecord, StoreDir,
24    StoreDirAccess, StoreLock, StoreLockError,
25};
26use crate::id_source::{IdSource, StoreId};
27use crate::locks::lock_unpoisoned;
28use std::{
29    fs, io,
30    path::{Path, PathBuf},
31    sync::Mutex,
32};
33
34/// A replacement of the installation in a published store's directory. It
35/// holds the store's bootstrap lease, and its writer lock until the new
36/// installation is in place. Dropping it keeps its work for the next call.
37pub struct ReplacementStore {
38    // Drops before the lease: the store's locks are closing before the
39    // bootstrap lock is released.
40    _closing: lock::StoreClosingGuard,
41    path: PathBuf,
42    id: StoreId,
43    reset: DeviceReset,
44    by: ReplacedBy,
45    /// What the registration does to the old id: the recorded choice for a
46    /// recorded replacement, else the call's.
47    registration: Registration,
48    lease: BootstrapLease,
49    /// Keeps every handle out while the new installation loads and swaps in.
50    writer: Mutex<Option<StoreLock>>,
51    /// Keeps read-only handles out from the record until the swap, so a
52    /// recorded replacement never waits on one (§19.3).
53    readers: Mutex<Option<FileLock>>,
54    /// The replacement's record, once written: past it, it only goes forward.
55    record: Mutex<Option<ReplacementRecord>>,
56    /// The new installation's own bootstrap while it loads in the hidden
57    /// directory; none once it has swapped in.
58    loading: Mutex<Option<BootstrapStore>>,
59    protection: Protection,
60    bugs: crate::task::BugSinkRef,
61}
62
63impl ReplacementStore {
64    /// The installation being replaced and its fresh successor.
65    pub fn device_reset(&self) -> DeviceReset {
66        self.reset
67    }
68
69    /// What the fresh device's registration does to the old id.
70    pub fn registration(&self) -> Registration {
71        self.registration
72    }
73
74    /// Whether the new installation has taken the store's place.
75    pub fn is_swapped(&self) -> bool {
76        lock_unpoisoned(&self.loading).is_none()
77    }
78
79    /// Where the new installation is: its hidden directory while it loads,
80    /// then the store's own, unpublished until `publish`.
81    pub fn directory(&self) -> StoreDir {
82        match &*lock_unpoisoned(&self.loading) {
83            Some(loading) => loading.directory(),
84            None => StoreDir::bootstrapping(
85                self.path.clone(),
86                self.id,
87                self.lease.instance(),
88                self.protection,
89                self.bugs.clone(),
90            ),
91        }
92    }
93
94    /// The replaced installation's database: in place while the new one
95    /// loads, then in its archive. Only its operation journal is read.
96    pub fn discarded_database_path(&self) -> PathBuf {
97        match &*lock_unpoisoned(&self.loading) {
98            Some(_) => self.path.join(super::directory::DATABASE),
99            None => device_reset::discarded_database(&self.path, self.reset.old_device),
100        }
101    }
102
103    /// Whether the replacement is recorded: past its point of no return.
104    pub fn is_recorded(&self) -> bool {
105        lock_unpoisoned(&self.record).is_some()
106    }
107
108    /// Record the replacement before its fresh device registers, naming the
109    /// call that began it and the store's `name` in the loaded database:
110    /// from here the store refuses opens and lists as this call's to finish,
111    /// and read-only handles are kept out until the swap. A reader holding
112    /// the store refuses the record, changing nothing. Recording again keeps
113    /// the first record.
114    pub fn record(&self, name: String) -> Result<(), BootstrapDirectoryError> {
115        let mut recorded = lock_unpoisoned(&self.record);
116        if recorded.is_some() {
117            return Ok(());
118        }
119        let readers = self.exclude_readers()?;
120        let record = ReplacementRecord {
121            reset: self.reset,
122            by: self.by,
123            registration: self.registration,
124            name,
125            phase: ReplacementPhase::Registering,
126        };
127        let kept =
128            device_reset::record(&self.path, &record).map_err(DirectoryCreationError::from)?;
129        *lock_unpoisoned(&self.readers) = Some(readers);
130        *recorded = Some(kept);
131        Ok(())
132    }
133
134    /// Mark the swap as begun, recording the replacement first when it has
135    /// no registration to precede (an unconnected reset), then move the old
136    /// local state into its archive and the loaded installation into the
137    /// store's directory, keeping the store's custody files in place. Then
138    /// release the writer and reader locks: from here the marker refuses
139    /// other opens. The loading database must be closed. A failure leaves the
140    /// swap for the next call to finish; nothing moves back.
141    pub fn swap(&self, name: String) -> Result<(), BootstrapDirectoryError> {
142        let mut loading = lock_unpoisoned(&self.loading);
143        if loading.is_none() {
144            return Ok(());
145        }
146        // No reader may hold the moving files open.
147        let held = lock_unpoisoned(&self.readers).take();
148        let _readers = match held {
149            Some(readers) => readers,
150            None => self.exclude_readers()?,
151        };
152        let recorded = lock_unpoisoned(&self.record).clone();
153        let record = match recorded {
154            Some(record) => record,
155            None => device_reset::record(
156                &self.path,
157                &ReplacementRecord {
158                    reset: self.reset,
159                    by: self.by,
160                    registration: self.registration,
161                    name,
162                    phase: ReplacementPhase::Swapping,
163                },
164            )
165            .map_err(DirectoryCreationError::from)?,
166        };
167        device_reset::swapping(&self.path, &record).map_err(DirectoryCreationError::from)?;
168        device_reset::forward(&self.path, self.id, self.reset)?;
169        drop(loading.take());
170        self.release_writer();
171        Ok(())
172    }
173
174    /// End a recorded replacement before its swap, once the facts say nothing
175    /// in storage names its fresh device as the old one's active replacement:
176    /// remove the record, so the old installation is the store again, then
177    /// the new installation. The loading database must be closed. A failure
178    /// part way leaves the new installation without its record, which the
179    /// next call continues as an unrecorded load.
180    pub fn abandon(self) -> Result<(), BootstrapDirectoryError> {
181        assert!(!self.is_swapped(), "only an unswapped replacement is abandoned");
182        device_reset::finish(&self.path)?;
183        lock_unpoisoned(&self.record).take();
184        lock_unpoisoned(&self.readers).take();
185        self.cancel()
186    }
187
188    fn exclude_readers(&self) -> Result<FileLock, StoreLockError> {
189        lock::exclude_readers(&self.path, self.id)
190    }
191
192    /// The name of the archive the swap keeps of the replaced installation,
193    /// which a restore removes before publication (§13.1).
194    pub fn discarded_device_name(&self) -> String {
195        device_reset::archive_name(self.reset.old_device)
196    }
197
198    /// Publish the swapped installation: remove the hidden directory, then
199    /// the marker, then the record. A failure before the marker leaves the
200    /// swap for the next call to finish. After a `Create(Published { .. })`
201    /// error the store is visible.
202    pub fn publish(&self) -> Result<(), BootstrapDirectoryError> {
203        assert!(self.is_swapped(), "publication follows the swap");
204        remove_area(&self.path)?;
205        let published = |source: io::Error| -> BootstrapDirectoryError {
206            DirectoryCreationError::Published { id: self.id, source }.into()
207        };
208        let result = bootstrap::remove_marker(&self.path, published);
209        self.lease.release();
210        result?;
211        device_reset::finish(&self.path).map_err(|error| published(io::Error::other(error)))
212    }
213
214    /// Remove the unrecorded replacement after its database closed, leaving
215    /// the store as it was. A later call starts a new one with a fresh id.
216    pub fn cancel(self) -> Result<(), BootstrapDirectoryError> {
217        assert!(!self.is_recorded(), "a recorded replacement only moves forward");
218        let loading = lock_unpoisoned(&self.loading)
219            .take()
220            .expect("only an unswapped replacement is cancelled");
221        loading.cancel()?;
222        drop(loading);
223        Ok(remove_area(&self.path)?)
224    }
225
226    fn release_writer(&self) {
227        lock_unpoisoned(&self.writer).take();
228    }
229}
230
231fn remove_area(directory: &Path) -> Result<(), FileError> {
232    let area = directory.join(device_reset::AREA);
233    if exists("inspect replacement area", &area)? {
234        fs::remove_dir_all(&area)
235            .map_err(|source| FileError::at("remove replacement area", &area, source))?;
236        atomic_file::sync_publication(&area)?;
237    }
238    Ok(())
239}
240
241/// Hold the store's bootstrap and writer locks, then continue a swap already
242/// under way or begin loading a replacement, resuming one that was loading.
243/// A swap that the other call began is refused before anything changes.
244pub(super) async fn begin(
245    root: &Path,
246    id: StoreId,
247    by: ReplacedBy,
248    registration: Registration,
249    ids: &dyn IdSource,
250    protection: Protection,
251    bugs: crate::task::BugSinkRef,
252) -> Result<ReplacementStore, BootstrapDirectoryError> {
253    let root = fs::canonicalize(root)
254        .map_err(|source| FileError::at("resolve store layout", root, source))?;
255    let path = root.join(id.to_string());
256    let lock = lock::acquire_bootstrap(&path, id, &bugs).await?;
257    let closing = lock.closing_guard();
258    let lease = BootstrapLease::new(lock);
259    // A live handle, in this process or another, refuses the replacement.
260    let writer = lock::acquire_for_open(&path, id, &bugs).await?;
261    let current = settings::read(&path, id).map_err(DirectoryCreationError::Settings)?;
262    // The device is leaving the store: only finishing that deletion, or
263    // discarding the store, ends it.
264    if super::deletion::read(&path)?.is_some() {
265        return Err(StoreLockError::DeletionUnfinished(id).into());
266    }
267    let pending = bootstrap::is_pending(&path)?;
268    let recorded = match device_reset::read(&path)? {
269        // Publication removed the marker but not the record: that replacement
270        // is finished, and this call begins a new one.
271        Some(record) if !pending && current.device_id == record.reset.new_device => {
272            device_reset::finish(&path)?;
273            None
274        }
275        recorded => recorded,
276    };
277    match &recorded {
278        // Finishing the other call's swap would load under different keys,
279        // or keep or remove a different copy.
280        Some(record) if record.by != by => {
281            return Err(StoreLockError::ReplacementUnfinished { store: id, by: record.by }.into())
282        }
283        None if pending => return Err(StoreLockError::BootstrapPending(id).into()),
284        _ => {}
285    }
286    // The installation that stays until the swap, and the replacement's
287    // area, made inside the store's directory, take the class (E1).
288    protection.apply(&path)?;
289    let (reset, loading, readers) = match &recorded {
290        // An interrupted swap finishes the swap.
291        Some(record) if record.phase == ReplacementPhase::Swapping => {
292            let _readers = lock::exclude_readers(&path, id)?;
293            device_reset::forward(&path, id, record.reset)?;
294            (record.reset, None, None)
295        }
296        // A recorded replacement continues its load, registration included,
297        // with the fresh id it recorded; read-only handles stay out.
298        Some(record) => {
299            let readers = lock::exclude_readers(&path, id)?;
300            let area = path.join(device_reset::AREA);
301            let loading_path = device_reset::loading(&path, id);
302            if !exists("inspect recorded replacement", &loading_path)? {
303                return Err(FileError::at(
304                    "resume a recorded replacement",
305                    &loading_path,
306                    io::Error::new(
307                        io::ErrorKind::NotFound,
308                        "the recorded replacement's installation is missing",
309                    ),
310                )
311                .into());
312            }
313            let loading =
314                bootstrap::reserve_bootstrap_directory(&area, id, ids, protection, bugs.clone())
315                    .await?;
316            let new =
317                loading.directory().settings().map_err(DirectoryCreationError::Settings)?.device_id;
318            if new != record.reset.new_device {
319                return Err(FileError::at(
320                    "resume a recorded replacement",
321                    &loading_path,
322                    io::Error::new(
323                        io::ErrorKind::InvalidData,
324                        "the loaded installation is not the recorded fresh device",
325                    ),
326                )
327                .into());
328            }
329            (record.reset, Some(loading), Some(readers))
330        }
331        None => {
332            let area = path.join(device_reset::AREA);
333            // A cancelled replacement may have left its area's lock files.
334            if !exists("inspect loading replacement", &device_reset::loading(&path, id))? {
335                remove_area(&path)?;
336            }
337            creation::create_directory(&area)
338                .map_err(|source| FileError::at("create replacement area", &area, source))?;
339            let loading =
340                bootstrap::reserve_bootstrap_directory(&area, id, ids, protection, bugs.clone())
341                    .await?;
342            let new =
343                loading.directory().settings().map_err(DirectoryCreationError::Settings)?.device_id;
344            (DeviceReset { old_device: current.device_id, new_device: new }, Some(loading), None)
345        }
346    };
347    // A recorded replacement registers the entry it recorded.
348    let registration = recorded.as_ref().map_or(registration, |record| record.registration);
349    // Once swapped in, the marker refuses other opens.
350    let writer = loading.is_some().then_some(writer);
351    Ok(ReplacementStore {
352        _closing: closing,
353        path,
354        id,
355        reset,
356        by,
357        registration,
358        lease,
359        writer: Mutex::new(writer),
360        readers: Mutex::new(readers),
361        record: Mutex::new(recorded),
362        loading: Mutex::new(loading),
363        protection,
364        bugs,
365    })
366}
367
368#[cfg(test)]
369#[path = "replacement_tests.rs"]
370mod tests;