Skip to main content

coven_database/
file_write_device_only.rs

1//! Making cloud files device-only on this device (§17.3): who may, and the
2//! write that switches every file of one call to this device, its copy
3//! becoming the original this device records.
4
5use super::FileWrite;
6use crate::sqlite::StoreSql;
7use crate::store_call::StoreCall;
8use crate::{
9    file_hashes::FileHashes,
10    file_location::{FileLocation, Place},
11    file_table::Record,
12    write_schema::WriteSchema,
13    DbError, Provenance,
14};
15use coven_foundation::id_source::{DeviceId, FileId};
16use coven_merge::RowId;
17use std::path::PathBuf;
18
19/// A cloud file to make device-only here: its id, the stored bytes its copy
20/// was downloaded from, the copy's path, which becomes the original this
21/// device records, and the hashes of the bytes written to it, which a later
22/// move to the cloud checks the copy against (§17.3).
23#[derive(Debug)]
24pub struct DeviceOnlyCopy {
25    /// The file.
26    pub file: FileId,
27    /// The stored bytes the copy holds.
28    pub location: FileLocation,
29    /// The copy, placed in its final path.
30    pub path: PathBuf,
31    /// The content hash and chunk hashes of the bytes written to the copy.
32    pub hashes: FileHashes,
33}
34
35/// The record of `file` once this device may make it device-only (§17.3):
36/// its record is here and in the cloud, of a user namespace; this device's
37/// member is in its audience; and it may change every row referencing it,
38/// which an `owner_only` table's rows another member created refuse, as
39/// does every row of an `admin_only` table for a member who isn't an admin.
40/// An admin gets no exception on an owned row, as with any change (§9.6).
41pub(crate) fn permitted(
42    db: &StoreSql,
43    call: &StoreCall<'_>,
44    schema: &WriteSchema,
45    device: DeviceId,
46    file: FileId,
47) -> Result<Record, DbError> {
48    let record = Record::read(db, file)?.ok_or(DbError::FileAbsent { file })?;
49    schema.namespace_of(&record.namespace, Provenance::UserProvided)?;
50    if !matches!(record.place, Place::Cloud(_)) {
51        return Err(DbError::NotInCloud { file });
52    }
53    crate::write_commit::check_membership(db, device, &record.audience)?;
54    let mut permissions = crate::permission::Permissions::new(
55        db,
56        call,
57        schema,
58        device,
59        crate::transaction_constants::schema_version(db, call)?,
60    )?;
61    for (table, key) in db.query(
62        "SELECT DISTINCT table_name,key FROM _coven_file_references WHERE file=?1
63         ORDER BY table_name,key",
64        [file],
65        |r| Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?)),
66    )? {
67        let row = RowId { table, key, audience: record.audience.clone() };
68        if let Some(denial) = permissions.denial(&row)? {
69            return Err(crate::permission::refusal(&row, &denial.failure())?);
70        }
71    }
72    Ok(record)
73}
74
75impl FileWrite<'_> {
76    /// Switch a prepared call's files to their copies in this write. Every
77    /// copy must be reserved in this store (`PreparedElsewhere`); the
78    /// reservation is let go once the write has decided.
79    pub(crate) fn make_prepared_device_only(
80        &self,
81        prepared: crate::PreparedDeviceOnly,
82    ) -> Result<(), DbError> {
83        super::held_here(self.files.copying, &prepared.paths())?;
84        let (copies, paths) = prepared.take();
85        self.files.held_copies.borrow_mut().extend(paths);
86        self.make_device_only(copies)
87    }
88
89    /// Switch each file to this device only, off the stored bytes its copy
90    /// was downloaded from, in this write (§17.3). Each must still be
91    /// permitted, and still stored there: a file another device's switch
92    /// took off them meanwhile is `NotInCloud`.
93    fn make_device_only(&self, copies: Vec<DeviceOnlyCopy>) -> Result<(), DbError> {
94        let db = self.database;
95        for copy in copies {
96            let record = permitted(db, self.call, self.files.schema, self.files.device, copy.file)?;
97            if record.place != Place::Cloud(copy.location.clone()) {
98                return Err(DbError::NotInCloud { file: copy.file });
99            }
100            crate::file_table::device_only(db, copy.file, self.files.device)?;
101            self.files.local.borrow_mut().push(copy);
102        }
103        Ok(())
104    }
105
106    /// Once the write applied, record each copy it switched as its file's
107    /// original here, with the size and modification time the copy had when
108    /// it was placed and the hashes of the bytes written to it, and keep the
109    /// copy (§17.3). An original recorded for the file before is forgotten,
110    /// never touched.
111    #[expect(
112        clippy::map_err_ignore,
113        reason = "a stored value that won't convert or decode is DamagedDatabase"
114    )]
115    pub(super) fn keep_device_only(&self) -> Result<(), DbError> {
116        let db = self.database;
117        for copy in self.files.local.take() {
118            let path = crate::database::file_database::copies::text(&copy.path)?;
119            let (size, modified_at) = db
120                .query(
121                    "SELECT size,modified_at FROM _coven_copies WHERE path=?1 AND state='placed'",
122                    [path],
123                    |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Vec<u8>>(1)?)),
124                )?
125                .pop()
126                .ok_or(DbError::Invariant {
127                    what: "a copy is placed before its file switches to it",
128                })?;
129            let original = crate::UserFile {
130                path: copy.path.clone(),
131                size: u64::try_from(size).map_err(|_| DbError::DamagedDatabase)?,
132                modified_at: crate::user_file::decode_time(&modified_at)?,
133            };
134            crate::user_file::forget(db, copy.file)?;
135            crate::user_file::record(db, copy.file, &original, &copy.hashes)?;
136            crate::database::file_database::copies::keep(db, path)?;
137        }
138        Ok(())
139    }
140}