legit-hasher 0.1.6

Every legit-hashes definition, images and text, for callers in any language: a command-line runner over JSON lines with resumable batches, and with the `serve` feature a worker that takes hashing tasks from Redis Streams
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! The batch: requests read as JSON lines, hashed on a pool of threads, results written as JSON
//! lines, in order or as they finish.

use std::collections::BTreeMap;
use std::io::{BufRead, Write};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError, TryRecvError};
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, Instant};

use crate::request::{Id, Request};
use crate::resume::{Finished, key};
use crate::{Error, Outcome, RequestError, Settings};

/// The longest request line read by default: 8 MiB, room for about 6 MiB of inline image.
pub const DEFAULT_MAX_LINE_BYTES: usize = 8 * 1024 * 1024;

/// How a batch runs.
#[derive(Debug, Clone)]
pub struct RunConfig {
    /// How many requests are hashed at once, each on its own thread. At least 1.
    pub jobs: usize,
    /// Write results in request order. Otherwise each is written as it finishes.
    pub ordered: bool,
    /// Settings for every request.
    pub settings: Settings,
    /// The longest line read; a longer one is an `invalid_request` result, and is never held in
    /// memory whole.
    pub max_line_bytes: usize,
    /// Write a progress line to standard error at this interval, and a summary at the end.
    pub progress: Option<Duration>,
}

impl RunConfig {
    /// The defaults: one job per available core, results in order, no timings, no progress.
    #[must_use]
    pub fn new() -> Self {
        Self {
            jobs: std::thread::available_parallelism().map_or(1, usize::from),
            ordered: true,
            settings: Settings::default(),
            max_line_bytes: DEFAULT_MAX_LINE_BYTES,
            progress: None,
        }
    }

    /// The most requests in flight at once: read and not yet written. It bounds the memory a run
    /// holds, whatever the length of its input.
    #[must_use]
    pub const fn window(&self) -> usize {
        self.jobs * 4 + 4
    }
}

impl Default for RunConfig {
    fn default() -> Self {
        Self::new()
    }
}

/// The counts of a finished run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Summary {
    /// Result lines written.
    pub written: u64,
    /// Of those, the failures: a request-level error or an error on any definition.
    pub failed: u64,
    /// Requests skipped because the output already held their result.
    pub skipped: u64,
}

/// One line of input, as the reader hands it to a worker.
enum Line {
    Text(Vec<u8>),
    TooLong(usize),
}

struct Job {
    sequence: u64,
    number: u64,
    line: Line,
}

/// What a worker hands the writer for a job.
enum Reply {
    Write { json: String, failed: bool },
    Skip,
}

/// The function that turns a request into its result; [`hash`](crate::hash) outside tests.
type Processor<'a> = &'a (dyn Fn(&Request, Settings) -> Outcome + Sync);

/// Run a batch: read requests from `input`, write one result line per request to `output`, and
/// skip the requests `finished` already holds.
///
/// Blank lines are skipped. Every other line gives exactly one result line, a bad line included,
/// and a panic while hashing one request gives that request an `internal` error and leaves the
/// others alone. Memory stays bounded on any input: at most [`RunConfig::window`] requests are in
/// flight, and no line longer than [`RunConfig::max_line_bytes`] is held.
///
/// # Errors
///
/// Returns [`Error::Io`] when reading `input` or writing `output` fails. The results written
/// before the failure stand, and a resumed run picks up after them.
pub fn run(
    input: impl BufRead + Send,
    output: impl Write,
    config: &RunConfig,
    finished: &Finished,
) -> Result<Summary, Error> {
    run_with(input, output, config, finished, &crate::hash)
}

