use std::{
io::{self, Write},
path::Path,
time::Duration,
};
use rho_protocol::SessionEvent;
use serde::Serialize;
const SCHEMA_VERSION: u8 = 2;
pub(crate) fn parse_duration(value: &str) -> Result<Duration, String> {
humantime::parse_duration(value).map_err(|error| format!("invalid duration '{value}': {error}"))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum TerminalReason {
Completed,
MaxSteps,
Timeout,
Interrupted,
Cancelled,
Detached,
Authentication,
ProviderError,
ToolHostError,
ConfigurationError,
OutputError,
OtherError,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub(crate) struct RunEnd {
pub(crate) reason: TerminalReason,
pub(crate) exit_code: u8,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) message: Option<String>,
}
impl RunEnd {
pub(crate) fn completed() -> Self {
Self {
reason: TerminalReason::Completed,
exit_code: 0,
message: None,
}
}
}
#[derive(Serialize)]
struct Line<'a> {
schema_version: u8,
seq: u64,
#[serde(flatten)]
record: Record<'a>,
}
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum Record<'a> {
RunStarted {
session: &'a str,
workspace: &'a Path,
},
Event { event: &'a SessionEvent },
RunEnded(&'a RunEnd),
}
pub(crate) struct JsonlStream<W = io::Stdout> {
out: W,
seq: u64,
failure: Option<String>,
}
impl JsonlStream {
pub(crate) fn stdout() -> Self {
Self::new(io::stdout())
}
}
impl<W: Write> JsonlStream<W> {
pub(crate) fn new(out: W) -> Self {
Self {
out,
seq: 0,
failure: None,
}
}
pub(crate) fn run_started(&mut self, session: &str, workspace: &Path) {
self.write(Record::RunStarted { session, workspace });
}
pub(crate) fn event(&mut self, event: &SessionEvent) {
self.write(Record::Event { event });
}
pub(crate) fn end(&mut self, end: &RunEnd) {
self.write(Record::RunEnded(end));
}
pub(crate) fn failure(&self) -> Option<&str> {
self.failure.as_deref()
}
fn write(&mut self, record: Record<'_>) {
if self.failure.is_some() {
return;
}
self.seq += 1;
let line = Line {
schema_version: SCHEMA_VERSION,
seq: self.seq,
record,
};
let written = serde_json::to_writer(&mut self.out, &line)
.map_err(io::Error::other)
.and_then(|()| self.out.write_all(b"\n"))
.and_then(|()| self.out.flush());
if let Err(error) = written {
self.failure = Some(format!("could not write JSONL output: {error}"));
}
}
}
#[cfg(test)]
#[path = "automation_protocol_tests.rs"]
mod tests;