use std::path::Path;
use shep_core::protocol::{BusEvent, ProcessInfo};
use crate::bus::Bus;
use crate::supervisor::SupervisorHandle;
const SHEP_VOICE: &str = "[shep]";
pub(crate) async fn narrate(events: &Bus, info: &ProcessInfo, message: &str) {
let line = format!("{SHEP_VOICE} {message}");
if let Some(path) = &info.err_file {
let mut written = String::with_capacity(line.len() + 32);
shep_core::logstamp::stamp_into(&mut written);
written.push_str(&line);
written.push('\n');
if let Ok(mut file) = crate::tokio_runner::open_append(Path::new(path)).await {
use tokio::io::AsyncWriteExt as _;
let _record = crate::tokio_runner::record_lock(Path::new(path))
.lock_owned()
.await;
let written = async {
file.write_all(written.as_bytes()).await?;
file.flush().await
}
.await;
if let Err(error) = written {
tracing::warn!(
dog = %info.name,
%error,
"shep's own narration did not reach this dog's log"
);
}
}
}
events.publish_log(BusEvent::LogErr { id: info.id, line });
}
pub(crate) fn narrate_by_name(
supervisor: &SupervisorHandle,
events: &Bus,
name: &str,
message: String,
) {
let supervisor = supervisor.clone();
let events = events.clone();
let name = name.to_string();
tokio::spawn(async move {
let Ok(infos) = supervisor.list_checked().await else {
return;
};
if let Some(info) = infos
.iter()
.find(|info| info.name == name && info.dog.is_some())
{
narrate(&events, info, &message).await;
}
});
}
pub(super) fn exit_words(info: &ProcessInfo) -> String {
match info.last_exit {
Some(exit) => match (exit.code, exit.signal) {
(Some(code), _) => format!("this dog's process exited with code {code}"),
(None, Some(signal)) => {
format!("this dog's process was killed by signal {signal}")
}
(None, None) => {
"this dog's process stopped, and the OS reported neither an exit code nor a signal"
.to_string()
}
},
None => "this dog's process stopped, and this shepherd has no record of how".to_string(),
}
}
#[cfg(test)]
mod tests {
use core::time::Duration;
use super::*;
use crate::fake::ProcScript;
use super::super::test_support::start_test_dog;
#[tokio::test]
async fn shep_s_own_account_of_a_dog_reaches_that_dog_s_log() {
let h = crate::testing::harness(vec![ProcScript::never_exits()]);
start_test_dog(&h.ctx, "log-rotate").await;
let info = h
.ctx
.supervisor
.list()
.await
.into_iter()
.find(|info| info.name == "log-rotate")
.expect("the dog fixture must be listed");
let err_log = info
.err_file
.clone()
.expect("a dog's log paths are resolved");
let (out_tx, mut following) = tokio::sync::mpsc::channel(16);
let forwarder = crate::bus::spawn_forwarder(
&h.ctx.events,
crate::bus::TopicFilter::new(&["log.*".to_string()]).unwrap(),
out_tx,
);
narrate(&h.ctx.events, &info, "shep did a thing worth saying").await;
let written = std::fs::read_to_string(&err_log).expect("the narration must reach the log");
let line = written
.strip_suffix('\n')
.expect("one whole line, newline included");
assert!(
line.ends_with("[shep] shep did a thing worth saying"),
"the line must be marked as shep's voice, not the dog's: {line:?}"
);
let (stamp, rest) = line.split_at(shep_core::logstamp::LOG_STAMP_BYTES);
assert_eq!(
rest, "[shep] shep did a thing worth saying",
"the stamp is the same fixed-width prefix every other line carries: {line:?}"
);
chrono::DateTime::parse_from_rfc3339(stamp.trim_end())
.unwrap_or_else(|err| panic!("{stamp:?} must parse as RFC 3339: {err}"));
let frame = tokio::time::timeout(Duration::from_secs(5), following.recv())
.await
.expect("a follower must be told inside the budget")
.expect("the forwarder must deliver rather than end");
match shep_core::protocol::decode_frame::<BusEvent>(&frame).unwrap() {
BusEvent::LogErr { id, line } => {
assert_eq!(id, info.id, "the line belongs to the dog it is about");
assert_eq!(
line, "[shep] shep did a thing worth saying",
"a follower sees the marker and not the file's stamp"
);
}
other => panic!("narration must reach a follower as a log line, got {other:?}"),
}
forwarder.abort();
}
}