opencitations-client 0.1.0

An async Rust client for the OpenCitations Index and Meta REST APIs
Documentation
//! The OpenCitations Index: the citation edges themselves.
//!
//! Every field of every response arrives as a string, including the ones that
//! are plainly numbers, dates and booleans, so the types here do the reading
//! once at the boundary and hand back something already parsed.

use crate::date::{PartialDate, Timespan};
use crate::id::{Identifier, Oci};
use serde::{Deserialize, Deserializer, Serialize};
use std::fmt;

/// One citation: an edge from a citing work to a cited one.
///
/// Both ends arrive as the whole bag of identifiers the work is known by, since
/// which scheme is present varies by source -- reach for
/// [`Citation::citing_doi`] rather than indexing into them.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Citation {
    /// the identifier of this citation itself
    pub oci: Oci,
    /// every identifier the citing work is known by
    #[serde(deserialize_with = "bag")]
    pub citing: Vec<Identifier>,
    /// every identifier the cited work is known by
    #[serde(deserialize_with = "bag")]
    pub cited: Vec<Identifier>,
    /// when the citing work was published, to whatever precision is recorded
    #[serde(default, deserialize_with = "blank_is_none")]
    pub creation: Option<PartialDate>,
    /// how long after the cited work the citing work appeared; negative when it
    /// appeared first
    #[serde(default, deserialize_with = "blank_is_none")]
    pub timespan: Option<Timespan>,
    /// whether both works appeared in the same venue
    #[serde(rename = "journal_sc", deserialize_with = "yes_or_no")]
    pub journal_self_citation: bool,
    /// whether the two works share an author
    #[serde(rename = "author_sc", deserialize_with = "yes_or_no")]
    pub author_self_citation: bool,
}

impl Citation {
    /// The citing work's DOI, when it has one.
    pub fn citing_doi(&self) -> Option<&str> {
        self.citing.iter().find_map(Identifier::as_doi)
    }

    /// The cited work's DOI, when it has one.
    pub fn cited_doi(&self) -> Option<&str> {
        self.cited.iter().find_map(Identifier::as_doi)
    }
}

/// Reads the space-separated bag of identifiers into all of them.
fn bag<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Identifier>, D::Error> {
    let raw = String::deserialize(deserializer)?;
    Identifier::parse_bag(&raw).map_err(serde::de::Error::custom)
}

/// Reads a field that is either a value or the empty string OpenCitations uses
/// where a value is unknown.
fn blank_is_none<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: std::str::FromStr,
    T::Err: fmt::Display,
{
    let raw = String::deserialize(deserializer)?;
    if raw.trim().is_empty() {
        return Ok(None);
    }
    raw.trim()
        .parse()
        .map(Some)
        .map_err(serde::de::Error::custom)
}

/// Reads the `yes`/`no` OpenCitations writes where a boolean belongs.
fn yes_or_no<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
    let raw = String::deserialize(deserializer)?;
    match raw.trim().to_ascii_lowercase().as_str() {
        "yes" | "true" | "1" => Ok(true),
        "no" | "false" | "0" | "" => Ok(false),
        other => Err(serde::de::Error::custom(format!(
            "`{other}` is neither `yes` nor `no`"
        ))),
    }
}

/// The count routes answer with a list holding one object holding one string.
#[derive(Debug, Deserialize)]
pub(crate) struct Count {
    pub(crate) count: String,
}

/// A field of a [`Citation`], as the api names it.
///
/// Used to narrow and to order a listing; the api reads these names in its
/// `filter` and `sort` parameters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Field {
    /// the citation's own identifier
    Oci,
    /// the citing work's identifiers
    Citing,
    /// the cited work's identifiers
    Cited,
    /// the citing work's publication date
    Creation,
    /// the interval between the two publication dates
    Timespan,
    /// whether both works appeared in the same venue
    JournalSelfCitation,
    /// whether the two works share an author
    AuthorSelfCitation,
}

impl Field {
    /// The name the api reads this field by.
    pub fn name(&self) -> &'static str {
        match self {
            Field::Oci => "oci",
            Field::Citing => "citing",
            Field::Cited => "cited",
            Field::Creation => "creation",
            Field::Timespan => "timespan",
            Field::JournalSelfCitation => "journal_sc",
            Field::AuthorSelfCitation => "author_sc",
        }
    }
}

impl fmt::Display for Field {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// How a [`Filter`] compares a field against its value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Comparison {
    /// the field is exactly the value
    #[default]
    Is,
    /// the field sorts after the value
    GreaterThan,
    /// the field sorts before the value
    LessThan,
}

impl Comparison {
    fn prefix(&self) -> &'static str {
        match self {
            Comparison::Is => "",
            Comparison::GreaterThan => ">",
            Comparison::LessThan => "<",
        }
    }
}

/// A narrowing applied by the api rather than by the caller.
///
/// Worth preferring over filtering the results here: a well cited work has
/// thousands of citations and they arrive in one unpaged response.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Filter {
    field: Field,
    comparison: Comparison,
    value: String,
}

impl Filter {
    /// The citations whose `field` is exactly `value`.
    pub fn is(field: Field, value: impl Into<String>) -> Self {
        Filter {
            field,
            comparison: Comparison::Is,
            value: value.into(),
        }
    }

    /// The citations whose `field` sorts after `value`, e.g. everything created
    /// after a given year.
    pub fn greater_than(field: Field, value: impl Into<String>) -> Self {
        Filter {
            field,
            comparison: Comparison::GreaterThan,
            value: value.into(),
        }
    }

