1 //! A trace is the recorded frames of one session, as their JSON mirrors.2 //!3 //! The protocol never looks inside `event` or `done`, so a body comparison at4 //! the type level cannot prove that a session is unchanged. A trace compares5 //! the frames a peer actually sent, in order, and names the first step that6 //! differs. That is what a golden needs.7 //!8 //! A descriptor has no portable spelling. `record` refuses one rather than9 //! writing a number that means a file in one process and another file in the10 //! next one. Issue 10.11 12 pub mod bundle;13 14 use std::fmt;15 16 use inf3r_json::Value;17 use inf3r_proto::body::{self, Body, Hold};18 use inf3r_proto::cbor;19 use inf3r_proto::frame::Kind;20 use inf3r_proto::mirror;21 22 /// The key that holds the seed of a trace.23 const SEED: &str = "seed";24 /// The key that holds the ordered steps.25 const STEPS: &str = "steps";26 /// The key that names the side that sent a step.27 const DIR: &str = "dir";28 /// The key that holds the stream id of a step.29 const STREAM: &str = "stream";30 /// The key that holds the body mirror.31 const BODY: &str = "body";32 /// The key that names the frame kind of a body mirror.33 const KIND: &str = "kind";34 35 /// The spelling of a caller step.36 const CALLER: &str = "caller";37 /// The spelling of a server step.38 const SERVER: &str = "server";39 40 /// A frame name of wire 1, lowercase as protocol.md section 3 spells it.41 const KIND_NAMES: [(&str, Kind); 16] = [42 ("hello", Kind::Hello),43 ("welcome", Kind::Welcome),44 ("catalogue", Kind::Catalogue),45 ("grant", Kind::Grant),46 ("ready", Kind::Ready),47 ("window", Kind::Window),48 ("ping", Kind::Ping),49 ("pong", Kind::Pong),50 ("bye", Kind::Bye),51 ("fatal", Kind::Fatal),52 ("open", Kind::Open),53 ("accept", Kind::Accept),54 ("event", Kind::Event),55 ("done", Kind::Done),56 ("reject", Kind::Reject),57 ("cancel", Kind::Cancel),58 ];59 60 /// The fallback for a kind that has no body. A trace never records one.61 const EXTENSION: &str = "extension";62 63 /// Which side sent a step.64 #[derive(Clone, Copy, PartialEq, Eq, Debug)]65 pub enum Dir {66 /// The side that opens streams.67 Caller,68 /// The side that answers them.69 Server,70 }71 72 impl Dir {73 /// The spelling in the trace file.74 const fn name(self) -> &'static str {75 match self {76 Dir::Caller => CALLER,77 Dir::Server => SERVER,78 }79 }80 81 /// The direction that a spelling names.82 fn parse(name: &str) -> Option<Dir> {83 match name {84 CALLER => Some(Dir::Caller),85 SERVER => Some(Dir::Server),86 _ => None,87 }88 }89 }90 91 impl fmt::Display for Dir {92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {93 f.write_str(self.name())94 }95 }96 97 /// One recorded frame.98 #[derive(Clone, PartialEq, Debug)]99 pub struct Step {100 /// The side that sent it.101 pub dir: Dir,102 /// The stream it travelled on. Zero is a session frame.103 pub stream: u16,104 /// The JSON mirror of its CBOR body.105 pub body: Value,106 }107 108 /// One recorded session. The seed is present when the session had one.109 #[derive(Clone, PartialEq, Debug, Default)]110 pub struct Trace {111 /// The seed of a session that records randomness or time. Spec.md 15.2112 /// rule 3 requires it.113 pub seed: Option<u64>,114 /// The frames in send order.115 pub steps: Vec<Step>,116 }117 118 impl Trace {119 /// Records one body that a peer sent, as its JSON mirror.120 ///121 /// A descriptor is refused because a trace is a file outside the process122 /// that saw the descriptor.123 pub fn record(&mut self, dir: Dir, stream: u16, body: &Body) -> Result<(), TraceError> {124 if has_descriptor(body) {125 return Err(TraceError::Descriptor);126 }127 self.steps.push(Step {128 dir,129 stream,130 body: body_json(body),131 });132 Ok(())133 }134 135 /// The trace as a JSON document, so that it can be written to a file.136 pub fn to_json(&self) -> Value {137 let mut object = inf3r_json::Object::new();138 if let Some(seed) = self.seed {139 object = object.put(SEED, seed_json(seed));140 }141 let steps = self.steps.iter().map(step_json).collect();142 object.put(STEPS, Value::Array(steps)).build()143 }144 145 /// Reads a trace back. Trailing text is an error like any other.146 pub fn parse(text: &str) -> Result<Trace, TraceError> {147 let root = inf3r_json::parse(text).map_err(|error| match error {148 inf3r_json::JsonError::Trailing { .. } => TraceError::Trailing,149 other => TraceError::Json(other),150 })?;151 if root.as_object().is_none() {152 return Err(TraceError::NotObject);153 }154 let seed = root.get(SEED).and_then(seed_from_json);155 let items = root156 .get(STEPS)157 .and_then(Value::as_array)158 .ok_or(TraceError::MissingSteps)?;159 let mut steps = Vec::with_capacity(items.len());160 for (index, item) in items.iter().enumerate() {161 steps.push(step_from_json(item, index)?);162 }163 Ok(Trace { seed, steps })164 }165 }166 167 /// The first step that differs between two traces.168 #[derive(Clone, PartialEq, Debug)]169 pub struct Diff {170 /// The zero-based index of the step.171 pub index: usize,172 /// The step that the expected trace holds. `Value::Null` when the trace173 /// ended before this index.174 pub expected: Step,175 /// The step that the actual trace holds. `Value::Null` when the trace176 /// ended before this index.177 pub actual: Step,178 }179 180 impl fmt::Display for Diff {181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {182 write!(183 f,184 "step {}: expected {}, got {}",185 self.index,186 step_text(&self.expected),187 step_text(&self.actual)188 )189 }190 }191 192 /// A trace that could not be read or recorded.193 #[derive(Clone, PartialEq, Debug)]194 pub enum TraceError {195 /// The document is not a JSON object.196 NotObject,197 /// The `steps` key is absent or is not an array.198 MissingSteps,199 /// A step is not an object or lacks a field that every step needs.200 BadStep {201 /// The zero-based index of the step.202 index: usize,203 },204 /// A step names a direction that wire 1 does not have.205 BadDir(String),206 /// A stream id is absent or does not fit a `u16`.207 BadStream,208 /// A body has no `kind`, or names a frame that is not one of the sixteen.209 UnknownKind(String),210 /// A body mirror has no form that CBOR can carry.211 Mirror,212 /// A body does not match the grammar of its frame.213 Body(body::BodyError),214 /// A body carries a descriptor. A trace file cannot hold one.215 Descriptor,216 /// The document is not JSON.217 Json(inf3r_json::JsonError),218 /// Bytes follow the JSON document.219 Trailing,220 }221 222 impl fmt::Display for TraceError {223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {224 match self {225 TraceError::NotObject => f.write_str("a trace must be a JSON object"),226 TraceError::MissingSteps => f.write_str("the key steps must be an array"),227 TraceError::BadStep { index } => write!(f, "step {index} is not a step"),228 TraceError::BadDir(name) => {229 write!(f, "the direction {name:?} is neither caller nor server")230 }231 TraceError::BadStream => f.write_str("a stream id must be a uint16"),232 TraceError::UnknownKind(name) => {233 write!(f, "the body kind {name:?} is not a frame of wire 1")234 }235 TraceError::Mirror => f.write_str("the body mirror has no CBOR form"),236 TraceError::Body(error) => write!(f, "body: {error}"),237 TraceError::Descriptor => {238 f.write_str("a trace cannot record a descriptor, it is not portable")239 }240 TraceError::Json(error) => write!(f, "json: {error}"),241 TraceError::Trailing => f.write_str("text follows the trace"),242 }243 }244 }245 246 impl std::error::Error for TraceError {247 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {248 match self {249 TraceError::Body(error) => Some(error),250 TraceError::Json(error) => Some(error),251 _ => None,252 }253 }254 }255 256 /// Compares two traces and reports the first difference by index.257 pub fn compare(expected: &Trace, actual: &Trace) -> Result<(), Diff> {258 let common = expected.steps.len().min(actual.steps.len());259 for index in 0..common {260 if expected.steps[index] != actual.steps[index] {261 return Err(Diff {262 index,263 expected: expected.steps[index].clone(),264 actual: actual.steps[index].clone(),265 });266 }267 }268 if expected.steps.len() != actual.steps.len() {269 return Err(Diff {270 index: common,271 expected: expected272 .steps273 .get(common)274 .cloned()275 .unwrap_or_else(absent_step),276 actual: actual277 .steps278 .get(common)279 .cloned()280 .unwrap_or_else(absent_step),281 });282 }283 Ok(())284 }285 286 /// A step that stands for a trace that has no step at this index.287 fn absent_step() -> Step {288 Step {289 dir: Dir::Caller,290 stream: 0,291 body: Value::Null,292 }293 }294 295 /// True when an `open` or `done` body carries a descriptor.296 fn has_descriptor(body: &Body) -> bool {297 match body {298 Body::Open(open) => open299 .parts300 .iter()301 .any(|part| matches!(part.hold, Hold::Fd(_))),302 Body::Done(done) => done303 .artifacts304 .iter()305 .any(|artifact| matches!(artifact.hold, Hold::Fd(_))),306 _ => false,307 }308 }309 310 /// The JSON mirror of a body, tagged with its frame name.311 fn body_json(body: &Body) -> Value {312 inf3r_json::Object::new()313 .put(KIND, Value::str(kind_name(body.kind())))314 .put(BODY, mirror::to_json(&body.to_value()))315 .build()316 }317 318 /// The frame name of a kind.319 fn kind_name(kind: Kind) -> &'static str {320 KIND_NAMES321 .iter()322 .find(|(_, name)| *name == kind)323 .map_or(EXTENSION, |(name, _)| *name)324 }325 326 /// The kind that a frame name assigns.327 fn kind_from_name(name: &str) -> Option<Kind> {328 KIND_NAMES329 .iter()330 .find(|(spelling, _)| *spelling == name)331 .map(|(_, kind)| *kind)332 }333 334 /// A seed as a JSON number. A seed that does not fit `i64` keeps its value as335 /// a float, because no seed in this tree is above 2^53.336 fn seed_json(seed: u64) -> Value {337 match i64::try_from(seed) {338 Ok(seed) => Value::Int(seed),339 Err(_) => Value::Float(seed as f64),340 }341 }342 343 /// A JSON number as a seed.344 fn seed_from_json(value: &Value) -> Option<u64> {345 match value {346 Value::Int(number) => u64::try_from(*number).ok(),347 Value::Float(number) => Some(*number as u64),348 _ => None,349 }350 }351 352 /// One step as a JSON object.353 fn step_json(step: &Step) -> Value {354 inf3r_json::Object::new()355 .put(DIR, Value::str(step.dir.name()))356 .put(STREAM, Value::Int(i64::from(step.stream)))357 .put(BODY, step.body.clone())358 .build()359 }360 361 /// One step from a JSON object.362 fn step_from_json(value: &Value, index: usize) -> Result<Step, TraceError> {363 if value.as_object().is_none() {364 return Err(TraceError::BadStep { index });365 }366 let dir = value367 .get(DIR)368 .and_then(Value::as_str)369 .ok_or(TraceError::BadStep { index })?;370 let dir = Dir::parse(dir).ok_or_else(|| TraceError::BadDir(dir.to_string()))?;371 let stream = value372 .get(STREAM)373 .and_then(Value::as_u64)374 .and_then(|id| u16::try_from(id).ok())375 .ok_or(TraceError::BadStream)?;376 let body = value377 .get(BODY)378 .ok_or(TraceError::BadStep { index })379 .and_then(body_from_json)?;380 Ok(Step { dir, stream, body })381 }382 383 /// A body from its JSON mirror, through the CBOR grammar of its kind.384 fn body_from_json(value: &Value) -> Result<Value, TraceError> {385 let name = value386 .get(KIND)387 .and_then(Value::as_str)388 .ok_or_else(|| TraceError::UnknownKind(String::new()))?;389 let kind = kind_from_name(name).ok_or_else(|| TraceError::UnknownKind(name.to_string()))?;390 let item = value.get(BODY).ok_or(TraceError::Mirror)?;391 let item = mirror::from_json(item).ok_or(TraceError::Mirror)?;392 let mut payload = Vec::new();393 cbor::encode(&item, &mut payload);394 let body = Body::decode(kind, &payload).map_err(TraceError::Body)?;395 if has_descriptor(&body) {396 return Err(TraceError::Descriptor);397 }398 Ok(body_json(&body))399 }400 401 /// One step as text for a diff. A missing step has no body and says so.402 fn step_text(step: &Step) -> String {403 let Some(kind) = step.body.get(KIND).and_then(Value::as_str) else {404 return format!("{}/{} <absent>", step.dir, step.stream);405 };406 let body = step407 .body408 .get(BODY)409 .map(inf3r_json::to_string)410 .unwrap_or_default();411 format!("{}/{} {kind}{body}", step.dir, step.stream)412 }