use std::io::Write as _;
use std::sync::Arc;
use sha2::{Digest, Sha256};
use super::change::{Condition, Content, Place};
use super::engine::Blobs;
use super::files::{FileCall, Files, Options};
use super::info::FileInfo;
use super::upload::{INLINE, past_its_bound};
use crate::sqlite::Ended;
use crate::transaction::sealed::Sealed;
use crate::{Error, Result, Transaction, TxHandle};
impl Sealed for Files {}
impl TxHandle for Files {
type InTx<'h> = TxFiles<'h>;
fn in_tx<'h>(&'h self, tx: &'h Transaction<'h>) -> TxFiles<'h> {
TxFiles { files: self, tx }
}
}
pub struct TxFiles<'a> {
files: &'a Files,
tx: &'a Transaction<'a>,
}
impl std::fmt::Debug for TxFiles<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "TxFiles({:?})", self.files)
}
}
impl<'a> TxFiles<'a> {
pub fn put(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
self.key(path).put(bytes)
}
pub fn create(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<bool> {
self.key(path).create(bytes)
}
pub fn delete(&self, path: &str) -> Result<()> {
self.key(path).delete()
}
pub fn head(&self, path: &str) -> Result<Option<FileInfo>> {
let whole = self.files.whole(path)?;
let read = |sql: &crate::sqlite::Tx<'_>| self.files.head_on(sql, &whole);
on_file(self.tx, self.files, read).map_err(|error| self.files.fail(&whole, error))
}
pub fn key(&self, path: &str) -> FileCall<'a> {
FileCall::inside(self.files, self.tx, path)
}
}
pub(super) fn on_file<T>(
tx: &Transaction<'_>,
files: &Files,
work: impl FnOnce(&crate::sqlite::Tx<'_>) -> Result<T>,
) -> Result<T> {
tx.takes(&files.blobs.file, files.blobs.place())?;
tx.call(work)
}
pub(super) fn write_in(
tx: &Transaction<'_>,
files: &Files,
(whole, options): (&str, &Options),
bytes: &[u8],
condition: Condition,
) -> Result<Option<FileInfo>> {
check_size(files, options, bytes.len() as u64)?;
if bytes.len() > INLINE {
files.blobs.room(bytes.len() as u64)?;
}
let (sha256, size) = (Sha256::digest(bytes).to_vec(), bytes.len() as i64);
on_file(tx, files, |sql| {
let id = id_in(files, sql)?;
let place = if bytes.len() <= INLINE {
Place::Inline(bytes.to_vec())
} else {
let placed = Placed::write(&files.blobs, id, bytes)?;
sql.after_commit_or_unknown(Box::new(move |ended| placed.keep(ended)));
Place::File
};
let content = Content { id, size, sha256, place };
let (_, publication) = files.publication(whole, options, content, condition);
let (info, _freed) = publication(sql)?;
Ok(info)
})
}
fn id_in(files: &Files, sql: &crate::sqlite::Tx<'_>) -> Result<i64> {
loop {
let id = files.blobs.id_in(sql)?;
if !files.blobs.ids.holds(id) {
return Ok(id);
}
}
}
fn check_size(files: &Files, options: &Options, size: u64) -> Result<()> {
if let Some(most) = files.max_file_size.filter(|most| size > *most) {
return Err(past_its_bound(size, most));
}
match options.size {
Some(declared) if declared != size => {
Err(Error::invalid(format!("a body of {size} bytes, where its size says {declared}")))
}
_ => Ok(()),
}
}
struct Placed {
blobs: Arc<Blobs>,
id: i64,
kept: bool,
}
impl Placed {
fn write(blobs: &Arc<Blobs>, id: i64, bytes: &[u8]) -> Result<Placed> {
let placed = Placed { blobs: Arc::clone(blobs), id, kept: false };
let mut file = blobs.disk.create_upload(id)?;
file.write_all(bytes).map_err(|error| Error::io("blobs: write a file's bytes", error))?;
if blobs.disk.durable() {
file.sync_data().map_err(|error| Error::io("blobs: sync a file's bytes", error))?;
}
drop(file);
blobs.disk.place(id)?;
blobs.disk.sync_placed(id)?;
Ok(placed)
}
fn keep(mut self, ended: Ended) {
self.kept = true;
if ended == Ended::Unknown {
self.blobs.ids.doubt(self.id);
}
}
}
impl Drop for Placed {
fn drop(&mut self) {
if self.kept {
return;
}
let _ = self.blobs.disk.remove_upload(self.id);
if let Err(error) = self.blobs.disk.remove_object(self.id) {
tracing::debug!(target: "tinystore", %error, "blobs: a rolled back file's bytes, removed later");
self.blobs.ids.doubt(self.id);
}
}
}
#[cfg(test)]
#[path = "tx_tests.rs"]
mod tests;