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
//! The core: one request in, one result out. The batch command and `serve` call [`hash`] and
//! nothing else.

use std::fs::File;
use std::io::Read;
use std::time::Instant;

use legit_hashes::{
    Algorithm, DECODE_MAX_ALLOC, DECODE_MAX_DIMENSION, DECODE_MAX_INPUT, Error as HashError, Hash, LumaBuf, RgbaBuf,
    Signature, SignatureAlgorithm, blockhash_v1, decode_luma_v1, decode_rgba_v1, minhash_legacy_v1,
    minhash_legacy_v1_shingles, minhash_v1, minhash_v1_shingles, pdq_v1, shingles_v1, simhash_v1, words_v1,
};
use sha1::{Digest, Sha1};

use crate::definition::{Definition, Input, Plan, Tokens};
use crate::inspect::{DECODED_FORMATS, Inspection, inspect};
use crate::orient::{moves_pixels, reorient};
use crate::request::{Entry, Orientation, Request, Source};
use crate::{DecodeFacts, DefinitionError, HashOutcome, Outcome, RequestError, SourceFacts, Timings};

/// Settings that apply to every request of a run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Settings {
    /// Report the time each step took, in microseconds.
    pub timings: bool,
    /// Refuse, as `too_large`, an image with more pixels than this: before decoding it, from the
    /// size its header states and the size the decoder reads from it, or when the header can't be
    /// read; and after decoding it, from what was decoded.
    /// `None` leaves only the library's limits.
    pub max_pixels: Option<u64>,
    /// Refuse, as `too_large`, a text longer than this many bytes, before tokenising it. `None`
    /// leaves the limits on the request's line or task.
    pub max_text_bytes: Option<u64>,
}

/// Why a text of `length` bytes is refused under `settings`, if it is.
pub(crate) fn text_too_large(length: usize, settings: Settings) -> Option<String> {
    settings
        .max_text_bytes
        .filter(|most| length as u64 > *most)
        .map(|most| format!("the text is `{length}` bytes; `--max-text-bytes` allows `{most}`"))
}

/// Compute every definition a request asks for, and say what was hashed.
///
/// One decode serves every image definition: the file is decoded to RGBA when `pdq-v1` or
/// `blockhash-v1` is asked for, and the luma the other image definitions read is converted from
/// that RGBA; with only luma definitions it's decoded straight to luma. Either way the pixels are
/// those `legit-hashes`' own `decode_rgba_v1` and `decode_luma_v1` give. A definition-level
/// failure, such as a text definition on an image, leaves the others to run. Never panics on any
/// input; a panic would be a bug.
#[must_use]
pub fn hash(request: &Request, settings: Settings) -> Outcome {
    let started = Instant::now();
    let mut outcome = match &request.source {
        Source::Text(text) => match text_too_large(text.len(), settings) {
            Some(message) => Outcome::error(Some(request.id.clone()), RequestError::TooLarge, message),
            None => hash_text(request, text),
        },
        Source::Path(path) => {
            let read = Instant::now();
            match read_file(path) {
                Ok(bytes) => hash_image(request, &bytes, settings, Some(elapsed_us(read))),
                Err((code, message)) => Outcome::error(Some(request.id.clone()), code, message),
            }
        }
        Source::Bytes(bytes) => hash_image(request, bytes, settings, None),
    };
    if settings.timings {
        let timings = outcome.timings.get_or_insert(Timings {
            read_us: None,
            decode_us: None,
            total_us: 0,
        });
        timings.total_us = elapsed_us(started);
    } else {
        outcome.timings = None;
        for entry in outcome.hashes.iter_mut().flatten() {
            entry.time_us = None;
        }
    }
    outcome
}

/// Bytes as lower-case hex.
fn hex(bytes: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    bytes
        .iter()
        .flat_map(|byte| [DIGITS[usize::from(byte >> 4)], DIGITS[usize::from(byte & 15)]])
        .map(char::from)
        .collect()
}

fn elapsed_us(since: Instant) -> u64 {
    u64::try_from(since.elapsed().as_micros()).unwrap_or(u64::MAX)
}

