1use crate::io::server::{MaybeSend, MaybeSync};
2use crate::model::{
3 core_config::Config,
4 crypto::EncryptedDocument,
5 errors::{LbErrKind, LbResult},
6 file_metadata::DocumentHmac,
7};
8use std::future::Future;
9use std::{
10 collections::{HashMap, HashSet},
11 path::{Path, PathBuf},
12 sync::{Arc, Mutex},
13};
14use uuid::Uuid;
15
16#[cfg(not(target_family = "wasm"))]
17use {
18 crate::model::errors::Unexpected,
19 std::io::ErrorKind,
20 tokio::{
21 fs::{self, File, OpenOptions},
22 io::{AsyncReadExt, AsyncWriteExt},
23 },
24};
25
26#[derive(Clone)]
28#[cfg_attr(target_family = "wasm", allow(dead_code))]
29pub enum AsyncDocs {
30 Disk { location: PathBuf },
31 Memory(DocMap),
32}
33
34type DocMap = Arc<Mutex<HashMap<(Uuid, DocumentHmac), EncryptedDocument>>>;
35
36impl AsyncDocs {
37 pub fn in_memory() -> Self {
38 Self::Memory(Default::default())
39 }
40
41 pub fn copy(&self) -> Option<Self> {
44 match self {
45 Self::Memory(docs) => {
46 Some(Self::Memory(Arc::new(Mutex::new(docs.lock().unwrap().clone()))))
47 }
48 Self::Disk { .. } => None,
49 }
50 }
51}
52
53pub trait DocumentStore: Clone + MaybeSend + MaybeSync + 'static {
55 fn insert(
56 &self, id: Uuid, hmac: DocumentHmac, document: &EncryptedDocument,
57 ) -> impl Future<Output = LbResult<()>> + MaybeSend;
58
59 fn maybe_get(
60 &self, id: Uuid, hmac: DocumentHmac,
61 ) -> impl Future<Output = LbResult<Option<EncryptedDocument>>> + MaybeSend;
62
63 fn get(
64 &self, id: Uuid, hmac: DocumentHmac,
65 ) -> impl Future<Output = LbResult<EncryptedDocument>> + MaybeSend {
66 async move {
67 self.maybe_get(id, hmac)
68 .await?
69 .ok_or_else(|| LbErrKind::FileNonexistent.into())
70 }
71 }
72
73 fn delete(
74 &self, id: Uuid, hmac: DocumentHmac,
75 ) -> impl Future<Output = LbResult<()>> + MaybeSend;
76
77 fn exists(&self, id: Uuid, hmac: DocumentHmac) -> bool;
78}
79
80pub trait LocalDocuments: DocumentStore {
82 fn insert_pending(
83 &self, id: Uuid, hmac: DocumentHmac, document: &EncryptedDocument,
84 ) -> impl Future<Output = LbResult<PendingDocument>> + MaybeSend;
85
86 fn retain(
88 &self, file_hmacs: HashSet<(Uuid, DocumentHmac)>,
89 ) -> impl Future<Output = LbResult<()>> + MaybeSend;
90}
91
92#[must_use]
96#[cfg(not(target_family = "wasm"))]
97pub enum PendingDocument {
98 File { path: String, final_path: String },
99 Memory { docs: DocMap, key: (Uuid, DocumentHmac), document: EncryptedDocument },
100}
101
102#[cfg(not(target_family = "wasm"))]
103impl PendingDocument {
104 pub async fn promote(self) -> LbResult<()> {
105 match self {
106 Self::File { path, final_path } => Ok(fs::rename(&path, &final_path).await?),
107 Self::Memory { docs, key, document } => {
108 docs.lock().unwrap().insert(key, document);
109 Ok(())
110 }
111 }
112 }
113}
114
115#[must_use]
116#[cfg(target_family = "wasm")]
117pub struct PendingDocument;
118
119#[cfg(target_family = "wasm")]
120impl PendingDocument {
121 pub async fn promote(self) -> LbResult<()> {
122 Ok(())
123 }
124}
125
126#[cfg(target_family = "wasm")]
127impl DocumentStore for AsyncDocs {
128 async fn insert(
129 &self, _id: Uuid, _hmac: DocumentHmac, _document: &EncryptedDocument,
130 ) -> LbResult<()> {
131 Ok(())
132 }
133
134 async fn maybe_get(
135 &self, _id: Uuid, _hmac: DocumentHmac,
136 ) -> LbResult<Option<EncryptedDocument>> {
137 Ok(None)
138 }
139
140 async fn delete(&self, _id: Uuid, _hmac: DocumentHmac) -> LbResult<()> {
141 Ok(())
142 }
143
144 fn exists(&self, _id: Uuid, _hmac: DocumentHmac) -> bool {
145 true
146 }
147}
148
149#[cfg(target_family = "wasm")]
150impl LocalDocuments for AsyncDocs {
151 async fn insert_pending(
152 &self, _id: Uuid, _hmac: DocumentHmac, _document: &EncryptedDocument,
153 ) -> LbResult<PendingDocument> {
154 Ok(PendingDocument)
155 }
156
157 async fn retain(&self, _file_hmacs: HashSet<(Uuid, DocumentHmac)>) -> LbResult<()> {
158 Ok(())
159 }
160}
161
162#[cfg(not(target_family = "wasm"))]
163impl AsyncDocs {
164 pub async fn maybe_size(&self, id: Uuid, hmac: Option<DocumentHmac>) -> LbResult<Option<u64>> {
165 let Some(hmac) = hmac else {
166 return Ok(None);
167 };
168 Ok(match self {
169 Self::Memory(docs) => docs
170 .lock()
171 .unwrap()
172 .get(&(id, hmac))
173 .map(|d| bincode::serialized_size(d).unwrap_or_default()),
174 Self::Disk { location } => Path::new(&key_path(location, id, hmac))
175 .metadata()
176 .ok()
177 .map(|meta| meta.len()),
178 })
179 }
180}
181
182#[cfg(not(target_family = "wasm"))]
183impl DocumentStore for AsyncDocs {
184 async fn insert(
185 &self, id: Uuid, hmac: DocumentHmac, document: &EncryptedDocument,
186 ) -> LbResult<()> {
187 let pending = self.insert_pending(id, hmac, document).await?;
188 pending.promote().await
189 }
190
191 fn exists(&self, id: Uuid, hmac: DocumentHmac) -> bool {
192 match self {
193 Self::Memory(docs) => docs.lock().unwrap().contains_key(&(id, hmac)),
194 Self::Disk { location } => Path::new(&key_path(location, id, hmac)).exists(),
195 }
196 }
197
198 async fn maybe_get(&self, id: Uuid, hmac: DocumentHmac) -> LbResult<Option<EncryptedDocument>> {
199 let location = match self {
200 Self::Memory(docs) => return Ok(docs.lock().unwrap().get(&(id, hmac)).cloned()),
201 Self::Disk { location } => location,
202 };
203 let path_str = key_path(location, id, hmac);
204 let path = Path::new(&path_str);
205 trace!("read\t{}", &path_str);
206 let maybe_data: Option<Vec<u8>> = match File::open(path).await {
207 Ok(mut f) => {
208 let mut buffer: Vec<u8> = Vec::new();
209 f.read_to_end(&mut buffer).await?;
210 Some(buffer)
211 }
212 Err(err) => match err.kind() {
213 ErrorKind::NotFound => None,
214 _ => return Err(err.into()),
215 },
216 };
217
218 Ok(match maybe_data {
219 Some(data) => bincode::deserialize(&data).map(Some).map_unexpected()?,
220 None => None,
221 })
222 }
223
224 async fn delete(&self, id: Uuid, hmac: DocumentHmac) -> LbResult<()> {
225 match self {
226 Self::Memory(docs) => {
227 docs.lock().unwrap().remove(&(id, hmac));
228 }
229 Self::Disk { location } => {
230 let path_str = key_path(location, id, hmac);
231 let path = Path::new(&path_str);
232 trace!("delete\t{}", &path_str);
233 if path.exists() {
234 fs::remove_file(path).await.map_unexpected()?;
235 }
236 }
237 }
238 Ok(())
239 }
240}
241
242#[cfg(not(target_family = "wasm"))]
243impl LocalDocuments for AsyncDocs {
244 async fn insert_pending(
245 &self, id: Uuid, hmac: DocumentHmac, document: &EncryptedDocument,
246 ) -> LbResult<PendingDocument> {
247 let location = match self {
248 Self::Memory(docs) => {
249 let (docs, key, document) = (docs.clone(), (id, hmac), document.clone());
250 return Ok(PendingDocument::Memory { docs, key, document });
251 }
252 Self::Disk { location } => location,
253 };
254 let value = &bincode::serialize(document).map_unexpected()?;
255 let path_str = pending_path(location, id, hmac);
256 let path = Path::new(&path_str);
257 trace!("write pending\t{} {:?} bytes", &path_str, value.len());
258 fs::create_dir_all(path.parent().unwrap()).await?;
259 let mut f = OpenOptions::new()
260 .write(true)
261 .create(true)
262 .truncate(true)
263 .open(path)
264 .await?;
265 f.write_all(value).await?;
266 f.flush().await?;
268 let final_path = key_path(location, id, hmac);
269 Ok(PendingDocument::File { path: path_str, final_path })
270 }
271
272 async fn retain(&self, file_hmacs: HashSet<(Uuid, DocumentHmac)>) -> LbResult<()> {
273 let location = match self {
274 Self::Memory(docs) => {
275 docs.lock()
276 .unwrap()
277 .retain(|key, _| file_hmacs.contains(key));
278 return Ok(());
279 }
280 Self::Disk { location } => location,
281 };
282 let dir_path = namespace_path(location);
283 fs::create_dir_all(&dir_path).await?;
284 let mut entries = fs::read_dir(&dir_path).await?;
285
286 while let Some(entry) = entries.next_entry().await? {
287 let path = entry.path();
288 let file_name = path
289 .file_name()
290 .and_then(|name| name.to_str())
291 .ok_or(LbErrKind::Unexpected("could not get filename from os".to_string()))?;
292
293 if file_name.contains("pending") {
294 continue;
295 }
296
297 let Some((id, hmac)) = parse_key_path(file_name) else {
299 continue;
300 };
301
302 if !file_hmacs.contains(&(id, hmac)) {
303 self.delete(id, hmac).await?;
304 }
305 }
306 Ok(())
307 }
308}
309
310fn parse_key_path(file_name: &str) -> Option<(Uuid, DocumentHmac)> {
312 let id = Uuid::parse_str(file_name.get(..36)?).ok()?;
313 let hmac = file_name.get(36..)?.strip_prefix('-')?;
314 let hmac = base64::decode_config(hmac, base64::URL_SAFE).ok()?;
315 Some((id, hmac.try_into().ok()?))
316}
317
318pub fn namespace_path(writeable_path: &Path) -> String {
319 format!("{}/documents", writeable_path.to_str().unwrap())
320}
321
322pub fn key_path(writeable_path: &Path, key: Uuid, hmac: DocumentHmac) -> String {
323 let hmac = base64::encode_config(hmac, base64::URL_SAFE);
324 format!("{}/{}-{}", namespace_path(writeable_path), key, hmac)
325}
326
327fn pending_path(writeable_path: &Path, key: Uuid, hmac: DocumentHmac) -> String {
328 format!("{}.{}.pending", key_path(writeable_path, key, hmac), Uuid::new_v4())
329}
330
331impl From<&Config> for AsyncDocs {
332 fn from(cfg: &Config) -> Self {
333 Self::Disk { location: PathBuf::from(&cfg.writeable_path) }
334 }
335}