use std::sync::{Arc, Mutex};
use std::time::Instant;
use printobserver_types::serde_json::{self, Value, json};
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::JoinHandle;
pub const RECORDED_PRINTER: &str = include_str!("obico-printer.json");
fn recorded() -> Value {
let recording: Value = serde_json::from_str(RECORDED_PRINTER).expect("the recording is JSON");
assert_eq!(
recording["provenance"]["sentinel"],
json!(AUTH_TOKEN_SENTINEL),
"the sentinel the recording's credentials were replaced with"
);
let answer = recording["answer"].clone();
assert_eq!(
answer["id"],
json!(RECORDED_PRINTER_ID),
"the recorded printer"
);
assert_eq!(
answer["auth_token"],
json!(AUTH_TOKEN_SENTINEL),
"the recording's credential is the sentinel"
);
answer
}
pub const RECORDED_PRINTER_ID: i64 = 1;
pub const ACTIVE_PRINT: i64 = 4211;
pub const AUTH_TOKEN_SENTINEL: &str = "SENTINEL-obico-printer-auth-token-0b6f3c";
#[derive(Debug, Clone)]
pub struct Request {
pub line: String,
pub headers: Vec<String>,
pub at: Instant,
}
impl Request {
pub fn path(&self) -> &str {
self.line.split(' ').nth(1).unwrap_or_default()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mood {
Answering,
Hanging,
BreakingOff,
BreakingOffLate,
}
#[derive(Debug)]
struct Held {
mood: Mood,
any_printer: bool,
answer: Value,
health: &'static str,
received: Vec<Request>,
}
#[derive(Debug)]
pub struct Host {
pub address: std::net::SocketAddr,
held: Arc<Mutex<Held>>,
serving: JoinHandle<()>,
}
impl Host {
pub async fn rest(token: &str) -> Self {
let host = Self::start(Some(token.to_owned())).await;
host.answer(|answer| answer["current_print"]["id"] = json!(ACTIVE_PRINT));
host
}
pub async fn ml_api() -> Self {
Self::start(None).await
}
async fn start(token: Option<String>) -> Self {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("a loopback port");
let address = listener.local_addr().expect("the bound address");
let held = Arc::new(Mutex::new(Held {
mood: Mood::Answering,
any_printer: false,
answer: recorded(),
health: "200 OK",
received: Vec::new(),
}));
let serving_held = Arc::clone(&held);
let serving_token = token;
let serving = tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let held = Arc::clone(&serving_held);
let token = serving_token.clone();
tokio::spawn(async move { respond(stream, &held, token.as_deref()).await });
}
});
Self {
address,
held,
serving,
}
}
pub fn url(&self) -> String {
format!("http://{}", self.address)
}
pub fn served(&self) -> Value {
self.held.lock().expect("the host holds").answer.clone()
}
pub fn answer(&self, change: impl FnOnce(&mut Value)) {
change(&mut self.held.lock().expect("the host holds").answer);
}
pub fn scores(&self, snapshot: u64, score: f64) {
self.answer(|answer| {
let recorded = answer["pic"]["img_url"]
.as_str()
.expect("the recording names a snapshot")
.to_owned();
let (address, _) = recorded
.split_once("?digest=")
.expect("the recorded snapshot carries a digest");
answer["pic"]["img_url"] = json!(format!("{address}?digest={snapshot}"));
answer["normalized_p"] = json!(score);
});
}
pub fn answers(&self, mood: Mood) {
self.held.lock().expect("the host holds").mood = mood;
}
pub fn answers_every_printer(&self) {
self.held.lock().expect("the host holds").any_printer = true;
}
pub fn stop(&self) {
self.serving.abort();
}
pub fn health(&self, status: &'static str) {
self.held.lock().expect("the host holds").health = status;
}
pub fn received(&self) -> Vec<Request> {
self.held.lock().expect("the host holds").received.clone()
}
}
impl Drop for Host {
fn drop(&mut self) {
self.serving.abort();
}
}
async fn respond(mut stream: TcpStream, held: &Mutex<Held>, token: Option<&str>) {
let mut request = Vec::new();
let mut buffer = [0_u8; 1024];
while !request.windows(4).any(|window| window == b"\r\n\r\n") {
match stream.read(&mut buffer).await {
Ok(0) | Err(_) => return,
Ok(read) => request.extend_from_slice(&buffer[..read]),
}
}
let text = String::from_utf8_lossy(&request).into_owned();
let mut lines = text.split("\r\n");
let line = lines.next().unwrap_or_default().to_owned();
let headers: Vec<String> = lines
.filter(|header| !header.is_empty())
.map(str::to_owned)
.collect();
let path = line.split(' ').nth(1).unwrap_or_default().to_owned();
let (status, body, mood) = {
let mut held = held.lock().expect("the host holds");
let mood = held.mood;
held.received.push(Request {
line: line.clone(),
headers: headers.clone(),
at: Instant::now(),
});
let (status, body) = match token {
None if path == "/hc/" => (held.health, b"ok".to_vec()),
None => ("404 Not Found", Vec::new()),
Some(token) => {
let bearer = format!("authorization: bearer {token}");
let admitted = headers
.iter()
.any(|header| header.eq_ignore_ascii_case(&bearer));
if !admitted {
(
"403 Forbidden",
br#"{"detail":"Authentication credentials were not provided."}"#.to_vec(),
)
} else if line.starts_with("GET ") && path.starts_with("/api/v1/printers/") {
let id = held.answer["id"].as_i64().unwrap_or_default();
if held.any_printer || path == format!("/api/v1/printers/{id}/") {
("200 OK", held.answer.to_string().into_bytes())
} else {
("404 Not Found", br#"{"detail":"Not found."}"#.to_vec())
}
} else if line.starts_with("POST ") && path.contains("/acknowledge_alert/") {
("200 OK", b"{}".to_vec())
} else {
("404 Not Found", br#"{"detail":"Not found."}"#.to_vec())
}
}
};
(status, body, mood)
};
let reading = line.starts_with("GET ") && path.starts_with("/api/v1/printers/");
if reading && status.starts_with("200") {
match mood {
Mood::Answering => {}
Mood::Hanging => {
tokio::time::sleep(std::time::Duration::from_secs(8)).await;
return;
}
Mood::BreakingOff | Mood::BreakingOffLate => {
if mood == Mood::BreakingOffLate {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
let cut = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
let _ = stream.write_all(cut.as_bytes()).await;
let _ = stream.write_all(&body[..body.len() / 2]).await;
let _ = stream.shutdown().await;
return;
}
}
}
let preamble = format!(
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
if stream.write_all(preamble.as_bytes()).await.is_err() {
return;
}
let _ = stream.write_all(&body).await;
let _ = stream.shutdown().await;
}