/// Read a file, refusing one over the decoder's input limit before reading it all.
fn read_file(path: &std::path::Path) -> Result<Vec<u8>, (RequestError, String)> {
    let failed = |error: std::io::Error| {
        (
            RequestError::ReadFailed,
            format!("couldn't read `{}`: {error}", path.display()),
        )
    };
    let file = File::open(path).map_err(failed)?;
    let limit = DECODE_MAX_INPUT as u64;
    let too_large = |bytes: u64| {
        (
            RequestError::TooLarge,
            format!("`{}` is `{bytes}` bytes; at most `{limit}` are read", path.display()),
        )
    };
    let length = file.metadata().map_err(failed)?.len();
    if length > limit {
        return Err(too_large(length));
    }
    let mut bytes = Vec::with_capacity(usize::try_from(length).unwrap_or(0));
    file.take(limit + 1).read_to_end(&mut bytes).map_err(failed)?;
    if bytes.len() as u64 > limit {
        return Err(too_large(bytes.len() as u64));
    }
    Ok(bytes)
}

/// The definition-level failure of an entry whose definition doesn't read this source.
fn wrong_source(entry: &Entry, plan: &Plan, image: bool) -> Option<HashOutcome> {
    let id = plan.definition.id();
    match (plan.definition.is_image(), image) {
        (true, false) => Some(HashOutcome::failed(
            &entry.id,
            DefinitionError::WrongSource,
            format!("`{id}` hashes images, and this request's source is text"),
        )),
        (false, true) => Some(HashOutcome::failed(
            &entry.id,
            DefinitionError::WrongSource,
            format!("`{id}` hashes text, and this request's source is an image"),
        )),
        _ => None,
    }
}

fn hash_text(request: &Request, text: &str) -> Outcome {
    let mut outcome = Outcome::success(Some(request.id.clone()));
    let hashes = request
        .options
        .definitions
        .iter()
        .map(|entry| match &entry.plan {
            Err(failure) => HashOutcome::failed(&entry.id, failure.code, &failure.message),
            Ok(plan) => wrong_source(entry, plan, false).unwrap_or_else(|| text_hash(entry, plan, text)),
        })
        .collect();
    outcome.hashes = Some(hashes);
    outcome
}

fn text_hash(entry: &Entry, plan: &Plan, text: &str) -> HashOutcome {
    let started = Instant::now();
    let mut result = HashOutcome::new(&entry.id);
    let tokens = plan.tokens.unwrap_or(Tokens::Words);
    match tokens {
        Tokens::Words => result.tokens = Some("words"),
        Tokens::Shingles(size) => result.shingle = Some(size),
    }
    let computed: Result<(), HashError> = (|| {
        match plan.definition {
            Definition::Bit(Algorithm::SimHashV1) => {
                let hash = match tokens {
                    Tokens::Words => simhash_v1(words_v1(text).map(|word| (word, 1))),
                    Tokens::Shingles(size) => simhash_v1(shingles_v1(text, size as usize)?.map(|shingle| (shingle, 1))),
                };
                bit_hash(&mut result, &hash, plan)?;
            }
            Definition::Signature(algorithm) => {
                let signature = signature(algorithm, tokens, text)?;
                result.value = Some(signature.to_string());
                result.empty = Some(signature.is_empty());
                if let Some(bands) = plan.band_keys {
                    result.band_keys = Some(signature.band_keys_i64(bands)?);
                }
            }
            Definition::Bit(algorithm) => return Err(HashError::NotAnImageAlgorithm(algorithm)),
        }
        Ok(())
    })();
    finish(result, computed, started)
}

