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
//! A request: an id, a source and the definitions to compute, read from one JSON line.

use std::fmt;
use std::io;
use std::path::PathBuf;

use serde::{Serialize, Serializer};
use serde_json::{Map, Value};

use crate::definition::{DefinitionFailure, Plan};
use crate::{FORMAT, Outcome, RequestError};

/// The most entries a request's `definitions` may hold, `16`.
pub const MAX_DEFINITIONS: usize = 16;

/// The most bytes a request's `options` may take as JSON text, `65536`: on the command line, as
/// compact JSON; in a task, its `options` field as sent.
pub const MAX_OPTIONS_BYTES: usize = 64 * 1024;

/// The caller's id for a request, echoed back untouched in its result: a JSON string or integer.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Id {
    /// A string id.
    Text(String),
    /// An integer id, from `-2^63` to `2^64 - 1`.
    Integer(i128),
}

impl Id {
    /// Read an id from JSON: a string, or an integer that fits 64 bits signed or unsigned.
    #[must_use]
    pub fn from_json(value: &Value) -> Option<Self> {
        match value {
            Value::String(text) => Some(Self::Text(text.clone())),
            Value::Number(number) => number
                .as_i64()
                .map(i128::from)
                .or_else(|| number.as_u64().map(i128::from))
                .map(Self::Integer),
            _ => None,
        }
    }
}

impl fmt::Display for Id {
    /// The id as JSON: a quoted, escaped string or a bare integer. Equal ids print equally.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Text(text) => f.write_str(&Value::String(text.clone()).to_string()),
            Self::Integer(number) => write!(f, "{number}"),
        }
    }
}

impl Serialize for Id {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Text(text) => serializer.serialize_str(text),
            Self::Integer(number) => serializer.serialize_i128(*number),
        }
    }
}

/// Where a request's bytes or text come from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
    /// An image file on the machine the runner runs on. A relative path is read from the runner's
    /// working directory.
    Path(PathBuf),
    /// Text to hash, unchanged: the runner changes no character.
    Text(String),
    /// Image bytes sent inline, decoded from the request's base64.
    Bytes(Vec<u8>),
}

/// Whether to turn an image by its EXIF orientation tag before hashing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Orientation {
    /// Hash the pixels as stored, the default: the hash definitions don't rotate.
    #[default]
    Ignore,
    /// Turn the pixels by the tag, so the image hashed is the one displayed upright.
    Apply,
}

/// One entry of `definitions`: the id as given, and the plan or the reason there's none.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    /// The id as the request gave it.
    pub id: String,
    /// The checked definition and parameters, or the definition-level error.
    pub plan: Result<Plan, DefinitionFailure>,
}

/// A request's `options`: which definitions to compute, and how.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Options {
    /// The definitions, in the order their results are returned.
    pub definitions: Vec<Entry>,
    /// Whether to apply EXIF orientation to an image.
    pub orientation: Orientation,
}

impl Options {
    /// Read `options` from JSON. A definition-level problem, such as an unknown id or a bad
    /// parameter, is kept in its [`Entry`] rather than refusing the whole object.
    ///
    /// # Errors
    ///
    /// Returns a message for `invalid_options` when `options` isn't an object, has a key the
    /// format doesn't define, lacks `format` or gives a version other than [`FORMAT`], lacks a
    /// non-empty `definitions` list or one of more than [`MAX_DEFINITIONS`] entries, holds an
    /// entry that isn't an object with a string `id` or that repeats an earlier entry (the same
    /// definition with the same parameters), or gives an `orientation` other than `ignore` or
    /// `apply`.
    pub fn from_json(value: &Value) -> Result<Self, String> {
        let Value::Object(options) = value else {
            return Err("`options` must be an object".to_owned());
        };
        if let Some(unknown) = options
            .keys()
            .find(|key| !matches!(key.as_str(), "format" | "definitions" | "orientation"))
        {
            return Err(format!(
                "`options` has no key `{unknown}`; it takes `format`, `definitions` and `orientation`"
            ));
        }
        match options.get("format") {
            Some(format) if format.as_u64() == Some(u64::from(FORMAT)) => {}
            Some(format) => {
                return Err(format!(
                    "this runner reads format `{FORMAT}`, not `{format}`; check `info` for the format it speaks"
                ));
            }
            None => return Err(format!("`options` needs `\"format\": {FORMAT}`")),
        }
        let orientation = match options.get("orientation").map(Value::as_str) {
            None | Some(Some("ignore")) => Orientation::Ignore,
            Some(Some("apply")) => Orientation::Apply,
            Some(_) => return Err("`orientation` is `\"ignore\"` or `\"apply\"`".to_owned()),
        };
        let entries = match options.get("definitions") {
            Some(Value::Array(entries)) if !entries.is_empty() => entries,
            _ => return Err("`options` needs `definitions`, a list of one or more `{\"id\": ...}` objects".to_owned()),
        };
        if entries.len() > MAX_DEFINITIONS {
            return Err(format!(
                "`definitions` holds `{}` entries; a request asks for at most `{MAX_DEFINITIONS}`",
                entries.len()
            ));
        }
        let definitions = entries
            .iter()
            .enumerate()
            .map(|(index, entry)| match entry {
                Value::Object(entry) => match entry.get("id") {
                    Some(Value::String(id)) => Ok(Entry {
                        id: id.clone(),
                        plan: Plan::from_entry(id, entry),
                    }),
                    _ => Err(format!("`definitions[{index}]` needs a string `id`")),
                },
                _ => Err(format!("`definitions[{index}]` must be an object with an `id`")),
            })
            .collect::<Result<Vec<Entry>, _>>()?;
        // The same object twice, its keys in any order, or two checked plans that are equal...
        for later in 1..definitions.len() {
            let repeats = (0..later).find(|&earlier| {
                entries[earlier] == entries[later]
                    || matches!((&definitions[earlier].plan, &definitions[later].plan), (Ok(a), Ok(b)) if a == b)
            });
            if let Some(earlier) = repeats {
                return Err(format!(
                    "`definitions[{later}]` repeats `definitions[{earlier}]`: the same definition with the same parameters"
                ));
            }
        }
        Ok(Self {
            definitions,
            orientation,
        })
    }
}

