1use std::collections::BTreeMap;
5use std::fmt;
6use std::sync::Arc;
7use std::time::Duration;
8
9use rusqlite::{OptionalExtension, params};
10
11use super::change::{Change, Condition, Content, Place, Version, WhenThere, hidden};
12use super::engine::Blobs;
13use super::info::{FileInfo, FileRow, OCTETS, file_columns, meta_text};
14use super::paths::Folder;
15use super::read::StoredFile;
16use super::upload::Upload;
17#[cfg(feature = "async")]
18use crate::memory::Waiting;
19use crate::sqlite::{Tx, sql_error};
20use crate::{Error, Key, Result, Store};
21
22const SET_EXPIRES: &str = "update _tinystore_blobs_files set expires = ?3 where set_id = ?1 and path = ?2";
23const MAX_TYPE: usize = 256;
25const MAX_META: usize = 2 << 10;
27
28#[derive(Debug)]
31pub struct FilesBuilder<'s> {
32 home: Home<'s>,
33 name: String,
34 ttl: Option<Duration>,
35 max_file_size: Option<u64>,
36}
37
38#[derive(Debug)]
40enum Home<'s> {
41 Store(&'s Store),
42 #[cfg(feature = "sql")]
43 Database(Arc<crate::engine::SharedFile>),
44}
45
46impl<'s> FilesBuilder<'s> {
47 pub(crate) fn new(store: &'s Store, name: &str) -> Self {
48 FilesBuilder { home: Home::Store(store), name: name.to_owned(), ttl: None, max_file_size: None }
49 }
50
51 #[cfg(feature = "sql")]
53 pub(crate) fn in_file(shared: Arc<crate::engine::SharedFile>, name: &str) -> FilesBuilder<'static> {
54 FilesBuilder { home: Home::Database(shared), name: name.to_owned(), ttl: None, max_file_size: None }
55 }
56
57 pub fn ttl(mut self, ttl: Duration) -> Self {
60 self.ttl = Some(ttl);
61 self
62 }
63
64 pub fn max_file_size(mut self, bytes: u64) -> Self {
67 self.max_file_size = Some(bytes);
68 self
69 }
70
71 pub fn open(self) -> Result<Files> {
72 check_name(&self.name)?;
73 let blobs = match &self.home {
74 Home::Store(store) => Blobs::of(store)?,
75 #[cfg(feature = "sql")]
76 Home::Database(shared) => Blobs::in_file(shared)?,
77 };
78 let set = blobs.set_id(&self.name)?;
79 Ok(Files {
80 blobs,
81 name: Arc::from(self.name),
82 set,
83 folder: Folder::default(),
84 refused: None,
85 ttl: self.ttl,
86 max_file_size: self.max_file_size,
87 })
88 }
89}
90
91#[derive(Clone)]
95pub struct Files {
96 pub(crate) blobs: Arc<Blobs>,
97 name: Arc<str>,
98 pub(crate) set: i64,
99 pub(crate) folder: Folder,
100 refused: Option<Arc<Error>>,
102 ttl: Option<Duration>,
103 pub(crate) max_file_size: Option<u64>,
104}
105
106impl fmt::Debug for Files {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 write!(f, "Files({}, {:?})", self.name, self.folder.prefix())
109 }
110}
111
112impl Files {
113 pub fn folder(&self, segment: impl Key) -> Files {
116 let mut folder = self.clone();
117 if folder.refused.is_none() {
118 match self.folder.folder(&segment.text()) {
119 Ok(inner) => folder.folder = inner,
120 Err(error) => folder.refused = Some(Arc::new(self.fail(self.folder.prefix(), error))),
121 }
122 }
123 folder
124 }
125
126 pub fn key(&self, path: &str) -> FileCall<'_> {
129 FileCall::new(self, path, Options::default())
130 }
131
132 pub fn put(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
135 self.key(path).put(bytes)
136 }
137
138 pub fn create(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<bool> {
140 self.key(path).create(bytes)
141 }
142
143 pub fn upload(&self, path: &str) -> Result<Upload> {
145 self.key(path).upload()
146 }
147
148 pub fn get(&self, path: &str) -> Result<Option<StoredFile>> {
151 let whole = self.whole(path)?;
152 StoredFile::open(self, &whole).map_err(|error| self.fail(&whole, error))
153 }
154
155 pub fn head(&self, path: &str) -> Result<Option<FileInfo>> {
157 let whole = self.whole(path)?;
158 self.head_of(&whole).map_err(|error| self.fail(&whole, error))
159 }
160
161 pub fn delete(&self, path: &str) -> Result<()> {
163 self.key(path).delete()
164 }
165
166 pub fn copy(&self, from: &str, to: &str) -> Result<FileInfo> {
171 self.key(to).copy_from(from)
172 }
173
174 pub fn rename(&self, from: &str, to: &str) -> Result<FileInfo> {
176 self.key(to).rename_from(from)
177 }
178
179 pub fn expire(&self, path: &str, after: Duration) -> Result<bool> {
182 let whole = self.whole(path)?;
183 self.expire_after(&whole, after).map_err(|error| self.fail(&whole, error))
184 }
185
186 #[cfg(any(feature = "replication", feature = "async"))]
189 pub(crate) fn call(&self, path: &str, options: Options) -> FileCall<'_> {
190 FileCall::new(self, path, options)
191 }
192
193 #[cfg(feature = "replication")]
195 pub(crate) fn is_copy(&self) -> bool {
196 self.blobs.file.is_copy()
197 }
198
199 #[cfg(feature = "replication")]
202 pub(crate) fn pass_on(&self, call: &super::forward::Call<'_>) -> Result<bool> {
203 let set = super::forward::Set { name: &self.name, ttl: self.ttl, max_file_size: self.max_file_size };
204 super::forward::pass_on(&self.blobs.store()?, &set, call)
205 }
206
207 #[cfg(feature = "replication")]
210 pub(crate) fn head_here(&self, whole: &str) -> Result<Option<FileInfo>> {
211 self.head_of(whole)
212 }
213
214 pub(crate) fn whole(&self, path: &str) -> Result<String> {
215 self.usable()?;
216 self.folder.path(path).map_err(|error| self.fail(&format!("{}{path}", self.folder.prefix()), error))
217 }
218
219 pub(crate) fn usable(&self) -> Result<()> {
221 self.refused.as_ref().map_or(Ok(()), |refused| Err(refused.duplicate()))
222 }
223
224 pub(crate) fn fail(&self, path: &str, error: Error) -> Error {
227 error.within(format!("{path:?}")).within(format!("files {}", self.name))
228 }
229
230 pub(crate) fn describe(&self) -> String {
231 format!("files {}", self.name)
232 }
233
234 pub(crate) fn expiry(&self, ttl: Option<Duration>, now: i64) -> Option<i64> {
235 ttl.or(self.ttl).map(|ttl| now.saturating_add(crate::clock::millis(ttl)))
236 }
237
238 fn head_of(&self, whole: &str) -> Result<Option<FileInfo>> {
239 self.blobs.file.read(|connection| self.head_on(connection, whole))
240 }
241
242 pub(super) fn head_on(&self, connection: &rusqlite::Connection, whole: &str) -> Result<Option<FileInfo>> {
244 const SELECT_HEAD: &str = concat!(
245 "select ",
246 file_columns!(),
247 " from _tinystore_blobs_files as f where f.set_id = ?1 and f.path = ?2 and (f.expires is null or f.expires > ?3) and not ",
248 hidden!()
249 );
250 let now = self.blobs.now();
251 let row = connection
252 .prepare_cached(SELECT_HEAD)
253 .and_then(|mut statement| statement.query_row(params![self.set, whole, now], FileRow::read).optional())
254 .map_err(|error| sql_error("blobs: a file's head", error))?;
255 row.map(|row| row.info(&self.folder)).transpose()
256 }
257
258 pub(crate) fn publish(
261 &self,
262 whole: &str,
263 options: &Options,
264 content: Content,
265 condition: Condition,
266 ) -> Result<Option<FileInfo>> {
267 let (bytes, publication) = self.publication(whole, options, content, condition);
268 let (info, freed) = self.blobs.file.write(bytes, publication)?;
269 self.blobs.remove_freed(&freed);
270 self.count_written(info.as_ref());
271 Ok(info)
272 }
273
274 pub(super) fn publication(
277 &self,
278 whole: &str,
279 options: &Options,
280 content: Content,
281 condition: Condition,
282 ) -> (usize, Writing<Option<FileInfo>>) {
283 let blobs = Arc::clone(&self.blobs);
284 let files = self.clone();
285 let (path, content_type, meta, ttl) =
286 (whole.to_owned(), options.content_type(), meta_text(&options.meta), options.ttl);
287 let bytes = match &content.place {
288 Place::Inline(body) => body.len(),
289 Place::File | Place::Shared => 0,
290 };
291 let publication = move |tx: &Tx<'_>| {
292 let mut change = Change::new(tx, &blobs);
293 let version =
294 Version { content, content_type, meta, modified: change.now, expires: files.expiry(ttl, change.now) };
295 if !change.write(files.set, &path, &version, &condition)? {
296 return Ok((None, Vec::new()));
297 }
298 Ok((Some(version.info(&files.folder, &path)?), change.freed))
299 };
300 (bytes, Box::new(publication))
301 }
302
303 pub(super) fn count_written(&self, info: Option<&FileInfo>) {
304 if let Some(info) = info {
305 self.blobs.probe.count("tinystore_blobs_written_total", &[], 1.0);
306 self.blobs.probe.count("tinystore_blobs_written_bytes_total", &[], info.size as f64);
307 }
308 }
309
310 #[cfg(feature = "async")]
313 pub(crate) fn remove_freed(&self, freed: &[i64]) {
314 self.blobs.remove_freed(freed);
315 }
316
317 fn copy_to(&self, from: &str, to: &str, options: &Options, rename: bool) -> Result<FileInfo> {
318 refuse_onto_itself(from, to)?;
319 #[cfg(feature = "replication")]
320 if self.is_copy() {
321 self.pass_on(&super::forward::Call::Copy { from, to, options, rename })?;
322 return self.head_of(to)?.ok_or_else(|| Error::internal("a copy its home wrote that this copy lacks"));
323 }
324 let (info, freed) = self.blobs.file.write(0, self.copying(from, to, options, rename))?;
325 self.blobs.remove_freed(&freed);
326 Ok(info)
327 }
328
329 fn copying(&self, from: &str, to: &str, options: &Options, rename: bool) -> Writing<FileInfo> {
331 let blobs = Arc::clone(&self.blobs);
332 let files = self.clone();
333 let (from, to, options) = (from.to_owned(), to.to_owned(), options.clone());
334 let condition = Condition { if_match: options.if_match.clone(), when_there: WhenThere::Conflict };
335 Box::new(move |tx| {
336 let mut change = Change::new(tx, &blobs);
337 let source =
338 change.current(files.set, &from)?.filter(|current| current.live(change.now)).ok_or_else(|| {
339 Error::not_found(format!("no file at {from:?} to {}", if rename { "rename" } else { "copy" }))
340 })?;
341 let version = Version {
342 content: Content { id: source.content, size: source.size, sha256: source.sha256, place: Place::Shared },
343 content_type: options.content_type.clone().unwrap_or(source.content_type),
344 meta: if options.meta_given { meta_text(&options.meta) } else { source.meta },
345 modified: change.now,
346 expires: files.expiry(options.ttl, change.now),
347 };
348 change.write(files.set, &to, &version, &condition)?;
349 if rename {
350 change.remove(files.set, &from)?;
351 }
352 Ok((version.info(&files.folder, &to)?, change.freed))
353 })
354 }
355
356 fn delete_at(&self, whole: &str, if_match: Option<String>) -> Result<()> {
357 #[cfg(feature = "replication")]
358 if self.is_copy() {
359 return self
360 .pass_on(&super::forward::Call::Delete { path: whole, if_match: if_match.as_deref() })
361 .map(drop);
362 }
363 let ((), freed) = self.blobs.file.write(0, self.deleting(whole, if_match))?;
364 self.blobs.remove_freed(&freed);
365 Ok(())
366 }
367
368 fn deleting(&self, whole: &str, if_match: Option<String>) -> Writing<()> {
370 let blobs = Arc::clone(&self.blobs);
371 let (set, path) = (self.set, whole.to_owned());
372 Box::new(move |tx| {
373 let mut change = Change::new(tx, &blobs);
374 if let Some(etag) = &if_match {
375 super::change::holds_etag(etag, change.current(set, &path)?.as_ref(), change.now)?;
376 }
377 change.remove(set, &path)?;
378 Ok(((), change.freed))
379 })
380 }
381
382 fn expire_after(&self, whole: &str, after: Duration) -> Result<bool> {
383 #[cfg(feature = "replication")]
384 if self.is_copy() {
385 return self.pass_on(&super::forward::Call::Expire { path: whole, after });
386 }
387 self.blobs.file.write(0, self.expiring(whole, after)).map(|(expired, _)| expired)
388 }
389
390 fn expiring(&self, whole: &str, after: Duration) -> Writing<bool> {
392 let blobs = Arc::clone(&self.blobs);
393 let (set, path) = (self.set, whole.to_owned());
394 let after = crate::clock::millis(after);
395 Box::new(move |tx| {
396 let change = Change::new(tx, &blobs);
397 if !change.current(set, &path)?.is_some_and(|current| current.live(change.now)) {
398 return Ok((false, Vec::new()));
399 }
400 let expires = change.now.saturating_add(after);
401 change.execute(SET_EXPIRES, params![set, path, expires])?;
402 Ok((true, Vec::new()))
403 })
404 }
405
406 #[cfg(feature = "async")]
409 pub(crate) fn expire_then(&self, path: &str, after: Duration, done: impl Done<bool>) {
410 let whole = match self.whole(path) {
411 Ok(whole) => whole,
412 Err(error) => return done(Err(error)),
413 };
414 let expiring = self.expiring(&whole, after);
415 let files = self.clone();
416 self.blobs.file.submit(0, expiring, move |expired| done(expired.map_err(|error| files.fail(&whole, error))));
417 }
418}
419
420#[cfg(feature = "async")]
425pub(crate) trait Done<T>: FnOnce(Result<(T, Freed)>) + Send + 'static {}
426
427#[cfg(feature = "async")]
428impl<T, F: FnOnce(Result<(T, Freed)>) + Send + 'static> Done<T> for F {}
429
430pub(crate) type Freed = Vec<i64>;
432
433pub(super) type Writing<T> = Box<dyn FnOnce(&Tx<'_>) -> Result<(T, Freed)> + Send>;
436
437fn refuse_onto_itself(from: &str, to: &str) -> Result<()> {
438 if from == to {
439 return Err(Error::invalid("a copy or a rename onto its own path"));
440 }
441 Ok(())
442}
443
444#[derive(Clone, Debug, Default)]
446pub(crate) struct Options {
447 pub(crate) content_type: Option<String>,
448 pub(crate) meta: BTreeMap<String, String>,
449 pub(crate) meta_given: bool,
450 pub(crate) ttl: Option<Duration>,
451 pub(crate) if_match: Option<String>,
452 pub(crate) size: Option<u64>,
454}
455
456impl Options {
457 fn content_type(&self) -> String {
458 self.content_type.clone().unwrap_or_else(|| OCTETS.to_owned())
459 }
460
461 fn check(&self) -> Result<()> {
462 if self.content_type.as_ref().is_some_and(|content_type| content_type.len() > MAX_TYPE) {
463 return Err(Error::invalid(format!("a content type over {MAX_TYPE} bytes")));
464 }
465 let meta: usize = self.meta.iter().map(|(name, value)| name.len() + value.len()).sum();
466 if meta > MAX_META {
467 return Err(Error::invalid(format!("meta of {meta} bytes, over 2 KiB")));
468 }
469 Ok(())
470 }
471}
472
473#[derive(Debug)]
475#[must_use = "a call does nothing until its verb"]
476pub struct FileCall<'f> {
477 files: &'f Files,
478 path: String,
479 options: Options,
480 #[cfg(feature = "sql")]
482 tx: Option<&'f crate::Transaction<'f>>,
483}
484
485impl<'f> FileCall<'f> {
486 fn new(files: &'f Files, path: &str, options: Options) -> Self {
487 #[cfg(feature = "sql")]
488 return FileCall { files, path: path.to_owned(), options, tx: None };
489 #[cfg(not(feature = "sql"))]
490 FileCall { files, path: path.to_owned(), options }
491 }
492
493 #[cfg(feature = "sql")]
495 pub(super) fn inside(files: &'f Files, tx: &'f crate::Transaction<'f>, path: &str) -> Self {
496 FileCall { tx: Some(tx), ..FileCall::new(files, path, Options::default()) }
497 }
498
499 pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
500 self.options.content_type = Some(content_type.into());
501 self
502 }
503
504 pub fn meta(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
507 self.options.meta.insert(name.into(), value.into());
508 self.options.meta_given = true;
509 self
510 }
511
512 pub fn ttl(mut self, ttl: Duration) -> Self {
514 self.options.ttl = Some(ttl);
515 self
516 }
517
518 pub fn if_match(mut self, etag: impl Into<String>) -> Self {
521 self.options.if_match = Some(etag.into());
522 self
523 }
524
525 pub fn size(mut self, bytes: u64) -> Self {
528 self.options.size = Some(bytes);
529 self
530 }
531
532 pub fn put(self, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
533 let condition = Condition { if_match: self.options.if_match.clone(), when_there: WhenThere::Replace };
534 self.write_all(bytes.as_ref(), condition)?.ok_or_else(|| Error::internal("a put that wrote nothing"))
535 }
536
537 pub fn create(self, bytes: impl AsRef<[u8]>) -> Result<bool> {
539 let condition = Condition { if_match: self.options.if_match.clone(), when_there: WhenThere::Skip };
540 self.write_all(bytes.as_ref(), condition).map(|info| info.is_some())
541 }
542
543 pub fn upload(self) -> Result<Upload> {
545 let whole = self.checked()?;
546 #[cfg(feature = "sql")]
547 if self.tx.is_some() {
548 let refused = Error::invalid("an upload inside a transaction: put its bytes, which commit with it");
549 return Err(self.files.fail(&whole, refused));
550 }
551 Upload::start(self.files.clone(), whole, self.options)
552 }
553
554 pub fn delete(self) -> Result<()> {
555 let whole = self.files.whole(&self.path)?;
556 #[cfg(feature = "sql")]
557 if let Some(tx) = self.tx {
558 let deleting = self.files.deleting(&whole, self.options.if_match);
559 let deleted = super::tx::on_file(tx, self.files, |sql| deleting(sql).map(drop));
560 return deleted.map_err(|error| self.files.fail(&whole, error));
561 }
562 self.files.delete_at(&whole, self.options.if_match).map_err(|error| self.files.fail(&whole, error))
563 }
564
565 pub fn copy_from(self, from: &str) -> Result<FileInfo> {
567 self.copied(from, false)
568 }
569
570 pub fn rename_from(self, from: &str) -> Result<FileInfo> {
572 self.copied(from, true)
573 }
574
575 fn copied(self, from: &str, rename: bool) -> Result<FileInfo> {
576 let (source, target) = (self.files.whole(from)?, self.checked()?);
577 #[cfg(feature = "sql")]
578 if let Some(tx) = self.tx {
579 let copied = refuse_onto_itself(&source, &target).and_then(|()| {
580 let copying = self.files.copying(&source, &target, &self.options, rename);
581 super::tx::on_file(tx, self.files, |sql| copying(sql).map(|(info, _)| info))
582 });
583 return copied.map_err(|error| self.files.fail(&target, error));
584 }
585 self.files.copy_to(&source, &target, &self.options, rename).map_err(|error| self.files.fail(&target, error))
586 }
587
588 fn checked(&self) -> Result<String> {
591 let whole = self.files.whole(&self.path)?;
592 self.options.check().map_err(|error| self.files.fail(&whole, error))?;
593 Ok(whole)
594 }
595
596 #[cfg(feature = "async")]
599 pub(crate) fn into_parts(self) -> (&'f Files, String, Options) {
600 (self.files, self.path, self.options)
601 }
602
603 #[cfg(feature = "async")]
609 pub(crate) fn upload_then(self, done: impl FnOnce(Result<Upload>) + Send + 'static) -> Option<Waiting> {
610 let whole = match self.checked() {
611 Ok(whole) => whole,
612 Err(error) => {
613 done(Err(error));
614 return None;
615 }
616 };
617 let (files, options) = (self.files.clone(), self.options);
618 Some(Upload::reserve_then(self.files, move |reserved| {
619 let reserved = reserved.map_err(|error| files.fail(&whole, error));
620 done(reserved.and_then(|reserved| Upload::reserved(files, whole, options, reserved)));
621 }))
622 }
623
624 #[cfg(feature = "async")]
627 pub(crate) fn delete_then(self, done: impl Done<()>) {
628 let whole = match self.files.whole(&self.path) {
629 Ok(whole) => whole,
630 Err(error) => return done(Err(error)),
631 };
632 let deleting = self.files.deleting(&whole, self.options.if_match);
633 let files = self.files.clone();
634 self.files
635 .blobs
636 .file
637 .submit(0, deleting, move |deleted| done(deleted.map_err(|error| files.fail(&whole, error))));
638 }
639
640 #[cfg(feature = "async")]
643 pub(crate) fn copied_then(self, from: &str, rename: bool, done: impl Done<FileInfo>) {
644 let wholes = self.files.whole(from).and_then(|source| Ok((source, self.checked()?)));
645 let (source, target) = match wholes {
646 Ok(wholes) => wholes,
647 Err(error) => return done(Err(error)),
648 };
649 if let Err(error) = refuse_onto_itself(&source, &target) {
650 return done(Err(self.files.fail(&target, error)));
651 }
652 let copying = self.files.copying(&source, &target, &self.options, rename);
653 let files = self.files.clone();
654 self.files
655 .blobs
656 .file
657 .submit(0, copying, move |copied| done(copied.map_err(|error| files.fail(&target, error))));
658 }
659
660 #[cfg(any(feature = "wire", feature = "replication", feature = "async"))]
665 pub(crate) fn written(self, bytes: &[u8], create: bool) -> Result<Option<FileInfo>> {
666 let when_there = if create { WhenThere::Skip } else { WhenThere::Replace };
667 let condition = Condition { if_match: self.options.if_match.clone(), when_there };
668 self.write_all(bytes, condition)
669 }
670
671 fn write_all(self, bytes: &[u8], condition: Condition) -> Result<Option<FileInfo>> {
672 let whole = self.checked()?;
673 #[cfg(feature = "sql")]
674 if let Some(tx) = self.tx {
675 let written = super::tx::write_in(tx, self.files, (&whole, &self.options), bytes, condition);
676 return written.map_err(|error| self.files.fail(&whole, error));
677 }
678 let mut upload = Upload::start(self.files.clone(), whole, self.options)?;
679 upload.take(bytes)?;
680 upload.finish(condition)
681 }
682}
683
684fn check_name(name: &str) -> Result<()> {
686 crate::text::check_name("a set's", name)
687}
688
689#[cfg(test)]
690#[path = "files_tests.rs"]
691mod tests;