1use crate::file_hashes::{FileHasher, FileHashes};
4use crate::sqlite::StoreSql;
5use crate::DbError;
6use coven_foundation::files::{FileLease, ObservationError, UserOriginal};
7use std::{
8 path::{Path, PathBuf},
9 time::SystemTime,
10};
11
12#[derive(Debug)]
16pub struct PreparedUserFile {
17 pub(crate) original: UserFile,
18 pub(crate) hashes: FileHashes,
19}
20
21impl PreparedUserFile {
22 pub fn size(&self) -> u64 {
25 self.original.size
26 }
27
28 pub fn modified_at(&self) -> SystemTime {
32 self.original.modified_at
33 }
34}
35
36#[derive(Clone, Debug, Eq, PartialEq)]
38pub struct UserFile {
39 pub path: PathBuf,
41 pub size: u64,
43 pub modified_at: SystemTime,
45}
46
47pub async fn prepare_user_file(
53 path: &Path,
54 lease: &FileLease,
55 progress: impl Fn(u64) + Send + Sync,
56) -> Result<PreparedUserFile, DbError> {
57 let mut hash = FileHasher::new();
58 let mut read = 0;
59 let observed = UserOriginal::at(path.to_owned())
60 .observe(lease.place().await, |bytes| {
61 hash.update(bytes);
62 read += bytes.len() as u64;
63 progress(read);
64 })
65 .await?;
66 Ok(PreparedUserFile {
67 original: UserFile {
68 path: observed.path().to_owned(),
69 size: observed.size(),
70 modified_at: observed.modified_at(),
71 },
72 hashes: hash.finish(),
73 })
74}
75
76impl From<ObservationError> for DbError {
77 fn from(error: ObservationError) -> Self {
78 match error {
79 ObservationError::Missing(path) => Self::UserFileMissing { path },
80 ObservationError::Changed(path) => Self::UserFileChanged { path },
81 ObservationError::File(error) => error.into(),
82 }
83 }
84}
85
86pub fn unix_seconds_and_nanos(time: SystemTime) -> (i64, u32) {
92 let (seconds, nanos) = match time.duration_since(std::time::UNIX_EPOCH) {
93 Ok(after) => (i128::from(after.as_secs()), after.subsec_nanos()),
94 Err(before) => {
95 let before = before.duration();
96 match before.subsec_nanos() {
97 0 => (-i128::from(before.as_secs()), 0),
98 nanos => (-i128::from(before.as_secs()) - 1, 1_000_000_000 - nanos),
99 }
100 }
101 };
102 (
103 i64::try_from(seconds)
104 .expect("every platform's time fits: Unix keeps i64 seconds, Windows's ends in 30828"),
105 nanos,
106 )
107}
108
109pub(crate) fn encode_time(time: SystemTime) -> Vec<u8> {
110 let (sign, elapsed) = match time.duration_since(std::time::UNIX_EPOCH) {
111 Ok(elapsed) => (0, elapsed),
112 Err(error) => (1, error.duration()),
113 };
114 let mut bytes = vec![sign];
115 bytes.extend(elapsed.as_secs().to_be_bytes());
116 bytes.extend(elapsed.subsec_nanos().to_be_bytes());
117 bytes
118}
119
120macro_rules! record_original {
126 ($db:expr, $file:expr, $original:expr, $hashes:expr) => {{
127 let (db, file, original, hashes) = ($db, $file, $original, $hashes);
128 let size = crate::sqlite::integer("file size", original.size)?;
129 db.execute(
130 "INSERT INTO _coven_user_files(file,path,size,modified_at,hash) VALUES(?1,?2,?3,?4,?5)",
131 sqlive::rusqlite::params![
132 file,
133 coven_foundation::files::path_bytes(&original.path),
134 size,
135 encode_time(original.modified_at),
136 hashes.content.as_bytes().as_slice()
137 ],
138 )?;
139 for (index, hash) in hashes.chunks().iter().enumerate() {
140 db.execute(
141 "INSERT INTO _coven_user_chunks(file,chunk,hash) VALUES(?1,?2,?3)",
142 sqlive::rusqlite::params![file, index as i64, hash.as_bytes().as_slice()],
143 )?;
144 }
145 Ok(())
146 }};
147}
148
149pub(crate) fn record(
152 db: &StoreSql,
153 file: coven_foundation::id_source::FileId,
154 original: &UserFile,
155 hashes: &FileHashes,
156) -> Result<(), DbError> {
157 record_original!(db, file, original, hashes)
158}
159
160#[cfg(any(test, feature = "test-utils"))]
164pub(crate) fn record_outside_store(
165 connection: &sqlive::rusqlite::Connection,
166 file: coven_foundation::id_source::FileId,
167 original: &UserFile,
168 hashes: &FileHashes,
169) -> Result<(), DbError> {
170 record_original!(connection, file, original, hashes)
171}
172
173pub(crate) fn forget(
176 db: &StoreSql,
177 file: coven_foundation::id_source::FileId,
178) -> Result<(), DbError> {
179 db.execute("DELETE FROM _coven_user_files WHERE file=?1", [file])?;
180 Ok(())
181}
182
183pub(crate) fn share(
186 db: &StoreSql,
187 from: coven_foundation::id_source::FileId,
188 to: coven_foundation::id_source::FileId,
189) -> Result<(), DbError> {
190 db.execute(
191 "INSERT INTO _coven_user_files(file,path,size,modified_at,hash)
192 SELECT ?2,path,size,modified_at,hash FROM _coven_user_files WHERE file=?1",
193 sqlive::rusqlite::params![from, to],
194 )?;
195 db.execute(
196 "INSERT INTO _coven_user_chunks(file,chunk,hash)
197 SELECT ?2,chunk,hash FROM _coven_user_chunks WHERE file=?1",
198 sqlive::rusqlite::params![from, to],
199 )?;
200 Ok(())
201}
202
203pub(crate) fn stored(
207 db: &StoreSql,
208 file: coven_foundation::id_source::FileId,
209) -> Result<(), DbError> {
210 db.execute("DELETE FROM _coven_user_chunks WHERE file=?1", [file])?;
211 Ok(())
212}
213
214pub(crate) fn hashes(
218 db: &StoreSql,
219 file: coven_foundation::id_source::FileId,
220) -> Result<Option<FileHashes>, DbError> {
221 let Some(content) = db
222 .query("SELECT hash FROM _coven_user_files WHERE file=?1", [file], |r| {
223 r.get::<_, Vec<u8>>(0)
224 })?
225 .pop()
226 else {
227 return Ok(None);
228 };
229 let chunks = db.query(
230 "SELECT hash FROM _coven_user_chunks WHERE file=?1 ORDER BY chunk",
231 [file],
232 |r| r.get::<_, Vec<u8>>(0),
233 )?;
234 Ok(Some(FileHashes::stored(content, chunks)?))
235}
236
237#[expect(
242 clippy::map_err_ignore,
243 reason = "a stored value that won't convert or decode is DamagedDatabase"
244)]
245pub(crate) fn read(
246 db: &StoreSql,
247 file: coven_foundation::id_source::FileId,
248) -> Result<Option<UserFile>, DbError> {
249 db.query(
250 "SELECT u.path,u.size,u.modified_at FROM _coven_user_files AS u
251 WHERE u.file=?1 AND EXISTS(SELECT 1 FROM coven_user_files AS v WHERE v.file=u.file)",
252 [file],
253 |row| Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, i64>(1)?, row.get::<_, Vec<u8>>(2)?)),
254 )?
255 .into_iter()
256 .next()
257 .map(|(path, size, modified_at)| {
258 Ok(UserFile {
259 path: decode_path(path)?,
260 size: u64::try_from(size).map_err(|_| DbError::DamagedDatabase)?,
261 modified_at: decode_time(&modified_at)?,
262 })
263 })
264 .transpose()
265}
266
267pub(crate) fn decode_time(bytes: &[u8]) -> Result<SystemTime, DbError> {
268 if bytes.len() != 13 {
269 return Err(DbError::DamagedDatabase);
270 }
271 let seconds = u64::from_be_bytes(bytes[1..9].try_into().expect("checked time width"));
272 let nanos = u32::from_be_bytes(bytes[9..].try_into().expect("checked time width"));
273 if nanos >= 1_000_000_000 {
274 return Err(DbError::DamagedDatabase);
275 }
276 let elapsed = std::time::Duration::new(seconds, nanos);
277 match bytes[0] {
278 0 => std::time::UNIX_EPOCH.checked_add(elapsed),
279 1 => std::time::UNIX_EPOCH.checked_sub(elapsed),
280 _ => None,
281 }
282 .ok_or(DbError::DamagedDatabase)
283}
284
285pub(crate) fn decode_path(bytes: Vec<u8>) -> Result<PathBuf, DbError> {
288 coven_foundation::files::path_from_bytes(bytes)
289 .map_err(|coven_foundation::files::PathBytesError| DbError::DamagedDatabase)
290}
291
292#[cfg(test)]
293#[path = "user_file_tests.rs"]
294pub(crate) mod tests;