Skip to main content

rightkit_ocr/
worker.rs

1//! Isolated child-per-request native OCR worker (ViewRight `ocr_worker.rs`).
2//!
3//! Accurate Vision requests can fail on the target Mac with precompiled-
4//! operation errors once a process has served one, so each request runs in a
5//! short-lived child. Protocol: raw encoded image bytes on stdin, one bounded
6//! JSON [`WorkerResponse`] line on stdout. Paths, environment and recognized
7//! text are never written to stderr.
8//!
9//! Server side: call [`run_if_requested`] first thing in `main` (before any
10//! UI/single-instance init). Client side: [`WorkerCommand::run`].
11
12use std::ffi::OsString;
13use std::io::{self, Read, Write};
14use std::path::PathBuf;
15use std::process::{Child, Command, ExitStatus, Stdio};
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::sync::Arc;
18use std::thread::{self, JoinHandle};
19use std::time::{Duration, Instant};
20
21use serde::{Deserialize, Serialize};
22
23use crate::types::OcrLine;
24
25pub const MAX_INPUT_BYTES: usize = 32 * 1024 * 1024;
26pub const MAX_OUTPUT_BYTES: usize = 8 * 1024 * 1024;
27const MAX_STDERR_BYTES: usize = 1024 * 1024;
28pub const WORKER_DEADLINE: Duration = Duration::from_secs(90);
29/// Exit code the worker uses when its own deadline fires.
30pub const SELF_DEADLINE_EXIT: i32 = 124;
31/// Default argv[1] selecting worker mode.
32pub const DEFAULT_WORKER_ARG: &str = "--rightkit-ocr-worker";
33
34#[derive(Debug, Serialize, Deserialize)]
35pub struct WorkerResponse {
36    pub ok: bool,
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub lines: Option<Vec<OcrLine>>,
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub error: Option<String>,
41}
42
43/// How to launch the worker: the executable (usually the app itself, which
44/// calls [`run_if_requested`]) plus the selecting argument.
45#[derive(Debug, Clone)]
46pub struct WorkerCommand {
47    pub executable: PathBuf,
48    pub args: Vec<OsString>,
49    pub deadline: Duration,
50}
51
52impl WorkerCommand {
53    /// Re-invoke the current executable with `arg` (the ViewRight shape).
54    pub fn current_exe(arg: &str) -> Result<Self, String> {
55        let executable = std::env::current_exe()
56            .map_err(|_| "OCR worker executable path unavailable".to_string())?;
57        Ok(Self::new(executable, [arg]))
58    }
59
60    pub fn new<I, S>(executable: impl Into<PathBuf>, args: I) -> Self
61    where
62        I: IntoIterator<Item = S>,
63        S: Into<OsString>,
64    {
65        Self {
66            executable: executable.into(),
67            args: args.into_iter().map(Into::into).collect(),
68            deadline: WORKER_DEADLINE,
69        }
70    }
71
72    pub fn with_deadline(mut self, deadline: Duration) -> Self {
73        self.deadline = deadline;
74        self
75    }
76
77    /// One isolated recognition request in a fresh child.
78    pub fn run(&self, bytes: &[u8]) -> Result<Vec<OcrLine>, String> {
79        run_isolated(self, bytes)
80    }
81}
82
83#[derive(Debug)]
84struct CapturedOutput {
85    bytes: Vec<u8>,
86    exceeded: bool,
87}
88
89/// If argv[1] equals `arg`, serve one request and exit; otherwise return
90/// `false` immediately. The worker never creates a window.
91pub fn run_if_requested(arg: &str) -> bool {
92    if std::env::args().nth(1).as_deref() != Some(arg) {
93        return false;
94    }
95    run_worker_process()
96}
97
98fn run_worker_process() -> ! {
99    worker_event("start", "stdin");
100    // The parent may die while Vision is inside its synchronous call; bound the
101    // child independently so losing the supervisor cannot leave it running.
102    thread::spawn(|| {
103        thread::sleep(WORKER_DEADLINE);
104        worker_event("timeout", "self-deadline");
105        std::process::exit(SELF_DEADLINE_EXIT);
106    });
107    let result = read_input_from(io::stdin())
108        .and_then(|bytes| {
109            let img = crate::types::decode_encoded(&bytes)?;
110            worker_event("start", "recognize");
111            crate::native::recognize_once(&img)
112        })
113        .map(|lines| WorkerResponse {
114            ok: true,
115            lines: Some(lines),
116            error: None,
117        })
118        .unwrap_or_else(|error| WorkerResponse {
119            ok: false,
120            lines: None,
121            error: Some(error),
122        });
123    worker_event(if result.ok { "success" } else { "failure" }, "recognize");
124    std::process::exit(write_response(result));
125}
126
127fn read_input_from(reader: impl Read) -> Result<Vec<u8>, String> {
128    let mut input = Vec::new();
129    reader
130        .take((MAX_INPUT_BYTES + 1) as u64)
131        .read_to_end(&mut input)
132        .map_err(|_| "OCR worker could not read request".to_string())?;
133    if input.len() > MAX_INPUT_BYTES {
134        return Err("OCR worker request exceeds the 32 MiB limit".to_string());
135    }
136    Ok(input)
137}
138
139fn write_response(response: WorkerResponse) -> i32 {
140    let mut encoded = match serde_json::to_vec(&response) {
141        Ok(bytes) => bytes,
142        Err(_) => return 1,
143    };
144    if encoded.len() > MAX_OUTPUT_BYTES {
145        encoded = serde_json::to_vec(&WorkerResponse {
146            ok: false,
147            lines: None,
148            error: Some("OCR worker result exceeds the 8 MiB limit".to_string()),
149        })
150        .expect("fixed worker error must serialize");
151    }
152    encoded.push(b'\n');
153    if io::stdout().write_all(&encoded).is_err() {
154        worker_event("failure", "stdout");
155        return 1;
156    }
157    0
158}
159
160fn worker_event(event: &str, stage: &str) {
161    eprintln!(
162        "ocr_worker event={event} pid={} stage={stage}",
163        std::process::id()
164    );
165}
166
167fn spawn_reader<R: Read + Send + 'static>(
168    mut reader: R,
169    limit: usize,
170    exceeded: Arc<AtomicBool>,
171) -> JoinHandle<CapturedOutput> {
172    thread::spawn(move || {
173        let mut bytes = Vec::new();
174        let read_result = reader
175            .by_ref()
176            .take((limit + 1) as u64)
177            .read_to_end(&mut bytes);
178        let over = bytes.len() > limit;
179        if read_result.is_err() || over {
180            exceeded.store(true, Ordering::Release);
181        }
182        CapturedOutput {
183            bytes,
184            exceeded: over,
185        }
186    })
187}
188
189fn kill_and_reap(child: &mut Child) {
190    let _ = child.kill();
191    let _ = child.wait();
192}
193
194fn wait_with_deadline(
195    child: &mut Child,
196    exceeded: &AtomicBool,
197    deadline: Duration,
198) -> Result<ExitStatus, String> {
199    let deadline = Instant::now() + deadline;
200    loop {
201        if exceeded.load(Ordering::Acquire) {
202            kill_and_reap(child);
203            return Err("OCR worker output exceeds the bounded protocol limit".to_string());
204        }
205        match child.try_wait() {
206            Ok(Some(status)) => return Ok(status),
207            Ok(None) if Instant::now() >= deadline => {
208                kill_and_reap(child);
209                return Err("OCR worker exceeded its deadline".to_string());
210            }
211            Ok(None) => thread::sleep(Duration::from_millis(10)),
212            Err(_) => {
213                kill_and_reap(child);
214                return Err("OCR worker process wait failed".to_string());
215            }
216        }
217    }
218}
219
220fn parse_response(stdout: &[u8], child_succeeded: bool) -> Result<Vec<OcrLine>, String> {
221    if stdout.len() > MAX_OUTPUT_BYTES {
222        return Err("OCR worker stdout exceeds the 8 MiB limit".to_string());
223    }
224    let response: WorkerResponse = serde_json::from_slice(stdout)
225        .map_err(|_| "OCR worker returned malformed JSON".to_string())?;
226    if !child_succeeded {
227        return Err("OCR worker exited with a failure status".to_string());
228    }
229    if response.ok {
230        response
231            .lines
232            .ok_or_else(|| "OCR worker success response omitted lines".to_string())
233    } else {
234        Err(response
235            .error
236            .unwrap_or_else(|| "OCR worker returned an unspecified error".to_string()))
237    }
238}
239
240fn run_isolated(cmd: &WorkerCommand, bytes: &[u8]) -> Result<Vec<OcrLine>, String> {
241    if bytes.len() > MAX_INPUT_BYTES {
242        return Err("OCR worker request exceeds the 32 MiB limit".to_string());
243    }
244    let mut command = Command::new(&cmd.executable);
245    command
246        .args(&cmd.args)
247        .stdin(Stdio::piped())
248        .stdout(Stdio::piped())
249        .stderr(Stdio::piped());
250    #[cfg(windows)]
251    {
252        use std::os::windows::process::CommandExt;
253        command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW: no visible console
254    }
255    let mut child = command
256        .spawn()
257        .map_err(|_| "OCR worker process could not start".to_string())?;
258
259    let (Some(stdin), Some(stdout), Some(stderr)) =
260        (child.stdin.take(), child.stdout.take(), child.stderr.take())
261    else {
262        kill_and_reap(&mut child);
263        return Err("OCR worker pipes unavailable".to_string());
264    };
265
266    let exceeded = Arc::new(AtomicBool::new(false));
267    let out_reader = spawn_reader(stdout, MAX_OUTPUT_BYTES, exceeded.clone());
268    let err_reader = spawn_reader(stderr, MAX_STDERR_BYTES, exceeded.clone());
269    let payload = bytes.to_vec();
270    let writer = thread::spawn(move || {
271        let mut stdin = stdin;
272        stdin
273            .write_all(&payload)
274            .map_err(|_| "OCR worker request write failed".to_string())
275    });
276
277    let status = wait_with_deadline(&mut child, &exceeded, cmd.deadline);
278    let write_result = writer
279        .join()
280        .unwrap_or(Err("OCR worker request writer panicked".to_string()));
281    let out = out_reader
282        .join()
283        .map_err(|_| "OCR worker stdout reader panicked".to_string())?;
284    let err = err_reader
285        .join()
286        .map_err(|_| "OCR worker stderr reader panicked".to_string())?;
287
288    let status = status?;
289    if status.code() == Some(SELF_DEADLINE_EXIT) {
290        return Err("OCR worker exceeded its deadline".to_string());
291    }
292    write_result?;
293    if out.exceeded || err.exceeded {
294        return Err("OCR worker output exceeds the bounded protocol limit".to_string());
295    }
296    parse_response(&out.bytes, status.success())
297}