use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use rusqlite::params;
use super::files::Files;
use crate::Result;
use crate::sqlite::{File, Tx, sql_error};
use crate::sync::lock;
const HEAD_START: i64 = 24 * HOUR;
const HOUR: i64 = 60 * 60 * 1000;
const REFRESHES: i64 = 30;
const RENEW_AT_ONCE: i64 = 60_000;
pub(crate) const USES: Duration = Duration::from_secs(1);
const MOST_WAITING: usize = 100_000;
const BATCH: usize = 10_000;
const RECORD_USE: &str = "update _tinystore_blobs_files
set rank = ?4 + ?5, used = ?4, expires = coalesce(?6, expires)
where set_id = ?1 and path = ?2 and revision = ?3 and (expires is null or expires > ?7)";
macro_rules! ceiled {
() => {
"(select s.max_size is not null from _tinystore_blobs_sets as s where s.id = f.set_id)"
};
}
pub(crate) use ceiled;
#[derive(Clone, Copy, Debug)]
pub(crate) struct Seen {
pub(crate) revision: i64,
pub(crate) modified: i64,
pub(crate) used: Option<i64>,
pub(crate) expires: Option<i64>,
pub(crate) ceiled: bool,
}
#[derive(Clone, Debug)]
pub(crate) struct Use {
#[cfg_attr(not(feature = "replication"), expect(dead_code, reason = "only a copy passes its uses home"))]
pub(crate) name: Arc<str>,
pub(crate) revision: i64,
pub(crate) used: i64,
pub(crate) until: Option<i64>,
}
#[derive(Default)]
pub(crate) struct Uses(Mutex<HashMap<(i64, String), Use>>);
impl std::fmt::Debug for Uses {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Uses").field("waiting", &lock(&self.0).len()).finish()
}
}
impl Uses {
pub(crate) fn ask(&self, set: i64, path: &str, asked: Use) {
let mut waiting = lock(&self.0);
let key = (set, path.to_owned());
if waiting.len() >= MOST_WAITING && !waiting.contains_key(&key) {
return;
}
waiting.insert(key, asked);
}
pub(crate) fn flush(&self, file: &File, now: impl Fn() -> i64 + Clone + Send + 'static) -> Result<usize> {
let asked: Vec<((i64, String), Use)> = lock(&self.0).drain().collect();
let mut recorded = 0;
for (index, batch) in asked.chunks(BATCH).enumerate() {
let (batch, now) = (batch.to_vec(), now.clone());
let written = file.write(0, move |tx| {
let now = now();
let mut recorded = 0;
for ((set, path), asked) in &batch {
recorded += usize::from(write(tx, *set, path, asked, now)?);
}
Ok(recorded)
});
match written {
Ok(written) => recorded += written,
Err(error) => {
let mut waiting = lock(&self.0);
for (key, asked) in &asked[index * BATCH..] {
waiting.entry(key.clone()).or_insert_with(|| asked.clone());
}
return Err(error);
}
}
}
Ok(recorded)
}
#[cfg(feature = "replication")]
pub(crate) fn take(&self) -> Vec<((i64, String), Use)> {
lock(&self.0).drain().collect()
}
}
pub(crate) fn write(tx: &Tx<'_>, set: i64, path: &str, asked: &Use, now: i64) -> Result<bool> {
tx.prepare_cached(RECORD_USE)
.and_then(|mut update| {
update.execute(params![set, path, asked.revision, asked.used, HEAD_START, asked.until, now])
})
.map(|changed| changed > 0)
.map_err(|error| sql_error("blobs: a file's use", error))
}
impl Files {
pub(super) fn used(&self, whole: &str, seen: &Seen) -> Result<Option<i64>> {
let Some((asked, at_once)) = self.use_due(seen) else { return Ok(None) };
if !at_once {
self.blobs.uses.ask(self.set, whole, asked);
return Ok(None);
}
crate::polled::may_wait(|| format!("{}: {whole:?}: a renewal", self.describe()))?;
#[cfg(feature = "replication")]
if self.is_copy() {
return Ok(self.use_at_home(whole, asked));
}
let (set, path, until, written) = (self.set, whole.to_owned(), asked.until, asked.clone());
let blobs = Arc::clone(&self.blobs);
match self.blobs.file.write(0, move |tx| write(tx, set, &path, &written, blobs.now())) {
Ok(true) => Ok(until),
Ok(false) => Ok(None),
Err(_) => {
self.blobs.uses.ask(self.set, whole, asked);
Ok(None)
}
}
}
#[cfg(feature = "replication")]
fn use_at_home(&self, whole: &str, asked: Use) -> Option<i64> {
let until = asked.until;
match self.pass_on(&super::forward::Call::Use { path: whole, used: &asked }) {
Ok(true) => until,
Ok(false) => None,
Err(_) => {
self.blobs.uses.ask(self.set, whole, asked);
None
}
}
}
#[cfg(feature = "replication")]
pub(crate) fn use_passed_on(&self, whole: &str, asked: &Use) -> Result<bool> {
let (set, path, asked, blobs) = (self.set, whole.to_owned(), asked.clone(), Arc::clone(&self.blobs));
self.blobs.file.write(0, move |tx| write(tx, set, &path, &asked, blobs.now()))
}
fn use_due(&self, seen: &Seen) -> Option<(Use, bool)> {
if !self.records_uses(seen) {
return None;
}
let now = self.blobs.now();
let asked = |until| Use { name: Arc::clone(&self.name), revision: seen.revision, used: now, until };
match self.idle() {
Some(term) => {
let (term, expires) = (crate::clock::millis(term), seen.expires?);
if expires - now > term - term / REFRESHES {
return None;
}
Some((asked(Some(now.saturating_add(term))), expires - now < RENEW_AT_ONCE))
}
None if now - seen.used.unwrap_or(seen.modified) >= HOUR => Some((asked(None), false)),
None => None,
}
}
}