coven_database/
file_database_pins.rs1use super::{file_ref, FileDatabase};
5use crate::{DbError, FileRef};
6use coven_foundation::files::StagedName;
7
8impl FileDatabase {
9 pub async fn pin_requests(&self) -> Result<Vec<crate::PinRequest>, DbError> {
12 self.read(|db, _| crate::file_pins::read(db)).await
13 }
14 pub async fn end_pin_request(&self, id: i64) -> Result<(), DbError> {
18 self.database
19 .call(move |inner| {
20 inner.with_files("end a pin request", |writer, _, _| {
22 crate::pending::state_transaction(writer, |db| {
23 crate::file_pins::end_request(db, id).map(drop)
24 })
25 })
26 })
27 .await
28 }
29 pub async fn keep(&self, prepared: crate::PreparedPin, id: i64) -> Result<bool, DbError> {
34 self.database
35 .write(move |sql| {
36 if !sql.end_pin_request(id)? {
37 return Ok(false);
38 }
39 sql.pin(prepared)?;
40 Ok(true)
41 })
42 .await
43 }
44 pub async fn drop_pin_copy(&self, id: i64) -> Result<(), DbError> {
47 self.database
48 .call(move |inner| {
49 inner.with_files("drop a pin's copy", |writer, _, _| {
50 writer.transaction(|db| crate::file_pins::drop_copy(db, id))
51 })
52 })
53 .await
54 }
55 pub async fn fail_pin<P: crate::PendingValue>(
59 &self,
60 request: &crate::PinRequest,
61 record: P,
62 retry: Option<crate::RetryWait>,
63 ) -> Result<(), DbError> {
64 let (id, file) = (request.id, request.file);
65 self.run(move |db, _, _, _, _| {
66 crate::pending::state_transaction(db, |db| {
67 if record.pin_of() != Some(file) {
68 return Err(DbError::Invariant {
69 what: "a kept pin's failure is its own record",
70 });
71 }
72 if !db.query_row(
73 "SELECT EXISTS(SELECT 1 FROM _coven_pin_requests WHERE id=?1)",
74 [id],
75 |r| r.get::<_, bool>(0),
76 )? {
77 return Ok(());
78 }
79 crate::retry::save_failure(
80 db,
81 &record,
82 crate::RetrySubject::Pin(id),
83 retry.as_ref(),
84 )
85 })
86 })
87 .await
88 }
89 #[expect(
92 clippy::map_err_ignore,
93 reason = "a stored value that won't convert is damage, a computed one a broken invariant"
94 )]
95 pub async fn copy_chunk_hash(
96 &self,
97 copy: &StagedName,
98 index: u64,
99 ) -> Result<coven_crypto::ContentHash, DbError> {
100 let copy = copy.as_str().to_owned();
101 self.read(move |db, _| {
102 let index = i64::try_from(index)
103 .map_err(|_| DbError::Invariant { what: "a chunk index fits SQLite" })?;
104 let hash = db
105 .query(
106 "SELECT hash FROM _coven_copy_chunks WHERE path=?1 AND chunk=?2",
107 sqlive::rusqlite::params![copy, index],
108 |r| r.get::<_, Vec<u8>>(0),
109 )?
110 .pop()
111 .ok_or(DbError::DamagedDatabase)?;
112 crate::file_hashes::stored_hash(hash)
113 })
114 .await
115 }
116 pub async fn open_pin_copy(
119 &self,
120 file: &FileRef,
121 copy: &StagedName,
122 ) -> Result<crate::LocalFileStream, crate::LocalFileError> {
123 let (id, size, copy) = (file.id().to_string(), file.size(), copy.clone());
124 self.database
125 .call(move |inner| file_ref::open_copy(&inner.access.directory, &id, size, ©))
126 .await
127 }
128}