Files
leleka/crates/worker-protocol/src/lines.rs
T

79 lines
2.2 KiB
Rust

//! What a worker writes. One function per line type; the gateway reads them back with [`crate::events::parse_line`].
use crate::events::Finish;
use std::fmt::Write as _;
pub fn ready_line(max_context: usize) -> String {
format!("READY {max_context} stop\n")
}
pub fn token_line(id: u32) -> String {
format!("T {id}\n")
}
pub fn progress_line(read: usize, total: usize) -> String {
format!("PP {read} {total}\n")
}
pub fn reused_line(reused: usize) -> String {
format!("REUSED {reused}\n")
}
/// An error line; newlines in the message would break the protocol, so they are flattened.
pub fn error_line(message: &str) -> String {
format!("ERR {}\n", message.replace(['\r', '\n'], " "))
}
/// The milliseconds a request spent reading its prompt and decoding.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PhaseMs {
pub prompt_ms: f64,
pub decode_ms: f64,
}
/// The terminal line of a request. The draft and expert counters are zero: this worker has neither.
pub fn done_line(
generated: u64,
prompt_tokens: u64,
phases: PhaseMs,
finish: Finish,
reused: u64,
) -> String {
let PhaseMs {
prompt_ms,
decode_ms,
} = phases;
let mut line = String::new();
write!(
line,
"DONE {generated} {prompt_tokens} {prompt_ms:.1} {decode_ms:.1} {} 0 0 {reused} 0 0",
finish.word()
)
.expect("writing to a String");
line.push('\n');
line
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn output_lines_have_the_shape_the_control_plane_parses() {
assert_eq!(ready_line(16384), "READY 16384 stop\n");
assert_eq!(token_line(42), "T 42\n");
assert_eq!(progress_line(64, 4096), "PP 64 4096\n");
assert_eq!(error_line("bad\nthing"), "ERR bad thing\n");
let phases = PhaseMs {
prompt_ms: 45.12,
decode_ms: 88.26,
};
let done = done_line(12, 300, phases, Finish::Stop, 200);
assert_eq!(done, "DONE 12 300 45.1 88.3 stop 0 0 200 0 0\n");
// at least five fields; reused is the field the control plane reads at index 7
let fields: Vec<&str> = done.split_whitespace().skip(1).collect();
assert_eq!(fields.len(), 10);
assert_eq!(fields[7], "200");
}
}