use super::EngineJournal;
use scientific_workflow_protocol::{Command, Request, Response, VERSION, read_frame, write_frame};
use std::{
io,
os::unix::{
fs::PermissionsExt,
net::{UnixListener, UnixStream},
},
path::Path,
thread,
};
pub(super) fn start(socket: &Path, journal: EngineJournal) -> io::Result<thread::JoinHandle<()>> {
let listener = UnixListener::bind(socket)?;
std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o600))?;
Ok(thread::spawn(move || {
for connection in listener.incoming() {
match connection {
Ok(stream) => {
let journal = journal.clone();
thread::spawn(move || {
let _ = serve(stream, journal);
});
}
Err(_) => break,
}
}
}))
}
fn serve(mut stream: UnixStream, journal: EngineJournal) -> io::Result<()> {
stream.set_read_timeout(Some(std::time::Duration::from_secs(10)))?;
stream.set_write_timeout(Some(std::time::Duration::from_secs(10)))?;
let request: Request = read_frame(&mut stream)?;
let mut error = None;
let mut message = None;
let mut events = Vec::new();
if request.version != VERSION {
error = Some("unsupported_version".into());
message = Some(format!("requires protocol {VERSION}"));
} else if request.id.is_empty() || request.id.len() > 128 {
error = Some("invalid_request_id".into());
} else {
match request.command {
Command::Hello | Command::Status => {}
Command::Events { after } => events = journal.events(after)?,
Command::Wait => {
let mut status = journal.0.state.lock().unwrap();
while !status.outcome.terminal()
|| journal
.0
.committed
.load(std::sync::atomic::Ordering::Acquire)
< status.sequence
{
status = journal.0.wake.wait(status).unwrap();
}
}
command => {
if journal.snapshot().outcome.terminal() {
error = Some("run_finished".into());
} else {
match command {
Command::Pause => journal.0.control.pause(true),
Command::Cancel => journal.0.control.cancel(),
Command::Resume => {
if !journal.0.control.resume() {
error = Some("safety_gate_closed".into());
}
}
_ => unreachable!(),
}
if error.is_none() {
journal.record_control(
"control_acknowledged",
serde_json::json!({"id":request.id,"command":command}),
)?;
}
}
}
}
}
write_frame(
&mut stream,
&Response {
version: VERSION,
id: request.id,
error,
message,
status: journal.snapshot(),
events,
},
)
}