Skip to main content

aspero_json/
claim.rs

1//! Claims as callers write them: one JSON object (or plain reference) per
2//! line, echoed back on every result.
3
4use aspero_core::{Claim, WorkId};
5use serde::Deserialize;
6use serde_json::{Value, json};
7
8const EMPTY: &str = "claim has no text, title, authors or identifiers";
9
10/// A claim as an agent would write it, one JSON object per stdin line.
11/// Unknown keys are rejected so typos aren't silently ignored.
12#[derive(Debug, Default, Deserialize)]
13#[serde(deny_unknown_fields)]
14pub struct ClaimInput {
15    pub text: Option<String>,
16    pub title: Option<String>,
17    #[serde(default)]
18    pub authors: Vec<String>,
19    pub year: Option<i16>,
20    #[serde(alias = "journal")]
21    pub container: Option<String>,
22    #[serde(default, deserialize_with = "text_or_number")]
23    pub volume: Option<String>,
24    /// The first page, or a range.
25    #[serde(default, alias = "pages", deserialize_with = "text_or_number")]
26    pub page: Option<String>,
27    /// The caller's own reference for this claim, echoed back untouched;
28    /// allowed here, read from the raw line (see [`InputClaim::from_line`]).
29    #[serde(rename = "key")]
30    pub _key: Option<serde::de::IgnoredAny>,
31    pub doi: Option<String>,
32    pub arxiv: Option<String>,
33    /// Any identifier form `lookup` accepts.
34    pub id: Option<String>,
35    #[serde(default)]
36    pub ids: Vec<String>,
37}
38
39/// Volumes and pages are written as numbers or strings ("e1234").
40fn text_or_number<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
41    Ok(match Option::<serde_json::Value>::deserialize(d)? {
42        Some(serde_json::Value::String(s)) => Some(s),
43        Some(serde_json::Value::Number(n)) => Some(n.to_string()),
44        None | Some(serde_json::Value::Null) => None,
45        Some(other) => {
46            return Err(serde::de::Error::custom(format!(
47                "expected text or a number, got {other}"
48            )));
49        }
50    })
51}
52
53impl ClaimInput {
54    pub fn into_claim(self) -> Result<Claim, String> {
55        let mut claim = match &self.text {
56            Some(text) => Claim::from_input(text),
57            None => Claim::default(),
58        };
59        let prefixed = [
60            self.doi.map(|d| format!("doi:{d}")),
61            self.arxiv.map(|a| format!("arxiv:{a}")),
62            self.id,
63        ];
64        for raw in prefixed.into_iter().flatten().chain(self.ids) {
65            let id: WorkId = raw.parse().map_err(|e| format!("{e}"))?;
66            if !claim.ids.contains(&id) {
67                claim.ids.push(id);
68            }
69        }
70        claim.title = self.title;
71        claim.authors = self.authors;
72        claim.year = self.year;
73        claim.container = self.container;
74        claim.volume = self.volume;
75        claim.page = self.page;
76        if claim.is_empty() {
77            return Err(EMPTY.into());
78        }
79        Ok(claim)
80    }
81}
82
83/// A claim with the input it came from and the caller's `key`, or why that
84/// input isn't one.
85pub struct InputClaim {
86    pub input: String,
87    pub key: Option<Value>,
88    pub claim: Result<Claim, String>,
89}
90
91impl InputClaim {
92    /// One stdin line: a JSON object or a plain reference. A JSON line's
93    /// `key` is kept even when the rest of it is invalid.
94    pub fn from_line(line: &str) -> Self {
95        let (key, claim) = match line.trim_start().starts_with('{') {
96            false => (
97                None,
98                Some(Claim::from_input(line))
99                    .filter(|c| !c.is_empty())
100                    .ok_or_else(|| EMPTY.to_owned()),
101            ),
102            true => match serde_json::from_str::<Value>(line) {
103                Err(e) => (None, Err(format!("invalid claim JSON: {e}"))),
104                Ok(value) => (
105                    value.get("key").cloned(),
106                    ClaimInput::deserialize(value)
107                        .map_err(|e| format!("invalid claim: {e}"))
108                        .and_then(ClaimInput::into_claim),
109                ),
110            },
111        };
112        InputClaim {
113            input: line.to_owned(),
114            key,
115            claim,
116        }
117    }
118
119    /// What every result for this claim starts with: the input, the
120    /// caller's key, and the claim as understood.
121    pub fn echo(&self) -> Value {
122        let mut echo = json!({ "input": self.input });
123        if let Some(key) = &self.key {
124            echo["key"] = key.clone();
125        }
126        if let Ok(claim) = &self.claim {
127            echo["claim"] = json!(claim);
128        }
129        echo
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    fn claim(line: &str) -> Result<Claim, String> {
138        InputClaim::from_line(line).claim
139    }
140
141    #[test]
142    fn json_lines_become_structured_claims() {
143        let c = claim(
144            r#"{"title": "Attention is all you need", "authors": ["Vaswani, A."], "year": 2017, "arxiv": "1706.03762"}"#,
145        )
146        .unwrap();
147        assert_eq!(c.year, Some(2017));
148        assert_eq!(c.ids[0].to_string(), "arxiv:1706.03762");
149        assert!(
150            claim(r#"{"titel": "typo"}"#)
151                .unwrap_err()
152                .contains("unknown field")
153        );
154        assert!(claim(r#"{"doi": "not a doi"}"#).is_err());
155    }
156
157    #[test]
158    fn journal_volume_and_page_as_text_or_numbers() {
159        let c = claim(
160            r#"{"title": "X", "journal": "N Engl J Med", "volume": 376, "pages": "2545-55"}"#,
161        )
162        .unwrap();
163        assert_eq!(c.container.as_deref(), Some("N Engl J Med"));
164        assert_eq!(c.volume.as_deref(), Some("376"));
165        assert_eq!(c.page.as_deref(), Some("2545-55"));
166        assert!(claim(r#"{"title": "X", "volume": [1]}"#).is_err());
167    }
168
169    #[test]
170    fn keys_are_echoed_even_for_invalid_claims() {
171        let ok = InputClaim::from_line(r#"{"key": {"note": "pe.md", "line": 7}, "title": "X"}"#);
172        assert_eq!(ok.echo()["key"], json!({"note": "pe.md", "line": 7}));
173        assert_eq!(ok.echo()["claim"], json!({"title": "X"}));
174        for blank in ["", "   ", r#"{"text": "  ", "key": 1}"#] {
175            assert!(claim(blank).is_err(), "{blank:?}");
176        }
177        let bad = InputClaim::from_line(r#"{"key": "ref-12", "titel": "typo"}"#);
178        assert!(bad.claim.is_err());
179        assert_eq!(bad.echo()["key"], "ref-12");
180        assert!(bad.echo().get("claim").is_none());
181    }
182}