use super::RuntimeError;
use std::{
fs,
path::{Path, PathBuf},
};
#[cfg(test)]
pub(crate) fn create_execution(root: &Path) -> Result<PathBuf, RuntimeError> {
let now = time::OffsetDateTime::now_utc();
let stamp = format!(
"{:04}{:02}{:02}T{:02}{:02}{:02}.{:09}Z",
now.year(),
u8::from(now.month()),
now.day(),
now.hour(),
now.minute(),
now.second(),
now.nanosecond()
);
create_execution_at(root, &stamp)
}
#[cfg(test)]
fn create_execution_at(root: &Path, stamp: &str) -> Result<PathBuf, RuntimeError> {
fs::create_dir_all(root).map_err(|source| RuntimeError::OutputScope {
path: root.to_path_buf(),
source,
})?;
for sequence in 0..1024 {
let suffix = if sequence == 0 {
String::new()
} else {
format!("-{sequence:04}")
};
let directory = root.join(format!("{stamp}{suffix}"));
match fs::create_dir(&directory) {
Ok(()) => return Ok(directory),
Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(source) => {
return Err(RuntimeError::OutputScope {
path: directory,
source,
});
}
}
}
Err(RuntimeError::OutputScope {
path: root.to_path_buf(),
source: std::io::Error::new(
std::io::ErrorKind::AlreadyExists,
"could not allocate a unique execution directory",
),
})
}
pub(crate) fn create_replicate(root: &Path, index: u64) -> Result<PathBuf, RuntimeError> {
let directory = root.join(format!("replicate-{index:06}"));
fs::create_dir(&directory).map_err(|source| RuntimeError::OutputScope {
path: directory.clone(),
source,
})?;
Ok(directory)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utc_namespace_collisions_preserve_the_original() {
let root =
std::env::temp_dir().join(format!("workflow-namespace-{}", crate::storage::run_id()));
let first = create_execution_at(&root, "20261128T174205.123456789Z").unwrap();
fs::write(first.join("keep"), b"original").unwrap();
let second = create_execution_at(&root, "20261128T174205.123456789Z").unwrap();
assert_ne!(first, second);
assert_eq!(
second.file_name().unwrap(),
"20261128T174205.123456789Z-0001"
);
assert_eq!(fs::read(first.join("keep")).unwrap(), b"original");
fs::remove_dir_all(root).unwrap();
}
}