pub(crate) fn run_with(
    input: impl BufRead + Send,
    mut output: impl Write,
    config: &RunConfig,
    finished: &Finished,
    processor: Processor<'_>,
) -> Result<Summary, Error> {
    let jobs = config.jobs.max(1);
    let window = config.window();
    let (token_sender, tokens) = mpsc::sync_channel::<()>(window);
    for _ in 0..window {
        token_sender
            .send(())
            .expect("the token channel holds exactly `window` tokens");
    }
    let (job_sender, job_receiver) = mpsc::sync_channel::<Job>(jobs);
    let job_receiver = Mutex::new(job_receiver);
    let (result_sender, results) = mpsc::channel::<(u64, Reply)>();
    let cancelled = AtomicBool::new(false);

    std::thread::scope(|scope| {
        let cancelled = &cancelled;
        let reader = scope.spawn(move || read(input, config.max_line_bytes, &tokens, &job_sender, cancelled));
        for _ in 0..jobs {
            let result_sender = result_sender.clone();
            let job_receiver = &job_receiver;
            scope.spawn(move || {
                loop {
                    let job = job_receiver.lock().unwrap_or_else(PoisonError::into_inner).recv();
                    let Ok(job) = job else { break };
                    let reply = handle(&job, config, finished, processor);
                    if result_sender.send((job.sequence, reply)).is_err() {
                        break;
                    }
                }
            });
        }
        drop(result_sender);
        let written = write(&mut output, &results, config, &token_sender);
        // On a write failure, stop the reader: the flag stops it reading on, the dropped token
        // sender ends its wait for a token, and draining the job queue ends a send blocked on a
        // full queue once the workers are gone. After a clean finish the queue is already closed.
        cancelled.store(true, Ordering::Relaxed);
        drop(token_sender);
        drop(results);
        while job_receiver
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .recv()
            .is_ok()
        {}
        let read = reader
            .join()
            .unwrap_or_else(|_| Err(Error::Internal("the reader thread panicked".to_owned())));
        let summary = written?;
        read?;
        Ok(summary)
    })
}

/// Read lines into jobs, waiting for a token before each so no more than the window is in flight.
fn read(
    mut input: impl BufRead,
    max: usize,
    tokens: &mpsc::Receiver<()>,
    jobs: &mpsc::SyncSender<Job>,
    cancelled: &AtomicBool,
) -> Result<(), Error> {
    let mut number = 0u64;
    let mut sequence = 0u64;
    let mut buffer = Vec::new();
    loop {
        if cancelled.load(Ordering::Relaxed) {
            return Ok(());
        }
        let Some(length) = read_line(&mut input, &mut buffer, max)? else {
            return Ok(());
        };
        number += 1;
        let line = if length > max {
            Line::TooLong(length)
        } else {
            while buffer.last().is_some_and(|byte| byte.is_ascii_whitespace()) {
                buffer.pop();
            }
            if buffer.iter().all(u8::is_ascii_whitespace) {
                continue;
            }
            Line::Text(std::mem::take(&mut buffer))
        };
        if tokens.recv().is_err() || cancelled.load(Ordering::Relaxed) {
            return Ok(());
        }
        if jobs.send(Job { sequence, number, line }).is_err() {
            return Ok(());
        }
        sequence += 1;
    }
}

/// Read one line into `buffer`, without its newline, keeping at most `max` bytes. Returns the
/// line's full length, or `None` at the end of the input.
fn read_line(input: &mut impl BufRead, buffer: &mut Vec<u8>, max: usize) -> Result<Option<usize>, Error> {
    buffer.clear();
    let mut length = 0usize;
    let mut any = false;
    loop {
        let available = input
            .fill_buf()
            .map_err(|error| Error::io("couldn't read the input", error))?;
        if available.is_empty() {
            return Ok(any.then_some(length));
        }
        any = true;
        let (part, done) = match available.iter().position(|&byte| byte == b'\n') {
            Some(end) => (&available[..end], true),
            None => (available, false),
        };
        if length + part.len() <= max {
            buffer.extend_from_slice(part);
        } else {
            buffer.clear();
        }
        length += part.len();
        let consumed = part.len() + usize::from(done);
        input.consume(consumed);
        if done {
            return Ok(Some(length));
        }
    }
}