/// One request: an id, a source and the definitions to compute.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
    /// The caller's id, echoed in the result.
    pub id: Id,
    /// The image or text to hash.
    pub source: Source,
    /// The definitions to compute.
    pub options: Options,
}

impl Request {
    /// Read a request from one line of JSON: `id`, one of `path`, `text` and `base64`, and
    /// `options`.
    ///
    /// # Errors
    ///
    /// Returns the error [`Outcome`] to write in the request's place, boxed, with the id when one
    /// could be read: `invalid_request`, `no_source`, `too_large` for inline bytes over the file
    /// limit, or `invalid_options`.
    pub fn from_json(line: &[u8]) -> Result<Self, Box<Outcome>> {
        let fail = |id: Option<&Id>, code, message: String| Box::new(Outcome::error(id.cloned(), code, message));
        let request: Map<String, Value> = match serde_json::from_slice(line) {
            Ok(Value::Object(request)) => request,
            Ok(_) => {
                return Err(fail(
                    None,
                    RequestError::InvalidRequest,
                    "a request must be a JSON object".to_owned(),
                ));
            }
            Err(error) => {
                return Err(fail(
                    None,
                    RequestError::InvalidRequest,
                    format!("the line isn't JSON: {error}"),
                ));
            }
        };
        let id = match request.get("id").map(Id::from_json) {
            Some(Some(id)) => id,
            Some(None) => {
                return Err(fail(
                    None,
                    RequestError::InvalidRequest,
                    "`id` must be a string or an integer".to_owned(),
                ));
            }
            None => {
                return Err(fail(
                    None,
                    RequestError::InvalidRequest,
                    "the request has no `id`".to_owned(),
                ));
            }
        };
        if let Some(unknown) = request
            .keys()
            .find(|key| !matches!(key.as_str(), "id" | "path" | "text" | "base64" | "options"))
        {
            return Err(fail(
                Some(&id),
                RequestError::InvalidRequest,
                format!("a request has no field `{unknown}`; it takes `id`, `path`, `text`, `base64` and `options`"),
            ));
        }
        let sources: Vec<(&str, &Value)> = ["path", "text", "base64"]
            .into_iter()
            .filter_map(|name| request.get(name).map(|value| (name, value)))
            .collect();
        let source = match sources.as_slice() {
            [(name, value)] => source(name, value).map_err(|(code, message)| fail(Some(&id), code, message))?,
            [] => {
                return Err(fail(
                    Some(&id),
                    RequestError::NoSource,
                    "the request needs one source: `path`, `text` or `base64`".to_owned(),
                ));
            }
            _ => {
                return Err(fail(
                    Some(&id),
                    RequestError::NoSource,
                    "the request gives more than one source; give exactly one of `path`, `text` and `base64`"
                        .to_owned(),
                ));
            }
        };
        let options = match request.get("options") {
            Some(options) if longer_than(options, MAX_OPTIONS_BYTES) => {
                Err(format!("`options` is more than `{MAX_OPTIONS_BYTES}` bytes of JSON"))
            }
            Some(options) => Options::from_json(options),
            None => Err("the request has no `options`".to_owned()),
        }
        .map_err(|message| fail(Some(&id), RequestError::InvalidOptions, message))?;
        Ok(Self { id, source, options })
    }
}

