opencitations-client 0.1.0

An async Rust client for the OpenCitations Index and Meta REST APIs
Documentation
//! The prefixed identifiers OpenCitations addresses everything by.
//!
//! Every id in both apis is written `scheme:value` -- `doi:10.1016/j.marpol.2021.104855`,
//! `pmid:22683049`, `omid:br/06220256775` -- and a work is usually known by
//! several at once, which is why the `citing`, `cited` and `id` fields arrive
//! as a space-separated bag of them rather than as one string.

use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

/// One identifier of a bibliographic entity, in the `scheme:value` form
/// OpenCitations writes.
///
/// The known schemes get a variant of their own so a caller can match on them;
/// anything else is kept verbatim in [`Identifier::Other`] rather than being
/// refused, because OpenCitations adds sources over time and an id this crate
/// has not heard of is still an id worth passing back.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Identifier {
    /// a DOI, e.g. `doi:10.1016/j.marpol.2021.104855`
    Doi(String),
    /// a PubMed id, e.g. `pmid:22683049`
    Pmid(String),
    /// a PubMed Central id, e.g. `pmcid:PMC3339580`
    Pmcid(String),
    /// an OpenCitations Meta id, e.g. `omid:br/06220256775` for a work or
    /// `omid:ra/06220760311` for an agent
    Omid(String),
    /// an ISSN, which identifies a venue rather than a work
    Issn(String),
    /// an ISBN
    Isbn(String),
    /// an OpenAlex id, e.g. `openalex:W3214241825`
    OpenAlex(String),
    /// an ORCID, which identifies a person rather than a work; Meta credits
    /// authors by one where it has it
    Orcid(String),
    /// a ROR id, which identifies an institution
    Ror(String),
    /// a Crossref member id, e.g. `crossref:78`
    Crossref(String),
    /// a scheme this crate does not know, kept as it arrived
    Other {
        /// the scheme, lowercased
        scheme: String,
        /// everything after the first `:`
        value: String,
    },
}

impl Identifier {
    /// A DOI identifier. The `doi:` prefix is added, not expected.
    pub fn doi(doi: impl Into<String>) -> Self {
        Identifier::Doi(doi.into())
    }

    /// A PubMed identifier. The `pmid:` prefix is added, not expected.
    pub fn pmid(pmid: impl Into<String>) -> Self {
        Identifier::Pmid(pmid.into())
    }

    /// An OpenCitations Meta identifier. The `omid:` prefix is added, not
    /// expected, so this takes the `br/06220256775` half.
    pub fn omid(omid: impl Into<String>) -> Self {
        Identifier::Omid(omid.into())
    }

    /// An ISSN, which is how a venue is addressed.
    pub fn issn(issn: impl Into<String>) -> Self {
        Identifier::Issn(issn.into())
    }

    /// The scheme, lowercased: `doi`, `pmid`, `omid`, ...
    pub fn scheme(&self) -> &str {
        match self {
            Identifier::Doi(_) => "doi",
            Identifier::Pmid(_) => "pmid",
            Identifier::Pmcid(_) => "pmcid",
            Identifier::Omid(_) => "omid",
            Identifier::Issn(_) => "issn",
            Identifier::Isbn(_) => "isbn",
            Identifier::OpenAlex(_) => "openalex",
            Identifier::Orcid(_) => "orcid",
            Identifier::Ror(_) => "ror",
            Identifier::Crossref(_) => "crossref",
            Identifier::Other { scheme, .. } => scheme,
        }
    }

    /// Everything after the scheme, without the `:`.
    pub fn value(&self) -> &str {
        match self {
            Identifier::Doi(value)
            | Identifier::Pmid(value)
            | Identifier::Pmcid(value)
            | Identifier::Omid(value)
            | Identifier::Issn(value)
            | Identifier::Isbn(value)
            | Identifier::OpenAlex(value)
            | Identifier::Orcid(value)
            | Identifier::Ror(value)
            | Identifier::Crossref(value)
            | Identifier::Other { value, .. } => value,
        }
    }

    /// The DOI, when this is one.
    ///
    /// The usual reason to reach into a `citing` or `cited` bag: a DOI is what
    /// another api -- crossref, a bibliography, a reference manager -- can be
    /// asked about next.
    pub fn as_doi(&self) -> Option<&str> {
        match self {
            Identifier::Doi(doi) => Some(doi),
            _ => None,
        }
    }

    /// Reads the space-separated bag of identifiers OpenCitations writes into
    /// its `citing`, `cited` and `id` fields.
    ///
    /// An id in the list that cannot be read stops the whole list, because a
    /// silently shortened bag is indistinguishable from a work that is known by
    /// fewer identifiers.
    pub fn parse_bag(bag: &str) -> Result<Vec<Identifier>> {
        bag.split_whitespace().map(Identifier::from_str).collect()
    }
}

impl FromStr for Identifier {
    type Err = Error;

    fn from_str(id: &str) -> Result<Self> {
        let id = id.trim();
        let Some((scheme, value)) = id.split_once(':') else {
            return Err(Error::UnprefixedIdentifier {
                given: id.to_string(),
            });
        };
        if scheme.is_empty() {
            return Err(Error::InvalidIdentifier {
                given: id.to_string(),
                why: "it has no scheme before the `:`",
            });
        }
        if value.is_empty() {
            return Err(Error::InvalidIdentifier {
                given: id.to_string(),
                why: "it has no value after the `:`",
            });
        }

        let value = value.to_string();
        Ok(match scheme.to_ascii_lowercase().as_str() {
            "doi" => Identifier::Doi(value),
            "pmid" => Identifier::Pmid(value),
            "pmcid" => Identifier::Pmcid(value),
            "omid" => Identifier::Omid(value),
            "issn" => Identifier::Issn(value),
            "isbn" => Identifier::Isbn(value),
            "openalex" => Identifier::OpenAlex(value),
            "orcid" => Identifier::Orcid(value),
            "ror" => Identifier::Ror(value),
            "crossref" => Identifier::Crossref(value),
            other => Identifier::Other {
                scheme: other.to_string(),
                value,
            },
        })
    }
}

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

