[repo] Format, clippy clean, FORMATS.md, the full crate table in DEPENDENCIES.md
This commit is contained in:
+323
-312
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user