/// Turn a job into its reply, catching a panic so it fails only this request.
fn handle(job: &Job, config: &RunConfig, finished: &Finished, processor: Processor<'_>) -> Reply {
    let mut parsed_id = None;
    let attempt = catch_unwind(AssertUnwindSafe(|| {
        let outcome = match &job.line {
            Line::TooLong(length) => Outcome::error(
                None,
                RequestError::InvalidRequest,
                format!(
                    "the line is `{length}` bytes; at most `{}` are read, set by `--max-line-bytes`",
                    config.max_line_bytes
                ),
            ),
            Line::Text(text) => match Request::from_json(text) {
                Ok(request) => {
                    parsed_id = Some(request.id.clone());
                    if finished.contains(key(&request.id.to_string())) {
                        return None;
                    }
                    processor(&request, config.settings)
                }
                Err(outcome) => *outcome,
            },
        };
        let resume_key = match &outcome.id {
            Some(id) => key(&id.to_string()),
            None => key(&format!("line:{}", job.number)),
        };
        (!finished.contains(resume_key)).then_some(outcome)
    }));
    let outcome = match attempt {
        Ok(Some(outcome)) => outcome,
        Ok(None) => return Reply::Skip,
        Err(panic) => Outcome::error(
            parsed_id.or_else(|| id_of(&job.line)),
            RequestError::Internal,
            format!("the runner panicked on this request: {}", panic_message(&*panic)),
        ),
    };
    let mut outcome = outcome;
    outcome.line = Some(job.number);
    Reply::Write {
        failed: outcome.is_failure(),
        json: outcome.to_json(),
    }
}

/// The id of a line, read again after a panic.
fn id_of(line: &Line) -> Option<Id> {
    let Line::Text(text) = line else { return None };
    let value: serde_json::Value = serde_json::from_slice(text).ok()?;
    Id::from_json(value.get("id")?)
}

fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {
    panic
        .downcast_ref::<&str>()
        .map(|message| (*message).to_owned())
        .or_else(|| panic.downcast_ref::<String>().cloned())
        .unwrap_or_else(|| "a panic without a message".to_owned())
}

/// Write replies as they come, in order when asked, returning a token for each one written.
fn write(
    output: &mut impl Write,
    results: &mpsc::Receiver<(u64, Reply)>,
    config: &RunConfig,
    tokens: &mpsc::SyncSender<()>,
) -> Result<Summary, Error> {
    let started = Instant::now();
    let mut last_progress = started;
    let mut summary = Summary::default();
    let mut pending: BTreeMap<u64, Reply> = BTreeMap::new();
    let mut next = 0u64;
    let failed = |error| Error::io("couldn't write the output", error);
    let emit = |reply: Reply, output: &mut dyn Write, summary: &mut Summary| -> Result<(), Error> {
        match reply {
            Reply::Skip => summary.skipped += 1,
            Reply::Write { json, failed: failure } => {
                output.write_all(json.as_bytes()).map_err(failed)?;
                output.write_all(b"\n").map_err(failed)?;
                summary.written += 1;
                summary.failed += u64::from(failure);
            }
        }
        // The reader may have finished already...
        let _ = tokens.try_send(());
        Ok(())
    };
    let mut unflushed = false;
    loop {
        // Flush whenever no result is waiting, so a caller that writes one request and reads
        // its result isn't kept waiting...
        let received = match results.try_recv() {
            Ok(received) => Some(received),
            Err(TryRecvError::Disconnected) => break,
            Err(TryRecvError::Empty) => {
                if unflushed {
                    output.flush().map_err(failed)?;
                    unflushed = false;
                }
                match results.recv_timeout(Duration::from_millis(250)) {
                    Ok(received) => Some(received),
                    Err(RecvTimeoutError::Timeout) => None,
                    Err(RecvTimeoutError::Disconnected) => break,
                }
            }
        };
        if let Some((sequence, reply)) = received {
            unflushed = true;
            if config.ordered {
                pending.insert(sequence, reply);
                while let Some(reply) = pending.remove(&next) {
                    emit(reply, output, &mut summary)?;
                    next += 1;
                }
            } else {
                emit(reply, output, &mut summary)?;
            }
        }
        if let Some(interval) = config.progress
            && last_progress.elapsed() >= interval
        {
            last_progress = Instant::now();
            report(&summary, started, false);
        }
    }
    output.flush().map_err(failed)?;
    if config.progress.is_some() {
        report(&summary, started, true);
    }
    Ok(summary)
}

