Skip to main content

coven_sync/
file_upload_queue.rs

1//! The upload queue as the app observes it (E7): the committed queue, with
2//! the uploads this process is sending now, and what each upload is doing.
3
4use crate::{PendingReason, PendingRecord};
5pub use coven_database::UploadProgress;
6use coven_database::{DbError, QueueFacts};
7use coven_foundation::id_source::FileId;
8use std::time::SystemTime;
9
10/// Observable upload queue state (E7): one committed snapshot of the queue,
11/// with the uploads this process is sending as it is read.
12#[derive(Clone, Debug, PartialEq)]
13pub struct UploadQueue {
14    /// Whether transfer work is paused; persisted across reopening.
15    pub paused: bool,
16    /// Waiting files, oldest first. Files sharing one upload share its
17    /// place, progress and phase.
18    pub files: Vec<QueuedUpload>,
19}
20/// One queued upload: what it is doing, and its committed progress.
21#[derive(Clone, Debug, PartialEq)]
22pub struct QueuedUpload {
23    /// The file its upload switches to the cloud.
24    pub file: FileId,
25    /// What the upload is doing (§17.9). App SQL reads the same phase from
26    /// `coven_upload_phases` (E4).
27    pub phase: UploadPhase,
28    /// Progress the provider confirmed and this device persisted in the
29    /// file's resumable session; `None` while it has no session, as a file
30    /// sent in one request never does.
31    pub progress: Option<UploadProgress>,
32    /// Enqueue time.
33    pub queued_at: SystemTime,
34}
35/// What a queued upload is doing, bound and trailing alike: the sync state
36/// names bound files only, so what a trailing file waits for, and its
37/// failure, are shown here (§17.9, §19.1). Whether it is sending is
38/// persisted nowhere: a reopened store starts with every file waiting.
39#[derive(Clone, Debug, PartialEq)]
40pub enum UploadPhase {
41    /// An attempt is sending it now, in one request or in parts.
42    Uploading,
43    /// Storage holds its bytes; it waits for the rest of its move (§17.3).
44    Stored,
45    /// Not being sent, for this reason.
46    Waiting(UploadWait),
47    /// Its pending record names a failure only a person clears, or one that
48    /// never clears: a file whose original is missing or changed, coven's
49    /// copy failing its check, stored bytes lost or refused, a full account.
50    Failed(PendingRecord),
51}
52
53/// What a queued upload waits for, the first that holds (§17.9).
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub enum UploadWait {
56    /// Sync isn't running (`start_sync`, `stop_sync`).
57    NotSyncing,
58    /// The provider asked every request to wait until then (§6.7).
59    CoolingDown {
60        /// When the cooldown ends, by the store's clock.
61        until: SystemTime,
62    },
63    /// A slot can't apply yet, so no transfer goes out until it does (§5.4).
64    Sync,
65    /// The app paused uploads, and the file's reference trails
66    /// (`set_uploads_paused`, §17.4).
67    Paused,
68    /// The network is metered, or may be, since the platform stopped
69    /// answering after opening (E5); the app moves files only on unmetered
70    /// networks (`set_unmetered_only`, §17.9), and the file's reference
71    /// trails.
72    Metered,
73    /// A self-replacement of this member's keys pauses writes, and the
74    /// file's reference trails (§12.3).
75    KeysChanging,
76    /// Its last attempt failed, and it retries then, or at the person's
77    /// retry (§6.7).
78    Retrying {
79        /// When its backoff ends, by the store's clock.
80        at: SystemTime,
81    },
82    /// Its turn hasn't come.
83    Queued,
84}
85
86impl UploadPhase {
87    /// The phase's kind, in snake case, as `coven_upload_phases.phase`
88    /// holds it.
89    pub fn kind(&self) -> &'static str {
90        match self {
91            Self::Uploading => "uploading",
92            Self::Stored => "stored",
93            Self::Waiting(_) => "waiting",
94            Self::Failed(_) => "failed",
95        }
96    }
97}
98
99impl UploadWait {
100    /// The wait's kind, in snake case, as `coven_upload_phases.wait` holds
101    /// it.
102    pub fn kind(self) -> &'static str {
103        match self {
104            Self::NotSyncing => "not_syncing",
105            Self::CoolingDown { .. } => "cooling_down",
106            Self::Sync => "sync",
107            Self::Paused => "paused",
108            Self::Metered => "metered",
109            Self::KeysChanging => "keys_changing",
110            Self::Retrying { .. } => "retrying",
111            Self::Queued => "queued",
112        }
113    }
114}
115
116impl UploadQueue {
117    /// The queue as one committed snapshot read it: each upload's phase from
118    /// the facts the sync state reads, what holds trailing uploads, the
119    /// upload's retry wait and what coven records about it. A move's record
120    /// names an original, and shows as the record of the upload that uploads
121    /// that original, as the upload's own record does for its bytes.
122    pub fn from_facts(facts: QueueFacts<PendingRecord>) -> Result<Self, DbError> {
123        let QueueFacts { sync, holds, queue, recorded } = facts;
124        let (state, _) = crate::sync_status::Facts::read(sync)?;
125        let mut files = Vec::new();
126        for upload in queue.uploads {
127            let recorded = recorded.iter().find(|recorded| recorded.upload == upload.id);
128            let record = recorded.and_then(|recorded| {
129                recorded.own.clone().or_else(|| {
130                    recorded.moving.clone().filter(|record| {
131                        names_original(&record.reason, recorded.original.as_deref())
132                    })
133                })
134            });
135            let sending = upload.files.iter().any(|file| queue.sending.contains(file));
136            let phase = state.upload_phase(
137                &holds,
138                &crate::sync_status::Upload {
139                    progress: if sending {
140                        crate::sync_status::Progress::Moving
141                    } else if upload.stored {
142                        crate::sync_status::Progress::Stored
143                    } else {
144                        crate::sync_status::Progress::Queued
145                    },
146                    bound: upload.holds.is_some(),
147                    retry_at: upload.retry.map(|retry| retry.not_before),
148                    record,
149                },
150            );
151            files.extend(upload.files.iter().map(|file| QueuedUpload {
152                phase: phase.clone(),
153                file: *file,
154                progress: upload.progress,
155                queued_at: upload.queued_at,
156            }));
157        }
158        Ok(Self { paused: queue.paused, files })
159    }
160}
161
162/// Whether `reason` names the original at `path`: a move's record shows as
163/// the phase of the upload that uploads the original it names.
164pub(crate) fn names_original(reason: &PendingReason, path: Option<&std::path::Path>) -> bool {
165    matches!(reason, PendingReason::Original { path: named, .. } if Some(named.as_path()) == path)
166}