/// A MinHash signature of `text` under `algorithm`.
fn signature(algorithm: SignatureAlgorithm, tokens: Tokens, text: &str) -> Result<Signature, HashError> {
    match (algorithm, tokens) {
        (SignatureAlgorithm::MinHashV1, Tokens::Words) => Ok(minhash_v1(words_v1(text))),
        (SignatureAlgorithm::MinHashV1, Tokens::Shingles(size)) => minhash_v1_shingles(text, size as usize),
        (SignatureAlgorithm::MinHashLegacyV1, Tokens::Words) => Ok(minhash_legacy_v1(words_v1(text))),
        (SignatureAlgorithm::MinHashLegacyV1, Tokens::Shingles(size)) => {
            minhash_legacy_v1_shingles(text, size as usize)
        }
        (other, _) => Err(HashError::UnknownAlgorithm(other.id().to_owned())),
    }
}

/// Fill in a bit hash's value and the chunk keys asked for.
fn bit_hash(result: &mut HashOutcome, hash: &Hash, plan: &Plan) -> Result<(), HashError> {
    result.value = Some(hash.to_string());
    if let Some(count) = plan.chunk_keys {
        // The signed form has the same bits, as `Hash::to_i64` reads them...
        result.chunk_keys = Some(hash.chunks(count)?.into_iter().map(|key| key as i64).collect());
    }
    Ok(())
}

/// Close an entry: its time, or the library's refusal as `invalid_parameter`.
fn finish(mut result: HashOutcome, computed: Result<(), HashError>, started: Instant) -> HashOutcome {
    match computed {
        Ok(()) => {
            result.time_us = Some(elapsed_us(started));
            result
        }
        Err(error) => HashOutcome::failed(result.id, DefinitionError::InvalidParameter, error.to_string()),
    }
}

/// The decoded pixels a request's image definitions read.
struct Pixels {
    rgba: Option<RgbaBuf>,
    luma: Option<LumaBuf>,
    width: u32,
    height: u32,
}

fn hash_image(request: &Request, bytes: &[u8], settings: Settings, read_us: Option<u64>) -> Outcome {
    let id = Some(request.id.clone());
    let inspection = inspect(bytes);
    let source = SourceFacts {
        bytes: bytes.len() as u64,
        sha1: hex(&Sha1::digest(bytes)),
    };
    let plans: Vec<&Plan> = request
        .options
        .definitions
        .iter()
        .filter_map(|entry| entry.plan.as_ref().ok())
        .collect();
    let wants = |input: Input| plans.iter().any(|plan| plan.definition.input() == input);
    let (wants_rgba, wants_luma) = (wants(Input::Rgba), wants(Input::Luma));
    let mut outcome = Outcome::success(id.clone());
    outcome.source = Some(source.clone());
    let fail = |code, message: String| {
        let mut failed = Outcome::error(id.clone(), code, message);
        failed.source = Some(source.clone());
        failed.detected_format = Some(inspection.format);
        failed.timings = read_us.map(|read_us| Timings {
            read_us: Some(read_us),
            decode_us: None,
            total_us: 0,
        });
        failed
    };
    let mut decode_us = None;
    if wants_rgba || wants_luma {
        if !DECODED_FORMATS.contains(&inspection.format) {
            return fail(
                RequestError::DecodeFailed,
                format!(
                    "unsupported format: {}; the runner decodes {}",
                    inspection.format,
                    DECODED_FORMATS.join(" and ")
                ),
            );
        }
        if let Some(message) =
            over_limits(&inspection, settings).or_else(|| over_decoders_size(bytes, &inspection, settings))
        {
            return fail(RequestError::TooLarge, message);
        }
        let started = Instant::now();
        let orientation = match (request.options.orientation, inspection.orientation) {
            (Orientation::Apply, Some(tag)) if moves_pixels(tag) => Some(tag),
            _ => None,
        };
        let pixels = match decode(bytes, wants_rgba, wants_luma, orientation) {
            Ok(pixels) => pixels,
            Err(HashError::Decode(message)) if message.contains("limit") => {
                return fail(RequestError::TooLarge, format!("couldn't decode the image: {message}"));
            }
            Err(error) => return fail(RequestError::DecodeFailed, error.to_string()),
        };
        decode_us = Some(elapsed_us(started));
        // The limit holds what was decoded, whatever the header said...
        if let Some(most) = settings.max_pixels
            && u64::from(pixels.width) * u64::from(pixels.height) > most
        {
            return fail(
                RequestError::TooLarge,
                format!(
                    "the image decoded to `{}x{}` pixels; `--max-pixels` allows `{most}`",
                    pixels.width, pixels.height
                ),
            );
        }
        outcome.width = Some(pixels.width);
        outcome.height = Some(pixels.height);
        outcome.decode = Some(DecodeFacts {
            format: inspection.format,
            frames: inspection.frames.unwrap_or(1),
            orientation_tag: inspection.orientation,
            orientation_applied: orientation.is_some(),
            truncated: inspection.truncated,
        });
        outcome.hashes = Some(image_hashes(request, &pixels));
    } else {
        outcome.hashes = Some(image_hashes(
            request,
            &Pixels {
                rgba: None,
                luma: None,
                width: 0,
                height: 0,
            },
        ));
    }
    outcome.timings = Some(Timings {
        read_us,
        decode_us,
        total_us: 0,
    });
    outcome
}

