use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::hash::{BuildHasher, Hasher};
use std::io::Read;
use std::path::PathBuf;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread::{self, ThreadId};
use std::time::Duration;
use rusqlite::{OptionalExtension, params};
use super::change::Change;
use super::engine::Blobs;
use super::files::{Files, Options};
use super::info::FileInfo;
use super::read::{PIECE, StoredFile};
use super::upload::Upload;
use crate::sqlite::{Tx, own_work, sql_error};
use crate::sync::lock;
use crate::{Error, ErrorKind, Result};
pub(crate) const LEASE: Duration = Duration::from_secs(30);
pub(crate) const RENEW_EVERY: Duration = Duration::from_secs(10);
pub(crate) const TIMEOUT: Duration = Duration::from_secs(10 * 60);
const SELECT_CLAIM: &str = "select owner, until from _tinystore_blobs_filling where set_id = ?1 and path = ?2";
const UPSERT_CLAIM: &str = "insert into _tinystore_blobs_filling (set_id, path, owner, until) values (?1, ?2, ?3, ?4)
on conflict (set_id, path) do update set owner = excluded.owner, until = excluded.until";
const RENEW_CLAIM: &str =
"update _tinystore_blobs_filling set until = ?4 where set_id = ?1 and path = ?2 and owner = ?3 and until > ?5";
const PURGE_CLAIMS: &str = "delete from _tinystore_blobs_filling where until <= ?1";
const FORGET_CLAIMS: &str = "delete from _tinystore_blobs_filling";
pub(super) const TAKE_CLAIM: &str =
"delete from _tinystore_blobs_filling where set_id = ?1 and path = ?2 and owner = ?3 and until > ?4";
pub(super) const END_CLAIM: &str =
"delete from _tinystore_blobs_filling where set_id = ?1 and path = ?2 returning owner";
pub(super) const END_CLAIMS_UNDER: &str =
"delete from _tinystore_blobs_filling where set_id = ?1 and path >= ?2 and path < ?3 returning owner";
pub struct Fill {
body: Body,
content_type: Option<String>,
meta: BTreeMap<String, String>,
}
enum Body {
Bytes(Vec<u8>),
Reader(Box<dyn Read + Send>),
Path(PathBuf),
}
impl Fill {
pub fn bytes(bytes: impl Into<Vec<u8>>) -> Fill {
Fill::of(Body::Bytes(bytes.into()))
}
pub fn reader(reader: impl Read + Send + 'static) -> Fill {
Fill::of(Body::Reader(Box::new(reader)))
}
pub fn file(path: impl Into<PathBuf>) -> Fill {
Fill::of(Body::Path(path.into()))
}
pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
self.content_type = Some(content_type.into());
self
}
pub fn meta(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.meta.insert(name.into(), value.into());
self
}
fn of(body: Body) -> Fill {
Fill { body, content_type: None, meta: BTreeMap::new() }
}
}
impl fmt::Debug for Fill {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let body = match &self.body {
Body::Bytes(bytes) => format!("{} bytes", bytes.len()),
Body::Reader(_) => "a reader".to_owned(),
Body::Path(path) => format!("{}", path.display()),
};
write!(f, "Fill({body})")
}
}
impl From<Vec<u8>> for Fill {
fn from(bytes: Vec<u8>) -> Fill {
Fill::bytes(bytes)
}
}
impl From<&[u8]> for Fill {
fn from(bytes: &[u8]) -> Fill {
Fill::bytes(bytes)
}
}
impl From<String> for Fill {
fn from(text: String) -> Fill {
Fill::bytes(text)
}
}
impl From<&str> for Fill {
fn from(text: &str) -> Fill {
Fill::bytes(text)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Outcome {
Hit,
Wait,
Run,
Failed,
}
impl Outcome {
fn as_str(self) -> &'static str {
match self {
Outcome::Hit => "hit",
Outcome::Wait => "wait",
Outcome::Run => "run",
Outcome::Failed => "failed",
}
}
pub(crate) fn count(self, files: &Files) {
let labels = [("set", files.name()), ("outcome", self.as_str())];
files.blobs.probe.count("tinystore_files_get_or_create_total", &labels, 1.0);
}
}
pub(crate) type Waiter = Box<dyn FnOnce(Option<Arc<Error>>) + Send>;
#[derive(Default)]
pub(crate) struct Fills {
runs: Mutex<HashMap<i64, Run>>,
}
struct Run {
set: i64,
path: String,
renew_until: i64,
thread: Option<ThreadId>,
waiters: Vec<Waiter>,
}
enum Joined {
Waiting,
NotHere,
Itself,
}
impl Fills {
fn start(&self, owner: i64, (set, path): (i64, &str), renew_until: i64, thread: Option<ThreadId>) {
let run = Run { set, path: path.to_owned(), renew_until, thread, waiters: Vec::new() };
lock(&self.runs).insert(owner, run);
}
fn join(&self, owner: i64, caller: Option<ThreadId>, waiter: Waiter) -> Joined {
let mut runs = lock(&self.runs);
match runs.get_mut(&owner) {
Some(run) if caller.is_some() && run.thread == caller => Joined::Itself,
Some(run) => {
run.waiters.push(waiter);
Joined::Waiting
}
None => Joined::NotHere,
}
}
pub(super) fn end(&self, owner: i64, failure: Option<Arc<Error>>) {
let run = lock(&self.runs).remove(&owner);
for waiter in run.map(|run| run.waiters).unwrap_or_default() {
waiter(failure.clone());
}
}
fn renewing(&self, now: i64) -> Vec<(i64, i64, String)> {
let runs = lock(&self.runs);
runs.iter()
.filter(|(_, run)| run.renew_until > now)
.map(|(&owner, run)| (owner, run.set, run.path.clone()))
.collect()
}
fn stop_renewing(&self, owner: i64) {
if let Some(run) = lock(&self.runs).get_mut(&owner) {
run.renew_until = i64::MIN;
}
}
#[cfg(test)]
pub(crate) fn under_way(&self) -> (usize, usize) {
let runs = lock(&self.runs);
(runs.len(), runs.values().map(|run| run.waiters.len()).sum())
}
}
impl fmt::Debug for Fills {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Fills({} under way)", lock(&self.runs).len())
}
}
pub(crate) enum Hand {
There,
Waiting,
Yours(Filling),
}
enum Claimed {
There,
Waiting,
Mine,
}
pub(crate) struct Filling {
files: Files,
whole: String,
owner: i64,
failure: Option<Arc<Error>>,
}
impl Files {
pub(crate) fn hand(
&self,
whole: &str,
timeout: Duration,
caller: Option<ThreadId>,
waiter: Waiter,
) -> Result<Hand> {
let owner = drawn();
let (blobs, set, path) = (Arc::clone(&self.blobs), self.set, whole.to_owned());
let renew_for = crate::clock::millis(timeout);
let claimed = self.blobs.file.write(0, move |tx| {
let asked = Asked { set, path: &path, owner, renew_for, caller };
claim(tx, &blobs, &asked, waiter)
});
match claimed {
Ok(Claimed::There) => Ok(Hand::There),
Ok(Claimed::Waiting) => Ok(Hand::Waiting),
Ok(Claimed::Mine) => {
Ok(Hand::Yours(Filling { files: self.clone(), whole: whole.to_owned(), owner, failure: None }))
}
Err(error) => {
self.blobs.fills.end(owner, None);
Err(error)
}
}
}
}
struct Asked<'a> {
set: i64,
path: &'a str,
owner: i64,
renew_for: i64,
caller: Option<ThreadId>,
}
fn claim(tx: &Tx<'_>, blobs: &Blobs, asked: &Asked<'_>, waiter: Waiter) -> Result<Claimed> {
let change = Change::new(tx, blobs);
if change.current(asked.set, asked.path)?.is_some_and(|current| current.live(change.now)) {
return Ok(Claimed::There);
}
let held: Option<(i64, i64)> = tx
.prepare_cached(SELECT_CLAIM)
.and_then(|mut select| select.query_row(params![asked.set, asked.path], |row| Ok((row.get(0)?, row.get(1)?))))
.optional()
.map_err(|error| sql_error("blobs: a path's claim", error))?;
if let Some((holder, until)) = held {
if until > change.now {
match blobs.fills.join(holder, asked.caller, waiter) {
Joined::Waiting => return Ok(Claimed::Waiting),
Joined::Itself => {
return Err(Error::invalid("a getOrCreate of a path inside its own run would wait for itself"));
}
Joined::NotHere => {}
}
}
blobs.fills.end(holder, None);
}
let until = change.now.saturating_add(crate::clock::millis(LEASE));
blobs.fills.start(asked.owner, (asked.set, asked.path), change.now.saturating_add(asked.renew_for), asked.caller);
change.execute(UPSERT_CLAIM, params![asked.set, asked.path, asked.owner, until])?;
Ok(Claimed::Mine)
}
impl Filling {
#[cfg(feature = "wire")]
pub(crate) fn owner(&self) -> i64 {
self.owner
}
#[cfg(feature = "wire")]
pub(crate) fn is_of(&self, files: &Files, whole: &str) -> bool {
Arc::ptr_eq(&self.files.blobs, &files.blobs) && self.files.set == files.set && self.whole == whole
}
pub(crate) fn land(&self, fill: Fill, options: &Options) -> Result<Option<FileInfo>> {
let mut options = Options { fill: Some(self.owner), ..options.clone() };
if let Some(content_type) = fill.content_type {
options.content_type = Some(content_type);
}
if !fill.meta.is_empty() {
options.meta = fill.meta;
options.meta_given = true;
}
options.check().map_err(|error| self.files.fail(&self.whole, error))?;
let mut upload = Upload::start(self.files.clone(), self.whole.clone(), options)?;
match fill.body {
Body::Bytes(bytes) => upload.take(&bytes)?,
Body::Reader(reader) => pour(&mut upload, reader)?,
Body::Path(path) => {
let file = std::fs::File::open(&path)
.map_err(|error| Error::io(format!("blobs: open {}", path.display()), error))
.map_err(|error| self.files.fail(&self.whole, error))?;
pour(&mut upload, file)?;
}
}
upload.publish(true)
}
pub(crate) fn fail(mut self, failure: Error) {
self.failure = Some(Arc::new(failure));
}
}
impl Drop for Filling {
fn drop(&mut self) {
self.files.blobs.fills.end(self.owner, self.failure.take());
}
}
impl fmt::Debug for Filling {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Filling({:?}, {})", self.files, self.whole)
}
}
fn pour(upload: &mut Upload, mut reader: impl Read) -> Result<()> {
let mut piece = vec![0; PIECE];
loop {
match reader.read(&mut piece) {
Ok(0) => return Ok(()),
Ok(read) => upload.take(&piece[..read])?,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
Err(error) => return Err(Error::io("blobs: read what a getOrCreate's function gave", error)),
}
}
}
impl Blobs {
pub(crate) fn renew_claims(self: &Arc<Self>) -> Result<()> {
let now = self.now();
let renewing = self.fills.renewing(now);
if renewing.is_empty() && lock(&self.fills.runs).is_empty() {
return Ok(());
}
let until = now.saturating_add(crate::clock::millis(LEASE));
let blobs = Arc::clone(self);
let lost = own_work(|| {
self.file.write(0, move |tx| {
let change = Change::new(tx, &blobs);
let mut lost = Vec::new();
for (owner, set, path) in renewing {
let renewed = tx
.prepare_cached(RENEW_CLAIM)
.and_then(|mut renew| renew.execute(params![set, path, owner, until, change.now]))
.map_err(|error| sql_error("blobs: renew a claim", error))?;
if renewed == 0 {
lost.push(owner);
}
}
change.execute(PURGE_CLAIMS, params![change.now])?;
Ok(lost)
})
})?;
for owner in lost {
self.fills.stop_renewing(owner);
}
Ok(())
}
pub(super) fn forget_claims(&self) -> Result<()> {
own_work(|| {
self.file.write(0, |tx| {
tx.execute(FORGET_CLAIMS, []).map(drop).map_err(|error| sql_error("blobs: forget the claims", error))
})
})
}
}
pub(super) fn get_or_create<T, E>(
files: &Files,
whole: &str,
options: &Options,
mut work: impl FnMut() -> std::result::Result<T, E>,
) -> std::result::Result<StoredFile, E>
where
T: Into<Fill>,
E: From<Error> + fmt::Display + 'static,
{
let timeout = options.timeout.unwrap_or(TIMEOUT);
let mut outcome = Outcome::Hit;
let answered = loop {
match files.get_whole(whole) {
Ok(Some(file)) => break Ok(file),
Ok(None) => {}
Err(error) => break Err(E::from(error)),
}
let (told, ended) = mpsc::channel();
let waiter: Waiter = Box::new(move |failure| {
let _ = told.send(failure);
});
let handed = crate::polled::may_wait(|| format!("{}: {whole:?}: a getOrCreate", files.describe()))
.and_then(|()| files.hand(whole, timeout, Some(thread::current().id()), waiter))
.map_err(|error| files.fail(whole, error));
let filling = match handed {
Err(error) => break Err(E::from(error)),
Ok(Hand::There) => continue,
Ok(Hand::Waiting) => {
outcome = outcome.max(Outcome::Wait);
match ended.recv() {
Ok(Some(failure)) => break Err(E::from(failure.duplicate())),
_ => continue,
}
}
Ok(Hand::Yours(filling)) => filling,
};
outcome = Outcome::Run;
let fill = match work() {
Ok(fill) => fill.into(),
Err(error) => {
filling.fail(failure_of(&error).within(format!("files {}: {whole:?}", files.name())));
break Err(error);
}
};
if let Err(error) = filling.land(fill, options) {
filling.fail(error.duplicate());
break Err(E::from(error));
}
};
if answered.is_err() {
outcome = Outcome::Failed;
}
outcome.count(files);
answered
}
pub(crate) fn failure_of<E: fmt::Display + 'static>(error: &E) -> Error {
match (error as &dyn std::any::Any).downcast_ref::<Error>() {
Some(error) => error.duplicate(),
None => Error::new(ErrorKind::Conflict, format!("the run waited for failed: {error}")),
}
}
fn drawn() -> i64 {
static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_u64(COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
i64::try_from(hasher.finish() >> 1).unwrap_or_default()
}
#[cfg(test)]
#[path = "filling_tests.rs"]
mod tests;