Skip to main content

coven_database/
file_moves.rs

1//! Moves of this device's files to the cloud (§17.3): the files one write
2//! stages for the cloud, or the files the app moves. Each upload belongs to
3//! one move. No file of a move switches to the cloud until every one of its
4//! uploads is stored; then one write switches them all. A move that fails
5//! or is cancelled switches none. Each moving or failed move lists its
6//! files, for the app to see in `coven_moves`.
7
8use crate::sqlite::StoreSql;
9use crate::DbError;
10use coven_foundation::id_source::FileId;
11
12/// One move's identity on this device, never reused (§17.3, E3).
13#[derive(
14    Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
15)]
16pub struct MoveId(pub i64);
17
18/// A move id bound and read as an SQL integer, as `coven_uploads.move`
19/// and `coven_pending.move` hold it for the app's `cancel_move` (E4).
20impl sqlive::rusqlite::ToSql for MoveId {
21    fn to_sql(&self) -> sqlive::rusqlite::Result<sqlive::rusqlite::types::ToSqlOutput<'_>> {
22        Ok(self.0.into())
23    }
24}
25
26impl sqlive::rusqlite::types::FromSql for MoveId {
27    fn column_result(
28        value: sqlive::rusqlite::types::ValueRef<'_>,
29    ) -> sqlive::rusqlite::types::FromSqlResult<Self> {
30        i64::column_result(value).map(Self)
31    }
32}
33
34/// Where a move stands.
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub(crate) enum MoveState {
37    /// Its uploads are queued; none of its files has switched.
38    Moving,
39    /// A user's original changed before its upload: none of its files
40    /// switched or waits for an upload, and its record says which original
41    /// and its list which files, until the app cancels it.
42    Failed,
43    /// The app cancelled it: none of its files switched, and it lists none.
44    Cancelled,
45    /// Its files switched to the cloud together, and it lists none.
46    Finished,
47}
48
49impl MoveState {
50    fn text(self) -> &'static str {
51        match self {
52            Self::Moving => "moving",
53            Self::Failed => "failed",
54            Self::Cancelled => "cancelled",
55            Self::Finished => "finished",
56        }
57    }
58}
59
60/// Record a new move, moving.
61pub(crate) fn create(db: &StoreSql) -> Result<MoveId, DbError> {
62    Ok(db.query_row("INSERT INTO _coven_moves(state) VALUES('moving') RETURNING id", [], |r| {
63        r.get(0)
64    })?)
65}
66
67/// The move's state, or `None` for a move this device never made.
68pub(crate) fn state(db: &StoreSql, id: MoveId) -> Result<Option<MoveState>, DbError> {
69    db.query("SELECT state FROM _coven_moves WHERE id=?1", [id], |r| r.get::<_, String>(0))?
70        .pop()
71        .map(|state| match state.as_str() {
72            "moving" => Ok(MoveState::Moving),
73            "failed" => Ok(MoveState::Failed),
74            "cancelled" => Ok(MoveState::Cancelled),
75            "finished" => Ok(MoveState::Finished),
76            _ => Err(DbError::DamagedDatabase),
77        })
78        .transpose()
79}
80
81/// Whether the move is a bound file's (§17.4): its upload holds a write
82/// until the file is stored, so the app can't cancel it.
83pub(crate) fn bound(db: &StoreSql, id: MoveId) -> Result<bool, DbError> {
84    Ok(db.query_row(
85        "SELECT EXISTS(SELECT 1 FROM _coven_file_uploads WHERE move=?1 AND holds IS NOT NULL)",
86        [id],
87        |r| r.get(0),
88    )?)
89}
90
91/// The move an upload belongs to.
92pub(crate) fn of_upload(db: &StoreSql, upload: i64) -> Result<MoveId, DbError> {
93    db.query_row("SELECT move FROM _coven_file_uploads WHERE id=?1", [upload], |r| r.get(0))
94        .map_err(|error| match error {
95            sqlive::Error::Sqlite(sqlive::rusqlite::Error::QueryReturnedNoRows) => {
96                DbError::Invariant { what: "a queued upload belongs to a move" }
97            }
98            error => DbError::from(error),
99        })
100}
101
102/// The move that lists `file`, moving or failed, if any: a file is in at
103/// most one move (§17.3).
104pub(crate) fn of_file(db: &StoreSql, file: FileId) -> Result<Option<MoveId>, DbError> {
105    Ok(db.query("SELECT move FROM _coven_move_files WHERE file=?1", [file], |r| r.get(0))?.pop())
106}
107
108/// List each file as one of its move's, as the uploads of the moves come to
109/// store them (§17.3), as one statement for each chunk.
110pub(crate) fn list_all(db: &StoreSql, files: &[(MoveId, FileId)]) -> Result<(), DbError> {
111    let rows: Vec<_> = files
112        .iter()
113        .map(|(id, file)| {
114            Ok(vec![crate::insert_rows::value(id)?, crate::insert_rows::value(file)?])
115        })
116        .collect::<Result<_, DbError>>()?;
117    crate::insert_rows::insert_rows(
118        db,
119        2,
120        &rows,
121        |values| format!("INSERT INTO _coven_move_files(move,file) VALUES{values}"),
122        |_| Ok(()),
123    )?;
124    Ok(())
125}
126
127/// The new file `to` over `from`'s bytes, now waiting for the upload `from`
128/// waits for, joins that upload's move (§17.2, §17.3).
129pub(crate) fn join(db: &StoreSql, from: FileId, to: FileId) -> Result<(), DbError> {
130    db.execute(
131        "INSERT INTO _coven_move_files(move,file)
132         SELECT u.move,?2 FROM _coven_upload_files AS l
133         JOIN _coven_file_uploads AS u ON u.id=l.upload WHERE l.file=?1",
134        sqlive::rusqlite::params![from, to],
135    )?;
136    Ok(())
137}
138
139/// `file`'s record is gone from this device: no move lists it.
140pub(crate) fn forget(db: &StoreSql, file: FileId) -> Result<(), DbError> {
141    db.execute("DELETE FROM _coven_move_files WHERE file=?1", [file])?;
142    Ok(())
143}
144
145/// Move `id` now stands at `state`. A switch or a cancel ends its list with
146/// it; a failure keeps the list, for the app to cancel (§17.3).
147fn set(db: &StoreSql, id: MoveId, state: MoveState) -> Result<(), DbError> {
148    match state {
149        MoveState::Cancelled | MoveState::Finished => {
150            db.execute("DELETE FROM _coven_move_files WHERE move=?1", [id])?;
151        }
152        MoveState::Moving | MoveState::Failed => {}
153    }
154    db.execute(
155        "UPDATE _coven_moves SET state=?2 WHERE id=?1",
156        sqlive::rusqlite::params![id, state.text()],
157    )?;
158    Ok(())
159}
160
161/// End a move switching none of its files: every file stays on this device
162/// only, keeping its bytes here, and no upload of the move stores a file any
163/// more, so the upload worker retires them, an attempt in flight once it
164/// ends, and their stored bytes become deletion candidates (§17.10). A
165/// failed move keeps its list; a cancelled one ends it. The move's pending
166/// record is replaced or cleared by the caller.
167pub(crate) fn end_unswitched(db: &StoreSql, id: MoveId, state: MoveState) -> Result<(), DbError> {
168    crate::file_queue::unswitch_move(db, id)?;
169    set(db, id, state)
170}
171
172/// The moving moves none of whose uploads that still store a file waits to
173/// be stored, each with those uploads: what one write switches now. A move
174/// whose files all dropped out has none.
175pub(crate) fn complete(db: &StoreSql) -> Result<Vec<(MoveId, Vec<i64>)>, DbError> {
176    let moves = db.query(
177        "SELECT m.id FROM _coven_moves AS m WHERE m.state='moving'
178         AND NOT EXISTS(SELECT 1 FROM _coven_file_uploads AS u
179             WHERE u.move=m.id AND u.stored=0
180             AND EXISTS(SELECT 1 FROM _coven_upload_files AS l WHERE l.upload=u.id))",
181        [],
182        |r| r.get(0),
183    )?;
184    moves
185        .into_iter()
186        .map(|id| {
187            let uploads = db.query(
188                "SELECT u.id FROM _coven_file_uploads AS u WHERE u.move=?1
189                 AND EXISTS(SELECT 1 FROM _coven_upload_files AS l WHERE l.upload=u.id)
190                 ORDER BY u.id",
191                [id],
192                |r| r.get(0),
193            )?;
194            Ok((id, uploads))
195        })
196        .collect()
197}
198
199/// A move ended with its files switched: whatever its record said ends.
200pub(crate) fn finish(db: &StoreSql, id: MoveId) -> Result<(), DbError> {
201    set(db, id, MoveState::Finished)?;
202    crate::pending::clear_move(db, id)
203}
204
205#[cfg(test)]
206#[path = "file_moves_tests.rs"]
207pub(crate) mod tests;