/// The reason to refuse an image from its header alone, before any pixel is decoded. With
/// `max_pixels` set, an image whose header gives no size is refused too.
fn over_limits(inspection: &Inspection, settings: Settings) -> Option<String> {
    let Some((width, height)) = inspection.size else {
        return settings.max_pixels.map(|most| {
            format!("its size could not be read before decoding, so `--max-pixels` (`{most}`) can't be held to; it isn't decoded")
        });
    };
    if width > DECODE_MAX_DIMENSION || height > DECODE_MAX_DIMENSION {
        return Some(format!(
            "the image is `{width}x{height}`; a side may be at most `{DECODE_MAX_DIMENSION}` pixels"
        ));
    }
    let pixels = u64::from(width) * u64::from(height);
    if let Some(bytes) = inspection.bytes_per_pixel.map(|each| pixels * each)
        && bytes > DECODE_MAX_ALLOC
    {
        return Some(format!(
            "the image is `{width}x{height}`, `{bytes}` bytes decoded; the decoder may allocate at most `{DECODE_MAX_ALLOC}`"
        ));
    }
    match settings.max_pixels {
        Some(most) if pixels > most => Some(format!(
            "the image is `{width}x{height}`, `{pixels}` pixels; `--max-pixels` allows `{most}`"
        )),
        _ => None,
    }
}

/// With `--max-pixels` set, the most bytes the decoder is allowed for an image's metadata while
/// its size is read, 16 MiB: chiefly a PNG's compressed ICC profile, which it inflates. A PNG whose
/// profile doesn't inflate within it, or not at all, is refused as `too_large` before it's decoded,
/// since the decoder would inflate it again within its own, larger limit. A JPEG's metadata is at
/// most the file. Without `--max-pixels` the size isn't read first, and the decoder's own limit,
/// [`DECODE_MAX_ALLOC`], holds its metadata as it does its pixels.
///
/// It is the decoder's allowance, not a ceiling on what reading the size costs in all: to tell
/// whether a profile was kept, the decoder hands back its own copy of it, so a kept profile of up
/// to this size exists twice for a moment, until that copy is dropped.
pub const MAX_METADATA_BYTES: u64 = 16 << 20;