/// A progress line on standard error, as JSON.
fn report(summary: &Summary, started: Instant, last: bool) {
    let elapsed = started.elapsed().as_secs_f64();
    let line = serde_json::json!({
        "progress": if last { "finished" } else { "running" },
        "done": summary.written,
        "failed": summary.failed,
        "skipped": summary.skipped,
        "elapsed_s": (elapsed * 10.0).round() / 10.0,
        "per_second": if elapsed > 0.0 { (summary.written as f64 / elapsed * 10.0).round() / 10.0 } else { 0.0 },
    });
    // Progress is best effort: a closed standard error mustn't stop the run...
    let _ = writeln!(std::io::stderr().lock(), "{line}");
}

#[cfg(test)]
mod tests {
    use super::*;

    const LINES: &str = concat!(
        r#"{"id":"a","text":"one","options":{"format":1,"definitions":[{"id":"simhash-v1","tokens":"words"}]}}"#,
        "\n",
        r#"{"id":"boom","text":"two","options":{"format":1,"definitions":[{"id":"simhash-v1","tokens":"words"}]}}"#,
        "\n",
        r#"{"id":"c","text":"three","options":{"format":1,"definitions":[{"id":"simhash-v1","tokens":"words"}]}}"#,
        "\n",
    );

    fn panicking(request: &Request, settings: Settings) -> Outcome {
        assert!(request.id != Id::Text("boom".to_owned()), "a test-only panic");
        crate::hash(request, settings)
    }

    #[test]
    fn a_panic_in_one_request_is_its_error_and_the_run_completes() {
        for jobs in [1, 3] {
            let mut output = Vec::new();
            let config = RunConfig {
                jobs,
                ..RunConfig::new()
            };
            let summary = run_with(LINES.as_bytes(), &mut output, &config, &Finished::default(), &panicking)
                .expect("the run completes");
            assert_eq!((summary.written, summary.failed), (3, 1));
            let lines: Vec<serde_json::Value> = String::from_utf8(output)
                .expect("UTF-8")
                .lines()
                .map(|line| serde_json::from_str(line).expect("JSON"))
                .collect();
            assert_eq!(lines[0]["id"], "a");
            assert_eq!(lines[0]["status"], "success");
            assert_eq!(lines[1]["id"], "boom");
            assert_eq!(lines[1]["error_type"], "internal");
            assert!(
                lines[1]["error"]
                    .as_str()
                    .expect("message")
                    .contains("a test-only panic")
            );
            assert_eq!(lines[2]["id"], "c");
            assert_eq!(lines[2]["status"], "success");
        }
    }

    /// An output that takes nothing, as a closed pipe does.
    struct Refusing;

    impl Write for Refusing {
        fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
            Err(std::io::ErrorKind::BrokenPipe.into())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn a_failing_output_ends_the_run_with_work_still_queued() {
        let input = LINES.repeat(2_000);
        for (jobs, ordered) in [(1, true), (1, false), (4, true)] {
            let (done, finished) = mpsc::channel();
            let input = input.clone();
            std::thread::spawn(move || {
                let config = RunConfig {
                    jobs,
                    ordered,
                    ..RunConfig::new()
                };
                let result = run_with(input.as_bytes(), Refusing, &config, &Finished::default(), &crate::hash);
                let _ = done.send(result);
            });
            let result = finished
                .recv_timeout(Duration::from_secs(30))
                .unwrap_or_else(|_| panic!("the run with {jobs} jobs stops after its output fails"));
            assert!(matches!(result, Err(Error::Io { .. })), "{result:?}");
        }
    }

    #[test]
    fn lines_are_read_whole_or_counted_when_too_long() {
        let mut input = "short\n0123456789\nend".as_bytes();
        let mut buffer = Vec::new();
        assert_eq!(read_line(&mut input, &mut buffer, 5).expect("read"), Some(5));
        assert_eq!(buffer, b"short");
        assert_eq!(read_line(&mut input, &mut buffer, 5).expect("read"), Some(10));
        assert!(buffer.is_empty());
        assert_eq!(read_line(&mut input, &mut buffer, 5).expect("read"), Some(3));
        assert_eq!(buffer, b"end");
        assert_eq!(read_line(&mut input, &mut buffer, 5).expect("read"), None);
    }
}