1use 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-";
27const REMOVING: &str = "removing-discarded-devices";
31pub(super) const AREA: &str = ".coven-replacement";
33const KEPT: [StoreFile; 3] =
36 [StoreFile::StorageSettings, StoreFile::StoreKeys, StoreFile::MemberKeys];
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
40pub struct DeviceReset {
41 pub old_device: DeviceId,
43 pub new_device: DeviceId,
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
51pub enum ReplacedBy {
52 Reset,
54 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
70pub enum Registration {
71 ReplacesOld,
73 NewDevice,
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
80pub enum ReplacementPhase {
81 Registering,
84 Swapping,
86}
87
88#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(deny_unknown_fields)]
92pub struct ReplacementRecord {
93 pub reset: DeviceReset,
95 pub by: ReplacedBy,
97 pub registration: Registration,
100 pub name: String,
103 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
111pub(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
131pub(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
155pub(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
165pub(super) fn loading(directory: &Path, id: StoreId) -> PathBuf {
167 directory.join(AREA).join(id.to_string())
168}
169
170fn archive(directory: &Path, old_device: DeviceId) -> PathBuf {
172 directory.join(archive_name(old_device))
173}
174
175pub(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 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
204pub(super) fn archive_name(old_device: DeviceId) -> String {
206 format!("{ARCHIVE_PREFIX}{}", old_device.0)
207}
208
209pub(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
223pub(super) fn discarded_device_size(directory: &Path, name: &str) -> Result<u64, FileError> {
225 tree_size(&named_archive(directory, name)?)
226}
227
228fn 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
240pub(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
247pub(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
252pub(super) fn remove_retired(directory: &Path) -> Result<(), FileError> {
257 set_aside::delete(&directory.join(REMOVING))
258}
259
260pub(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
287pub(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
304fn 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
318fn 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, ¤t)?;
350 }
351 Ok(())
352}
353
354pub(super) fn discarded_database(directory: &Path, old_device: DeviceId) -> PathBuf {
356 archive(directory, old_device).join(super::directory::DATABASE)
357}
358
359pub(super) fn finish(directory: &Path) -> Result<(), FileError> {
362 atomic_file::remove(&directory.join(RECORD))
363}