1 //! The event object that every hop sends (spec section 11).2 //!3 //! One type builds every event, so the plugin, the core, and the web cannot4 //! disagree about a field name. `seq` increases by one for each event of a job5 //! and each channel keeps its own order, because the whole object is written in6 //! the order that it is built: the sequence is the tie-breaker that a client7 //! already has.8 9 use inf3r_json::{Object, Value};10 11 use crate::clock;12 13 /// The sequence number of one job.14 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]15 pub struct Seq(u64);16 17 impl Seq {18 /// The first event of a job.19 pub fn new() -> Seq {20 Seq(0)21 }22 23 /// The next event's number. The first event that a job sends is 1.24 ///25 /// The name is `next` and not an `Iterator`: a job's events are made, not26 /// pulled.27 #[allow(clippy::should_implement_trait)]28 pub fn next(&mut self) -> u64 {29 self.0 += 1;30 self.031 }32 33 /// The number that the last `next` gave.34 pub fn value(self) -> u64 {35 self.036 }37 }38 39 impl Default for Seq {40 fn default() -> Seq {41 Seq::new()42 }43 }44 45 /// The body of one event.46 #[derive(Clone, PartialEq, Debug)]47 pub enum Body {48 /// The job started. `est_ms` is the estimate of the plugin.49 Started {50 /// The served name.51 model: String,52 /// The plugin binary.53 plugin: String,54 /// Estimated milliseconds to the first useful byte.55 est_ms: Option<u32>,56 },57 /// One chunk of text on a channel.58 Text {59 /// Channel name, as the capability declares it.60 channel: String,61 /// The text.62 text: String,63 },64 /// One chunk of bytes on a channel.65 Bytes {66 /// Channel name, as the capability declares it.67 channel: String,68 /// MIME type of this chunk.69 mime: String,70 /// The bytes, base64 is applied here and nowhere else.71 data: Vec<u8>,72 },73 /// Progress on a channel, as a fraction of the whole.74 Progress {75 /// Channel name: `progress`.76 channel: String,77 /// 0 to 1.78 pct: f64,79 /// The step that is running, for a human.80 stage: Option<String>,81 },82 /// What the job used, as the counts of the event body. The core collects83 /// this for `/stats`.84 Usage(Value),85 /// The job ended.86 Done {87 /// `completed` or `cancelled`.88 outcome: String,89 /// One entry per artifact.90 artifacts: Vec<Artifact>,91 /// Free-form values that the capability defines.92 meta: Option<Value>,93 },94 /// The job failed after the headers.95 Error {96 /// A code from section 12.97 code: String,98 /// One sentence for a human.99 message: String,100 },101 }102 103 /// One artifact of a finished job.104 #[derive(Clone, PartialEq, Eq, Debug)]105 pub struct Artifact {106 /// Channel name.107 pub channel: String,108 /// MIME type.109 pub mime: String,110 /// The content address, 64 hex characters.111 pub blob: String,112 /// Bytes of the blob.113 pub bytes: u64,114 }115 116 impl Body {117 /// The body as JSON, with `t` first.118 fn to_json(&self) -> Value {119 match self {120 Body::Started {121 model,122 plugin,123 est_ms,124 } => {125 let mut body = Object::new()126 .put("t", Value::str("started"))127 .put("model", Value::str(model.clone()))128 .put("plugin", Value::str(plugin.clone()));129 if let Some(est_ms) = est_ms {130 body = body.put("est_ms", Value::Int(i64::from(*est_ms)));131 }132 body.build()133 }134 Body::Text { channel, text } => Object::new()135 .put("t", Value::str("delta"))136 .put("channel", Value::str(channel.clone()))137 .put("text", Value::str(text.clone()))138 .build(),139 Body::Bytes {140 channel,141 mime,142 data,143 } => Object::new()144 .put("t", Value::str("delta"))145 .put("channel", Value::str(channel.clone()))146 .put("mime", Value::str(mime.clone()))147 .put("b64", Value::str(crate::b64::encode(data)))148 .build(),149 Body::Progress {150 channel,151 pct,152 stage,153 } => {154 let mut body = Object::new()155 .put("t", Value::str("delta"))156 .put("channel", Value::str(channel.clone()))157 .put("pct", Value::Float(*pct));158 if let Some(stage) = stage {159 body = body.put("stage", Value::str(stage.clone()));160 }161 body.build()162 }163 Body::Usage(counts) => {164 // The spec writes the counts at the top of the body:165 // `{"t":"usage","text_in":12,...}`. The object that the caller166 // supplies is merged there instead of gaining a second wrapper.167 let mut body = Object::new();168 if let Value::Object(fields) = counts {169 for (key, value) in fields {170 body = body.put(key.clone(), value.clone());171 }172 } else {173 body = body.put("counts", counts.clone());174 }175 body.put("t", Value::str("usage")).build()176 }177 Body::Done {178 outcome,179 artifacts,180 meta,181 } => {182 let artifacts = artifacts183 .iter()184 .map(|artifact| {185 Object::new()186 .put("channel", Value::str(artifact.channel.clone()))187 .put("mime", Value::str(artifact.mime.clone()))188 .put("blob", Value::str(artifact.blob.clone()))189 .put("bytes", Value::Int(artifact.bytes as i64))190 .build()191 })192 .collect();193 let mut body = Object::new()194 .put("t", Value::str("done"))195 .put("outcome", Value::str(outcome.clone()))196 .put("artifacts", Value::Array(artifacts));197 if let Some(meta) = meta {198 body = body.put("meta", meta.clone());199 }200 body.build()201 }202 Body::Error { code, message } => Object::new()203 .put("t", Value::str("error"))204 .put("code", Value::str(code.clone()))205 .put("message", Value::str(message.clone()))206 .build(),207 }208 }209 }210 211 /// One event, with the fields that a client can use to join it to its request.212 #[derive(Clone, PartialEq, Debug)]213 pub struct Event {214 /// The job identifier that the core made.215 pub job: Option<String>,216 /// The identifier that the client sent.217 pub request_id: Option<String>,218 /// When the event was made, in RFC 3339 with milliseconds.219 pub at: Option<String>,220 /// What happened.221 pub body: Body,222 }223 224 impl Event {225 /// An event with no envelope: the core adds the identifiers.226 pub fn new(body: Body) -> Event {227 Event {228 job: None,229 request_id: None,230 at: None,231 body,232 }233 }234 235 /// The same event with the job and the request that it belongs to.236 pub fn about(self, job: impl Into<String>, request_id: impl Into<String>) -> Event {237 Event {238 job: Some(job.into()),239 request_id: Some(request_id.into()),240 at: Some(clock::now_rfc3339()),241 ..self242 }243 }244 245 /// The event as JSON, with the sequence number that `seq` gives.246 pub fn to_json(&self, seq: u64) -> Value {247 let mut root = Object::new().put("seq", Value::Int(seq as i64));248 if let Some(job) = &self.job {249 root = root.put("job", Value::str(job.clone()));250 }251 if let Some(request_id) = &self.request_id {252 root = root.put("request_id", Value::str(request_id.clone()));253 }254 if let Some(at) = &self.at {255 root = root.put("at", Value::str(at.clone()));256 }257 root.put("body", self.body.to_json()).build()258 }259 }