/// With `max_pixels` set, the reason to refuse an image from the size the decoder itself reads from
/// its header, before any pixel is allocated. The header walk above can read another size than the
/// decoder, such as from a second `IHDR` chunk; this is the size the pixels are decoded at. The
/// read is held to [`MAX_METADATA_BYTES`] and to the decoder's largest side, so reading the size
/// can't cost more than they allow either. The PNG decoder drops an ICC profile it can't inflate
/// within that rather than fail, so a PNG with a profile the read didn't keep is refused. When the
/// decoder can't read a size for another reason, decoding fails at the same step, having
/// allocated no more than this read did.
fn over_decoders_size(bytes: &[u8], inspection: &Inspection, settings: Settings) -> Option<String> {
    use image::ImageDecoder;

    let most = settings.max_pixels?;
    let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
        .with_guessed_format()
        .ok()?;
    let mut limits = image::Limits::default();
    limits.max_image_width = Some(DECODE_MAX_DIMENSION);
    limits.max_image_height = Some(DECODE_MAX_DIMENSION);
    limits.max_alloc = Some(MAX_METADATA_BYTES);
    reader.limits(limits);
    let metadata = || {
        format!(
            "the decoder needs more than `{MAX_METADATA_BYTES}` bytes for the image's metadata, its ICC profile, or can't read it, before its size is known; `--max-pixels` is set"
        )
    };
    let mut decoder = match reader.into_decoder() {
        Ok(decoder) => decoder,
        Err(image::ImageError::Limits(limit)) => {
            return Some(match limit.kind() {
                image::error::LimitErrorKind::DimensionError => format!(
                    "the decoder reads a side of more than `{DECODE_MAX_DIMENSION}` pixels; `--max-pixels` allows `{most}`"
                ),
                _ => metadata(),
            });
        }
        Err(_) => return None,
    };
    // The decoder offers the profile only as a copy, dropped at the end of this statement.
    if inspection.icc_profile && !matches!(decoder.icc_profile(), Ok(Some(_))) {
        return Some(metadata());
    }
    let (width, height) = decoder.dimensions();
    let pixels = u64::from(width) * u64::from(height);
    (pixels > most).then(|| {
        format!("the decoder reads the image as `{width}x{height}`, `{pixels}` pixels; `--max-pixels` allows `{most}`")
    })
}

/// Decode once to what the definitions read, turning the pixels by `orientation` if given.
fn decode(bytes: &[u8], rgba: bool, luma: bool, orientation: Option<u16>) -> Result<Pixels, HashError> {
    if rgba {
        let mut image = decode_rgba_v1(bytes)?;
        if let Some(tag) = orientation {
            let (width, height, pixels) = reorient(image.width(), image.height(), 4, image.into_pixels(), tag);
            image = RgbaBuf::new(width, height, pixels)?;
        }
        let luma = if luma {
            Some(LumaBuf::from_rgba8_v1(image.width(), image.height(), image.pixels())?)
        } else {
            None
        };
        return Ok(Pixels {
            width: image.width(),
            height: image.height(),
            rgba: Some(image),
            luma,
        });
    }
    let mut image = decode_luma_v1(bytes)?;
    if let Some(tag) = orientation {
        let (width, height, pixels) = reorient(image.width(), image.height(), 1, image.into_pixels(), tag);
        image = LumaBuf::new(width, height, pixels)?;
    }
    Ok(Pixels {
        width: image.width(),
        height: image.height(),
        rgba: None,
        luma: Some(image),
    })
}

fn image_hashes(request: &Request, pixels: &Pixels) -> Vec<HashOutcome> {
    request
        .options
        .definitions
        .iter()
        .map(|entry| match &entry.plan {
            Err(failure) => HashOutcome::failed(&entry.id, failure.code, &failure.message),
            Ok(plan) => wrong_source(entry, plan, true).unwrap_or_else(|| image_hash(entry, plan, pixels)),
        })
        .collect()
}

fn image_hash(entry: &Entry, plan: &Plan, pixels: &Pixels) -> HashOutcome {
    let started = Instant::now();
    let mut result = HashOutcome::new(&entry.id);
    let computed: Result<(), HashError> = (|| {
        let Definition::Bit(algorithm) = plan.definition else {
            return Err(HashError::UnknownAlgorithm(plan.definition.id().to_owned()));
        };
        let hash = match (algorithm, &pixels.rgba, &pixels.luma) {
            (Algorithm::PdqV1, Some(rgba), _) => {
                let pdq = pdq_v1(rgba.view());
                result.quality = Some(pdq.quality);
                pdq.hash
            }
            (Algorithm::BlockhashV1, Some(rgba), _) => blockhash_v1(rgba.view()),
            (_, _, Some(luma)) => algorithm.hash_luma(luma.view())?,
            _ => return Err(HashError::NotAnImageAlgorithm(algorithm)),
        };
        bit_hash(&mut result, &hash, plan)
    })();
    finish(result, computed, started)
}