Skip to main content

coven_sync/
file_status.rs

1//! A file's availability: for a file this device uploads, from local facts
2//! alone; for a file only on another device, from its record; for a stored
3//! file, from one storage observation of its path. Never written to a record
4//! (§17.6).
5
6use super::FilesMode;
7use crate::FileSourceFailure;
8use crate::{
9    files::{file_failure::upload_subject, Files, FilesInner},
10    FileMissingReason, FileReadError, PendingReason, PendingRecord,
11};
12use coven_database::{DbError, FileLocation, FilePlace, FileRef};
13use coven_format::file::FileHeader;
14use coven_foundation::id_source::DeviceId;
15use coven_storage::StoredObject;
16
17/// A file's current availability (E8).
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub enum FileStatus {
20    /// Storage holds the complete file at its fixed path.
21    Available,
22    /// This device is uploading it; until then it is on this device only.
23    Uploading,
24    /// It is on one device only, with no upload: another device, which may
25    /// be gone, and then nothing here can read it, or this one, which reads
26    /// it from its bytes here. Nothing waits for it (§17.3).
27    DeviceOnly {
28        /// The device that has it.
29        device: DeviceId,
30    },
31    /// Unreadable from storage, with the reason.
32    Missing {
33        /// The device that uploaded, or is uploading, it.
34        device: DeviceId,
35        /// Why.
36        reason: FileMissingReason,
37    },
38}
39
40/// A file this device uploads: its upload, where its bytes go, its move,
41/// and its source's recorded failure.
42pub(crate) struct Uploading {
43    pub(crate) upload: i64,
44    pub(crate) location: FileLocation,
45    pub(crate) of: coven_database::MoveId,
46    pub(crate) failure: Option<FileSourceFailure>,
47}
48
49/// What this device knows locally about a file: `None` for a stored one,
50/// `Some(report)` for one it uploads, with its source failure if one is
51/// recorded (ST `Files.Local`).
52pub(crate) type Local = Option<Option<FileSourceFailure>>;
53
54/// §17.6, ST `Files.status`. A file this device uploads is judged locally.
55/// For a stored file, presence wins; a failed observation is never absence,
56/// and a confirmed absence is lost, whoever uploaded it.
57pub(crate) fn status<E>(
58    uploader: DeviceId,
59    remote: impl FnOnce() -> Result<bool, E>,
60    here: Local,
61) -> Result<FileStatus, E> {
62    match here {
63        Some(None) => Ok(FileStatus::Uploading),
64        Some(Some(failure)) => {
65            Ok(FileStatus::Missing { device: uploader, reason: FileMissingReason::Source(failure) })
66        }
67        None => Ok(if remote()? {
68            FileStatus::Available
69        } else {
70            FileStatus::Missing { device: uploader, reason: FileMissingReason::Lost }
71        }),
72    }
73}
74
75impl Files {
76    /// The file as its record now stands: a file this device uploads is
77    /// judged from local facts with no storage request, one only on another
78    /// device from its record, and a stored one by one fresh single-object
79    /// status call for its fixed path. Network failures and denied access are
80    /// errors, not absence.
81    pub async fn file_status(&self, file: &FileRef) -> Result<FileStatus, FileReadError> {
82        self.inner.check_open()?;
83        let file = self.inner.current(file).await?;
84        let location = match file.place() {
85            FilePlace::DeviceOnly { device } => {
86                return match self.inner.local(&file).await? {
87                    Some(here) => status::<FileReadError>(
88                        here.location.uploader(),
89                        || Ok(false),
90                        Some(here.failure),
91                    ),
92                    None => match self.inner.unreadable(&file, device).await {
93                        FileReadError::DeviceOnly { .. } => Ok(FileStatus::DeviceOnly { device }),
94                        error => Err(error),
95                    },
96                };
97            }
98            FilePlace::Cloud { location, .. } => location,
99        };
100        let storage = super::file_storage::connected(self.inner.settled().await?)?;
101        let path = location.path(self.inner.directory.id());
102        let remote = match storage.status(&path).await? {
103            Some(object) => complete(&file, &object).map(|()| true),
104            None => Ok(false),
105        };
106        status(location.uploader(), || remote, None)
107    }
108}
109
110impl<M: FilesMode> FilesInner<M> {
111    /// The file as its record now stands. A file never changes its bytes, so
112    /// a reference taken earlier, while the file uploaded, reads the stored
113    /// file once it is stored; one whose record went reads as it was named.
114    pub(crate) async fn current(&self, file: &FileRef) -> Result<FileRef, FileReadError> {
115        match self.database.file_ref(file.id()).await {
116            Ok(current) => Ok(current),
117            Err(DbError::FileAbsent { .. }) => Ok(file.clone()),
118            Err(error) => Err(error.into()),
119        }
120    }
121
122    /// Why a file on one device only can't be read here: this device has no
123    /// record of it any more, or it is only on that device.
124    pub(crate) async fn unreadable(&self, file: &FileRef, device: DeviceId) -> FileReadError {
125        match self.database.file_ref(file.id()).await {
126            Err(error @ DbError::FileAbsent { .. }) => error.into(),
127            _ => FileReadError::DeviceOnly { file: file.id(), device },
128        }
129    }
130
131    /// The upload of a file this device uploads, with the source failure
132    /// recorded about it: its original's, on its move's record, or coven's
133    /// copy's, on its upload's; `None` for any other file.
134    /// A read-only handle keeps no file records, so it knows no upload.
135    pub(crate) async fn local(&self, file: &FileRef) -> Result<Option<Uploading>, FileReadError> {
136        let Some(records) = self.database.records() else {
137            return Ok(None);
138        };
139        let evidence = records
140            .local_evidence::<PendingRecord>(file, upload_subject, |id| {
141                crate::PendingSubject::Move { id }
142            })
143            .await?;
144        Ok(evidence.map(|evidence| {
145            let original = evidence.moving.and_then(|record| match record.reason {
146                PendingReason::Original { path, failure }
147                    if evidence.original.as_ref() == Some(&path) =>
148                {
149                    Some(failure)
150                }
151                _ => None,
152            });
153            let copy = evidence.record.and_then(|record| match record.reason {
154                PendingReason::FileUnavailable(FileMissingReason::Source(failure)) => Some(failure),
155                _ => None,
156            });
157            Uploading {
158                upload: evidence.upload,
159                location: evidence.location,
160                of: evidence.of,
161                failure: original.or(copy),
162            }
163        }))
164    }
165
166    /// The typed read failure for stored bytes storage confirms are absent
167    /// at their path: lost (§17.6).
168    pub(crate) fn absence_error(&self, file: &FileRef, location: &FileLocation) -> FileReadError {
169        FileReadError::Missing { id: file.id().to_string(), device: location.uploader() }
170    }
171}
172
173/// An object at the fixed path counts as the file only at the file's complete
174/// encrypted size; anything else there is damage, not absence. Status and every
175/// ranged read check it, so they agree (ST `read_agrees_with_status`).
176#[expect(
177    clippy::map_err_ignore,
178    reason = "a size whose encrypted layout overflows fails the integrity check"
179)]
180pub(crate) fn complete(file: &FileRef, object: &StoredObject) -> Result<(), FileReadError> {
181    let expected = FileHeader::new(file.size())
182        .encrypted_size()
183        .map_err(|_| FileReadError::Integrity { id: file.id().to_string(), cause: None })?;
184    if object.size == expected {
185        Ok(())
186    } else {
187        Err(FileReadError::Integrity { id: file.id().to_string(), cause: None })
188    }
189}