1 //! A recorded job for one bundle.2 //!3 //! The specification's golden is a request and the output that a binding owed4 //! it. This module reads that shape, starts one binary on a private filesystem5 //! socket, sends the request, and compares the events that the binary wrote.6 //! It is deliberately small: a golden compares only the fields that its7 //! `compare` list names.8 9 use std::fmt;10 use std::fs;11 use std::io;12 use std::os::fd::AsFd;13 use std::os::unix::fs::DirBuilderExt;14 use std::os::unix::net::UnixListener;15 use std::path::{Path, PathBuf};16 use std::process::{Child, Command, Stdio};17 use std::sync::atomic::{AtomicU64, Ordering};18 use std::thread;19 use std::time::{Duration, Instant};20 21 use inf3r_json::Value as JsonValue;22 use inf3r_proto::Value;23 use inf3r_proto::body::{self, Dependency, Done, Grant, Open, Outcome, PartKind};24 use inf3r_proto::client::{Item, Peer};25 use inf3r_proto::mirror;26 27 /// The pause between two polls of a child that has not connected.28 const POLL: Duration = Duration::from_millis(5);29 30 /// The default time that one golden may take.31 const DEFAULT_WAIT: Duration = Duration::from_secs(60);32 33 /// One recorded input part.34 #[derive(Clone, PartialEq, Eq, Debug)]35 pub struct GoldenPart {36 /// The part kind, in the spelling of the capability pages.37 pub kind: PartKind,38 /// The MIME type.39 pub mime: String,40 /// The role, when the capability defines one.41 pub role: Option<String>,42 /// The text bytes. A binary part is not in a bundle golden.43 pub text: Vec<u8>,44 }45 46 /// One recorded event.47 #[derive(Clone, PartialEq, Eq, Debug)]48 pub struct GoldenEvent {49 /// The channel.50 pub channel: String,51 /// The UTF-8 data, when the event carries text.52 pub text: Option<String>,53 /// The raw data, for an event that is not text.54 pub data: Vec<u8>,55 }56 57 /// What a golden expects.58 #[derive(Clone, PartialEq, Eq, Debug)]59 pub struct GoldenExpect {60 /// The events, in order.61 pub events: Vec<GoldenEvent>,62 /// The terminal outcome.63 pub outcome: Outcome,64 }65 66 /// One golden file.67 #[derive(Clone, PartialEq, Debug)]68 pub struct Golden {69 /// The human name of the case.70 pub name: String,71 /// The capability that the request names.72 pub capability: String,73 /// The input parts.74 pub parts: Vec<GoldenPart>,75 /// The capability parameters.76 pub params: Value,77 /// The expected events.78 pub expect: GoldenExpect,79 /// The fields that a comparison reads.80 pub compare: Vec<String>,81 }82 83 impl Golden {84 /// Reads one golden file.85 pub fn read(path: impl AsRef<Path>) -> Result<Golden, GoldenError> {86 let text =87 fs::read_to_string(path.as_ref()).map_err(|why| GoldenError::Io(why.to_string()))?;88 Golden::parse(&text)89 }90 91 /// Reads one golden document.92 pub fn parse(text: &str) -> Result<Golden, GoldenError> {93 let root = inf3r_json::parse(text).map_err(GoldenError::Json)?;94 let name = string(&root, "name")?;95 let protocol = root96 .get("protocol")97 .and_then(JsonValue::as_i64)98 .unwrap_or(1);99 if protocol != 1 {100 return Err(GoldenError::Shape(format!("protocol {protocol} is not 1")));101 }102 let request = root103 .get("request")104 .ok_or_else(|| GoldenError::Shape("request is missing".into()))?;105 let capability = string(request, "capability")?;106 let parts = request107 .get("input")108 .and_then(JsonValue::as_array)109 .ok_or_else(|| GoldenError::Shape("request.input is missing".into()))?110 .iter()111 .map(parse_part)112 .collect::<Result<Vec<_>, _>>()?;113 let params = request114 .get("params")115 .and_then(mirror::from_json)116 .unwrap_or_else(|| Value::Map(Vec::new()));117 let expect = parse_expect(118 root.get("expect")119 .ok_or_else(|| GoldenError::Shape("expect is missing".into()))?,120 )?;121 let compare = root122 .get("compare")123 .and_then(JsonValue::as_array)124 .map(|items| {125 items126 .iter()127 .filter_map(JsonValue::as_str)128 .map(str::to_string)129 .collect()130 })131 .unwrap_or_else(|| vec!["channel".into(), "text".into()]);132 Ok(Golden {133 name,134 capability,135 parts,136 params,137 expect,138 compare,139 })140 }141 142 /// Runs the golden against one binary. A weights file is granted through a143 /// descriptor, exactly as the core would grant it.144 pub fn run(145 &self,146 program: impl AsRef<Path>,147 weights: Option<&Path>,148 ) -> Result<Run, GoldenError> {149 self.run_with(program, weights, DEFAULT_WAIT)150 }151 152 /// Runs the golden with an explicit whole deadline.153 pub fn run_with(154 &self,155 program: impl AsRef<Path>,156 weights: Option<&Path>,157 wait: Duration,158 ) -> Result<Run, GoldenError> {159 let deadline = Instant::now() + wait;160 let (peer, mut child, _socket_dir) = start(program.as_ref(), deadline)?;161 let catalogue = peer162 .catalogue()163 .ok_or_else(|| GoldenError::Run("the server sent no catalogue".into()))?;164 let model = catalogue165 .models166 .iter()167 .find(|model| model.capabilities.contains_key(&self.capability))168 .ok_or_else(|| {169 GoldenError::Run(format!(170 "the catalogue does not declare {}",171 self.capability172 ))173 })?;174 load(&peer, weights, deadline)?;175 let parts = self176 .parts177 .iter()178 .map(|part| body::Part {179 kind: part.kind,180 mime: part.mime.clone(),181 role: part.role.clone(),182 len: part.text.len() as u64,183 hold: body::Hold::Inline(part.text.clone()),184 })185 .collect();186 let open = Open {187 request_id: format!("golden-{}", self.name),188 model: model.serve.clone(),189 capability: self.capability.clone(),190 credit: 1 << 20,191 budget_ms: u32::try_from(wait.as_millis()).unwrap_or(u32::MAX),192 parts,193 params: self.params.clone(),194 };195 let mut job = peer196 .open(open, &[])197 .map_err(|why| GoldenError::Run(why.to_string()))?;198 let mut events = Vec::new();199 let done = loop {200 match job201 .next_deadline(deadline)202 .map_err(|why| GoldenError::Run(why.to_string()))?203 {204 None => return Err(GoldenError::Run("the stream closed".into())),205 Some(Item::Accepted(_)) => {}206 Some(Item::Event { ch, data, .. }) => events.push(Observed {207 channel: ch,208 text: std::str::from_utf8(&data).ok().map(str::to_string),209 data,210 }),211 Some(Item::Reject(refusal)) => {212 return Err(GoldenError::Run(format!("refused: {refusal:?}")));213 }214 Some(Item::Done(done, _)) => break done,215 }216 };217 drop(job);218 let _ = peer.close();219 kill(&mut child);220 Ok(Run { events, done })221 }222 }223 224 /// The event shape that a comparison sees.225 #[derive(Clone, PartialEq, Eq, Debug)]226 pub struct Observed {227 /// The channel.228 pub channel: String,229 /// The UTF-8 data, when it is text.230 pub text: Option<String>,231 /// The raw data.232 pub data: Vec<u8>,233 }234 235 /// The result of one golden run.236 #[derive(Clone, PartialEq, Debug)]237 pub struct Run {238 /// The events, in order.239 pub events: Vec<Observed>,240 /// The terminal frame.241 pub done: Done,242 }243 244 impl Run {245 /// Compares this run with a golden's expectation. The first difference is246 /// named by index.247 pub fn check(&self, golden: &Golden) -> Result<(), GoldenError> {248 if self.done.outcome != golden.expect.outcome {249 return Err(GoldenError::Run(format!(250 "the outcome is {:?}, not {:?}",251 self.done.outcome, golden.expect.outcome252 )));253 }254 if self.events.len() != golden.expect.events.len() {255 return Err(GoldenError::Run(format!(256 "{} events, expected {}",257 self.events.len(),258 golden.expect.events.len()259 )));260 }261 for (index, (actual, expected)) in self.events.iter().zip(&golden.expect.events).enumerate()262 {263 for field in &golden.compare {264 match field.as_str() {265 "channel" if actual.channel != expected.channel => {266 return Err(GoldenError::Run(format!(267 "event {index}: channel {:?}, expected {:?}",268 actual.channel, expected.channel269 )));270 }271 "text" if actual.text != expected.text => {272 return Err(GoldenError::Run(format!(273 "event {index}: text {:?}, expected {:?}",274 actual.text, expected.text275 )));276 }277 "data" if actual.data != expected.data => {278 return Err(GoldenError::Run(format!("event {index}: data differs")));279 }280 _ => {}281 }282 }283 }284 Ok(())285 }286 }287 288 /// Why a golden did not run or match.289 #[derive(Clone, PartialEq, Debug)]290 pub enum GoldenError {291 /// A file could not be read.292 Io(String),293 /// The document is not JSON.294 Json(inf3r_json::JsonError),295 /// A field is missing or has the wrong shape.296 Shape(String),297 /// The binary did not connect, did not answer, or differed.298 Run(String),299 }300 301 impl fmt::Display for GoldenError {302 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {303 match self {304 GoldenError::Io(why) => write!(f, "{why}"),305 GoldenError::Json(why) => write!(f, "json: {why}"),306 GoldenError::Shape(why) => write!(f, "shape: {why}"),307 GoldenError::Run(why) => write!(f, "run: {why}"),308 }309 }310 }311 312 impl std::error::Error for GoldenError {}313 impl From<io::Error> for GoldenError {314 fn from(why: io::Error) -> GoldenError {315 GoldenError::Io(why.to_string())316 }317 }318 319 fn string(root: &JsonValue, key: &str) -> Result<String, GoldenError> {320 root.get(key)321 .and_then(JsonValue::as_str)322 .map(str::to_string)323 .ok_or_else(|| GoldenError::Shape(format!("{key} is missing")))324 }325 326 fn parse_part(part: &JsonValue) -> Result<GoldenPart, GoldenError> {327 let kind = match part328 .get("kind")329 .and_then(JsonValue::as_str)330 .ok_or_else(|| GoldenError::Shape("a part has no kind".into()))?331 {332 "text" => PartKind::Text,333 "json" => PartKind::Json,334 "audio" => PartKind::Audio,335 "image" => PartKind::Image,336 other => return Err(GoldenError::Shape(format!("unknown part kind {other}"))),337 };338 let text = part339 .get("text")340 .and_then(JsonValue::as_str)341 .ok_or_else(|| GoldenError::Shape("a part has no text".into()))?342 .as_bytes()343 .to_vec();344 let mime = part345 .get("mime")346 .and_then(JsonValue::as_str)347 .map(str::to_string)348 .unwrap_or_else(|| match kind {349 PartKind::Text => "text/plain; charset=utf-8".into(),350 PartKind::Json => "application/json".into(),351 PartKind::Audio => "audio/pcm; enc=s16le; rate=24000; channels=1".into(),352 PartKind::Image => "image/png".into(),353 _ => "application/octet-stream".into(),354 });355 Ok(GoldenPart {356 kind,357 mime,358 role: part359 .get("role")360 .and_then(JsonValue::as_str)361 .map(str::to_string),362 text,363 })364 }365 366 fn parse_expect(expect: &JsonValue) -> Result<GoldenExpect, GoldenError> {367 let events = expect368 .get("events")369 .and_then(JsonValue::as_array)370 .ok_or_else(|| GoldenError::Shape("expect.events is missing".into()))?371 .iter()372 .map(|event| {373 let channel = string(event, "channel")?;374 let text = event375 .get("text")376 .and_then(JsonValue::as_str)377 .map(str::to_string);378 Ok(GoldenEvent {379 channel,380 text,381 data: Vec::new(),382 })383 })384 .collect::<Result<Vec<_>, GoldenError>>()?;385 let outcome = match expect386 .get("done")387 .and_then(|done| done.get("outcome"))388 .and_then(JsonValue::as_str)389 .ok_or_else(|| GoldenError::Shape("expect.done.outcome is missing".into()))?390 {391 "completed" => Outcome::Completed,392 "failed" => Outcome::Failed,393 "cancelled" => Outcome::Cancelled,394 "expired" => Outcome::Expired,395 other => return Err(GoldenError::Shape(format!("unknown outcome {other}"))),396 };397 Ok(GoldenExpect { events, outcome })398 }399 400 /// A private directory that is removed when the golden ends.401 struct SocketDir(PathBuf);402 403 impl SocketDir {404 fn new() -> Result<SocketDir, GoldenError> {405 static NEXT: AtomicU64 = AtomicU64::new(1);406 let serial = NEXT.fetch_add(1, Ordering::Relaxed);407 let path = Path::new("/tmp").join(format!("inf3r-golden-{}-{serial}", std::process::id()));408 fs::DirBuilder::new()409 .mode(0o700)410 .create(&path)411 .map_err(|why| GoldenError::Run(format!("{}: {why}", path.display())))?;412 Ok(SocketDir(path))413 }414 }415 416 impl Drop for SocketDir {417 fn drop(&mut self) {418 let _ = fs::remove_dir_all(&self.0);419 }420 }421 422 fn start(program: &Path, deadline: Instant) -> Result<(Peer, Child, SocketDir), GoldenError> {423 let socket_dir = SocketDir::new()?;424 let path = socket_dir.0.join("socket");425 let listener = UnixListener::bind(&path)?;426 listener.set_nonblocking(true)?;427 let mut command = Command::new(program);428 command429 .arg("--socket")430 .arg(&path)431 .stdout(Stdio::null())432 .stderr(Stdio::null());433 let mut child = command.spawn()?;434 loop {435 match child.try_wait() {436 Ok(Some(status)) => {437 return Err(GoldenError::Run(format!(438 "the binary exited before it connected: {status}"439 )));440 }441 Ok(None) => {}442 Err(why) => return Err(GoldenError::Run(why.to_string())),443 }444 if Instant::now() >= deadline {445 kill(&mut child);446 return Err(GoldenError::Run("the binary did not connect".into()));447 }448 match listener.accept() {449 Ok((stream, _)) => {450 stream.set_nonblocking(false)?;451 let peer = Peer::connect(452 stream,453 "golden",454 deadline.saturating_duration_since(Instant::now()),455 )456 .map_err(|why| GoldenError::Run(why.to_string()))?;457 return Ok((peer, child, socket_dir));458 }459 Err(why) if why.kind() == io::ErrorKind::WouldBlock => thread::sleep(POLL),460 Err(why) => return Err(GoldenError::Run(why.to_string())),461 }462 }463 }464 465 fn load(peer: &Peer, path: Option<&Path>, deadline: Instant) -> Result<(), GoldenError> {466 let file = match path {467 Some(path) => Some((fs::File::open(path)?, path.to_path_buf())),468 None => None,469 };470 let deps = match &file {471 Some((file, path)) => vec![Dependency {472 role: "weights".into(),473 fd: 0,474 len: file.metadata()?.len(),475 path: path.to_string_lossy().into_owned(),476 }],477 None => Vec::new(),478 };479 let fds: Vec<_> = file.iter().map(|(file, _)| file.as_fd()).collect();480 peer.load_fds(481 &Grant { deps },482 &fds,483 deadline.saturating_duration_since(Instant::now()),484 )485 .map_err(|why| GoldenError::Run(why.to_string()))?;486 Ok(())487 }488 489 fn kill(child: &mut Child) {490 let _ = child.kill();491 let _ = child.wait();492 }