use std::collections::HashSet;
use std::fs::{self, File, OpenOptions};
use std::hash::Hasher;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
use serde::Deserialize;
use serde_json::Value;
use siphasher::sip128::{Hasher128, SipHasher24};
use crate::Error;
use crate::request::Id;
#[derive(Debug, Default, Clone)]
pub struct Finished {
keys: HashSet<u128>,
kept: u64,
torn: bool,
retried: u64,
}
#[derive(Deserialize)]
struct ResultLine {
id: Value,
line: Option<u64>,
status: String,
#[serde(default)]
hashes: Vec<HashLine>,
}
#[derive(Deserialize)]
struct HashLine {
error_type: Option<Value>,
}
impl Finished {
pub fn load(path: &Path, retry_failed: bool) -> Result<Self, Error> {
let file = match File::open(path) {
Ok(file) => file,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Self::default()),
Err(error) => return Err(Error::io(format!("couldn't open `{}`", path.display()), error)),
};
let mut finished = Self::default();
let mut reader = BufReader::new(file);
let rewrite_path = rewrite_path(path);
let mut rewrite = if retry_failed {
let file = File::create(&rewrite_path)
.map_err(|error| Error::io(format!("couldn't create `{}`", rewrite_path.display()), error))?;
Some(BufWriter::new(file))
} else {
None
};
let mut good_length = 0u64;
let mut line = Vec::new();
let mut number = 0u64;
loop {
line.clear();
let read = reader
.read_until(b'\n', &mut line)
.map_err(|error| Error::io(format!("couldn't read `{}`", path.display()), error))?;
if read == 0 {
break;
}
number += 1;
if line.last() != Some(&b'\n') {
finished.torn = true;
break;
}
let parsed: ResultLine = serde_json::from_slice(&line).map_err(|_| Error::NotAResult {
path: path.to_path_buf(),
line: number,
})?;
let key = match (Id::from_json(&parsed.id), parsed.line) {
(Some(id), _) => key(&id.to_string()),
(None, Some(line)) => key(&format!("line:{line}")),
(None, None) => {
return Err(Error::NotAResult {
path: path.to_path_buf(),
line: number,
});
}
};
let failed = parsed.status != "success" || parsed.hashes.iter().any(|hash| hash.error_type.is_some());
if retry_failed && failed {
finished.retried += 1;
continue;
}
finished.keys.insert(key);
finished.kept += 1;
good_length += read as u64;
if let Some(rewrite) = &mut rewrite {
rewrite
.write_all(&line)
.map_err(|error| Error::io(format!("couldn't write `{}`", rewrite_path.display()), error))?;
}
}
drop(reader);
if let Some(rewrite) = rewrite {
let file = rewrite.into_inner().map_err(|error| {
Error::io(
format!("couldn't write `{}`", rewrite_path.display()),
error.into_error(),
)
})?;
file.sync_all()
.map_err(|error| Error::io(format!("couldn't write `{}`", rewrite_path.display()), error))?;
fs::rename(&rewrite_path, path).map_err(|error| {
Error::io(
format!(
"couldn't replace `{}` with `{}`",
path.display(),
rewrite_path.display()
),
error,
)
})?;
} else if finished.torn {
OpenOptions::new()
.write(true)
.open(path)
.and_then(|file| file.set_len(good_length))
.map_err(|error| {
Error::io(
format!("couldn't cut the torn last line of `{}`", path.display()),
error,
)
})?;
}
Ok(finished)
}
pub(crate) fn contains(&self, key: u128) -> bool {
self.keys.contains(&key)
}
#[must_use]
pub const fn kept(&self) -> u64 {
self.kept
}
#[must_use]
pub const fn was_torn(&self) -> bool {
self.torn
}
#[must_use]
pub const fn retried(&self) -> u64 {
self.retried
}
}
fn rewrite_path(path: &Path) -> PathBuf {
let mut name = path.file_name().map(|name| name.to_os_string()).unwrap_or_default();
name.push(".resume-tmp");
path.with_file_name(name)
}
pub(crate) fn key(text: &str) -> u128 {
let mut hasher = SipHasher24::new_with_keys(0, 0);
hasher.write(text.as_bytes());
hasher.finish128().as_u128()
}