mod progress;
mod state;
#[cfg(test)]
mod tests;
use crate::protocol::{Event, Outcome, Status, VERSION};
use crate::{
runtime::{PresentationFailure, RunControl, RuntimeEvent, RuntimeObserver},
storage::{Store, atomic_json, utc_now},
};
use serde_json::{Value, json};
use std::{
io::{self},
path::{Path, PathBuf},
sync::{Arc, Condvar, Mutex},
time::Instant,
};
#[derive(Clone)]
pub(crate) struct EngineJournal(pub(crate) Arc<Inner>);
pub(crate) struct Inner {
pub(crate) state: Mutex<Status>,
pub(crate) wake: Condvar,
pub(crate) control: RunControl,
root: PathBuf,
store: Store,
start: Instant,
active_start: Instant,
remote: Mutex<u64>,
writer: Mutex<()>,
pending: Mutex<progress::Pending>,
pub(crate) committed: std::sync::atomic::AtomicU64,
}
impl EngineJournal {
pub(crate) fn new(id: &str, root: &Path, store: Store) -> io::Result<Self> {
std::fs::create_dir_all(root.join("records"))?;
let control = RunControl::default();
let status = Status {
version: VERSION,
run_id: id.into(),
sequence: 0,
updated_at: utc_now(),
pid: std::process::id(),
outcome: Outcome::Starting,
pause_reason: None,
control: "running".into(),
study: None,
tasks: Default::default(),
allocations: json!({}),
message: None,
wall_ms: 0,
active_ms: 0,
};
let active_start = control.now();
let this = Self(Arc::new(Inner {
state: Mutex::new(status),
wake: Condvar::new(),
control,
root: root.into(),
store,
start: Instant::now(),
active_start,
remote: Mutex::new(0),
writer: Mutex::new(()),
pending: Mutex::new(progress::Pending::default()),
committed: std::sync::atomic::AtomicU64::new(0),
}));
this.record("engine_started", json!({"pid":std::process::id()}))?;
let weak = Arc::downgrade(&this.0);
std::thread::Builder::new()
.name("workflow-journal".into())
.spawn(move || {
loop {
std::thread::sleep(progress::INTERVAL);
let Some(inner) = weak.upgrade() else { break };
let journal = Self(inner);
match journal.record_local(None) {
Ok(sequence) => {
journal.0.control.storage_pressure("journal_local", true);
if journal
.0
.committed
.load(std::sync::atomic::Ordering::Acquire)
< sequence
{
let _ = journal.flush_remote(sequence);
}
}
Err(_) => journal.0.control.storage_pressure("journal_local", false),
}
}
})?;
Ok(this)
}
pub(crate) fn snapshot(&self) -> Status {
let mut status = self.0.state.lock().unwrap().clone();
if status.outcome.terminal()
&& self.0.committed.load(std::sync::atomic::Ordering::Acquire) < status.sequence
{
status.outcome = Outcome::Running;
status.message = Some("committing final durable records".into());
}
status.control = self.0.control.status().into();
status.pause_reason = if self.0.control.storage_paused() {
Some("storage_pressure".into())
} else if self.0.control.disk_paused() {
Some("disk_pressure".into())
} else if self.0.control.paused() {
Some("manual".into())
} else {
None
};
status
}
pub(crate) fn record(&self, kind: &str, data: Value) -> io::Result<()> {
if progress::coalescible(kind) {
self.0
.pending
.lock()
.map_err(|_| io::Error::other("progress lock poisoned"))?
.insert(kind, data);
return Ok(());
}
let sequence = self.record_local(Some((kind, data)))?;
self.flush_remote(sequence)
}
pub(crate) fn record_control(&self, kind: &str, data: Value) -> io::Result<()> {
self.record_local(Some((kind, data)))?;
Ok(())
}
fn record_local(&self, event: Option<(&str, Value)>) -> io::Result<u64> {
let _writer = self
.0
.writer
.lock()
.map_err(|_| io::Error::other("writer lock poisoned"))?;
let pending = self
.0
.pending
.lock()
.map_err(|_| io::Error::other("progress lock poisoned"))?
.take();
let mut status = self
.0
.state
.lock()
.map_err(|_| io::Error::other("journal lock poisoned"))?
.clone();
if status.outcome.terminal() || (pending.is_empty() && event.is_none()) {
return Ok(status.sequence);
}
let result = (|| {
let mut events = Vec::with_capacity(pending.len() + usize::from(event.is_some()));
for (kind, data) in pending
.iter()
.map(|p| (p.kind.as_str(), &p.data))
.chain(event.as_ref().map(|(kind, data)| (*kind, data)))
{
state::apply(
&mut status,
kind,
data,
&self.0.control,
self.0.start,
self.0.active_start,
);
events.push(Event {
sequence: status.sequence,
at: status.updated_at.clone(),
kind: kind.into(),
data: data.clone(),
});
}
while !status.tasks.is_empty()
&& (status.tasks.len() > 512
|| serde_json::to_vec(&status).map_err(io::Error::other)?.len()
> 2 * 1024 * 1024)
{
let key = status
.tasks
.iter()
.find(|(_, v)| {
matches!(
v["event"].as_str(),
Some("task_completed" | "task_failed" | "task_reused")
)
})
.or_else(|| status.tasks.iter().next())
.unwrap()
.0
.clone();
status.tasks.remove(&key);
}
let records = self.0.root.join("records");
for event in &events {
atomic_json(
&records.join(format!("event-{:012}.json", event.sequence)),
event,
)?;
}
atomic_json(&records.join("status.json"), &status)?;
let sequence = status.sequence;
*self
.0
.state
.lock()
.map_err(|_| io::Error::other("journal lock poisoned"))? = status;
self.0.wake.notify_all();
Ok(sequence)
})();
if result.is_err() {
let mut queue = self
.0
.pending
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for entry in pending {
queue.restore(entry);
}
}
result
}
fn flush_remote(&self, required: u64) -> io::Result<()> {
let mut acknowledged = self
.0
.remote
.lock()
.map_err(|_| io::Error::other("remote journal lock poisoned"))?;
let mut failures = 0;
loop {
let snapshot = self.0.state.lock().unwrap().clone();
let operation = (|| -> io::Result<()> {
while *acknowledged < snapshot.sequence {
let sequence = *acknowledged + 1;
let segment = self
.0
.root
.join(format!("records/event-{sequence:012}.json"));
match self.0.store.backend.write(
&format!("{}/records/event-{sequence:012}.json", snapshot.run_id),
&segment,
true,
) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
let stored: Event = self.0.store.json(&format!(
"{}/records/event-{sequence:012}.json",
snapshot.run_id
))?;
let local: Event =
serde_json::from_reader(std::fs::File::open(&segment)?)
.map_err(io::Error::other)?;
if serde_json::to_value(stored).map_err(io::Error::other)?
!= serde_json::to_value(local).map_err(io::Error::other)?
{
return Err(io::Error::other(
"committed event conflicts with local journal",
));
}
}
Err(error) => return Err(error),
}
*acknowledged = sequence;
if sequence > 256 {
let _ = std::fs::remove_file(
self.0
.root
.join(format!("records/event-{:012}.json", sequence - 256)),
);
}
}
self.0.store.put_json(
&format!("{}/records/status.json", snapshot.run_id),
&snapshot,
&self.0.root,
false,
)?;
Ok(())
})();
match operation {
Ok(()) => {
self.0.control.storage_pressure("journal", true);
self.acknowledge(snapshot.sequence)?;
if snapshot.sequence >= required {
return Ok(());
}
}
Err(error) => {
failures += 1;
if self.0.control.cancelled() {
return Err(error);
}
if failures >= 3 {
self.0.control.storage_pressure("journal", false);
}
std::thread::sleep(std::time::Duration::from_millis(
(failures * 200).min(2000),
));
}
}
}
}
fn acknowledge(&self, sequence: u64) -> io::Result<()> {
let _state = self
.0
.state
.lock()
.map_err(|_| io::Error::other("journal lock poisoned"))?;
self.0
.committed
.store(sequence, std::sync::atomic::Ordering::Release);
self.0.wake.notify_all();
Ok(())
}
pub(crate) fn events(&self, after: u64) -> io::Result<Vec<Event>> {
let last = self.snapshot().sequence;
let mut events = Vec::new();
let mut size = 0;
for sequence in (after.saturating_add(1))..=last {
let segment = self
.0
.root
.join(format!("records/event-{sequence:012}.json"));
let bytes = match std::fs::read(&segment) {
Ok(bytes) => bytes,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
use std::io::Read;
let mut bytes = Vec::new();
self.0
.store
.backend
.read(&format!(
"{}/records/event-{sequence:012}.json",
self.snapshot().run_id
))?
.take(2 * 1024 * 1024)
.read_to_end(&mut bytes)?;
bytes
}
Err(error) => return Err(error),
};
size += bytes.len();
if size > 2 * 1024 * 1024 && !events.is_empty() {
break;
}
events.push(serde_json::from_slice(&bytes).map_err(io::Error::other)?);
if events.len() >= 256 {
break;
}
}
Ok(events)
}
}
impl RuntimeObserver for EngineJournal {
fn publish(&self, event: RuntimeEvent<'_>) -> Result<(), PresentationFailure> {
let value = serde_json::to_value(event)?;
let kind = value["type"].as_str().unwrap_or("runtime").to_owned();
self.record(&kind, value)?;
Ok(())
}
fn cancellation_requested(&self) -> Result<bool, PresentationFailure> {
Ok(self.0.control.cancelled())
}
fn control(&self) -> RunControl {
self.0.control.clone()
}
fn finish(&self) -> Result<(), PresentationFailure> {
self.flush_remote(self.record_local(None)?)?;
Ok(())
}
}
impl crate::workspace::TransferObserver for EngineJournal {
fn blocked(&self, reason: &str) {
self.0.control.storage_pressure("objects", false);
let _ = self.record_control("storage_blocked", json!({"reason":reason}));
}
fn recovered(&self) {
self.0.control.storage_pressure("objects", true);
let _ = self.record_control("storage_ready", json!({"requires_explicit_resume":true}));
}
fn cancelled(&self) -> bool {
self.0.control.cancelled()
}
fn wait_for_resume(&self) -> io::Result<()> {
let cancel = std::sync::atomic::AtomicBool::new(false);
self.0.control.checkpoint(&cancel);
if self.0.control.cancelled() {
Err(io::Error::new(
io::ErrorKind::Interrupted,
"upload cancelled while waiting for explicit resume",
))
} else {
Ok(())
}
}
}