Skip to main content

legit_hasher/
distance.rs

1//! `legit-hasher distance`: compare pairs of stored hashes or signatures, one JSON line each way.
2
3use std::io::{BufRead, Write};
4
5use legit_hashes::{Error as HashError, Hash, Signature};
6use serde::Serialize;
7use serde_json::{Map, Value};
8
9use crate::request::Id;
10use crate::{Error, FORMAT, Status, Summary};
11
12/// Why a pair wasn't compared.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
14#[serde(rename_all = "snake_case")]
15#[non_exhaustive]
16pub enum DistanceError {
17    /// The line isn't an object with string fields `a` and `b`, an optional `id`, and no others.
18    InvalidRequest,
19    /// `a` or `b` isn't a stored form this runner reads.
20    InvalidHash,
21    /// `a` and `b` come from different definitions, or one is a bit hash and the other a
22    /// signature.
23    Mismatch,
24}
25
26impl DistanceError {
27    /// The code as results carry it, such as `mismatch`.
28    ///
29    /// ```
30    /// assert_eq!(legit_hasher::DistanceError::InvalidHash.as_str(), "invalid_hash");
31    /// ```
32    #[must_use]
33    pub const fn as_str(self) -> &'static str {
34        match self {
35            Self::InvalidRequest => "invalid_request",
36            Self::InvalidHash => "invalid_hash",
37            Self::Mismatch => "mismatch",
38        }
39    }
40}
41
42/// The comparison of one pair, as one JSON line.
43#[derive(Debug, Clone, PartialEq, Serialize)]
44pub struct Comparison {
45    /// The format version of the line: [`FORMAT`].
46    pub format: u32,
47    /// The pair's `id`, when it gave one.
48    pub id: Option<Id>,
49    /// The input line, counting from 1, in batch mode. A task on a stream has none.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub line: Option<u64>,
52    /// Whether the pair was compared.
53    pub status: Status,
54    /// Why it wasn't.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub error_type: Option<DistanceError>,
57    /// What was wrong, for a person.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub error: Option<String>,
60    /// The definition both come from.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub definition: Option<&'static str>,
63    /// For bit hashes, how many bits differ.
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub distance: Option<u32>,
66    /// For bit hashes, their width.
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub bits: Option<u32>,
69    /// For signatures, how many values match.
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub matching: Option<u32>,
72    /// For signatures, how many values each holds.
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub values: Option<u32>,
75    /// For signatures, the estimated Jaccard similarity: `matching / values`.
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub similarity: Option<f64>,
78}
79
80impl Comparison {
81    fn new(id: Option<Id>, line: Option<u64>) -> Self {
82        Self {
83            format: FORMAT,
84            id,
85            line,
86            status: Status::Success,
87            error_type: None,
88            error: None,
89            definition: None,
90            distance: None,
91            bits: None,
92            matching: None,
93            values: None,
94            similarity: None,
95        }
96    }
97
98    fn failed(mut self, code: DistanceError, message: impl Into<String>) -> Self {
99        self.status = Status::Error;
100        self.error_type = Some(code);
101        self.error = Some(message.into());
102        self
103    }
104}
105
106/// A stored form read as whichever kind it names.
107enum Stored {
108    Bit(Hash),
109    Signature(Box<Signature>),
110}
111
112fn parse(name: &str, text: &str) -> Result<Stored, String> {
113    match text.parse::<Hash>() {
114        Ok(hash) => Ok(Stored::Bit(hash)),
115        Err(HashError::NotABitHash(_)) => text
116            .parse::<Signature>()
117            .map(|signature| Stored::Signature(Box::new(signature)))
118            .map_err(|error| format!("`{name}`: {error}")),
119        Err(error) => Err(format!("`{name}`: {error}")),
120    }
121}
122
123/// Compare the pair on one line: `{"id": ..., "a": "<stored form>", "b": "<stored form>"}`.
124#[must_use]
125pub fn compare(line: &[u8], number: u64) -> Comparison {
126    let pair: Map<String, Value> = match serde_json::from_slice(line) {
127        Ok(Value::Object(pair)) => pair,
128        _ => {
129            return Comparison::new(None, Some(number)).failed(
130                DistanceError::InvalidRequest,
131                "a pair is a JSON object with `a` and `b`",
132            );
133        }
134    };
135    let id = pair.get("id").and_then(Id::from_json);
136    let comparison = Comparison::new(id, Some(number));
137    if let Some(unknown) = pair.keys().find(|key| !matches!(key.as_str(), "id" | "a" | "b")) {
138        return comparison.failed(
139            DistanceError::InvalidRequest,
140            format!("a pair has no field `{unknown}`; it takes `id`, `a` and `b`"),
141        );
142    }
143    if pair.get("id").is_some() && comparison.id.is_none() {
144        return comparison.failed(DistanceError::InvalidRequest, "`id` must be a string or an integer");
145    }
146    let (Some(Value::String(a)), Some(Value::String(b))) = (pair.get("a"), pair.get("b")) else {
147        return comparison.failed(DistanceError::InvalidRequest, "a pair needs `a` and `b`, each a string");
148    };
149    compare_stored(comparison, a, b)
150}
151
152/// Compare `a` and `b`, two stored forms, as one pair with this `id` and no line: the comparison
153/// a distance task on a stream gets.
154#[cfg(feature = "serve")]
155pub(crate) fn compare_pair(id: Id, a: &str, b: &str) -> Comparison {
156    compare_stored(Comparison::new(Some(id), None), a, b)
157}
158
159/// The comparison of a distance task on a stream that doesn't give both `a` and `b`.
160#[cfg(feature = "serve")]
161pub(crate) fn invalid_pair(id: Id, message: &str) -> Comparison {
162    Comparison::new(Some(id), None).failed(DistanceError::InvalidRequest, message)
163}
164
165/// Fill in `comparison` with the distance between the stored forms `a` and `b`.
166fn compare_stored(comparison: Comparison, a: &str, b: &str) -> Comparison {
167    let (a, b) = match (parse("a", a), parse("b", b)) {
168        (Ok(a), Ok(b)) => (a, b),
169        (Err(message), _) | (_, Err(message)) => return comparison.failed(DistanceError::InvalidHash, message),
170    };
171    let mut comparison = comparison;
172    match (a, b) {
173        (Stored::Bit(a), Stored::Bit(b)) => match a.distance(&b) {
174            Ok(distance) => {
175                comparison.definition = Some(a.algorithm().id());
176                comparison.distance = Some(distance);
177                comparison.bits = Some(a.bits());
178                comparison
179            }
180            Err(error) => comparison.failed(DistanceError::Mismatch, error.to_string()),
181        },
182        (Stored::Signature(a), Stored::Signature(b)) => match a.matching(&b) {
183            Ok(matching) => {
184                let values = a.algorithm().value_count();
185                comparison.definition = Some(a.algorithm().id());
186                comparison.matching = Some(matching);
187                comparison.values = Some(values);
188                comparison.similarity = Some(f64::from(matching) / f64::from(values));
189                comparison
190            }
191            Err(error) => comparison.failed(DistanceError::Mismatch, error.to_string()),
192        },
193        (Stored::Bit(a), Stored::Signature(b)) => comparison.failed(
194            DistanceError::Mismatch,
195            format!(
196                "can't compare a `{}` hash with a `{}` signature",
197                a.algorithm(),
198                b.algorithm()
199            ),
200        ),
201        (Stored::Signature(a), Stored::Bit(b)) => comparison.failed(
202            DistanceError::Mismatch,
203            format!(
204                "can't compare a `{}` signature with a `{}` hash",
205                a.algorithm(),
206                b.algorithm()
207            ),
208        ),
209    }
210}
211
212/// Compare every pair in `input`, writing one line each to `output`, in order. Blank lines are
213/// skipped. Each line is flushed as it is written, so a caller that sends a pair and waits for its
214/// reply gets it while the input stays open.
215///
216/// # Errors
217///
218/// Returns [`Error::Io`] when reading `input` or writing `output` fails.
219pub fn distances(input: impl BufRead, mut output: impl Write) -> Result<Summary, Error> {
220    let mut summary = Summary::default();
221    for (index, line) in input.split(b'\n').enumerate() {
222        let line = line.map_err(|error| Error::io("couldn't read the input", error))?;
223        if line.iter().all(u8::is_ascii_whitespace) {
224            continue;
225        }
226        let comparison = compare(&line, index as u64 + 1);
227        summary.written += 1;
228        summary.failed += u64::from(comparison.status == Status::Error);
229        let json = serde_json::to_string(&comparison).map_err(|error| Error::Internal(error.to_string()))?;
230        writeln!(output, "{json}")
231            .and_then(|()| output.flush())
232            .map_err(|error| Error::io("couldn't write the output", error))?;
233    }
234    Ok(summary)
235}