scientific-workflow 0.18.1

Configuration-driven scientific tasks, typed state, and durable recordings
Documentation
use std::{
    fs::{File, OpenOptions},
    io::{self, BufWriter, Write},
    path::Path,
};
pub(crate) fn run_id() -> String {
    let n = time::OffsetDateTime::now_utc();
    format!(
        "{:04}{:02}{:02}T{:02}{:02}{:02}.{:09}Z",
        n.year(),
        u8::from(n.month()),
        n.day(),
        n.hour(),
        n.minute(),
        n.second(),
        n.nanosecond()
    )
}
pub(crate) fn utc_now() -> String {
    time::OffsetDateTime::now_utc()
        .format(&time::format_description::well_known::Rfc3339)
        .expect("current UTC is representable")
}
pub(crate) fn atomic_json(path: &Path, value: &impl serde::Serialize) -> io::Result<()> {
    let parent = path
        .parent()
        .ok_or_else(|| io::Error::other("missing parent"))?;
    std::fs::create_dir_all(parent)?;
    let temp = parent.join(format!(".tmp-{}-{}", std::process::id(), run_id()));
    let f = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&temp)?;
    let result = (|| {
        let mut buffered = BufWriter::with_capacity(64 * 1024, &f);
        serde_json::to_writer_pretty(&mut buffered, value).map_err(io::Error::other)?;
        buffered.write_all(b"\n")?;
        buffered.flush()?;
        drop(buffered);
        f.sync_all()?;
        drop(f);
        std::fs::rename(&temp, path)?;
        File::open(parent)?.sync_all()
    })();
    if result.is_err() {
        let _ = std::fs::remove_file(temp);
    }
    result
}

/// A resumable upload only rewinds within its most recently buffered chunk.
/// This keeps a remote input stream seekable for retry without a full local copy.
pub(super) struct WindowReader {
    input: Box<dyn std::io::Read + Send>,
    window: Vec<u8>,
    capacity: usize,
    start: u64,
    position: u64,
    end: u64,
}
impl WindowReader {
    pub(super) fn new(input: Box<dyn std::io::Read + Send>, capacity: usize) -> Self {
        Self {
            input,
            window: Vec::with_capacity(capacity),
            capacity,
            start: 0,
            position: 0,
            end: 0,
        }
    }
}
impl std::io::Read for WindowReader {
    fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
        if output.is_empty() {
            return Ok(0);
        }
        if self.position < self.end {
            let offset = (self.position - self.start) as usize;
            let n = output.len().min(self.window.len() - offset);
            output[..n].copy_from_slice(&self.window[offset..offset + n]);
            self.position += n as u64;
            return Ok(n);
        }
        let limit = output.len().min(self.capacity);
        let n = self.input.read(&mut output[..limit])?;
        if self.window.len() + n > self.capacity {
            let discard = self.window.len() + n - self.capacity;
            self.window.drain(..discard);
            self.start += discard as u64;
        }
        self.window.extend_from_slice(&output[..n]);
        self.position += n as u64;
        self.end += n as u64;
        Ok(n)
    }
}
impl std::io::Seek for WindowReader {
    fn seek(&mut self, position: std::io::SeekFrom) -> io::Result<u64> {
        let position = match position {
            std::io::SeekFrom::Start(p) => p,
            std::io::SeekFrom::Current(delta) => self
                .position
                .checked_add_signed(delta)
                .ok_or_else(|| io::Error::other("upload seek overflow"))?,
            std::io::SeekFrom::End(_) => {
                return Err(io::Error::other(
                    "stream has no arbitrary end-relative seek",
                ));
            }
        };
        if !(self.start..=self.end).contains(&position) {
            return Err(io::Error::other(
                "server requested an upload offset outside the retained retry window",
            ));
        }
        self.position = position;
        Ok(position)
    }
}