impl Serialize for Identifier {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Identifier {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        let raw = String::deserialize(deserializer)?;
        Identifier::from_str(&raw).map_err(serde::de::Error::custom)
    }
}

/// An Open Citation Identifier: the citing and cited work's OMIDs, joined by a
/// `-`, naming one citation.
///
/// `06024047477-06220256775` is the citation *from* `omid:br/06024047477` *to*
/// `omid:br/06220256775`, and is the only thing `/index/v2/citation/{oci}`
/// takes.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Oci {
    citing: String,
    cited: String,
}

impl Oci {
    /// The OMID of the citing work, without its `omid:br/` prefix.
    pub fn citing(&self) -> &str {
        &self.citing
    }

    /// The OMID of the cited work, without its `omid:br/` prefix.
    pub fn cited(&self) -> &str {
        &self.cited
    }
}

impl FromStr for Oci {
    type Err = Error;

    fn from_str(oci: &str) -> Result<Self> {
        // written `oci:0610-0620` in some of OpenCitations' own documentation,
        // but the route takes it bare, so accept either and send the bare form
        let bare = oci.trim().strip_prefix("oci:").unwrap_or(oci.trim());

        let Some((citing, cited)) = bare.split_once('-') else {
            return Err(Error::InvalidOci {
                given: oci.to_string(),
                why: "it is two omids joined by a `-`",
            });
        };
        let numeric = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
        if !numeric(citing) || !numeric(cited) {
            return Err(Error::InvalidOci {
                given: oci.to_string(),
                why: "both halves are numbers",
            });
        }

        Ok(Oci {
            citing: citing.to_string(),
            cited: cited.to_string(),
        })
    }
}

impl fmt::Display for Oci {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}-{}", self.citing, self.cited)
    }
}

impl Serialize for Oci {
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> std::result::Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Oci {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> std::result::Result<Self, D::Error> {
        let raw = String::deserialize(deserializer)?;
        Oci::from_str(&raw).map_err(serde::de::Error::custom)
    }
}

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

    #[test]
    fn an_identifier_keeps_its_scheme_and_value() {
        let id: Identifier = "doi:10.1016/j.marpol.2021.104855".parse().unwrap();
        assert_eq!(id, Identifier::doi("10.1016/j.marpol.2021.104855"));
        assert_eq!(id.scheme(), "doi");
        assert_eq!(id.value(), "10.1016/j.marpol.2021.104855");
        assert_eq!(id.as_doi(), Some("10.1016/j.marpol.2021.104855"));
        assert_eq!(id.to_string(), "doi:10.1016/j.marpol.2021.104855");
    }

    /// An omid's value carries a `/`, and a doi's carries several -- only the
    /// first `:` separates.
    #[test]
    fn only_the_first_colon_separates() {
        let omid: Identifier = "omid:br/06220256775".parse().unwrap();
        assert_eq!(omid, Identifier::omid("br/06220256775"));

        let url: Identifier = "url:https://example.com/a".parse().unwrap();
        assert_eq!(url.value(), "https://example.com/a");
    }

    /// A bare doi is refused rather than guessed at: OpenCitations answers an
    /// identifier it cannot parse the same way it answers one it has never
    /// heard of, so a guess would read as "nobody has cited this".
    #[test]
    fn an_unprefixed_identifier_is_refused_with_the_form_it_should_take() {
        let err = "10.1016/j.marpol.2021.104855"
            .parse::<Identifier>()
            .unwrap_err();
        assert!(err.to_string().contains("doi:10.1016"), "{err}");

        assert!("doi:".parse::<Identifier>().is_err());
        assert!(":10.1016".parse::<Identifier>().is_err());
    }

    #[test]
    fn an_unknown_scheme_is_kept_rather_than_refused() {
        let id: Identifier = "wikidata:Q42".parse().unwrap();
        assert_eq!(id.scheme(), "wikidata");
        assert_eq!(id.value(), "Q42");
        assert_eq!(id.as_doi(), None);
    }

    #[test]
    fn a_bag_of_identifiers_reads_as_all_of_them() {
        let bag = Identifier::parse_bag(
            "omid:br/06220256775 doi:10.1016/j.marpol.2021.104855 openalex:W3214241825",
        )
        .unwrap();

        assert_eq!(bag.len(), 3);
        assert_eq!(
            bag.iter().find_map(Identifier::as_doi),
            Some("10.1016/j.marpol.2021.104855")
        );
    }

    #[test]
    fn an_oci_is_the_two_omids_it_joins() {
        let oci: Oci = "06024047477-06220256775".parse().unwrap();
        assert_eq!(oci.citing(), "06024047477");
        assert_eq!(oci.cited(), "06220256775");
        assert_eq!(oci.to_string(), "06024047477-06220256775");

        // the documented `oci:` prefix is accepted, and dropped
        assert_eq!("oci:06024047477-06220256775".parse::<Oci>().unwrap(), oci);
    }

    #[test]
    fn something_that_is_not_an_oci_is_refused() {
        assert!("06024047477".parse::<Oci>().is_err());
        assert!("abc-def".parse::<Oci>().is_err());
        assert!("-06220256775".parse::<Oci>().is_err());
    }
}