Skip to main content

coven_sync/
upload_phase.rs

1//! What each upload in the queue is doing (§17.9, api.md E7), computed from the
2//! facts the sync state reads, as `Upload.phase` of the Lean model in
3//! `spec/proofs/io/CovenIO/Transfers.lean` computes it. The state names bound
4//! uploads only; every upload, a trailing one included, has this phase, which
5//! an app shows where files are. `uploads()` gives it, and the
6//! `coven_upload_phases` view shows it through `_coven_upload_phase`
7//! (`upload_phase_row`), so an app's live query reads the same phase.
8
9use crate::files::{UploadPhase, UploadWait};
10use crate::sync_status::{Facts, Progress, Upload};
11use crate::{PendingRecord, SyncWait};
12use coven_database::{DbError, TransferHolds, UploadPhaseFacts, UploadPhaseRow};
13
14impl SyncWait {
15    /// What the same hold shows as an upload's wait: only what holds every
16    /// transfer, the pass's, each upload's and a queued write's alike,
17    /// holds an upload as well (the model's `Facts.heldAll`).
18    fn held_transfers(self) -> Option<UploadWait> {
19        match self {
20            Self::NotSyncing => Some(UploadWait::NotSyncing),
21            Self::CoolingDown { until } => Some(UploadWait::CoolingDown { until }),
22            Self::KeyCopy { .. } | Self::Snapshot { .. } => Some(UploadWait::Sync),
23            Self::Retrying { .. } => None,
24        }
25    }
26}
27
28impl Facts {
29    /// What one upload in the queue is doing, a trailing one's included (the
30    /// model's `Upload.phase`), with what holds every transfer as these facts
31    /// say it: `upload_phase`.
32    pub(crate) fn upload_phase(&self, holds: &TransferHolds, upload: &Upload) -> UploadPhase {
33        match upload_phase(self.held_all(), holds, upload, |record| record) {
34            Phase::Uploading => UploadPhase::Uploading,
35            Phase::Stored => UploadPhase::Stored,
36            Phase::Waiting(wait) => UploadPhase::Waiting(wait),
37            Phase::Failed(record) => UploadPhase::Failed(record.clone()),
38        }
39    }
40}
41
42/// An upload's phase, as `UploadPhase` names it, with a failed phase
43/// carrying the upload's record as its reader keeps it.
44enum Phase<R> {
45    Uploading,
46    Stored,
47    Waiting(UploadWait),
48    Failed(R),
49}
50
51/// What one upload in the queue is doing, a trailing one's included (the
52/// model's `Upload.phase`): sending, stored, failed once its record names a
53/// state, else waiting for the first that holds. What holds every transfer
54/// (`held_all`) comes first, then what holds a trailing upload only
55/// (`holds`: the pause, the network, a self-replacement's write pause),
56/// then its backoff, then its turn. The network comes before the backoff,
57/// since an upload whose backoff ends still can't go out on a metered
58/// network. `record_of` gives the pending record of what the upload keeps as `R`.
59fn upload_phase<'a, R>(
60    held_all: Option<SyncWait>,
61    holds: &TransferHolds,
62    upload: &'a Upload<R>,
63    record_of: impl Fn(&R) -> &PendingRecord,
64) -> Phase<&'a R> {
65    match upload.progress {
66        Progress::Moving => Phase::Uploading,
67        Progress::Stored => Phase::Stored,
68        Progress::Queued => {
69            if let Some(record) =
70                upload.record.as_ref().filter(|record| record_of(record).reason.names_a_state())
71            {
72                return Phase::Failed(record);
73            }
74            Phase::Waiting(if let Some(held) = held_all.and_then(SyncWait::held_transfers) {
75                held
76            } else if holds.paused && !upload.bound {
77                UploadWait::Paused
78            } else if holds.unmetered_only
79                && holds.metered
80                && crate::files::held_on_metered(upload.bound)
81            {
82                UploadWait::Metered
83            } else if holds.keys_changing && !upload.bound {
84                UploadWait::KeysChanging
85            } else if let Some(at) = upload.retry_at {
86                UploadWait::Retrying { at }
87            } else {
88                UploadWait::Queued
89            })
90        }
91    }
92}
93
94/// One upload's phase as `coven_upload_phases` shows it, from the facts the
95/// view passes `_coven_upload_phase`: the phase `uploads()` gives the
96/// upload, with its record chosen as `uploads()` chooses it, its own, else
97/// its move's when that names the original the upload uploads.
98fn upload_phase_row(facts: UploadPhaseFacts<PendingRecord>) -> Result<UploadPhaseRow, DbError> {
99    let last = crate::sync_status::last_pass(facts.last_pass)?;
100    let original = facts.original.as_deref();
101    let record = facts.own.or_else(|| {
102        facts.moving.filter(|(_, record)| crate::files::names_original(&record.reason, original))
103    });
104    let upload = Upload {
105        progress: if facts.sending {
106            Progress::Moving
107        } else if facts.stored {
108            Progress::Stored
109        } else {
110            Progress::Queued
111        },
112        bound: facts.bound,
113        retry_at: facts.retry_at,
114        record,
115    };
116    let held_all = crate::sync_status::held_all(facts.sync, last.as_ref());
117    // The record keeps its position in `coven_pending`, which a failure names.
118    Ok(match upload_phase(held_all, &facts.holds, &upload, |(_, record)| record) {
119        Phase::Uploading => UploadPhaseRow::Uploading,
120        Phase::Stored => UploadPhaseRow::Stored,
121        Phase::Waiting(wait) => UploadPhaseRow::Waiting(wait.kind()),
122        Phase::Failed((position, _)) => UploadPhaseRow::Failed(*position),
123    })
124}
125
126/// `_coven_sync_state` and `_coven_upload_phase`, the functions
127/// `coven_sync_state` and `coven_upload_phases` call, for the database to
128/// register on every connection: the state and each upload's phase computed
129/// in this crate's Rust code, so that it stays the one definition the Lean
130/// model checks while an app's screen reads them in SQL (§17.9, §19.1).
131pub fn sync_functions() -> coven_database::SyncFunctions {
132    coven_database::SyncFunctions::new(crate::sync_status::SyncStatus::row, upload_phase_row)
133}
134
135#[cfg(test)]
136#[path = "upload_phase_tests.rs"]
137mod tests;