    /// The citations whose `field` sorts before `value`.
    pub fn less_than(field: Field, value: impl Into<String>) -> Self {
        Filter {
            field,
            comparison: Comparison::LessThan,
            value: value.into(),
        }
    }
}

impl fmt::Display for Filter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}:{}{}",
            self.field,
            self.comparison.prefix(),
            self.value
        )
    }
}

/// Which way a [`Sort`] runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Order {
    /// earliest, or lowest, first
    #[default]
    Ascending,
    /// latest, or highest, first
    Descending,
}

/// The order the api returns a listing in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sort {
    field: Field,
    order: Order,
}

impl Sort {
    /// Earliest, or lowest, first.
    pub fn ascending(field: Field) -> Self {
        Sort {
            field,
            order: Order::Ascending,
        }
    }

    /// Latest, or highest, first.
    pub fn descending(field: Field) -> Self {
        Sort {
            field,
            order: Order::Descending,
        }
    }
}

impl fmt::Display for Sort {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let order = match self.order {
            Order::Ascending => "asc",
            Order::Descending => "desc",
        };
        write!(f, "{order}({})", self.field)
    }
}

/// What to ask of a citation listing beyond the identifier itself.
///
/// The api applies all of it before answering, so a narrow listing is one
/// response rather than one response and a lot of discarding.
///
/// ```
/// use opencitations_client::{Field, Filter, Refine, Sort};
///
/// // the citations this work picked up since 2024, earliest first
/// let refine = Refine::new()
///     .filter(Filter::greater_than(Field::Creation, "2023"))
///     .sort(Sort::ascending(Field::Creation));
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Refine {
    filters: Vec<Filter>,
    sort: Option<Sort>,
}

impl Refine {
    /// Asks for everything, in whatever order the api answers in.
    pub fn new() -> Self {
        Refine::default()
    }

    /// Narrows the listing. Repeating this ANDs the filters.
    pub fn filter(mut self, filter: Filter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Orders the listing. The last one set wins.
    pub fn sort(mut self, sort: Sort) -> Self {
        self.sort = Some(sort);
        self
    }

    /// Whether this asks for anything at all.
    pub fn is_empty(&self) -> bool {
        self.filters.is_empty() && self.sort.is_none()
    }

    /// The query parameters this renders to, ready to be percent-encoded.
    pub(crate) fn params(&self) -> Vec<(&'static str, String)> {
        let filters = self
            .filters
            .iter()
            .map(|filter| ("filter", filter.to_string()));
        let sort = self.sort.map(|sort| ("sort", sort.to_string()));
        filters.chain(sort).collect()
    }
}

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

    /// The shape the api actually answers with, as captured from
    /// `/index/v2/citations/doi:10.1016/j.marpol.2021.104855`.
    const WIRE: &str = r#"{
        "oci": "06024047477-06220256775",
        "citing": "omid:br/06024047477 doi:10.22533/at.ed.9662430046",
        "cited": "omid:br/06220256775 doi:10.1016/j.marpol.2021.104855 openalex:W3214241825",
        "creation": "2024",
        "timespan": "P2Y",
        "journal_sc": "no",
        "author_sc": "no"
    }"#;

    #[test]
    fn a_citation_reads_every_stringly_typed_field() {
        let citation: Citation = serde_json::from_str(WIRE).unwrap();

        assert_eq!(citation.oci.to_string(), "06024047477-06220256775");
        assert_eq!(citation.citing_doi(), Some("10.22533/at.ed.9662430046"));
        assert_eq!(citation.cited_doi(), Some("10.1016/j.marpol.2021.104855"));
        assert_eq!(citation.creation.unwrap().year(), 2024);
        assert_eq!(citation.timespan.unwrap().as_months(), 24);
        assert!(!citation.journal_self_citation);
        assert!(!citation.author_self_citation);
        // the bag keeps every scheme, not just the doi
        assert_eq!(citation.cited.len(), 3);
    }

    #[test]
    fn an_unknown_creation_or_timespan_is_none_rather_than_an_error() {
        let wire = WIRE.replace(r#""creation": "2024""#, r#""creation": """#);
        let wire = wire.replace(r#""timespan": "P2Y""#, r#""timespan": """#);

        let citation: Citation = serde_json::from_str(&wire).unwrap();
        assert_eq!(citation.creation, None);
        assert_eq!(citation.timespan, None);
    }

    #[test]
    fn a_self_citation_reads_as_the_boolean_it_is() {
        let wire = WIRE.replace(r#""author_sc": "no""#, r#""author_sc": "yes""#);
        let citation: Citation = serde_json::from_str(&wire).unwrap();
        assert!(citation.author_self_citation);
    }

    #[test]
    fn a_refinement_renders_the_parameters_the_api_reads() {
        let refine = Refine::new()
            .filter(Filter::greater_than(Field::Creation, "2023"))
            .filter(Filter::is(Field::AuthorSelfCitation, "no"))
            .sort(Sort::descending(Field::Timespan));

        assert_eq!(
            refine.params(),
            vec![
                ("filter", "creation:>2023".to_string()),
                ("filter", "author_sc:no".to_string()),
                ("sort", "desc(timespan)".to_string()),
            ]
        );
    }

    #[test]
    fn an_empty_refinement_asks_for_nothing() {
        assert!(Refine::new().is_empty());
        assert!(Refine::new().params().is_empty());
    }
}