fix(store): logs, uploads, exports and git can be closed, so a handle from before a close can never write after it
A book closed while the server runs stays a book of the root: another process may open it, or this one may open it again, and a new access log is then opened against the file's own head. Any holder of the old handle that appends (an access record written late), sweeps (a timer) or renames (an upload part, a claim dropped) reaches the new book's files and breaks its chain. Each of these now has a closed state, set under the very lock every change to its files goes in under, so a change whose work began before the close is whole and one after it is refused, unwritten. git also takes a cancel flag: a command running is stopped with all it started, and none starts, so a close can end a backup that is still going instead of leaving it to run against books reported closed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8056e3bbc8
commit
181859d801
5 files changed
+286
-20
No files matched your search
@@ -19,6 +19,12 @@
|
|||||||
//! name and version, a request id, the tool or resource it named)
|
//! name and version, a request id, the tool or resource it named)
|
||||||
//! has any full TIN masked and is then cut to 64 characters.
|
//! has any full TIN masked and is then cut to 64 characters.
|
||||||
//! 3. Records go in one at a time, in the order they are made.
|
//! 3. Records go in one at a time, in the order they are made.
|
||||||
|
//! 4. A log can be closed (`close`, under the lock every record goes in
|
||||||
|
//! under): a record whose append began before it is whole, one after
|
||||||
|
//! it is refused (`ChainError::Closed`), unwritten. So a record
|
||||||
|
//! still on its way when its book is let go (a refusal written late)
|
||||||
|
//! never reaches the file, nor, once the book is opened again, the
|
||||||
|
//! new log's chain.
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::chain::{self, ChainError, ChainLog, Head};
|
use crate::chain::{self, ChainError, ChainLog, Head};
|
||||||
@@ -220,6 +226,12 @@ impl AccessLog {
|
|||||||
log.append(fields).map(|(_, head)| head)
|
log.append(fields).map(|(_, head)| head)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Take no more records, ever (INVARIANT 4): waits for the record
|
||||||
|
/// being appended, if one is.
|
||||||
|
pub fn close(&self) {
|
||||||
|
self.log.lock().unwrap_or_else(|e| e.into_inner()).close();
|
||||||
|
}
|
||||||
|
|
||||||
/// Where the log ends now.
|
/// Where the log ends now.
|
||||||
pub fn head(&self) -> Head {
|
pub fn head(&self) -> Head {
|
||||||
self.log
|
self.log
|
||||||
@@ -289,6 +301,30 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A closed log takes no more records (INVARIANT 4): a handle kept from
|
||||||
|
/// before a close can't append after the log is opened again, which
|
||||||
|
/// would break the new log's chain.
|
||||||
|
#[test]
|
||||||
|
fn a_closed_log_writes_nothing_and_a_reopened_one_stays_whole() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let old = AccessLog::open(dir.path()).unwrap();
|
||||||
|
old.record(&access(1)).unwrap();
|
||||||
|
old.close();
|
||||||
|
let file = || std::fs::read(dir.path().join(ACCESS_FILE)).unwrap();
|
||||||
|
let at_close = file();
|
||||||
|
assert_eq!(old.record(&access(2)), Err(ChainError::Closed));
|
||||||
|
assert_eq!(file(), at_close, "a closed log wrote");
|
||||||
|
// The book is opened again: a new log, against its own head.
|
||||||
|
let new = AccessLog::open(dir.path()).unwrap();
|
||||||
|
new.record(&access(3)).unwrap();
|
||||||
|
// The old handle, used late, writes nothing.
|
||||||
|
assert_eq!(old.record(&access(4)), Err(ChainError::Closed));
|
||||||
|
new.record(&access(5)).unwrap();
|
||||||
|
let (back, head) = read(dir.path()).unwrap();
|
||||||
|
assert_eq!(back.len(), 3);
|
||||||
|
assert_eq!(head.seq, 3);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn records_read_back_as_written() {
|
fn records_read_back_as_written() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -82,6 +82,10 @@ pub enum BackupError {
|
|||||||
/// A git command ran past its time limit.
|
/// A git command ran past its time limit.
|
||||||
#[error("git {0} took too long and was stopped")]
|
#[error("git {0} took too long and was stopped")]
|
||||||
TimedOut(String),
|
TimedOut(String),
|
||||||
|
/// A git command stopped because the books it served were let go
|
||||||
|
/// ([`Git::with_cancel`]).
|
||||||
|
#[error("git {0} was stopped: the books are closing")]
|
||||||
|
Cancelled(String),
|
||||||
/// A folder target that isn't there (an external disk not mounted).
|
/// A folder target that isn't there (an external disk not mounted).
|
||||||
#[error("the backup folder isn't there (is its disk connected?)")]
|
#[error("the backup folder isn't there (is its disk connected?)")]
|
||||||
NoFolder,
|
NoFolder,
|
||||||
@@ -114,6 +118,9 @@ pub struct Git {
|
|||||||
exe: PathBuf,
|
exe: PathBuf,
|
||||||
/// How long it may say nothing before it is stopped (GIT_TIMEOUT).
|
/// How long it may say nothing before it is stopped (GIT_TIMEOUT).
|
||||||
quiet: Duration,
|
quiet: Duration,
|
||||||
|
/// Set by whoever serves the books when they are let go: a git
|
||||||
|
/// command running is stopped, with what it started, and none starts.
|
||||||
|
cancel: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Git {
|
impl Git {
|
||||||
@@ -145,10 +152,27 @@ impl Git {
|
|||||||
.map(|exe| Git {
|
.map(|exe| Git {
|
||||||
exe,
|
exe,
|
||||||
quiet: GIT_TIMEOUT,
|
quiet: GIT_TIMEOUT,
|
||||||
|
cancel: None,
|
||||||
})
|
})
|
||||||
.ok_or(BackupError::NoGit)
|
.ok_or(BackupError::NoGit)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This git, stopped (every command running, and any that would
|
||||||
|
/// start) once `cancel` is set: how the server's close ends a backup
|
||||||
|
/// that is still going, instead of leaving it to run against books it
|
||||||
|
/// reported closed.
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_cancel(mut self, cancel: std::sync::Arc<std::sync::atomic::AtomicBool>) -> Self {
|
||||||
|
self.cancel = Some(cancel);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cancelled(&self) -> bool {
|
||||||
|
self.cancel
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|c| c.load(std::sync::atomic::Ordering::SeqCst))
|
||||||
|
}
|
||||||
|
|
||||||
/// A git command with a clean configuration (INVARIANT 4).
|
/// A git command with a clean configuration (INVARIANT 4).
|
||||||
fn command(&self) -> Command {
|
fn command(&self) -> Command {
|
||||||
let mut c = Command::new(&self.exe);
|
let mut c = Command::new(&self.exe);
|
||||||
@@ -222,6 +246,9 @@ impl Git {
|
|||||||
/// (a push or a clone reports its progress as it goes).
|
/// (a push or a clone reports its progress as it goes).
|
||||||
fn run(&self, what: &str, args: &[&std::ffi::OsStr]) -> Result<String, BackupError> {
|
fn run(&self, what: &str, args: &[&std::ffi::OsStr]) -> Result<String, BackupError> {
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
if self.cancelled() {
|
||||||
|
return Err(BackupError::Cancelled(what.to_string()));
|
||||||
|
}
|
||||||
let mut c = self.command();
|
let mut c = self.command();
|
||||||
// A path made canonical on Windows carries `\\?\`, which git refuses.
|
// A path made canonical on Windows carries `\\?\`, which git refuses.
|
||||||
c.args(args.iter().map(|a| match a.to_str() {
|
c.args(args.iter().map(|a| match a.to_str() {
|
||||||
@@ -306,6 +333,12 @@ impl Git {
|
|||||||
let quiet_for = started
|
let quiet_for = started
|
||||||
.elapsed()
|
.elapsed()
|
||||||
.saturating_sub(Duration::from_millis(heard.load(Ordering::Relaxed)));
|
.saturating_sub(Duration::from_millis(heard.load(Ordering::Relaxed)));
|
||||||
|
if self.cancelled() {
|
||||||
|
kill_group(child.id());
|
||||||
|
let _ = child.kill();
|
||||||
|
let _ = child.wait();
|
||||||
|
return Err(BackupError::Cancelled(what.to_string()));
|
||||||
|
}
|
||||||
if quiet_for > self.quiet {
|
if quiet_for > self.quiet {
|
||||||
kill_group(child.id());
|
kill_group(child.id());
|
||||||
let _ = child.kill();
|
let _ = child.kill();
|
||||||
@@ -1877,6 +1910,7 @@ mod tests {
|
|||||||
Git {
|
Git {
|
||||||
exe: wrapper,
|
exe: wrapper,
|
||||||
quiet: GIT_TIMEOUT,
|
quiet: GIT_TIMEOUT,
|
||||||
|
cancel: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1928,7 +1962,59 @@ mod tests {
|
|||||||
let exe = dir.join("fake-git");
|
let exe = dir.join("fake-git");
|
||||||
std::fs::write(&exe, format!("#!/bin/sh\n{script}\n")).unwrap();
|
std::fs::write(&exe, format!("#!/bin/sh\n{script}\n")).unwrap();
|
||||||
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
|
std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
Git { exe, quiet }
|
Git {
|
||||||
|
exe,
|
||||||
|
quiet,
|
||||||
|
cancel: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancelled, a git that is running is stopped at once, with all it
|
||||||
|
/// started, and one that would start doesn't (the server's close ends
|
||||||
|
/// a backup instead of leaving it to run against closed books).
|
||||||
|
#[test]
|
||||||
|
fn a_cancelled_git_stops_what_runs_and_starts_nothing() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let pid = dir.path().join("pid");
|
||||||
|
let cancel = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||||
|
let slow = fake_git(
|
||||||
|
dir.path(),
|
||||||
|
&format!("sleep 30 & echo $! > '{}'; sleep 30", pid.display()),
|
||||||
|
Duration::from_secs(60),
|
||||||
|
)
|
||||||
|
.with_cancel(cancel.clone());
|
||||||
|
let running = {
|
||||||
|
let slow = slow.clone();
|
||||||
|
std::thread::spawn(move || slow.run("slow", &[]))
|
||||||
|
};
|
||||||
|
// It is running (it wrote its child's pid) before it is cancelled.
|
||||||
|
let by = Instant::now() + Duration::from_secs(10);
|
||||||
|
while !pid.exists() {
|
||||||
|
assert!(Instant::now() < by, "the fake git never started");
|
||||||
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
let cancelled_at = Instant::now();
|
||||||
|
cancel.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
assert_eq!(
|
||||||
|
running.join().unwrap().unwrap_err(),
|
||||||
|
BackupError::Cancelled("slow".into())
|
||||||
|
);
|
||||||
|
assert!(cancelled_at.elapsed() < Duration::from_secs(5));
|
||||||
|
let child: i32 = std::fs::read_to_string(&pid)
|
||||||
|
.unwrap()
|
||||||
|
.trim()
|
||||||
|
.parse()
|
||||||
|
.unwrap();
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
// SAFETY: signal 0 only asks whether the process is there.
|
||||||
|
assert_ne!(unsafe { libc::kill(child, 0) }, 0, "what it started ran on");
|
||||||
|
// And none starts now.
|
||||||
|
std::fs::remove_file(&pid).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
slow.run("again", &[]).unwrap_err(),
|
||||||
|
BackupError::Cancelled("again".into())
|
||||||
|
);
|
||||||
|
assert!(!pid.exists(), "a cancelled git started anyway");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -2005,6 +2091,7 @@ mod tests {
|
|||||||
let odd = Git {
|
let odd = Git {
|
||||||
exe: quoted.join("git"),
|
exe: quoted.join("git"),
|
||||||
quiet: GIT_TIMEOUT,
|
quiet: GIT_TIMEOUT,
|
||||||
|
cancel: None,
|
||||||
};
|
};
|
||||||
let b = dir.path().join("book");
|
let b = dir.path().join("book");
|
||||||
let s = book(&b);
|
let s = book(&b);
|
||||||
|
|||||||
@@ -28,6 +28,11 @@
|
|||||||
//! 4. Only an unfinished last line (no newline: an append cut short by
|
//! 4. Only an unfinished last line (no newline: an append cut short by
|
||||||
//! a crash, never acknowledged) is set aside: open cuts it away,
|
//! a crash, never acknowledged) is set aside: open cuts it away,
|
||||||
//! read reports it.
|
//! read reports it.
|
||||||
|
//! 5. A log can be closed (`close`), and a closed log takes no more
|
||||||
|
//! appends, ever: a holder of it from before the book was let go can
|
||||||
|
//! never write after the book is opened again, when a new log is
|
||||||
|
//! opened on the file against its own head (an append from the old
|
||||||
|
//! handle would break the chain there).
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::journal::{canonical_json, sha256_hex};
|
use crate::journal::{canonical_json, sha256_hex};
|
||||||
@@ -60,6 +65,8 @@ pub enum ChainError {
|
|||||||
Io(std::io::ErrorKind),
|
Io(std::io::ErrorKind),
|
||||||
/// An earlier append failed: the log must be reopened (INVARIANT 2).
|
/// An earlier append failed: the log must be reopened (INVARIANT 2).
|
||||||
Broken,
|
Broken,
|
||||||
|
/// The log was closed: its book was let go (INVARIANT 5).
|
||||||
|
Closed,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for ChainError {
|
impl std::fmt::Display for ChainError {
|
||||||
@@ -68,6 +75,7 @@ impl std::fmt::Display for ChainError {
|
|||||||
ChainError::Damaged { line, why } => write!(f, "record {line} is damaged: {why}"),
|
ChainError::Damaged { line, why } => write!(f, "record {line} is damaged: {why}"),
|
||||||
ChainError::Io(kind) => write!(f, "the disk refused: {kind}"),
|
ChainError::Io(kind) => write!(f, "the disk refused: {kind}"),
|
||||||
ChainError::Broken => f.write_str("an earlier record couldn't be written"),
|
ChainError::Broken => f.write_str("an earlier record couldn't be written"),
|
||||||
|
ChainError::Closed => f.write_str("the log was closed: its books are not open"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -168,6 +176,7 @@ pub struct ChainLog {
|
|||||||
file: File,
|
file: File,
|
||||||
head: Head,
|
head: Head,
|
||||||
broken: bool,
|
broken: bool,
|
||||||
|
closed: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for ChainLog {
|
impl std::fmt::Debug for ChainLog {
|
||||||
@@ -175,6 +184,7 @@ impl std::fmt::Debug for ChainLog {
|
|||||||
f.debug_struct("ChainLog")
|
f.debug_struct("ChainLog")
|
||||||
.field("head", &self.head)
|
.field("head", &self.head)
|
||||||
.field("broken", &self.broken)
|
.field("broken", &self.broken)
|
||||||
|
.field("closed", &self.closed)
|
||||||
.finish_non_exhaustive()
|
.finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -224,6 +234,7 @@ impl ChainLog {
|
|||||||
file,
|
file,
|
||||||
head: read.head,
|
head: read.head,
|
||||||
broken: false,
|
broken: false,
|
||||||
|
closed: false,
|
||||||
},
|
},
|
||||||
read.records,
|
read.records,
|
||||||
))
|
))
|
||||||
@@ -234,6 +245,11 @@ impl ChainLog {
|
|||||||
&self.head
|
&self.head
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Take no more appends, ever (INVARIANT 5).
|
||||||
|
pub fn close(&mut self) {
|
||||||
|
self.closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
/// The log's file.
|
/// The log's file.
|
||||||
pub fn path(&self) -> &Path {
|
pub fn path(&self) -> &Path {
|
||||||
&self.path
|
&self.path
|
||||||
@@ -243,6 +259,9 @@ impl ChainLog {
|
|||||||
/// and `hash` (which `fields` must not hold). Returns the record as
|
/// and `hash` (which `fields` must not hold). Returns the record as
|
||||||
/// written and the new head (INVARIANT 2).
|
/// written and the new head (INVARIANT 2).
|
||||||
pub fn append(&mut self, fields: Map<String, Value>) -> Result<(Value, Head), ChainError> {
|
pub fn append(&mut self, fields: Map<String, Value>) -> Result<(Value, Head), ChainError> {
|
||||||
|
if self.closed {
|
||||||
|
return Err(ChainError::Closed);
|
||||||
|
}
|
||||||
if self.broken {
|
if self.broken {
|
||||||
return Err(ChainError::Broken);
|
return Err(ChainError::Broken);
|
||||||
}
|
}
|
||||||
@@ -600,6 +619,7 @@ mod tests {
|
|||||||
hash: genesis(G),
|
hash: genesis(G),
|
||||||
},
|
},
|
||||||
broken: false,
|
broken: false,
|
||||||
|
closed: false,
|
||||||
};
|
};
|
||||||
assert!(matches!(log.append(fields(1)), Err(ChainError::Io(_))));
|
assert!(matches!(log.append(fields(1)), Err(ChainError::Io(_))));
|
||||||
assert_eq!(log.head().seq, 0, "the head didn't move");
|
assert_eq!(log.head().seq, 0, "the head didn't move");
|
||||||
|
|||||||
@@ -21,6 +21,11 @@
|
|||||||
//! lapsed ones are swept when the books open, whenever one is made,
|
//! lapsed ones are swept when the books open, whenever one is made,
|
||||||
//! and by the server's sweeper. A token has at most MAX_LIVE.
|
//! and by the server's sweeper. A token has at most MAX_LIVE.
|
||||||
//! 4. No error names a path.
|
//! 4. No error names a path.
|
||||||
|
//! 5. Exports can be closed (`close`, under the lock every change to the
|
||||||
|
//! folder is made under): after it none is made, given or swept by
|
||||||
|
//! any holder of these exports from before, so a book let go is
|
||||||
|
//! never touched by a late request or a sweep, whoever has it open
|
||||||
|
//! by then.
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::journal::sha256_hex;
|
use crate::journal::sha256_hex;
|
||||||
@@ -87,8 +92,9 @@ impl From<std::io::Error> for ExportError {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Exports {
|
pub struct Exports {
|
||||||
dir: PathBuf,
|
dir: PathBuf,
|
||||||
/// Held while exports are made or swept (INVARIANT 3).
|
/// Held while exports are made or swept (INVARIANT 3). True once
|
||||||
lock: std::sync::Arc<std::sync::Mutex<()>>,
|
/// closed (INVARIANT 5).
|
||||||
|
lock: std::sync::Arc<std::sync::Mutex<bool>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `ex_` and 32 letters `a` to `p`, a letter a nibble (INVARIANT 1).
|
/// `ex_` and 32 letters `a` to `p`, a letter a nibble (INVARIANT 1).
|
||||||
@@ -132,10 +138,16 @@ impl Exports {
|
|||||||
Ok(exports)
|
Ok(exports)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn locked(&self) -> std::sync::MutexGuard<'_, ()> {
|
fn locked(&self) -> std::sync::MutexGuard<'_, bool> {
|
||||||
self.lock.lock().unwrap_or_else(|e| e.into_inner())
|
self.lock.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Change nothing in these exports, and give none, from now on
|
||||||
|
/// (INVARIANT 5): waits for the change being made, if one is.
|
||||||
|
pub fn close(&self) {
|
||||||
|
*self.locked() = true;
|
||||||
|
}
|
||||||
|
|
||||||
fn path(&self, id: &str, ext: &str) -> PathBuf {
|
fn path(&self, id: &str, ext: &str) -> PathBuf {
|
||||||
self.dir.join(format!("{id}.{ext}"))
|
self.dir.join(format!("{id}.{ext}"))
|
||||||
}
|
}
|
||||||
@@ -152,7 +164,10 @@ impl Exports {
|
|||||||
if let Some(why) = file_name_problem(file_name).or_else(|| mime_problem(mime)) {
|
if let Some(why) = file_name_problem(file_name).or_else(|| mime_problem(mime)) {
|
||||||
return Err(ExportError::Bad(why));
|
return Err(ExportError::Bad(why));
|
||||||
}
|
}
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
return Err(ExportError::Bad("the books aren't open".into()));
|
||||||
|
}
|
||||||
self.sweep_held(now);
|
self.sweep_held(now);
|
||||||
if self.live_for(token, now) >= MAX_LIVE {
|
if self.live_for(token, now) >= MAX_LIVE {
|
||||||
return Err(ExportError::Bad(format!(
|
return Err(ExportError::Bad(format!(
|
||||||
@@ -196,6 +211,9 @@ impl Exports {
|
|||||||
return Err(ExportError::Unknown(id.chars().take(40).collect()));
|
return Err(ExportError::Unknown(id.chars().take(40).collect()));
|
||||||
}
|
}
|
||||||
let unknown = || ExportError::Unknown(id.to_string());
|
let unknown = || ExportError::Unknown(id.to_string());
|
||||||
|
if *self.locked() {
|
||||||
|
return Err(ExportError::Bad("the books aren't open".into()));
|
||||||
|
}
|
||||||
let record = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?;
|
let record = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?;
|
||||||
let export: Export = serde_json::from_slice(&record).map_err(|_| unknown())?;
|
let export: Export = serde_json::from_slice(&record).map_err(|_| unknown())?;
|
||||||
if export.expires <= now {
|
if export.expires <= now {
|
||||||
@@ -228,8 +246,10 @@ impl Exports {
|
|||||||
/// Sweep away every export that lapsed by `now`, and anything left
|
/// Sweep away every export that lapsed by `now`, and anything left
|
||||||
/// without one (INVARIANT 3).
|
/// without one (INVARIANT 3).
|
||||||
pub fn sweep(&self, now: i64) {
|
pub fn sweep(&self, now: i64) {
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
self.sweep_held(now);
|
if !*held {
|
||||||
|
self.sweep_held(now);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sweep_held(&self, now: i64) {
|
fn sweep_held(&self, now: i64) {
|
||||||
@@ -259,6 +279,29 @@ mod tests {
|
|||||||
|
|
||||||
const NOW: i64 = 1_800_000_000;
|
const NOW: i64 = 1_800_000_000;
|
||||||
|
|
||||||
|
/// Closed, exports are made, given and swept by no one (INVARIANT 5).
|
||||||
|
#[test]
|
||||||
|
fn closed_exports_change_nothing_and_give_nothing() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let x = Exports::open(dir.path(), NOW).unwrap();
|
||||||
|
let e = x.put("t", "a.csv", "text/csv", b"x", NOW).unwrap();
|
||||||
|
x.close();
|
||||||
|
let seen = || {
|
||||||
|
let mut names: Vec<_> = std::fs::read_dir(dir.path().join(EXPORTS_DIR))
|
||||||
|
.unwrap()
|
||||||
|
.map(|f| f.unwrap().file_name())
|
||||||
|
.collect();
|
||||||
|
names.sort();
|
||||||
|
names
|
||||||
|
};
|
||||||
|
let before = seen();
|
||||||
|
assert!(x.put("t", "b.csv", "text/csv", b"y", NOW).is_err());
|
||||||
|
assert!(x.get(&e.id, "t", NOW).is_err());
|
||||||
|
// A sweep long after everything lapsed removes nothing.
|
||||||
|
x.sweep(NOW + 10 * EXPORT_TTL);
|
||||||
|
assert_eq!(seen(), before);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn an_export_is_kept_fifteen_minutes() {
|
fn an_export_is_kept_fifteen_minutes() {
|
||||||
// What its refusal tells the human: kept 15 minutes, then gone.
|
// What its refusal tells the human: kept 15 minutes, then gone.
|
||||||
|
|||||||
@@ -28,6 +28,12 @@
|
|||||||
//! 4. No error names a path.
|
//! 4. No error names a path.
|
||||||
//! 5. A token has at most MAX_LIVE grants under way, so what one agent
|
//! 5. A token has at most MAX_LIVE grants under way, so what one agent
|
||||||
//! can keep on the disk is bounded.
|
//! can keep on the disk is bounded.
|
||||||
|
//! 6. Uploads can be closed (`close`, under the lock every change to
|
||||||
|
//! the folder is made under): after it nothing is granted, received,
|
||||||
|
//! taken, swept, given back or forgotten, by any holder of these
|
||||||
|
//! uploads from before, so a book let go (closed, or replaced by a
|
||||||
|
//! restore) is never touched by a sweep, a late request or a claim
|
||||||
|
//! dropped after, whoever has the book open by then.
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::journal::sha256_hex;
|
use crate::journal::sha256_hex;
|
||||||
@@ -36,6 +42,8 @@ use sha2::{Digest, Sha256};
|
|||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// What an upload is told when its books were let go (INVARIANT 6).
|
||||||
|
const CLOSED: &str = "the books aren't open";
|
||||||
/// The uploads' folder, in a book's folder.
|
/// The uploads' folder, in a book's folder.
|
||||||
pub const UPLOADS_DIR: &str = "uploads";
|
pub const UPLOADS_DIR: &str = "uploads";
|
||||||
/// The largest file taken (plan 4.7).
|
/// The largest file taken (plan 4.7).
|
||||||
@@ -99,7 +107,10 @@ impl Claim {
|
|||||||
impl Drop for Claim {
|
impl Drop for Claim {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if !self.spent {
|
if !self.spent {
|
||||||
let _held = self.uploads.locked();
|
let held = self.uploads.locked();
|
||||||
|
if *held {
|
||||||
|
return;
|
||||||
|
}
|
||||||
let _ = std::fs::rename(
|
let _ = std::fs::rename(
|
||||||
self.uploads.path(&self.id, TAKEN),
|
self.uploads.path(&self.id, TAKEN),
|
||||||
self.uploads.path(&self.id, "bin"),
|
self.uploads.path(&self.id, "bin"),
|
||||||
@@ -169,8 +180,8 @@ pub struct Uploads {
|
|||||||
dir: PathBuf,
|
dir: PathBuf,
|
||||||
/// Held while grants are made or swept and while bytes change name
|
/// Held while grants are made or swept and while bytes change name
|
||||||
/// (INVARIANTS 1, 2, 5): one server serves a book, so this orders
|
/// (INVARIANTS 1, 2, 5): one server serves a book, so this orders
|
||||||
/// every request to its uploads.
|
/// every request to its uploads. True once closed (INVARIANT 6).
|
||||||
lock: std::sync::Arc<std::sync::Mutex<()>>,
|
lock: std::sync::Arc<std::sync::Mutex<bool>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The longest file name taken, in bytes (most file systems' limit).
|
/// The longest file name taken, in bytes (most file systems' limit).
|
||||||
@@ -287,10 +298,25 @@ impl Uploads {
|
|||||||
Ok(uploads)
|
Ok(uploads)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn locked(&self) -> std::sync::MutexGuard<'_, ()> {
|
fn locked(&self) -> std::sync::MutexGuard<'_, bool> {
|
||||||
self.lock.lock().unwrap_or_else(|e| e.into_inner())
|
self.lock.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The lock, if the uploads aren't closed (INVARIANT 6).
|
||||||
|
fn locked_open(&self) -> Result<std::sync::MutexGuard<'_, bool>, UploadError> {
|
||||||
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
return Err(UploadError::Bad(CLOSED.into()));
|
||||||
|
}
|
||||||
|
Ok(held)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change nothing in these uploads from now on (INVARIANT 6): waits
|
||||||
|
/// for the change being made, if one is.
|
||||||
|
pub fn close(&self) {
|
||||||
|
*self.locked() = true;
|
||||||
|
}
|
||||||
|
|
||||||
fn path(&self, id: &str, ext: &str) -> PathBuf {
|
fn path(&self, id: &str, ext: &str) -> PathBuf {
|
||||||
self.dir.join(format!("{id}.{ext}"))
|
self.dir.join(format!("{id}.{ext}"))
|
||||||
}
|
}
|
||||||
@@ -327,7 +353,7 @@ impl Uploads {
|
|||||||
"purpose is receipt, document, import (a bank or chart CSV) or w9".into(),
|
"purpose is receipt, document, import (a bank or chart CSV) or w9".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let _held = self.locked();
|
let _held = self.locked_open()?;
|
||||||
self.sweep_held(now);
|
self.sweep_held(now);
|
||||||
// INVARIANT 5.
|
// INVARIANT 5.
|
||||||
if self.live_for(token, now) >= MAX_LIVE {
|
if self.live_for(token, now) >= MAX_LIVE {
|
||||||
@@ -378,6 +404,7 @@ impl Uploads {
|
|||||||
return Err(UploadError::Unknown(id.chars().take(40).collect()));
|
return Err(UploadError::Unknown(id.chars().take(40).collect()));
|
||||||
}
|
}
|
||||||
let unknown = || UploadError::Unknown(id.to_string());
|
let unknown = || UploadError::Unknown(id.to_string());
|
||||||
|
drop(self.locked_open()?);
|
||||||
let bytes = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?;
|
let bytes = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?;
|
||||||
let grant: Grant = serde_json::from_slice(&bytes).map_err(|_| unknown())?;
|
let grant: Grant = serde_json::from_slice(&bytes).map_err(|_| unknown())?;
|
||||||
if grant.expires <= now {
|
if grant.expires <= now {
|
||||||
@@ -406,7 +433,7 @@ impl Uploads {
|
|||||||
// One request at a time (INVARIANT 2): no bytes kept or held, and
|
// One request at a time (INVARIANT 2): no bytes kept or held, and
|
||||||
// no `.part` of another request.
|
// no `.part` of another request.
|
||||||
let mut out = {
|
let mut out = {
|
||||||
let _held = self.locked();
|
let _held = self.locked_open()?;
|
||||||
if done.exists() || self.path(id, TAKEN).exists() {
|
if done.exists() || self.path(id, TAKEN).exists() {
|
||||||
return Err(UploadError::AlreadySent);
|
return Err(UploadError::AlreadySent);
|
||||||
}
|
}
|
||||||
@@ -459,7 +486,11 @@ impl Uploads {
|
|||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
// Kept only if its grant still stands (it may have lapsed,
|
// Kept only if its grant still stands (it may have lapsed,
|
||||||
// or been filed by another request's bytes, meanwhile).
|
// or been filed by another request's bytes, meanwhile).
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
let _ = std::fs::remove_file(&part);
|
||||||
|
return Err(UploadError::Bad(CLOSED.into()));
|
||||||
|
}
|
||||||
let standing = std::fs::read(self.path(id, "json"))
|
let standing = std::fs::read(self.path(id, "json"))
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|b| serde_json::from_slice::<Grant>(&b).ok())
|
.and_then(|b| serde_json::from_slice::<Grant>(&b).ok())
|
||||||
@@ -493,7 +524,7 @@ impl Uploads {
|
|||||||
let taken = self.path(id, TAKEN);
|
let taken = self.path(id, TAKEN);
|
||||||
// The rename is the hold: of two calls, one gets it.
|
// The rename is the hold: of two calls, one gets it.
|
||||||
{
|
{
|
||||||
let _held = self.locked();
|
let _held = self.locked_open()?;
|
||||||
if let Err(e) = std::fs::rename(self.path(id, "bin"), &taken) {
|
if let Err(e) = std::fs::rename(self.path(id, "bin"), &taken) {
|
||||||
return Err(match e.kind() {
|
return Err(match e.kind() {
|
||||||
std::io::ErrorKind::NotFound if taken.exists() => UploadError::InUse,
|
std::io::ErrorKind::NotFound if taken.exists() => UploadError::InUse,
|
||||||
@@ -527,14 +558,19 @@ impl Uploads {
|
|||||||
/// be written): the grant stands, its bytes are to be sent again.
|
/// be written): the grant stands, its bytes are to be sent again.
|
||||||
pub fn discard(&self, id: &str) {
|
pub fn discard(&self, id: &str) {
|
||||||
if is_id(id) {
|
if is_id(id) {
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
let _ = std::fs::remove_file(self.path(id, "bin"));
|
if !*held {
|
||||||
|
let _ = std::fs::remove_file(self.path(id, "bin"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Forget grant `id` and anything kept for it.
|
/// Forget grant `id` and anything kept for it.
|
||||||
fn forget(&self, id: &str) {
|
fn forget(&self, id: &str) {
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
return;
|
||||||
|
}
|
||||||
for ext in ["json", "part", "bin", TAKEN] {
|
for ext in ["json", "part", "bin", TAKEN] {
|
||||||
let _ = std::fs::remove_file(self.path(id, ext));
|
let _ = std::fs::remove_file(self.path(id, ext));
|
||||||
}
|
}
|
||||||
@@ -543,8 +579,10 @@ impl Uploads {
|
|||||||
/// Sweep away every grant that lapsed by `now`, and anything left
|
/// Sweep away every grant that lapsed by `now`, and anything left
|
||||||
/// without one (INVARIANT 3).
|
/// without one (INVARIANT 3).
|
||||||
pub fn sweep(&self, now: i64) {
|
pub fn sweep(&self, now: i64) {
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
self.sweep_held(now);
|
if !*held {
|
||||||
|
self.sweep_held(now);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [`Self::sweep`], the lock held.
|
/// [`Self::sweep`], the lock held.
|
||||||
@@ -588,6 +626,48 @@ mod tests {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Closed, uploads are granted, received, taken, swept and given back
|
||||||
|
/// by no one, and a claim dropped after puts nothing back (INVARIANT 6).
|
||||||
|
#[test]
|
||||||
|
fn closed_uploads_change_nothing() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let u = Uploads::open(dir.path(), NOW).unwrap();
|
||||||
|
let bytes = b"%PDF-1.4 a receipt".to_vec();
|
||||||
|
let g = grant_for(&u, "tok_a", &bytes);
|
||||||
|
u.receive(&g.id, "tok_a", &mut &bytes[..], NOW).unwrap();
|
||||||
|
let received = u.take(&g.id, "tok_a", NOW).unwrap();
|
||||||
|
let seen = || {
|
||||||
|
let mut names: Vec<_> = std::fs::read_dir(dir.path().join(UPLOADS_DIR))
|
||||||
|
.unwrap()
|
||||||
|
.map(|f| f.unwrap().file_name())
|
||||||
|
.collect();
|
||||||
|
names.sort();
|
||||||
|
names
|
||||||
|
};
|
||||||
|
let held = seen();
|
||||||
|
u.close();
|
||||||
|
assert!(
|
||||||
|
u.grant(
|
||||||
|
"tok_a",
|
||||||
|
&sha256_hex(&bytes),
|
||||||
|
bytes.len() as u64,
|
||||||
|
"application/pdf",
|
||||||
|
"r.pdf",
|
||||||
|
"receipt",
|
||||||
|
NOW
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(u.receive(&g.id, "tok_a", &mut &bytes[..], NOW).is_err());
|
||||||
|
assert!(u.take(&g.id, "tok_a", NOW).is_err());
|
||||||
|
u.discard(&g.id);
|
||||||
|
u.sweep(NOW + 10 * UPLOAD_TTL);
|
||||||
|
// The call that held the bytes lets go of them, unspent: nothing
|
||||||
|
// is put back, nor forgotten, in a folder that is no longer ours.
|
||||||
|
drop(received);
|
||||||
|
assert_eq!(seen(), held);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn bytes_sent_as_declared_are_taken_once() {
|
fn bytes_sent_as_declared_are_taken_once() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
Reference in new issue
Block a user