mod capture_budget;
mod cleanup;
mod process_guard;
use crate::{
artifact::{ArtifactRef, ArtifactRole},
storage::Store,
};
pub(crate) use capture_budget::{CaptureBudget, reserve_copy};
pub(crate) use cleanup::{cleanup_completed, remove_sealed_cache};
use fs4::FileExt;
pub(crate) use process_guard::ProcessGuard;
use std::{
io::{self, Read},
path::{Path, PathBuf},
sync::{Arc, Mutex, OnceLock},
};
pub(crate) struct WorkspaceLease {
pub(crate) root: PathBuf,
_lock: std::fs::File,
}
impl WorkspaceLease {
pub(crate) fn create(root: &Path, id: &str) -> io::Result<Self> {
std::fs::create_dir_all(root)?;
let root = root.join(id);
std::fs::create_dir(&root)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700))?;
}
let lock = std::fs::OpenOptions::new()
.write(true)
.read(true)
.create_new(true)
.open(root.join("engine.lock"))?;
FileExt::try_lock(&lock)?;
Ok(Self { root, _lock: lock })
}
}
#[derive(Clone)]
pub(crate) struct TransferContext {
pub(crate) root: PathBuf,
pub(crate) store: Store,
pub(crate) references: Arc<Mutex<std::collections::BTreeMap<PathBuf, ArtifactRef>>>,
pub(crate) remote: bool,
pub(crate) max_bytes: u64,
pub(crate) assertions: Arc<Mutex<std::collections::BTreeMap<String, String>>>,
pub(crate) manifest: Arc<Mutex<crate::artifact::RunManifest>>,
pub(crate) observer: Arc<dyn TransferObserver>,
pub(crate) relocations: Arc<Mutex<Vec<(PathBuf, PathBuf)>>>,
pub(crate) external_references: Arc<Mutex<std::collections::BTreeMap<PathBuf, ArtifactRef>>>,
}
static TRANSFER: OnceLock<Mutex<Option<TransferContext>>> = OnceLock::new();
pub(crate) fn install(context: Option<TransferContext>) {
*TRANSFER.get_or_init(|| Mutex::new(None)).lock().unwrap() = context;
}
fn context() -> Option<TransferContext> {
TRANSFER
.get_or_init(|| Mutex::new(None))
.lock()
.unwrap()
.clone()
}
pub(crate) fn bytes(root: &Path) -> io::Result<u64> {
fn scan(root: &Path) -> io::Result<u64> {
let mut sum = 0u64;
for entry in std::fs::read_dir(root)? {
let result = (|| -> io::Result<u64> {
let entry = entry?;
let kind = entry.file_type()?;
if kind.is_symlink() {
return Ok(0);
}
if kind.is_dir() {
scan(&entry.path())
} else {
Ok(entry.metadata()?.len())
}
})();
match result {
Ok(size) => sum = sum.saturating_add(size),
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
}
Ok(sum)
}
scan(root)
}
pub(crate) fn check_capacity() -> io::Result<()> {
if let Some(c) = context()
&& bytes(&c.root)? > c.max_bytes
{
return Err(io::Error::other(
"workspace capacity exceeded; increase runtime.workspace.max_bytes",
));
}
Ok(())
}
pub(crate) fn commit_chunk(path: &Path) -> io::Result<()> {
let Some(c) = context().filter(|c| c.remote && path.starts_with(&c.root)) else {
return Ok(());
};
check_capacity()?;
let key = path
.strip_prefix(&c.root)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
let mut attempts = 0u64;
let mut pressured = false;
loop {
match c.store.publish(&key, path, ArtifactRole::Raw) {
Ok(reference) => {
if pressured {
c.observer.recovered();
c.observer.wait_for_resume()?;
}
c.references
.lock()
.unwrap()
.insert(path.into(), reference.clone());
crate::storage::atomic_json(
&path.with_extension("wf-object"),
&serde_json::json!({"reference":reference,"locator":crate::artifact::ArtifactLocator{storage:c.store.location.clone(),run_id:c.manifest.lock().unwrap().run_id.clone(),prefix:reference.key.clone()}}),
)?;
std::fs::remove_file(path)?;
return Ok(());
}
Err(error) => {
attempts += 1;
if c.observer.cancelled() {
return Err(error);
}
if attempts >= 3 && !pressured {
pressured = true;
c.observer.blocked(&error.to_string());
}
}
}
std::thread::sleep(std::time::Duration::from_millis((200 * attempts).min(2000)));
}
}
pub(crate) trait TransferObserver: Send + Sync {
fn blocked(&self, reason: &str);
fn recovered(&self);
fn cancelled(&self) -> bool;
fn wait_for_resume(&self) -> io::Result<()>;
}
pub(crate) fn open_file(path: &Path) -> io::Result<Box<dyn Read + Send>> {
let relocated = relocate(path);
let path = relocated.as_path();
if let Ok(file) = std::fs::File::open(path) {
return Ok(Box::new(file));
}
if let Some(c) = context()
&& let Some(reference) = c.references.lock().unwrap().get(path)
{
return c.store.read_verified(reference);
}
let pointer = path.with_extension("wf-object");
if pointer.is_file() {
let value: serde_json::Value =
serde_json::from_reader(std::fs::File::open(pointer)?).map_err(io::Error::other)?;
let locator = serde_json::from_value(value["locator"].clone()).map_err(io::Error::other)?;
let reference =
serde_json::from_value(value["reference"].clone()).map_err(io::Error::other)?;
return crate::artifact::open_reference(&locator, &reference);
}
Err(io::Error::new(
io::ErrorKind::NotFound,
"local file or verified remote chunk unavailable",
))
}
pub(crate) fn remote_references() -> Vec<(PathBuf, ArtifactRef)> {
context()
.map(|c| {
c.references
.lock()
.unwrap()
.iter()
.map(|(p, r)| (p.clone(), r.clone()))
.collect()
})
.unwrap_or_default()
}
pub(crate) fn commit_task(
directory: &Path,
processed: Option<&Path>,
roles: &crate::artifact::ArtifactDeclarations,
) -> io::Result<()> {
let Some(c) = context().filter(|c| directory.starts_with(&c.root)) else {
return Ok(());
};
for (name, relative) in &roles.shared_inputs {
let path = directory.join(relative);
let mut inventory = Vec::new();
fn content(
path: &Path,
root: &Path,
inventory: &mut Vec<(String, String)>,
) -> io::Result<()> {
if path.is_file() {
inventory.push((
path.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.into_owned(),
crate::artifact::digest_reader(std::fs::File::open(path)?)?.0,
));
} else {
for e in std::fs::read_dir(path)? {
content(&e?.path(), root, inventory)?;
}
}
Ok(())
}
content(&path, &path, &mut inventory)?;
inventory.sort();
let digest = crate::artifact::digest_bytes(
&serde_json::to_vec(&inventory).map_err(io::Error::other)?,
);
let mut assertions = c.assertions.lock().unwrap();
if let Some(expected) = assertions.get(name) {
if expected != &digest {
return Err(io::Error::other(format!(
"shared input assertion '{name}' failed: actual scientific contents differ"
)));
}
} else {
assertions.insert(name.clone(), digest);
}
}
let role_list = roles
.reproduction
.iter()
.map(|p| (p, ArtifactRole::Reproduction))
.chain(roles.raw.iter().map(|p| (p, ArtifactRole::Raw)))
.chain(roles.processed.iter().map(|p| (p, ArtifactRole::Processed)))
.collect::<Vec<_>>();
for (relative, _) in &role_list {
let path = directory.join(relative);
if !path.exists() {
return Err(io::Error::other(format!(
"declared artifact is missing: {relative}"
)));
}
}
fn walk(
c: &TransferContext,
base: &Path,
dir: &Path,
roles: &[(&String, ArtifactRole)],
default: ArtifactRole,
) -> io::Result<()> {
if !dir.exists() {
return Ok(());
}
for e in std::fs::read_dir(dir)? {
let e = e?;
let path = e.path();
if e.file_type()?.is_symlink() {
return Err(io::Error::other("task output contains symlink"));
}
if e.file_type()?.is_dir() {
walk(c, base, &path, roles, default)?;
} else {
if path.extension().is_some_and(|e| e == "wf-object") {
continue;
}
let relative = path
.strip_prefix(base)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
let role = roles
.iter()
.find(|(p, _)| relative == p.as_str() || relative.starts_with(&format!("{p}/")))
.map(|(_, r)| *r)
.unwrap_or_else(|| {
if [
"workflow-result.json",
"workflow-config.json",
"workflow-dependencies.json",
"workflow-inputs.json",
"program.json",
]
.contains(&relative.as_str())
|| (relative.ends_with("/metadata.json")
&& !relative.starts_with("artifacts/"))
{
ArtifactRole::Record
} else {
default
}
});
let key = path
.strip_prefix(&c.root)
.unwrap()
.to_string_lossy()
.replace('\\', "/");
let reference = c.store.publish(&key, &path, role)?;
c.references.lock().unwrap().insert(path, reference);
}
}
Ok(())
}
walk(&c, directory, directory, &role_list, ArtifactRole::Raw)?;
if let Some(path) = processed {
walk(&c, path, path, &[], ArtifactRole::Processed)?;
}
let refs = c
.references
.lock()
.unwrap()
.values()
.cloned()
.chain(c.external_references.lock().unwrap().values().cloned())
.collect::<Vec<_>>();
let task_id = crate::artifact::digest_bytes(
directory
.strip_prefix(&c.root)
.unwrap()
.to_string_lossy()
.as_bytes(),
);
let handle: serde_json::Value =
serde_json::from_reader(std::fs::File::open(c.root.join("handle.json"))?)
.map_err(io::Error::other)?;
let id = handle["run_id"]
.as_str()
.ok_or_else(|| io::Error::other("missing run identity"))?;
c.store.put_json(
&format!("{id}/records/task-{task_id}.json"),
&refs,
&c.root,
false,
)?;
let mut manifest = c
.manifest
.lock()
.map_err(|_| io::Error::other("manifest lock poisoned"))?;
for reference in refs {
manifest.artifacts.insert(reference.key.clone(), reference);
}
c.store
.put_json(&format!("{id}/manifest.json"), &*manifest, &c.root, false)?;
Ok(())
}
pub(crate) fn file_size(path: &Path) -> io::Result<u64> {
let relocated = relocate(path);
let path = relocated.as_path();
if let Ok(metadata) = std::fs::metadata(path) {
return Ok(metadata.len());
}
if let Some(c) = context()
&& let Some(reference) = c.references.lock().unwrap().get(path)
{
return Ok(reference.bytes);
}
let pointer: serde_json::Value =
serde_json::from_reader(std::fs::File::open(path.with_extension("wf-object"))?)
.map_err(io::Error::other)?;
pointer["reference"]["bytes"]
.as_u64()
.ok_or_else(|| io::Error::other("invalid workspace object reference"))
}
pub(crate) fn locator_for(path: &Path) -> Option<crate::artifact::ArtifactLocator> {
for root in path.ancestors() {
let handle = root.join("handle.json");
if handle.is_file() {
let value: serde_json::Value =
serde_json::from_reader(std::fs::File::open(handle).ok()?).ok()?;
return Some(crate::artifact::ArtifactLocator {
storage: serde_json::from_value(value["storage"].clone()).ok()?,
run_id: value["run_id"].as_str()?.into(),
prefix: path
.strip_prefix(root)
.ok()?
.to_string_lossy()
.replace('\\', "/"),
});
}
}
None
}
pub(crate) fn relocate(path: &Path) -> PathBuf {
if let Some(c) = context()
&& let Some((old, new)) = c
.relocations
.lock()
.unwrap()
.iter()
.filter(|(old, _)| path.starts_with(old))
.max_by_key(|(old, _)| old.components().count())
{
return new.join(path.strip_prefix(old).unwrap());
}
path.to_path_buf()
}
pub(crate) fn add_relocation(old: PathBuf, new: PathBuf) {
if let Some(c) = context() {
c.relocations.lock().unwrap().push((old, new));
}
}
pub(crate) fn add_reference(path: PathBuf, reference: ArtifactRef) {
if let Some(c) = context() {
c.external_references
.lock()
.unwrap()
.insert(path, reference);
}
}
pub(crate) fn external_references() -> Vec<(PathBuf, ArtifactRef)> {
context()
.map(|c| {
c.external_references
.lock()
.unwrap()
.iter()
.map(|(p, r)| (p.clone(), r.clone()))
.collect()
})
.unwrap_or_default()
}
pub(crate) fn capture_identity() -> Option<std::collections::BTreeMap<String, String>> {
context().map(|c| {
c.manifest
.lock()
.unwrap()
.artifacts
.iter()
.filter(|(key, _)| {
(key.starts_with("inputs/") && !key.starts_with("inputs/wf_configs/"))
|| *key == "reproduction/environment/numerical.json"
|| [
"reproduction/software/",
"reproduction/libraries/",
"reproduction/python/",
"reproduction/external-inputs/",
]
.iter()
.any(|p| key.starts_with(p))
})
.map(|(key, r)| (key.clone(), r.sha256.clone()))
.collect()
})
}
pub(crate) fn host_id() -> String {
let mut identity = std::fs::read("/etc/machine-id")
.unwrap_or_else(|_| std::env::var("HOSTNAME").unwrap_or_default().into_bytes());
identity.extend_from_slice(
std::fs::read_link("/proc/self/ns/pid")
.unwrap_or_default()
.as_os_str()
.as_encoded_bytes(),
);
crate::artifact::digest_bytes(&identity)
}