Files
leleka/control-plane/src/vision.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 e74376430f fix(control-plane): a failing log sink can no longer kill the worker supervisor mid-request
eprintln! panics when stderr is unwritable (consumer gone: EPIPE, disk full:
ENOSPC). worker.rs logged before it marked the worker Failed, so with a dead log
consumer the supervisor task died, readiness stayed true and later requests hit a
dead worker (charter M1 / Gate A). All diagnostics now go through the
non-panicking elog! macro.

tests/log_failure_sse.rs starts the real strata-next binary with a scripted
engine, drops the stderr consumer after startup and provokes a protocol failure
inside a streamed Responses request: the stream must end with response.failed and
readiness must drop (the control case with a live sink passes before and after;
the dead-sink case failed before). A source scan keeps eprintln! out of the crate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-16 01:59:26 +02:00

780 lines
28 KiB
Rust

//! The image encoder client: the resident `strata-vision` process (llama.cpp mtmd plus the model's mmproj
//! file), its `ENC <image> <out>` line protocol, the content-hash cache, and the per-request embeddings file
//! (`serve/server.py` `Vision` and the image branch of `Service.prepare`).
//!
//! Everything format-level (SVE1 records, `<|image_pad|>` expansion, base64 wording, native formats) lives in
//! `leleka_serving_policy::vision`; this module owns the process and the files.
//!
//! Differences from the Python server, all deliberate:
//! * images in formats `stb_image` cannot read (WebP, TIFF, AVIF, ...) are refused with a clear message: Python
//! converts them with Pillow, which a Python-free serving path does not have;
//! * a fetched `http(s)` image is capped at [`MAX_IMAGE_BYTES`], and a network failure is a 400 naming it;
//! * the per-request `req-*.sve` file is removed when the request ends (Python leaves it behind);
//! * the encoder's stderr is inherited, not discarded.
use std::{
collections::VecDeque,
path::{Path, PathBuf},
process::Stdio,
sync::{
Arc,
atomic::{AtomicBool, AtomicU64, Ordering},
},
time::Duration,
};
use leleka_serving_policy::vision as policy;
use serde::Deserialize;
use sha2::{Digest, Sha256};
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
process::{Child, ChildStdin, ChildStdout, Command},
sync::Mutex,
time::timeout,
};
/// Encoded images kept on disk, oldest evicted first (`len(self.cache) > 64`).
pub const CACHE_LIMIT: usize = 64;
/// A fetched image larger than this is refused (Python reads without a limit).
pub const MAX_IMAGE_BYTES: usize = 64 * 1024 * 1024;
const FETCH_TIMEOUT: Duration = Duration::from_secs(60);
const START_TIMEOUT: Duration = Duration::from_secs(600);
/// The config's `vision` section.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct VisionConfig {
/// The `strata-vision` executable.
pub exe: PathBuf,
pub mmproj: PathBuf,
/// The text model's first GGUF split (opened vocab-only for the tokenizer).
pub model: PathBuf,
#[serde(default)]
pub gpu: bool,
pub threads: Option<u32>,
pub max_tokens: Option<u32>,
/// Run the encoder on this card alone (`CUDA_DEVICE_ORDER=PCI_BUS_ID`, `CUDA_VISIBLE_DEVICES`), so a spare GPU can
/// hold it while the engine keeps the VRAM of its own cards.
pub cuda_device: Option<u32>,
}
impl VisionConfig {
/// `Vision.__init__`'s arguments.
pub fn args(&self) -> Vec<String> {
let mut args = vec![
"--mmproj".to_owned(),
self.mmproj.to_string_lossy().into_owned(),
"--model".to_owned(),
self.model.to_string_lossy().into_owned(),
];
if self.gpu {
args.push("--gpu".into());
}
if let Some(threads) = self.threads.filter(|t| *t > 0) {
args.extend(["--threads".to_owned(), threads.to_string()]);
}
if let Some(max) = self.max_tokens.filter(|t| *t > 0) {
args.extend(["--max-tokens".to_owned(), max.to_string()]);
}
args
}
/// `vision_env`: the environment overrides of the encoder process.
pub fn env(&self) -> Vec<(&'static str, String)> {
match self.cuda_device {
Some(device) => vec![
("CUDA_DEVICE_ORDER", "PCI_BUS_ID".to_owned()),
("CUDA_VISIBLE_DEVICES", device.to_string()),
],
None => Vec::new(),
}
}
pub fn validate(&self) -> Result<(), String> {
for (name, path) in [
("exe", &self.exe),
("mmproj", &self.mmproj),
("model", &self.model),
] {
if path.as_os_str().is_empty() {
return Err(format!("vision.{name} must not be empty"));
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VisionError {
/// The caller's image is the problem: HTTP 400 (`ValueError` in Python).
Invalid(String),
/// The encoder itself failed (the pipe is gone, the process would not start).
Failed(String),
}
impl std::fmt::Display for VisionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Invalid(message) | Self::Failed(message) => f.write_str(message),
}
}
}
impl std::error::Error for VisionError {}
/// One encoded image: its SVE1 file and the number of image tokens it stands for.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Encoded {
pub path: PathBuf,
pub tokens: usize,
}
/// Keeps a request's temporary files alive until the last clone of the request is dropped.
#[derive(Clone, Debug, Default)]
pub struct Keep(Option<Arc<TempFile>>);
impl Keep {
pub fn none() -> Self {
Self(None)
}
}
impl PartialEq for Keep {
fn eq(&self, other: &Self) -> bool {
match (&self.0, &other.0) {
(None, None) => true,
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
_ => false,
}
}
}
#[derive(Debug)]
struct TempFile(PathBuf);
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
struct Proc {
child: Child,
stdin: ChildStdin,
lines: tokio::io::Lines<BufReader<ChildStdout>>,
}
#[derive(Default)]
struct Inner {
proc: Option<Proc>,
/// Content hash (first 32 hex of SHA-256 of the normalized bytes) -> encoded file; insertion order.
cache: VecDeque<(String, Encoded)>,
}
pub struct Vision {
config: VisionConfig,
dir: PathBuf,
inner: Mutex<Inner>,
stopped: AtomicBool,
serial: AtomicU64,
/// Taken for the length of an encode and for every engine generation: the engine and the encoder (two processes)
/// must not use the GPU at the same time. Python does the same with its request FIFO.
pub gate: Arc<Mutex<()>>,
}
static NEXT_DIR: AtomicU64 = AtomicU64::new(0);
impl Vision {
/// Start the encoder and wait for its `READY` line (`Vision.__init__`).
pub async fn start(config: VisionConfig) -> Result<Arc<Self>, VisionError> {
let vision = Self::unstarted(config)?;
{
let mut inner = vision.inner.lock().await;
vision.spawn(&mut inner).await?;
}
Ok(Arc::new(vision))
}
/// A client whose process is started by the first [`Vision::restart`] or [`Vision::ensure_running`].
pub fn unstarted(config: VisionConfig) -> Result<Self, VisionError> {
let dir = std::env::temp_dir().join(format!(
"strata-vision-{}-{}",
std::process::id(),
NEXT_DIR.fetch_add(1, Ordering::Relaxed)
));
std::fs::create_dir_all(&dir)
.map_err(|e| VisionError::Failed(format!("cannot create {}: {e}", dir.display())))?;
Ok(Self {
config,
dir,
inner: Mutex::new(Inner::default()),
stopped: AtomicBool::new(true),
serial: AtomicU64::new(0),
gate: Arc::new(Mutex::new(())),
})
}
pub fn dir(&self) -> &Path {
&self.dir
}
async fn spawn(&self, inner: &mut Inner) -> Result<(), VisionError> {
let mut command = Command::new(&self.config.exe);
command
.args(self.config.args())
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
for (name, value) in self.config.env() {
command.env(name, value);
}
let mut child = command.spawn().map_err(|e| {
VisionError::Failed(format!(
"the vision encoder did not start: {}: {e}",
self.config.exe.display()
))
})?;
let stdin = child.stdin.take().expect("piped encoder stdin");
let stdout = child.stdout.take().expect("piped encoder stdout");
let mut lines = BufReader::new(stdout).lines();
let first = match timeout(START_TIMEOUT, lines.next_line()).await {
Ok(Ok(Some(line))) => line,
Ok(Ok(None)) => String::new(),
Ok(Err(e)) => {
return Err(VisionError::Failed(format!(
"the vision encoder did not start: {e}"
)));
}
Err(_) => {
let _ = child.kill().await;
return Err(VisionError::Failed(
"the vision encoder did not start: no READY line in time".into(),
));
}
};
if !first.starts_with("READY") {
let _ = child.kill().await;
return Err(VisionError::Failed(format!(
"the vision encoder did not start: {}",
first.trim()
)));
}
inner.proc = Some(Proc {
child,
stdin,
lines,
});
self.stopped.store(false, Ordering::Release);
Ok(())
}
/// `Vision.alive`: started, not unloaded, and the process still runs.
pub async fn alive(&self) -> bool {
if self.stopped.load(Ordering::Acquire) {
return false;
}
let mut inner = self.inner.lock().await;
inner
.proc
.as_mut()
.is_some_and(|proc| matches!(proc.child.try_wait(), Ok(None)))
}
async fn close_inner(inner: &mut Inner) {
let Some(mut proc) = inner.proc.take() else {
return;
};
let quit = async {
proc.stdin.write_all(b"QUIT\n").await.ok()?;
proc.stdin.flush().await.ok()?;
drop(proc.stdin);
timeout(Duration::from_secs(10), proc.child.wait())
.await
.ok()?
.ok()
};
if quit.await.is_none() {
let _ = proc.child.kill().await;
}
}
/// `Vision.close`: ask the encoder to quit, kill it if it does not.
pub async fn close(&self) {
let mut inner = self.inner.lock().await;
Self::close_inner(&mut inner).await;
self.stopped.store(true, Ordering::Release);
}
/// `Vision.unload`: stop the process (its VRAM or RAM goes back); the encoded images stay cached on disk.
pub async fn unload(&self) {
self.close().await;
}
/// `Vision.restart`: start the process again after an unload or a death; the cache is kept.
pub async fn restart(&self) -> Result<(), VisionError> {
let mut inner = self.inner.lock().await;
if let Some(mut proc) = inner.proc.take() {
let _ = proc.child.kill().await;
}
self.spawn(&mut inner).await
}
/// `Service.ensure_loaded`'s vision step: start the encoder again unless it runs. Done before the engine starts
/// (a GPU encoder takes its VRAM first, the engine sizes its cache from what is left).
pub async fn ensure_running(&self) -> Result<(), VisionError> {
if self.alive().await {
return Ok(());
}
crate::elog!("starting the vision encoder again ...");
self.restart().await
}
/// `Vision.load`: the bytes behind an image source (a `data:` URL, an http(s) URL or a local path).
pub async fn load(source: &str) -> Result<Vec<u8>, VisionError> {
if let Some(rest) = source.strip_prefix("data:") {
let (_, payload) = rest.split_once(',').ok_or_else(|| {
VisionError::Invalid("an image data: URL needs a comma before its data".into())
})?;
return policy::b64decode(payload).map_err(VisionError::Invalid);
}
if source.starts_with("http://") || source.starts_with("https://") {
return fetch(source).await;
}
let path = source.strip_prefix("file://").unwrap_or(source);
if !path.is_empty() && tokio::fs::metadata(path).await.is_ok_and(|m| m.is_file()) {
return tokio::fs::read(path)
.await
.map_err(|e| VisionError::Invalid(format!("the image could not be read ({e})")));
}
Err(VisionError::Invalid(
"an image must be a data: URL, an http(s) URL or a local file path".into(),
))
}
/// `Vision.normalize` without an image library: the formats `strata-vision`'s decoder reads pass through.
pub fn normalize(data: Vec<u8>) -> Result<Vec<u8>, VisionError> {
if policy::is_native_image_format(&data) {
Ok(data)
} else {
Err(VisionError::Invalid(
"this image format is not supported (JPEG, PNG, BMP and GIF are; convert WebP, TIFF, AVIF, ... first)"
.into(),
))
}
}
/// `Vision.encode`: the embeddings file of an image and its number of image tokens; the same picture
/// (by content) is encoded once.
pub async fn encode(&self, source: &str) -> Result<Encoded, VisionError> {
let data = Self::normalize(Self::load(source).await?)?;
let key = hex::encode(Sha256::digest(&data))[..32].to_owned();
let mut inner = self.inner.lock().await;
if let Some((_, hit)) = inner.cache.iter().find(|(k, _)| *k == key) {
return Ok(hit.clone());
}
let image = self.dir.join(format!("{key}.img"));
let out = self.dir.join(format!("{key}.sve"));
tokio::fs::write(&image, &data)
.await
.map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", image.display())))?;
let reply = Self::exchange(&mut inner, &image, &out).await;
let _ = tokio::fs::remove_file(&image).await; // #352: also when the encoder's pipe is gone
let line = reply?;
if !line.starts_with("OK") {
return Err(VisionError::Invalid(format!(
"the image could not be read: {}",
match line.strip_prefix("ERR") {
Some(_) => line.get(4..).unwrap_or(""),
None => "the vision encoder stopped",
}
)));
}
let tokens = line
.split_whitespace()
.nth(1)
.and_then(|n| n.parse::<usize>().ok())
.ok_or_else(|| {
VisionError::Failed(format!("unexpected vision encoder reply: {line}"))
})?;
let encoded = Encoded { path: out, tokens };
inner.cache.push_back((key, encoded.clone()));
if inner.cache.len() > CACHE_LIMIT
&& let Some((_, old)) = inner.cache.pop_front()
{
let _ = tokio::fs::remove_file(&old.path).await; // oldest first
}
Ok(encoded)
}
/// One `ENC` line and its reply (`""` when the encoder's output ended).
async fn exchange(inner: &mut Inner, image: &Path, out: &Path) -> Result<String, VisionError> {
let proc = inner
.proc
.as_mut()
.ok_or_else(|| VisionError::Failed("the vision encoder is not running".into()))?;
let line = format!("ENC {} {}\n", image.display(), out.display());
proc.stdin
.write_all(line.as_bytes())
.await
.map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?;
proc.stdin
.flush()
.await
.map_err(|e| VisionError::Failed(format!("the vision encoder is gone: {e}")))?;
match proc.lines.next_line().await {
Ok(Some(reply)) => Ok(reply.trim().to_owned()),
Ok(None) => Ok(String::new()),
Err(e) => Err(VisionError::Failed(format!(
"the vision encoder is gone: {e}"
))),
}
}
/// The concatenation of the images' SVE1 files in prompt order: `GENI`'s embeddings file for one request.
pub async fn combine(&self, images: &[Encoded]) -> Result<(PathBuf, Keep), VisionError> {
let name = format!(
"req-{:x}-{:x}.sve",
std::process::id(),
self.serial.fetch_add(1, Ordering::Relaxed)
);
let path = self.dir.join(name);
let mut bytes = Vec::new();
for image in images {
bytes.extend(tokio::fs::read(&image.path).await.map_err(|e| {
VisionError::Failed(format!("cannot read {}: {e}", image.path.display()))
})?);
}
tokio::fs::write(&path, bytes)
.await
.map_err(|e| VisionError::Failed(format!("cannot write {}: {e}", path.display())))?;
Ok((path.clone(), Keep(Some(Arc::new(TempFile(path))))))
}
}
impl Drop for Vision {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
async fn fetch(url: &str) -> Result<Vec<u8>, VisionError> {
let fail = |e: &dyn std::fmt::Display| {
VisionError::Invalid(format!("the image could not be fetched ({e})"))
};
let roots = webpki_root_certs::TLS_SERVER_ROOT_CERTS
.iter()
.map(|der| reqwest::Certificate::from_der(der.as_ref()))
.collect::<Result<Vec<_>, _>>()
.map_err(|e| fail(&e))?;
let client = reqwest::Client::builder()
.tls_certs_only(roots)
.timeout(FETCH_TIMEOUT)
.user_agent("strata")
.build()
.map_err(|e| fail(&e))?;
let mut response = client
.get(url)
.send()
.await
.map_err(|e| fail(&e))?
.error_for_status()
.map_err(|e| fail(&e))?;
let mut data = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(|e| fail(&e))? {
data.extend_from_slice(&chunk);
if data.len() > MAX_IMAGE_BYTES {
return Err(VisionError::Invalid(format!(
"the image is larger than {} MiB",
MAX_IMAGE_BYTES >> 20
)));
}
}
Ok(data)
}
#[cfg(test)]
mod tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
fn fake(dir: &Path, mode: &str) -> VisionConfig {
let exe = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fake_vision.sh");
let wrapper = dir.join(format!("vision-{mode}.sh"));
std::fs::write(
&wrapper,
format!(
"#!/bin/sh\nexec '{}' {mode} '{}' \"$@\"\n",
exe.display(),
dir.display()
),
)
.unwrap();
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o755)).unwrap();
VisionConfig {
exe: wrapper,
mmproj: "/m/mmproj.gguf".into(),
model: "/m/model.gguf".into(),
gpu: false,
threads: None,
max_tokens: None,
cuda_device: None,
}
}
fn scratch(name: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("strata-vision-test-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn png(tag: u8) -> Vec<u8> {
let mut data = b"\x89PNG\r\n\x1a\n".to_vec();
data.push(tag);
data
}
fn data_url(bytes: &[u8]) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::from("data:image/png;base64,");
for chunk in bytes.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0u32, |n, (i, b)| n | u32::from(*b) << (16 - 8 * i));
for i in 0..4 {
if i <= chunk.len() {
out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
#[test]
fn arguments_and_environment_follow_the_python_server() {
let mut config = VisionConfig {
exe: "/bin/strata-vision".into(),
mmproj: "/m/p.gguf".into(),
model: "/m/t.gguf".into(),
gpu: true,
threads: Some(6),
max_tokens: Some(1024),
cuda_device: Some(2),
};
assert_eq!(
config.args(),
[
"--mmproj",
"/m/p.gguf",
"--model",
"/m/t.gguf",
"--gpu",
"--threads",
"6",
"--max-tokens",
"1024"
]
);
assert_eq!(
config.env(),
vec![
("CUDA_DEVICE_ORDER", "PCI_BUS_ID".to_owned()),
("CUDA_VISIBLE_DEVICES", "2".to_owned())
]
);
config.gpu = false;
config.threads = Some(0);
config.max_tokens = None;
config.cuda_device = None;
assert_eq!(
config.args(),
["--mmproj", "/m/p.gguf", "--model", "/m/t.gguf"]
);
assert!(config.env().is_empty());
assert!(
serde_json::from_str::<VisionConfig>(r#"{"exe":"a","mmproj":"b","model":"c","x":1}"#)
.is_err()
);
}
#[tokio::test]
async fn sources_load_like_the_python_server() {
let dir = scratch("load");
let file = dir.join("a.png");
std::fs::write(&file, png(1)).unwrap();
assert_eq!(Vision::load(file.to_str().unwrap()).await.unwrap(), png(1));
assert_eq!(
Vision::load(&format!("file://{}", file.display()))
.await
.unwrap(),
png(1)
);
assert_eq!(Vision::load(&data_url(&png(2))).await.unwrap(), png(2));
let nothing = "an image must be a data: URL, an http(s) URL or a local file path";
for source in ["", "nope.png", dir.to_str().unwrap()] {
assert_eq!(
Vision::load(source).await.unwrap_err(),
VisionError::Invalid(nothing.into())
);
}
assert_eq!(
Vision::load("data:image/png;base64,QQ").await.unwrap_err(),
VisionError::Invalid("Incorrect padding".into())
);
assert!(matches!(
Vision::load("data:image/png").await,
Err(VisionError::Invalid(_))
));
assert!(Vision::normalize(b"RIFF....WEBP".to_vec()).is_err());
assert_eq!(Vision::normalize(png(3)).unwrap(), png(3));
}
#[tokio::test]
async fn http_images_are_fetched_with_the_strata_agent() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/pic.png", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
let mut agents = Vec::new();
for status in ["200 OK", "404 Not Found"] {
let (mut socket, _) = listener.accept().await.unwrap();
let mut buffer = vec![0u8; 4096];
let n = socket.read(&mut buffer).await.unwrap();
agents.push(
String::from_utf8_lossy(&buffer[..n])
.lines()
.find(|l| l.to_ascii_lowercase().starts_with("user-agent"))
.unwrap_or("")
.to_owned(),
);
let body = png(9);
let head = format!(
"HTTP/1.1 {status}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
body.len()
);
socket.write_all(head.as_bytes()).await.unwrap();
socket.write_all(&body).await.unwrap();
}
agents
});
assert_eq!(Vision::load(&url).await.unwrap(), png(9));
assert!(
matches!(Vision::load(&url).await, Err(VisionError::Invalid(m)) if m.contains("404"))
);
assert!(server.await.unwrap().iter().all(|a| a.ends_with("strata")));
}
#[tokio::test]
async fn encoding_caches_by_content_and_combines_in_prompt_order() {
let dir = scratch("encode");
let vision = Vision::start(fake(&dir, "ok")).await.unwrap();
assert!(vision.alive().await);
let a = vision.encode(&data_url(&png(1))).await.unwrap();
let b = vision.encode(&data_url(&png(2))).await.unwrap();
let again = vision.encode(&data_url(&png(1))).await.unwrap();
assert_eq!((a.tokens, b.tokens), (6, 6));
assert_eq!(a, again, "the same picture is encoded once");
assert_ne!(a.path, b.path);
let log = std::fs::read_to_string(dir.join("enc.log")).unwrap();
assert_eq!(log.lines().count(), 2);
// The fake writes one SVE1 record whose first float carries the image's first byte count.
let (combined, keep) = vision
.combine(&[a.clone(), b.clone(), a.clone()])
.await
.unwrap();
let one = std::fs::read(&a.path).unwrap();
let two = std::fs::read(&b.path).unwrap();
let mut want = one.clone();
want.extend(&two);
want.extend(&one);
assert_eq!(std::fs::read(&combined).unwrap(), want);
let parsed = policy::parse_embeddings(&want, 4).unwrap();
assert_eq!(parsed.images.len(), 3);
assert_eq!((parsed.images[0].nx, parsed.images[0].ny), (3, 2));
drop(keep);
assert!(
!combined.exists(),
"the per-request file goes with the request"
);
// The temporary image is gone once its reply arrived.
assert!(std::fs::read_dir(vision.dir()).unwrap().all(|e| {
let name = e.unwrap().file_name().into_string().unwrap();
!name.ends_with(".img")
}));
vision.close().await;
assert!(!vision.alive().await);
}
#[tokio::test]
async fn encoder_errors_and_death_are_reported_like_the_python_server() {
let dir = scratch("err");
let vision = Vision::start(fake(&dir, "err")).await.unwrap();
assert_eq!(
vision.encode(&data_url(&png(1))).await.unwrap_err(),
VisionError::Invalid("the image could not be read: cannot read the image".into())
);
vision.close().await;
let dir = scratch("die");
let vision = Vision::start(fake(&dir, "die")).await.unwrap();
assert_eq!(
vision.encode(&data_url(&png(1))).await.unwrap_err(),
VisionError::Invalid("the image could not be read: the vision encoder stopped".into())
);
assert!(!vision.alive().await, "the process ended");
assert!(std::fs::read_dir(vision.dir()).unwrap().all(|e| {
!e.unwrap()
.file_name()
.into_string()
.unwrap()
.ends_with(".img")
}));
let dir = scratch("bad");
match Vision::start(fake(&dir, "badready")).await {
Err(VisionError::Failed(m)) => assert_eq!(m, "the vision encoder did not start: NOPE"),
other => panic!("{:?}", other.map(|_| ())),
}
}
#[tokio::test]
async fn unload_keeps_the_cache_and_restart_starts_the_encoder_again() {
let dir = scratch("unload");
let vision = Vision::start(fake(&dir, "ok")).await.unwrap();
let first = vision.encode(&data_url(&png(5))).await.unwrap();
vision.unload().await;
assert!(!vision.alive().await);
// cached images need no process
assert_eq!(vision.encode(&data_url(&png(5))).await.unwrap(), first);
vision.ensure_running().await.unwrap();
assert!(vision.alive().await);
vision.ensure_running().await.unwrap();
vision.encode(&data_url(&png(6))).await.unwrap();
assert_eq!(
std::fs::read_to_string(dir.join("starts.log"))
.unwrap()
.lines()
.count(),
2
);
vision.close().await;
}
#[tokio::test]
async fn the_cache_evicts_the_oldest_image_and_its_file() {
let dir = scratch("evict");
let vision = Vision::start(fake(&dir, "ok")).await.unwrap();
let mut first = None;
for tag in 0..=CACHE_LIMIT as u8 {
let encoded = vision.encode(&data_url(&png(tag))).await.unwrap();
first.get_or_insert(encoded);
}
assert!(!first.unwrap().path.exists());
assert_eq!(vision.inner.lock().await.cache.len(), CACHE_LIMIT);
vision.close().await;
}
}