[repo] Format, clippy clean, FORMATS.md, the full crate table in DEPENDENCIES.md

This commit is contained in:
2026-11-16 13:58:06 +01:00
parent 196802863a
commit a06e3f9b73
17 changed files with 2708 additions and 2125 deletions
+323 -312
View File
@@ -1,312 +1,323 @@
//! The app's side of the worker: spawn, send, wait with a time cap, and survive whatever the worker does.
//!
//! On Windows the worker runs inside a Job Object that caps its memory and kills it when the job handle closes (so
//! a worker never outlives the app). A request that exceeds its time cap kills the worker; the next request starts
//! a fresh one (open PDFs must then be opened again: the error kind says `restarted`).
use crate::{OpError, PROTOCOL};
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
use std::sync::{Arc, Mutex};
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct WorkerOptions {
pub exe: PathBuf,
/// Where pdfium.dll lives (passed as PICTOR_PDFIUM_DIR).
pub pdfium_dir: Option<PathBuf>,
/// The worker's memory cap.
pub memory_mb: u64,
/// Enables the debug.* operations (tests).
pub debug: bool,
}
impl WorkerOptions {
pub fn new(exe: impl Into<PathBuf>) -> WorkerOptions {
WorkerOptions { exe: exe.into(), pdfium_dir: None, memory_mb: 2048, debug: false }
}
}
#[derive(Debug, thiserror::Error)]
pub enum WorkerError {
/// The operation failed cleanly (bad file, wrong password, …): show `message`.
#[error("{0}")]
Op(OpError),
#[error("Pictor stopped reading this file after {0} seconds. It may be damaged or far too large.")]
TimedOut(u64),
#[error("Pictor ran out of memory reading this file and stopped. It may be damaged or far too large.")]
OutOfMemory,
#[error("Pictor's file reader stopped unexpectedly while reading this file. It may be damaged.")]
Crashed(String),
#[error("Pictor's file reader could not start: {0}")]
Spawn(String),
}
impl WorkerError {
/// A short machine-readable kind, like [`OpError::kind`].
pub fn kind(&self) -> &str {
match self {
WorkerError::Op(e) => &e.kind,
WorkerError::TimedOut(_) => "timed_out",
WorkerError::OutOfMemory => "out_of_memory",
WorkerError::Crashed(_) => "crashed",
WorkerError::Spawn(_) => "spawn",
}
}
}
struct Running {
child: Child,
stdin: ChildStdin,
lines: Receiver<String>,
stderr: Arc<Mutex<String>>,
#[cfg(windows)]
_job: job::Job,
}
pub struct Worker {
opts: WorkerOptions,
running: Option<Running>,
next_id: u64,
/// Set when the worker had to be restarted since the caller last asked (open documents are gone).
restarted: bool,
}
impl Worker {
pub fn new(opts: WorkerOptions) -> Worker {
Worker { opts, running: None, next_id: 1, restarted: false }
}
pub fn exe(&self) -> &Path {
&self.opts.exe
}
/// True once after the worker was restarted (its open documents are gone).
pub fn take_restarted(&mut self) -> bool {
std::mem::take(&mut self.restarted)
}
fn spawn(&mut self) -> Result<(), WorkerError> {
let mut cmd = Command::new(&self.opts.exe);
cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
if let Some(d) = &self.opts.pdfium_dir {
cmd.env("PICTOR_PDFIUM_DIR", d);
}
if self.opts.debug {
cmd.env("PICTOR_WORKER_DEBUG", "1");
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(format!("{}: {e}", self.opts.exe.display())))?;
#[cfg(windows)]
let job = match job::Job::new(self.opts.memory_mb).and_then(|j| j.assign(&child).map(|_| j)) {
Ok(j) => j,
Err(e) => {
let _ = child.kill();
return Err(WorkerError::Spawn(format!("job object: {e}")));
}
};
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let stderr_pipe = child.stderr.take().expect("piped");
let (tx, rx) = channel();
std::thread::spawn(move || {
let mut r = BufReader::new(stdout);
loop {
let mut line = String::new();
match r.read_line(&mut line) {
Ok(0) | Err(_) => return,
Ok(_) => {
if tx.send(line).is_err() {
return;
}
}
}
}
});
let stderr = Arc::new(Mutex::new(String::new()));
let sink = stderr.clone();
std::thread::spawn(move || {
let mut r = BufReader::new(stderr_pipe);
let mut line = String::new();
while let Ok(n) = r.read_line(&mut line) {
if n == 0 {
return;
}
let mut s = sink.lock().unwrap_or_else(|p| p.into_inner());
if s.len() < 16 << 10 {
s.push_str(&line);
}
line.clear();
}
});
let mut running = Running {
child,
stdin,
lines: rx,
stderr,
#[cfg(windows)]
_job: job,
};
let hello = running.lines.recv_timeout(Duration::from_secs(20)).map_err(|_| {
let _ = running.child.kill();
WorkerError::Spawn("it did not answer".into())
})?;
let hello: Value = serde_json::from_str(&hello).map_err(|e| WorkerError::Spawn(format!("bad hello: {e}")))?;
if hello["protocol"].as_u64() != Some(PROTOCOL as u64) {
let _ = running.child.kill();
return Err(WorkerError::Spawn(format!("it speaks protocol {}, Pictor needs {PROTOCOL}", hello["protocol"])));
}
self.running = Some(running);
Ok(())
}
fn kill(&mut self) {
if let Some(mut r) = self.running.take() {
let _ = r.child.kill();
let _ = r.child.wait();
self.restarted = true;
}
}
/// Runs `op` with `args`, waiting at most `timeout`. Starts (or restarts) the worker as needed.
pub fn call(&mut self, op: &str, args: Value, timeout: Duration) -> Result<Value, WorkerError> {
if self.running.as_mut().is_some_and(|r| r.child.try_wait().ok().flatten().is_some()) {
self.kill();
}
if self.running.is_none() {
self.spawn()?;
}
let id = self.next_id;
self.next_id += 1;
let r = self.running.as_mut().expect("spawned");
let line = json!({"id": id, "op": op, "args": args}).to_string();
if writeln!(r.stdin, "{line}").and_then(|_| r.stdin.flush()).is_err() {
return Err(self.died());
}
let deadline = std::time::Instant::now() + timeout;
loop {
let r = self.running.as_mut().expect("spawned");
let left = deadline.saturating_duration_since(std::time::Instant::now());
match r.lines.recv_timeout(left) {
Ok(text) => {
let v: Value = match serde_json::from_str(&text) {
Ok(v) => v,
Err(_) => continue,
};
if v["id"].as_u64() != Some(id) {
continue; // a late answer to a request that already timed out
}
if let Some(ok) = v.get("ok") {
return Ok(ok.clone());
}
let err: OpError = serde_json::from_value(v["err"].clone())
.unwrap_or_else(|_| OpError::new("damaged", "The file reader sent a bad answer."));
return Err(WorkerError::Op(err));
}
Err(RecvTimeoutError::Timeout) => {
self.kill();
return Err(WorkerError::TimedOut(timeout.as_secs().max(1)));
}
Err(RecvTimeoutError::Disconnected) => return Err(self.died()),
}
}
}
fn died(&mut self) -> WorkerError {
let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or_default();
// Give the stderr thread a moment to collect the last words.
std::thread::sleep(Duration::from_millis(50));
let stderr = self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr);
// pdfium aborts without a word when an allocation fails; the job's peak memory tells that story.
#[cfg(windows)]
let hit_cap = self.running.as_ref().and_then(|r| r._job.peak_bytes()).is_some_and(|peak| peak * 10 >= (self.opts.memory_mb << 20) * 9);
#[cfg(not(windows))]
let hit_cap = false;
self.kill();
if hit_cap || stderr.contains("memory allocation") || stderr.contains("out of memory") {
WorkerError::OutOfMemory
} else {
WorkerError::Crashed(stderr.lines().last().unwrap_or("").to_string())
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.kill();
}
}
#[cfg(windows)]
mod job {
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::System::JobObjects::*;
use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
pub struct Job(HANDLE);
unsafe impl Send for Job {}
impl Job {
pub fn new(memory_mb: u64) -> Result<Job, String> {
unsafe {
let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?;
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20;
SetInformationJobObject(
h,
JobObjectExtendedLimitInformation,
&info as *const _ as *const _,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
.map_err(|e| {
let _ = CloseHandle(h);
e.to_string()
})?;
Ok(Job(h))
}
}
pub fn assign(&self, child: &std::process::Child) -> Result<(), String> {
unsafe {
let p = OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?;
let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string());
let _ = CloseHandle(p);
r
}
}
}
impl Job {
/// The most memory the worker ever committed, in bytes.
pub fn peak_bytes(&self) -> Option<u64> {
unsafe {
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
QueryInformationJobObject(
Some(self.0),
JobObjectExtendedLimitInformation,
&mut info as *mut _ as *mut _,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
None,
)
.ok()?;
Some(info.PeakProcessMemoryUsed as u64)
}
}
}
impl Drop for Job {
fn drop(&mut self) {
unsafe {
let _ = CloseHandle(self.0);
}
}
}
}
//! The app's side of the worker: spawn, send, wait with a time cap, and survive whatever the worker does.
//!
//! On Windows the worker runs inside a Job Object that caps its memory and kills it when the job handle closes (so
//! a worker never outlives the app). A request that exceeds its time cap kills the worker; the next request starts
//! a fresh one (open PDFs must then be opened again: the error kind says `restarted`).
use crate::{OpError, PROTOCOL};
use serde_json::{Value, json};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::mpsc::{Receiver, RecvTimeoutError, channel};
use std::sync::{Arc, Mutex};
use std::time::Duration;
#[derive(Debug, Clone)]
pub struct WorkerOptions {
pub exe: PathBuf,
/// Where pdfium.dll lives (passed as PICTOR_PDFIUM_DIR).
pub pdfium_dir: Option<PathBuf>,
/// The worker's memory cap.
pub memory_mb: u64,
/// Enables the debug.* operations (tests).
pub debug: bool,
}
impl WorkerOptions {
pub fn new(exe: impl Into<PathBuf>) -> WorkerOptions {
WorkerOptions { exe: exe.into(), pdfium_dir: None, memory_mb: 2048, debug: false }
}
}
#[derive(Debug, thiserror::Error)]
pub enum WorkerError {
/// The operation failed cleanly (bad file, wrong password, …): show `message`.
#[error("{0}")]
Op(OpError),
#[error("Pictor stopped reading this file after {0} seconds. It may be damaged or far too large.")]
TimedOut(u64),
#[error("Pictor ran out of memory reading this file and stopped. It may be damaged or far too large.")]
OutOfMemory,
#[error("Pictor's file reader stopped unexpectedly while reading this file. It may be damaged.")]
Crashed(String),
#[error("Pictor's file reader could not start: {0}")]
Spawn(String),
}
impl WorkerError {
/// A short machine-readable kind, like [`OpError::kind`].
pub fn kind(&self) -> &str {
match self {
WorkerError::Op(e) => &e.kind,
WorkerError::TimedOut(_) => "timed_out",
WorkerError::OutOfMemory => "out_of_memory",
WorkerError::Crashed(_) => "crashed",
WorkerError::Spawn(_) => "spawn",
}
}
}
struct Running {
child: Child,
stdin: ChildStdin,
lines: Receiver<String>,
stderr: Arc<Mutex<String>>,
#[cfg(windows)]
_job: job::Job,
}
pub struct Worker {
opts: WorkerOptions,
running: Option<Running>,
next_id: u64,
/// Set when the worker had to be restarted since the caller last asked (open documents are gone).
restarted: bool,
}
impl Worker {
pub fn new(opts: WorkerOptions) -> Worker {
Worker { opts, running: None, next_id: 1, restarted: false }
}
pub fn exe(&self) -> &Path {
&self.opts.exe
}
/// True once after the worker was restarted (its open documents are gone).
pub fn take_restarted(&mut self) -> bool {
std::mem::take(&mut self.restarted)
}
fn spawn(&mut self) -> Result<(), WorkerError> {
let mut cmd = Command::new(&self.opts.exe);
cmd.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped());
if let Some(d) = &self.opts.pdfium_dir {
cmd.env("PICTOR_PDFIUM_DIR", d);
}
if self.opts.debug {
cmd.env("PICTOR_WORKER_DEBUG", "1");
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(format!("{}: {e}", self.opts.exe.display())))?;
#[cfg(windows)]
let job = match job::Job::new(self.opts.memory_mb).and_then(|j| j.assign(&child).map(|_| j)) {
Ok(j) => j,
Err(e) => {
let _ = child.kill();
return Err(WorkerError::Spawn(format!("job object: {e}")));
}
};
let stdin = child.stdin.take().expect("piped");
let stdout = child.stdout.take().expect("piped");
let stderr_pipe = child.stderr.take().expect("piped");
let (tx, rx) = channel();
std::thread::spawn(move || {
let mut r = BufReader::new(stdout);
loop {
let mut line = String::new();
match r.read_line(&mut line) {
Ok(0) | Err(_) => return,
Ok(_) => {
if tx.send(line).is_err() {
return;
}
}
}
}
});
let stderr = Arc::new(Mutex::new(String::new()));
let sink = stderr.clone();
std::thread::spawn(move || {
let mut r = BufReader::new(stderr_pipe);
let mut line = String::new();
while let Ok(n) = r.read_line(&mut line) {
if n == 0 {
return;
}
let mut s = sink.lock().unwrap_or_else(|p| p.into_inner());
if s.len() < 16 << 10 {
s.push_str(&line);
}
line.clear();
}
});
let mut running = Running {
child,
stdin,
lines: rx,
stderr,
#[cfg(windows)]
_job: job,
};
let hello = running.lines.recv_timeout(Duration::from_secs(20)).map_err(|_| {
let _ = running.child.kill();
WorkerError::Spawn("it did not answer".into())
})?;
let hello: Value = serde_json::from_str(&hello).map_err(|e| WorkerError::Spawn(format!("bad hello: {e}")))?;
if hello["protocol"].as_u64() != Some(PROTOCOL as u64) {
let _ = running.child.kill();
return Err(WorkerError::Spawn(format!(
"it speaks protocol {}, Pictor needs {PROTOCOL}",
hello["protocol"]
)));
}
self.running = Some(running);
Ok(())
}
fn kill(&mut self) {
if let Some(mut r) = self.running.take() {
let _ = r.child.kill();
let _ = r.child.wait();
self.restarted = true;
}
}
/// Runs `op` with `args`, waiting at most `timeout`. Starts (or restarts) the worker as needed.
pub fn call(&mut self, op: &str, args: Value, timeout: Duration) -> Result<Value, WorkerError> {
if self.running.as_mut().is_some_and(|r| r.child.try_wait().ok().flatten().is_some()) {
self.kill();
}
if self.running.is_none() {
self.spawn()?;
}
let id = self.next_id;
self.next_id += 1;
let r = self.running.as_mut().expect("spawned");
let line = json!({"id": id, "op": op, "args": args}).to_string();
if writeln!(r.stdin, "{line}").and_then(|_| r.stdin.flush()).is_err() {
return Err(self.died());
}
let deadline = std::time::Instant::now() + timeout;
loop {
let r = self.running.as_mut().expect("spawned");
let left = deadline.saturating_duration_since(std::time::Instant::now());
match r.lines.recv_timeout(left) {
Ok(text) => {
let v: Value = match serde_json::from_str(&text) {
Ok(v) => v,
Err(_) => continue,
};
if v["id"].as_u64() != Some(id) {
continue; // a late answer to a request that already timed out
}
if let Some(ok) = v.get("ok") {
return Ok(ok.clone());
}
let err: OpError = serde_json::from_value(v["err"].clone())
.unwrap_or_else(|_| OpError::new("damaged", "The file reader sent a bad answer."));
return Err(WorkerError::Op(err));
}
Err(RecvTimeoutError::Timeout) => {
self.kill();
return Err(WorkerError::TimedOut(timeout.as_secs().max(1)));
}
Err(RecvTimeoutError::Disconnected) => return Err(self.died()),
}
}
}
fn died(&mut self) -> WorkerError {
let stderr =
self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or_default();
// Give the stderr thread a moment to collect the last words.
std::thread::sleep(Duration::from_millis(50));
let stderr =
self.running.as_ref().map(|r| r.stderr.lock().map(|s| s.clone()).unwrap_or_default()).unwrap_or(stderr);
// pdfium aborts without a word when an allocation fails; the job's peak memory tells that story.
#[cfg(windows)]
let hit_cap = self
.running
.as_ref()
.and_then(|r| r._job.peak_bytes())
.is_some_and(|peak| peak * 10 >= (self.opts.memory_mb << 20) * 9);
#[cfg(not(windows))]
let hit_cap = false;
self.kill();
if hit_cap || stderr.contains("memory allocation") || stderr.contains("out of memory") {
WorkerError::OutOfMemory
} else {
WorkerError::Crashed(stderr.lines().last().unwrap_or("").to_string())
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.kill();
}
}
#[cfg(windows)]
mod job {
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::System::JobObjects::*;
use windows::Win32::System::Threading::{OpenProcess, PROCESS_SET_QUOTA, PROCESS_TERMINATE};
pub struct Job(HANDLE);
unsafe impl Send for Job {}
impl Job {
pub fn new(memory_mb: u64) -> Result<Job, String> {
unsafe {
let h = CreateJobObjectW(None, None).map_err(|e| e.to_string())?;
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
info.BasicLimitInformation.LimitFlags =
JOB_OBJECT_LIMIT_PROCESS_MEMORY | JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
info.ProcessMemoryLimit = (memory_mb.max(64) as usize) << 20;
SetInformationJobObject(
h,
JobObjectExtendedLimitInformation,
&info as *const _ as *const _,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
.map_err(|e| {
let _ = CloseHandle(h);
e.to_string()
})?;
Ok(Job(h))
}
}
pub fn assign(&self, child: &std::process::Child) -> Result<(), String> {
unsafe {
let p =
OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, false, child.id()).map_err(|e| e.to_string())?;
let r = AssignProcessToJobObject(self.0, p).map_err(|e| e.to_string());
let _ = CloseHandle(p);
r
}
}
}
impl Job {
/// The most memory the worker ever committed, in bytes.
pub fn peak_bytes(&self) -> Option<u64> {
unsafe {
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
QueryInformationJobObject(
Some(self.0),
JobObjectExtendedLimitInformation,
&mut info as *mut _ as *mut _,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
None,
)
.ok()?;
Some(info.PeakProcessMemoryUsed as u64)
}
}
}
impl Drop for Job {
fn drop(&mut self) {
unsafe {
let _ = CloseHandle(self.0);
}
}
}
}
+5 -1
View File
@@ -31,7 +31,11 @@ fn main() {
let req: Value = match serde_json::from_str(line.trim_end()) {
Ok(v) => v,
Err(e) => {
let _ = writeln!(out, "{}", json!({"id": null, "err": OpError::new("invalid", format!("bad request line: {e}"))}));
let _ = writeln!(
out,
"{}",
json!({"id": null, "err": OpError::new("invalid", format!("bad request line: {e}"))})
);
let _ = out.flush();
continue;
}
+11 -5
View File
@@ -238,8 +238,11 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
}
let a: A = args(a)?;
let engine = state.engine()?;
let files: Vec<(Vec<u8>, Option<String>)> =
a.inputs.iter().map(|i| read_file(&i.path).map(|b| (b, i.password.clone()))).collect::<Result<_, _>>()?;
let files: Vec<(Vec<u8>, Option<String>)> = a
.inputs
.iter()
.map(|i| read_file(&i.path).map(|b| (b, i.password.clone())))
.collect::<Result<_, _>>()?;
let refs: Vec<(&[u8], Option<&str>)> = files.iter().map(|(b, p)| (b.as_slice(), p.as_deref())).collect();
let bytes = pictor_pdf::merge(engine, &refs)?;
write_out(&a.output, &bytes, SaveMode::New)
@@ -309,7 +312,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
let bytes = read_file(&a.path)?;
let img = pictor_raster::decode(&bytes, &Limits::default())?;
let (w, h) = (img.width(), img.height());
let t = pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?;
let t =
pictor_raster::resize(&img, pictor_raster::Fit::LongEdge(a.max.clamp(16, 2048)), &Limits::default())?;
Ok(json!({"png": b64(&png(&t)?), "width": w, "height": h}))
}
"image.convert" => {
@@ -347,7 +351,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
if let Some(f) = a.resize {
img = pictor_raster::resize(&img, f, &limits)?;
}
let format = Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose an output format."))?;
let format =
Format::from_name(&a.format).ok_or_else(|| OpError::new("invalid", "Choose an output format."))?;
let (bytes, format) = if let Some(target) = a.target_bytes {
let c = pictor_raster::compress_to(&img, format, target, &limits)?;
(c.bytes, c.format)
@@ -391,7 +396,8 @@ pub fn dispatch(state: &mut State, op: &str, a: Value) -> Result<Value, OpError>
let a: A = args(a)?;
let bytes = read_file(&a.input)?;
let stripped = pictor_meta::strip(&bytes)?;
let mut out = write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?;
let mut out =
write_out(&a.output, &stripped.bytes, if a.overwrite { SaveMode::Overwrite } else { SaveMode::New })?;
out["removed"] = json!(stripped.removed);
Ok(out)
}
+335 -294
View File
@@ -1,294 +1,335 @@
//! Mandatory test 2: hostile PDFs. Each fixture goes through the real worker process (open, render page 1, text,
//! metadata, a save with an annotation). Every step either works or fails with a typed error within its time cap;
//! a worker that crashes, hangs or runs out of memory is reported as such and replaced. This test process plays the
//! tray: it must never crash, and the next request after a bad file must work.
//! Fixtures are generated here; fixtures-fetch/fetch.ps1 adds real-world corpora under fixtures/fetched/ (optional).
use flate2::{Compression, write::ZlibEncoder};
use lopdf::{Document, Object, Stream, dictionary};
use pictor_worker::client::{Worker, WorkerError, WorkerOptions};
use serde_json::json;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
const CAP: Duration = Duration::from_secs(15);
fn worker() -> Worker {
let mut o = WorkerOptions::new(env!("CARGO_BIN_EXE_pictor-worker"));
o.pdfium_dir = Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
o.memory_mb = 1024;
o.debug = true;
Worker::new(o)
}
fn base_doc(content: &[u8]) -> Document {
let mut doc = Document::with_version("1.7");
let pages = doc.new_object_id();
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
let c = doc.add_object(Stream::new(dictionary! {}, content.to_vec()));
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages, "Contents" => c,
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}});
doc.objects.insert(pages, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1,
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}));
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
doc.trailer.set("Root", cat);
doc
}
fn save(mut doc: Document) -> Vec<u8> {
let mut v = Vec::new();
doc.save_to(&mut v).unwrap();
v
}
fn valid() -> Vec<u8> {
save(base_doc(b"BT /F1 24 Tf 72 700 Td (Hello hostile world) Tj ET"))
}
fn replace(hay: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
let i = hay.windows(from.len()).position(|w| w == from).expect("pattern");
[&hay[..i], to, &hay[i + from.len()..]].concat()
}
fn font_doc(font_key: &str, font_bytes: Vec<u8>) -> Vec<u8> {
let mut doc = base_doc(b"BT /F2 24 Tf 72 700 Td (Font) Tj ET");
let ff = doc.add_object(Stream::new(dictionary! {}, font_bytes));
let desc = doc.add_object(dictionary! {"Type" => "FontDescriptor", "FontName" => "Broken", "Flags" => 32,
"FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800,
"Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff});
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" },
"BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc});
let page = *doc.get_pages().values().next().unwrap();
doc.get_dictionary_mut(page).unwrap().set("Resources", dictionary! {"Font" => dictionary! {"F2" => font}});
save(doc)
}
fn fixtures() -> Vec<(&'static str, Vec<u8>)> {
let v = valid();
let mut out: Vec<(&str, Vec<u8>)> = vec![
("empty file", Vec::new()),
("header only", b"%PDF-1.7\n".to_vec()),
("truncated at 10%", v[..v.len() / 10].to_vec()),
("truncated at 50%", v[..v.len() / 2].to_vec()),
("truncated before the trailer", v[..v.len() - 40].to_vec()),
("random bytes after a header", {
let mut x = b"%PDF-1.7\n".to_vec();
let mut s = 0x2545_4446u32;
for _ in 0..20_000 {
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
x.push(s as u8);
}
x
}),
];
// Broken xref: startxref points nowhere, then the table itself is garbage.
let sx = v.windows(9).rposition(|w| w == b"startxref").unwrap();
out.push(("startxref beyond the end", [&v[..sx], b"startxref\n99999999\n%%EOF\n"].concat()));
// lopdf writes a cross-reference stream: garble its binary table, or cut it off and leave a bare trailer.
let xr = v.windows(10).rposition(|w| w == b"/Type/XRef").unwrap();
let obj_kw = v[..xr].windows(4).rposition(|w| w == b"obj\n").unwrap();
let xr_obj = v[..obj_kw].iter().rposition(|&b| b == b'\n').map(|i| i + 1).unwrap_or(0);
let mut garbled = v.clone();
let data = xr + garbled[xr..].windows(7).position(|w| w == b"stream\n").unwrap() + 7;
let end = (data + 40).min(garbled.len());
for b in garbled[data..end].iter_mut() {
*b = b.wrapping_mul(31).wrapping_add(7);
}
out.push(("garbled xref table", garbled));
out.push(("no xref at all", [&v[..xr_obj], b"trailer\n<< /Root 5 0 R >>\n%%EOF\n"].concat()));
// Recursive references.
{
let mut doc = base_doc(b"");
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
doc.get_dictionary_mut(pages).unwrap().set("Kids", vec![Object::Reference(pages)]);
out.push(("page tree that contains itself", save(doc)));
}
{
let mut doc = base_doc(b"");
let page = *doc.get_pages().values().next().unwrap();
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
doc.get_dictionary_mut(pages).unwrap().set("Parent", Object::Reference(page));
out.push(("parent loop", save(doc)));
}
out.push(("object that is a reference to itself", replace(&valid(), b"/Contents 3 0 R", b"/Contents 99 0 R").into_iter().chain(b"\n99 0 obj\n99 0 R\nendobj\n".iter().copied()).collect()));
out.push(("deeply nested arrays", {
let mut deep = vec![b'['; 200_000];
deep.extend(vec![b']'; 200_000]);
replace(&valid(), b"/Type/Catalog", &[b"/Type/Catalog /Deep ".as_slice(), &deep].concat())
}));
out.push(("page count of two billion", replace(&valid(), b"/Count 1", b"/Count 2147483647")));
out.push(("media box of 1e30 points", replace(&valid(), b"/MediaBox[0 0 595 842]", b"/MediaBox[0 0 1e30 1e30]")));
// A 1 GB declared stream, and a deflate bomb that expands to 1 GiB.
{
let doc = base_doc(b"BT /F1 24 Tf 72 700 Td (x) Tj ET");
let bytes = save(doc);
let i = bytes.windows(7).position(|w| w == b"/Length").unwrap();
let end = i + bytes[i..].iter().position(|&b| b == b'>').unwrap();
out.push(("stream that declares 1 GB", [&bytes[..i], b"/Length 1073741824", &bytes[end..]].concat()));
}
{
let mut z = ZlibEncoder::new(Vec::new(), Compression::best());
let zeros = vec![b' '; 1 << 20];
for _ in 0..1024 {
z.write_all(&zeros).unwrap();
}
let bomb = z.finish().unwrap();
let mut doc = base_doc(b"");
let page = *doc.get_pages().values().next().unwrap();
let c = doc.add_object(Stream::new(dictionary! {"Filter" => "FlateDecode"}, bomb).with_compression(false));
doc.get_dictionary_mut(page).unwrap().set("Contents", c);
out.push(("content stream that inflates to 1 GiB", save(doc)));
}
// Malformed fonts.
out.push(("TrueType font of garbage", font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect())));
out.push(("TrueType claiming 65535 tables", font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat())));
out.push(("truncated Type 1 font", font_doc("FontFile", b"%!PS-AdobeFont-1.0: Broken\n/FontName /Broken def\neexec\x00\x01".to_vec())));
// Encryption with a handler that does not exist.
out.push(("unknown security handler", replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>")));
out
}
fn fetched() -> Vec<(String, Vec<u8>)> {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched");
let Ok(rd) = std::fs::read_dir(&dir) else { return Vec::new() };
let mut v: Vec<(String, Vec<u8>)> = rd
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("pdf")))
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap()))
.collect();
v.sort();
v
}
#[derive(Default, Debug)]
struct Tally {
ok: usize,
typed_error: usize,
timed_out: usize,
out_of_memory: usize,
crashed: usize,
}
fn run(w: &mut Worker, tally: &mut Tally, name: &str, op: &str, args: serde_json::Value) {
let start = Instant::now();
let r = w.call(op, args, CAP);
let took = start.elapsed();
assert!(took < CAP + Duration::from_secs(5), "{name}: {op} took {took:?}, past its cap");
let outcome = match &r {
Ok(_) => {
tally.ok += 1;
"ok".to_string()
}
Err(WorkerError::Op(e)) => {
assert!(!e.message.is_empty() && !e.message.contains("panicked"), "{name}: unclear message {e:?}");
tally.typed_error += 1;
format!("{} ({})", e.kind, e.message)
}
Err(WorkerError::TimedOut(_)) => {
tally.timed_out += 1;
"timed out".into()
}
Err(WorkerError::OutOfMemory) => {
tally.out_of_memory += 1;
"out of memory".into()
}
Err(WorkerError::Crashed(m)) => {
tally.crashed += 1;
format!("crashed: {m}")
}
Err(WorkerError::Spawn(e)) => panic!("worker would not start: {e}"),
};
println!("{name:40} {op:10} {took:>8.2?} {outcome}");
}
#[test]
fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() {
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
let mut w = worker();
let mut tally = Tally::default();
let mut all: Vec<(String, Vec<u8>)> = fixtures().into_iter().map(|(n, b)| (n.to_string(), b)).collect();
all.extend(fetched());
let annotation = json!({"annotations": [{"page": 0, "kind": "highlight", "rects": [{"x": 10, "y": 10, "w": 50, "h": 10}]}]});
for (i, (name, bytes)) in all.iter().enumerate() {
let path = dir.path().join(format!("f{i}.pdf"));
std::fs::write(&path, bytes).unwrap();
let p = path.to_string_lossy().to_string();
let start = Instant::now();
let opened = w.call("pdf.open", json!({"path": p}), CAP);
let took = start.elapsed();
let doc = match &opened {
Ok(v) => {
tally.ok += 1;
println!("{name:40} {:10} {took:>8.2?} ok, {} pages", "open", v["info"]["pages"].as_array().map(|a| a.len()).unwrap_or(0));
v["doc"].as_u64()
}
Err(e) => {
match e {
WorkerError::Op(_) => tally.typed_error += 1,
WorkerError::TimedOut(_) => tally.timed_out += 1,
WorkerError::OutOfMemory => tally.out_of_memory += 1,
WorkerError::Crashed(_) => tally.crashed += 1,
WorkerError::Spawn(e) => panic!("{e}"),
}
println!("{name:40} {:10} {took:>8.2?} {} ({e})", "open", e.kind());
None
}
};
if let Some(doc) = doc {
run(&mut w, &mut tally, name, "pdf.render", json!({"doc": doc, "page": 0, "width": 800}));
if w.take_restarted() {
continue;
}
run(&mut w, &mut tally, name, "pdf.text", json!({"doc": doc}));
if w.take_restarted() {
continue;
}
let out = dir.path().join(format!("f{i}-edited.pdf")).to_string_lossy().to_string();
run(&mut w, &mut tally, name, "pdf.save", json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"}));
}
run(&mut w, &mut tally, name, "meta.read", json!({"path": p}));
w.take_restarted();
// The tray carries on: a normal request right after works.
let good = dir.path().join("good.pdf");
std::fs::write(&good, valid()).unwrap();
let r = w.call("pdf.open", json!({"path": good.to_string_lossy()}), CAP).expect("a good PDF after a bad one");
w.call("pdf.close", json!({"doc": r["doc"]}), CAP).unwrap();
}
println!("{} fixtures: {tally:?}", all.len());
assert!(all.len() >= 21);
assert_eq!(tally.timed_out, 0, "a fixture hung");
assert_eq!(tally.crashed, 0, "a worker died without a known cause");
}
#[test]
fn the_client_survives_crash_hang_and_memory_blowup() {
let mut w = worker();
let crash = w.call("debug.crash", json!({}), CAP);
assert!(matches!(crash, Err(WorkerError::Crashed(_))), "{crash:?}");
assert!(w.take_restarted());
let start = Instant::now();
let hang = w.call("debug.sleep", json!({"secs": 120}), Duration::from_secs(2));
assert!(matches!(hang, Err(WorkerError::TimedOut(_))), "{hang:?}");
assert!(start.elapsed() < Duration::from_secs(10));
let oom = w.call("debug.alloc", json!({"mb": 3000}), CAP);
// try_reserve fails cleanly under the cap (a typed error); a hard allocation would be OutOfMemory.
assert!(matches!(&oom, Err(WorkerError::OutOfMemory) | Err(WorkerError::Op(_))), "the 1 GB memory cap did not hold: {oom:?}");
// And it works again.
let ok = w.call("image.heif_support", json!({}), CAP).unwrap();
assert!(ok["support"].is_string());
}
#[test]
fn unknown_operations_and_bad_arguments_are_typed_errors() {
let mut w = worker();
for (op, args) in [("nope", json!({})), ("pdf.open", json!({"wrong": 1})), ("pdf.render", json!({"doc": 77, "page": 0, "width": 10}))] {
match w.call(op, args, CAP) {
Err(WorkerError::Op(e)) => assert!(["invalid", "not_open"].contains(&e.kind.as_str()), "{e:?}"),
other => panic!("{op}: {other:?}"),
}
}
let missing = w.call("pdf.open", json!({"path": "F:/definitely/not/here.pdf"}), CAP);
assert!(matches!(missing, Err(WorkerError::Op(ref e)) if e.kind == "io"), "{missing:?}");
}
//! Mandatory test 2: hostile PDFs. Each fixture goes through the real worker process (open, render page 1, text,
//! metadata, a save with an annotation). Every step either works or fails with a typed error within its time cap;
//! a worker that crashes, hangs or runs out of memory is reported as such and replaced. This test process plays the
//! tray: it must never crash, and the next request after a bad file must work.
//! Fixtures are generated here; fixtures-fetch/fetch.ps1 adds real-world corpora under fixtures/fetched/ (optional).
use flate2::{Compression, write::ZlibEncoder};
use lopdf::{Document, Object, Stream, dictionary};
use pictor_worker::client::{Worker, WorkerError, WorkerOptions};
use serde_json::json;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
const CAP: Duration = Duration::from_secs(15);
fn worker() -> Worker {
let mut o = WorkerOptions::new(env!("CARGO_BIN_EXE_pictor-worker"));
o.pdfium_dir = Some(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin"));
o.memory_mb = 1024;
o.debug = true;
Worker::new(o)
}
fn base_doc(content: &[u8]) -> Document {
let mut doc = Document::with_version("1.7");
let pages = doc.new_object_id();
let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"});
let c = doc.add_object(Stream::new(dictionary! {}, content.to_vec()));
let page = doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages, "Contents" => c,
"Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}});
doc.objects.insert(
pages,
Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => vec![page.into()], "Count" => 1,
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}),
);
let cat = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages});
doc.trailer.set("Root", cat);
doc
}
fn save(mut doc: Document) -> Vec<u8> {
let mut v = Vec::new();
doc.save_to(&mut v).unwrap();
v
}
fn valid() -> Vec<u8> {
save(base_doc(b"BT /F1 24 Tf 72 700 Td (Hello hostile world) Tj ET"))
}
fn replace(hay: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
let i = hay.windows(from.len()).position(|w| w == from).expect("pattern");
[&hay[..i], to, &hay[i + from.len()..]].concat()
}
fn font_doc(font_key: &str, font_bytes: Vec<u8>) -> Vec<u8> {
let mut doc = base_doc(b"BT /F2 24 Tf 72 700 Td (Font) Tj ET");
let ff = doc.add_object(Stream::new(dictionary! {}, font_bytes));
let desc = doc.add_object(dictionary! {"Type" => "FontDescriptor", "FontName" => "Broken", "Flags" => 32,
"FontBBox" => vec![0.into(), 0.into(), 1000.into(), 1000.into()], "ItalicAngle" => 0, "Ascent" => 800,
"Descent" => -200, "CapHeight" => 700, "StemV" => 80, font_key => ff});
let font = doc.add_object(
dictionary! {"Type" => "Font", "Subtype" => if font_key == "FontFile" { "Type1" } else { "TrueType" },
"BaseFont" => "Broken", "FirstChar" => 32, "LastChar" => 126, "FontDescriptor" => desc},
);
let page = *doc.get_pages().values().next().unwrap();
doc.get_dictionary_mut(page).unwrap().set("Resources", dictionary! {"Font" => dictionary! {"F2" => font}});
save(doc)
}
fn fixtures() -> Vec<(&'static str, Vec<u8>)> {
let v = valid();
let mut out: Vec<(&str, Vec<u8>)> = vec![
("empty file", Vec::new()),
("header only", b"%PDF-1.7\n".to_vec()),
("truncated at 10%", v[..v.len() / 10].to_vec()),
("truncated at 50%", v[..v.len() / 2].to_vec()),
("truncated before the trailer", v[..v.len() - 40].to_vec()),
("random bytes after a header", {
let mut x = b"%PDF-1.7\n".to_vec();
let mut s = 0x2545_4446u32;
for _ in 0..20_000 {
s ^= s << 13;
s ^= s >> 17;
s ^= s << 5;
x.push(s as u8);
}
x
}),
];
// Broken xref: startxref points nowhere, then the table itself is garbage.
let sx = v.windows(9).rposition(|w| w == b"startxref").unwrap();
out.push(("startxref beyond the end", [&v[..sx], b"startxref\n99999999\n%%EOF\n"].concat()));
// lopdf writes a cross-reference stream: garble its binary table, or cut it off and leave a bare trailer.
let xr = v.windows(10).rposition(|w| w == b"/Type/XRef").unwrap();
let obj_kw = v[..xr].windows(4).rposition(|w| w == b"obj\n").unwrap();
let xr_obj = v[..obj_kw].iter().rposition(|&b| b == b'\n').map(|i| i + 1).unwrap_or(0);
let mut garbled = v.clone();
let data = xr + garbled[xr..].windows(7).position(|w| w == b"stream\n").unwrap() + 7;
let end = (data + 40).min(garbled.len());
for b in garbled[data..end].iter_mut() {
*b = b.wrapping_mul(31).wrapping_add(7);
}
out.push(("garbled xref table", garbled));
out.push(("no xref at all", [&v[..xr_obj], b"trailer\n<< /Root 5 0 R >>\n%%EOF\n"].concat()));
// Recursive references.
{
let mut doc = base_doc(b"");
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
doc.get_dictionary_mut(pages).unwrap().set("Kids", vec![Object::Reference(pages)]);
out.push(("page tree that contains itself", save(doc)));
}
{
let mut doc = base_doc(b"");
let page = *doc.get_pages().values().next().unwrap();
let pages = doc.catalog().unwrap().get(b"Pages").unwrap().as_reference().unwrap();
doc.get_dictionary_mut(pages).unwrap().set("Parent", Object::Reference(page));
out.push(("parent loop", save(doc)));
}
out.push((
"object that is a reference to itself",
replace(&valid(), b"/Contents 3 0 R", b"/Contents 99 0 R")
.into_iter()
.chain(b"\n99 0 obj\n99 0 R\nendobj\n".iter().copied())
.collect(),
));
out.push(("deeply nested arrays", {
let mut deep = vec![b'['; 200_000];
deep.extend(vec![b']'; 200_000]);
replace(&valid(), b"/Type/Catalog", &[b"/Type/Catalog /Deep ".as_slice(), &deep].concat())
}));
out.push(("page count of two billion", replace(&valid(), b"/Count 1", b"/Count 2147483647")));
out.push(("media box of 1e30 points", replace(&valid(), b"/MediaBox[0 0 595 842]", b"/MediaBox[0 0 1e30 1e30]")));
// A 1 GB declared stream, and a deflate bomb that expands to 1 GiB.
{
let doc = base_doc(b"BT /F1 24 Tf 72 700 Td (x) Tj ET");
let bytes = save(doc);
let i = bytes.windows(7).position(|w| w == b"/Length").unwrap();
let end = i + bytes[i..].iter().position(|&b| b == b'>').unwrap();
out.push(("stream that declares 1 GB", [&bytes[..i], b"/Length 1073741824", &bytes[end..]].concat()));
}
{
let mut z = ZlibEncoder::new(Vec::new(), Compression::best());
let zeros = vec![b' '; 1 << 20];
for _ in 0..1024 {
z.write_all(&zeros).unwrap();
}
let bomb = z.finish().unwrap();
let mut doc = base_doc(b"");
let page = *doc.get_pages().values().next().unwrap();
let c = doc.add_object(Stream::new(dictionary! {"Filter" => "FlateDecode"}, bomb).with_compression(false));
doc.get_dictionary_mut(page).unwrap().set("Contents", c);
out.push(("content stream that inflates to 1 GiB", save(doc)));
}
// Malformed fonts.
out.push((
"TrueType font of garbage",
font_doc("FontFile2", (0..4096u32).map(|i| (i * 7919 % 251) as u8).collect()),
));
out.push((
"TrueType claiming 65535 tables",
font_doc("FontFile2", [&[0, 1, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0, 0, 0][..], &[0x41; 64]].concat()),
));
out.push((
"truncated Type 1 font",
font_doc("FontFile", b"%!PS-AdobeFont-1.0: Broken\n/FontName /Broken def\neexec\x00\x01".to_vec()),
));
// Encryption with a handler that does not exist.
out.push((
"unknown security handler",
replace(&valid(), b"/Root 5 0 R", b"/Root 5 0 R /Encrypt << /Filter /Bogus /V 9 /R 9 >>"),
));
out
}
fn fetched() -> Vec<(String, Vec<u8>)> {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/fetched");
let Ok(rd) = std::fs::read_dir(&dir) else { return Vec::new() };
let mut v: Vec<(String, Vec<u8>)> = rd
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().is_some_and(|x| x.eq_ignore_ascii_case("pdf")))
.map(|e| (e.file_name().to_string_lossy().into_owned(), std::fs::read(e.path()).unwrap()))
.collect();
v.sort();
v
}
#[derive(Default, Debug)]
struct Tally {
ok: usize,
typed_error: usize,
timed_out: usize,
out_of_memory: usize,
crashed: usize,
}
fn run(w: &mut Worker, tally: &mut Tally, name: &str, op: &str, args: serde_json::Value) {
let start = Instant::now();
let r = w.call(op, args, CAP);
let took = start.elapsed();
assert!(took < CAP + Duration::from_secs(5), "{name}: {op} took {took:?}, past its cap");
let outcome = match &r {
Ok(_) => {
tally.ok += 1;
"ok".to_string()
}
Err(WorkerError::Op(e)) => {
assert!(!e.message.is_empty() && !e.message.contains("panicked"), "{name}: unclear message {e:?}");
tally.typed_error += 1;
format!("{} ({})", e.kind, e.message)
}
Err(WorkerError::TimedOut(_)) => {
tally.timed_out += 1;
"timed out".into()
}
Err(WorkerError::OutOfMemory) => {
tally.out_of_memory += 1;
"out of memory".into()
}
Err(WorkerError::Crashed(m)) => {
tally.crashed += 1;
format!("crashed: {m}")
}
Err(WorkerError::Spawn(e)) => panic!("worker would not start: {e}"),
};
println!("{name:40} {op:10} {took:>8.2?} {outcome}");
}
#[test]
fn hostile_pdfs_fail_cleanly_and_never_take_the_tray_down() {
let dir = tempfile::tempdir_in(env!("CARGO_TARGET_TMPDIR")).unwrap();
let mut w = worker();
let mut tally = Tally::default();
let mut all: Vec<(String, Vec<u8>)> = fixtures().into_iter().map(|(n, b)| (n.to_string(), b)).collect();
all.extend(fetched());
let annotation =
json!({"annotations": [{"page": 0, "kind": "highlight", "rects": [{"x": 10, "y": 10, "w": 50, "h": 10}]}]});
for (i, (name, bytes)) in all.iter().enumerate() {
let path = dir.path().join(format!("f{i}.pdf"));
std::fs::write(&path, bytes).unwrap();
let p = path.to_string_lossy().to_string();
let start = Instant::now();
let opened = w.call("pdf.open", json!({"path": p}), CAP);
let took = start.elapsed();
let doc = match &opened {
Ok(v) => {
tally.ok += 1;
println!(
"{name:40} {:10} {took:>8.2?} ok, {} pages",
"open",
v["info"]["pages"].as_array().map(|a| a.len()).unwrap_or(0)
);
v["doc"].as_u64()
}
Err(e) => {
match e {
WorkerError::Op(_) => tally.typed_error += 1,
WorkerError::TimedOut(_) => tally.timed_out += 1,
WorkerError::OutOfMemory => tally.out_of_memory += 1,
WorkerError::Crashed(_) => tally.crashed += 1,
WorkerError::Spawn(e) => panic!("{e}"),
}
println!("{name:40} {:10} {took:>8.2?} {} ({e})", "open", e.kind());
None
}
};
if let Some(doc) = doc {
run(&mut w, &mut tally, name, "pdf.render", json!({"doc": doc, "page": 0, "width": 800}));
if w.take_restarted() {
continue;
}
run(&mut w, &mut tally, name, "pdf.text", json!({"doc": doc}));
if w.take_restarted() {
continue;
}
let out = dir.path().join(format!("f{i}-edited.pdf")).to_string_lossy().to_string();
run(
&mut w,
&mut tally,
name,
"pdf.save",
json!({"doc": doc, "edits": annotation, "output": out, "mode": "new"}),
);
}
run(&mut w, &mut tally, name, "meta.read", json!({"path": p}));
w.take_restarted();
// The tray carries on: a normal request right after works.
let good = dir.path().join("good.pdf");
std::fs::write(&good, valid()).unwrap();
let r = w.call("pdf.open", json!({"path": good.to_string_lossy()}), CAP).expect("a good PDF after a bad one");
w.call("pdf.close", json!({"doc": r["doc"]}), CAP).unwrap();
}
println!("{} fixtures: {tally:?}", all.len());
assert!(all.len() >= 21);
assert_eq!(tally.timed_out, 0, "a fixture hung");
assert_eq!(tally.crashed, 0, "a worker died without a known cause");
}
#[test]
fn the_client_survives_crash_hang_and_memory_blowup() {
let mut w = worker();
let crash = w.call("debug.crash", json!({}), CAP);
assert!(matches!(crash, Err(WorkerError::Crashed(_))), "{crash:?}");
assert!(w.take_restarted());
let start = Instant::now();
let hang = w.call("debug.sleep", json!({"secs": 120}), Duration::from_secs(2));
assert!(matches!(hang, Err(WorkerError::TimedOut(_))), "{hang:?}");
assert!(start.elapsed() < Duration::from_secs(10));
let oom = w.call("debug.alloc", json!({"mb": 3000}), CAP);
// try_reserve fails cleanly under the cap (a typed error); a hard allocation would be OutOfMemory.
assert!(
matches!(&oom, Err(WorkerError::OutOfMemory) | Err(WorkerError::Op(_))),
"the 1 GB memory cap did not hold: {oom:?}"
);
// And it works again.
let ok = w.call("image.heif_support", json!({}), CAP).unwrap();
assert!(ok["support"].is_string());
}
#[test]
fn unknown_operations_and_bad_arguments_are_typed_errors() {
let mut w = worker();
for (op, args) in [
("nope", json!({})),
("pdf.open", json!({"wrong": 1})),
("pdf.render", json!({"doc": 77, "page": 0, "width": 10})),
] {
match w.call(op, args, CAP) {
Err(WorkerError::Op(e)) => assert!(["invalid", "not_open"].contains(&e.kind.as_str()), "{e:?}"),
other => panic!("{op}: {other:?}"),
}
}
let missing = w.call("pdf.open", json!({"path": "F:/definitely/not/here.pdf"}), CAP);
assert!(matches!(missing, Err(WorkerError::Op(ref e)) if e.kind == "io"), "{missing:?}");
}