legit-hasher 0.1.6

Every legit-hashes definition, images and text, for callers in any language: a command-line runner over JSON lines with resumable batches, and with the `serve` feature a worker that takes hashing tasks from Redis Streams
Documentation
//! Resuming a batch: which requests an earlier run's output already answers.

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;

/// The requests an earlier run already answered, by id, read from its output file.
///
/// It holds a 128-bit hash of each id, not the id: about 32 bytes a request in memory, so a
/// million finished requests take about 32 MB.
#[derive(Debug, Default, Clone)]
pub struct Finished {
    keys: HashSet<u128>,
    kept: u64,
    torn: bool,
    retried: u64,
}

/// The fields of a result line that resuming reads.
#[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 {
    /// Read the output of an earlier run at `path`, ready to append to.
    ///
    /// Every complete result line counts as finished, successful or failed. A last line without
    /// its newline, which a killed process can leave, isn't trusted: the file is cut back to the
    /// end of the line before it, and that request runs again. With `retry_failed`, the lines of
    /// failed requests are removed from the file too, and those requests run again. A missing
    /// file is an empty one.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] when the file can't be read or rewritten, and [`Error::NotAResult`]
    /// when a complete line isn't a result line, so the file isn't this runner's output.
    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)
    }

    /// Whether the request with this resume key is already finished.
    pub(crate) fn contains(&self, key: u128) -> bool {
        self.keys.contains(&key)
    }

    /// How many result lines were kept.
    #[must_use]
    pub const fn kept(&self) -> u64 {
        self.kept
    }

    /// Whether the file ended in a torn line, which was cut away.
    #[must_use]
    pub const fn was_torn(&self) -> bool {
        self.torn
    }

    /// How many failed results were removed to run again.
    #[must_use]
    pub const fn retried(&self) -> u64 {
        self.retried
    }
}

/// Where a rewritten output goes before it replaces the original: beside it.
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)
}

/// The resume key of an id printed as JSON, or of `line:N` for a line without one.
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()
}