/// Whether `value` takes more than `most` bytes as compact JSON, counted without writing it out.
fn longer_than(value: &Value, most: usize) -> bool {
    struct Count {
        bytes: usize,
        most: usize,
    }

    impl io::Write for Count {
        fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
            self.bytes += buffer.len();
            if self.bytes > self.most {
                return Err(io::Error::other("over the limit"));
            }
            Ok(buffer.len())
        }

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

    serde_json::to_writer(&mut Count { bytes: 0, most }, value).is_err()
}

/// The source named `name`, read from its JSON value.
fn source(name: &str, value: &Value) -> Result<Source, (RequestError, String)> {
    let Value::String(text) = value else {
        return Err((RequestError::InvalidRequest, format!("`{name}` must be a string")));
    };
    match name {
        "path" if text.is_empty() => Err((RequestError::InvalidRequest, "`path` is empty".to_owned())),
        "path" => Ok(Source::Path(PathBuf::from(text))),
        "text" => Ok(Source::Text(text.clone())),
        _ => inline_bytes(name, text).map(Source::Bytes),
    }
}

/// Image bytes sent inline as base64 in the field `name`: refused as `too_large` when they'd be
/// more than the decoder reads, before decoding any, and as `invalid_request` when they aren't
/// base64.
pub(crate) fn inline_bytes(name: &str, text: &str) -> Result<Vec<u8>, (RequestError, String)> {
    let longest = legit_hashes::DECODE_MAX_INPUT;
    if text.len() / 4 * 3 > longest {
        return Err((
            RequestError::TooLarge,
            format!("the {name} holds more than `{longest}` bytes, the most the decoder reads"),
        ));
    }
    crate::base64::decode(text).map_err(|message| (RequestError::InvalidRequest, format!("`{name}` {message}")))
}

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

    #[test]
    fn ids_print_as_json_so_equal_ids_compare_equal() {
        assert_eq!(Id::Text("a\"b".to_owned()).to_string(), r#""a\"b""#);
        assert_eq!(Id::Integer(-3).to_string(), "-3");
        assert_eq!(
            Id::from_json(&serde_json::json!(u64::MAX)),
            Some(Id::Integer(i128::from(u64::MAX)))
        );
        assert_eq!(Id::from_json(&serde_json::json!(1.5)), None);
        assert_eq!(Id::from_json(&serde_json::json!(null)), None);
    }

    #[test]
    fn a_request_is_read_with_its_definitions() {
        let request = Request::from_json(
            br#"{"id":7,"text":"hello","options":{"format":1,"definitions":[{"id":"simhash-v1","tokens":"words"},{"id":"nope-v1"}]}}"#,
        )
        .expect("valid");
        assert_eq!(request.id, Id::Integer(7));
        assert_eq!(request.source, Source::Text("hello".to_owned()));
        assert_eq!(request.options.definitions.len(), 2);
        assert!(request.options.definitions[0].plan.is_ok());
        assert!(request.options.definitions[1].plan.is_err());
    }

    #[test]
    fn each_malformed_request_has_its_code() {
        let cases: [(&str, RequestError, bool); 12] = [
            ("not json", RequestError::InvalidRequest, false),
            ("[1]", RequestError::InvalidRequest, false),
            (r#"{"text":"x"}"#, RequestError::InvalidRequest, false),
            (r#"{"id":true,"text":"x"}"#, RequestError::InvalidRequest, false),
            (
                r#"{"id":"a","text":"x","extra":1,"options":{}}"#,
                RequestError::InvalidRequest,
                true,
            ),
            (r#"{"id":"a","options":{}}"#, RequestError::NoSource, true),
            (
                r#"{"id":"a","text":"x","path":"y","options":{}}"#,
                RequestError::NoSource,
                true,
            ),
            (
                r#"{"id":"a","base64":"!!!!","options":{}}"#,
                RequestError::InvalidRequest,
                true,
            ),
            (r#"{"id":"a","text":"x"}"#, RequestError::InvalidOptions, true),
            (
                r#"{"id":"a","text":"x","options":{"definitions":[{"id":"pdq-v1"}]}}"#,
                RequestError::InvalidOptions,
                true,
            ),
            (
                r#"{"id":"a","text":"x","options":{"format":2,"definitions":[{"id":"pdq-v1"}]}}"#,
                RequestError::InvalidOptions,
                true,
            ),
            (
                r#"{"id":"a","text":"x","options":{"format":1,"definitions":["pdq-v1"]}}"#,
                RequestError::InvalidOptions,
                true,
            ),
        ];
        for (line, code, has_id) in cases {
            let outcome = Request::from_json(line.as_bytes()).expect_err(line);
            assert_eq!(outcome.error_type, Some(code), "{line}");
            assert_eq!(outcome.id.is_some(), has_id, "{line}");
        }
    }
}