Skip to main content

crossref_client/query/
mod.rs

1use crate::error::Result;
2pub use crate::query::funders::{Funders, FundersQuery};
3pub use crate::query::journals::{Journals, JournalsQuery};
4pub use crate::query::licenses::{Licenses, LicensesQuery};
5pub use crate::query::members::{Members, MembersQuery};
6pub use crate::query::prefixes::Prefixes;
7pub use crate::query::types::{Type, Types};
8use crate::query::works::Works;
9pub use crate::query::works::{WorksIdentQuery, WorksQuery};
10use core::fmt::Debug;
11use serde::{Deserialize, Serialize};
12use std::borrow::Cow;
13use std::fmt;
14use std::str::FromStr;
15
16/// How a filter's payload renders inside a `filter` fragment.
17///
18/// Implemented for the handful of types a filter can carry, so
19/// [`define_filter!`] can render every variant without a per-type match arm --
20/// the catch-all arm that used to do that job silently turned
21/// `WorksFilter::AlternativeId(id)` into `alternative-id:true`.
22pub(crate) trait FilterValue: Sized {
23    /// the value as it appears after the `:`
24    fn render(&self) -> Cow<'_, str>;
25
26    /// the value read back from the way it renders, for callers that learn a
27    /// filter at runtime -- a command line flag, a config file
28    fn parse(value: &str) -> Option<Self>;
29}
30
31impl FilterValue for String {
32    fn render(&self) -> Cow<'_, str> {
33        Cow::Borrowed(self)
34    }
35
36    fn parse(value: &str) -> Option<Self> {
37        Some(value.to_string())
38    }
39}
40
41impl FilterValue for i32 {
42    fn render(&self) -> Cow<'_, str> {
43        Cow::Owned(self.to_string())
44    }
45
46    fn parse(value: &str) -> Option<Self> {
47        value.parse().ok()
48    }
49}
50
51impl FilterValue for u64 {
52    fn render(&self) -> Cow<'_, str> {
53        Cow::Owned(self.to_string())
54    }
55
56    fn parse(value: &str) -> Option<Self> {
57        value.parse().ok()
58    }
59}
60
61impl FilterValue for chrono::NaiveDate {
62    fn render(&self) -> Cow<'_, str> {
63        Cow::Owned(self.format("%Y-%m-%d").to_string())
64    }
65
66    fn parse(value: &str) -> Option<Self> {
67        chrono::NaiveDate::parse_from_str(value, "%Y-%m-%d").ok()
68    }
69}
70
71impl FilterValue for types::Type {
72    fn render(&self) -> Cow<'_, str> {
73        Cow::Borrowed(self.id())
74    }
75
76    fn parse(value: &str) -> Option<Self> {
77        value.parse().ok()
78    }
79}
80
81/// Why a `name` and `value` are not a filter a route takes, as
82/// [`WorksFilter::from_name`](crate::WorksFilter::from_name) reports it.
83///
84/// The name a caller got wrong is carried along, since the caller that reads
85/// filters at runtime is the one that has to say which of them was refused.
86#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
87pub enum FilterParseError {
88    /// no filter of this route goes by that name
89    #[error("`{name}` is not a filter this route takes")]
90    UnknownName {
91        /// the name that was asked for
92        name: String,
93    },
94    /// the filter narrows to records that have something, which is not a thing
95    /// records can have a value of
96    #[error("`{name}` takes no value; it asks only whether the record has one")]
97    MarkerWithValue {
98        /// the filter that was given a value
99        name: String,
100    },
101    /// the filter narrows to a value and was given none
102    #[error("`{name}` needs a value, as `{name}:<value>`")]
103    MissingValue {
104        /// the filter that was given no value
105        name: String,
106    },
107    /// the value is not of the kind the filter narrows by, e.g. a date that is
108    /// not a date
109    #[error("`{value}` is not a value `{name}` can narrow by")]
110    UnreadableValue {
111        /// the filter that was given the value
112        name: String,
113        /// the value it could not read
114        value: String,
115    },
116}
117
118/// Defines a route's filter enum together with everything that has to stay in
119/// step with it: the key each variant renders under, how its payload renders,
120/// and -- for the coverage tests -- one value of every variant.
121///
122/// Marker filters carry no payload and render as `key:true`; value filters
123/// carry one, whose type implements [`FilterValue`].
124macro_rules! define_filter {
125    (
126        $(#[$meta:meta])*
127        $name:ident;
128        markers { $($(#[$m_doc:meta])* $m_variant:ident => $m_key:literal,)* }
129        values  { $($(#[$v_doc:meta])* $v_variant:ident($v_ty:ty) => $v_key:literal,)* }
130    ) => {
131        $(#[$meta])*
132        #[derive(Debug, Clone, PartialEq, Eq)]
133        pub enum $name {
134            $($(#[$m_doc])* $m_variant,)*
135            $($(#[$v_doc])* $v_variant($v_ty),)*
136        }
137
138        impl $name {
139            /// Every filter name this route accepts, in declaration order.
140            ///
141            /// Pinned against the list crossref reports in its `400` body by
142            /// the coverage tests, so it is the vocabulary of the live api
143            /// rather than of this crate's enum.
144            pub const ALL_NAMES: &'static [&'static str] = &[$($m_key,)* $($v_key,)*];
145
146            /// the key this filter renders under in the query string
147            pub fn name(&self) -> &'static str {
148                match self {
149                    $($name::$m_variant => $m_key,)*
150                    $($name::$v_variant(_) => $v_key,)*
151                }
152            }
153
154            /// The filter crossref knows by this name, carrying this value --
155            /// the inverse of [`name`](Self::name), for callers that learn a
156            /// filter at runtime rather than writing it out.
157            ///
158            /// A marker takes no value, or the `true` it renders as; every
159            /// other filter takes one, parsed into whatever that filter
160            /// carries, so a date that is not a date is caught here rather
161            /// than by crossref.
162            pub fn from_name(
163                name: &str,
164                value: Option<&str>,
165            ) -> ::std::result::Result<Self, $crate::query::FilterParseError> {
166                use $crate::query::{FilterParseError, FilterValue};
167
168                match name {
169                    $($m_key => match value {
170                        None | Some("true") => Ok($name::$m_variant),
171                        Some(_) => Err(FilterParseError::MarkerWithValue {
172                            name: name.to_string(),
173                        }),
174                    },)*
175                    $($v_key => match value {
176                        None => Err(FilterParseError::MissingValue { name: name.to_string() }),
177                        Some(value) => <$v_ty as FilterValue>::parse(value)
178                            .map($name::$v_variant)
179                            .ok_or_else(|| FilterParseError::UnreadableValue {
180                                name: name.to_string(),
181                                value: value.to_string(),
182                            }),
183                    },)*
184                    _ => Err(FilterParseError::UnknownName { name: name.to_string() }),
185                }
186            }
187        }
188
189        impl $crate::query::ParamFragment for $name {
190            fn key(&self) -> ::std::borrow::Cow<'_, str> {
191                ::std::borrow::Cow::Borrowed(self.name())
192            }
193
194            fn value(&self) -> Option<::std::borrow::Cow<'_, str>> {
195                match self {
196                    $($name::$m_variant => Some(::std::borrow::Cow::Borrowed("true")),)*
197                    $($name::$v_variant(value) => {
198                        Some($crate::query::FilterValue::render(value))
199                    })*
200                }
201            }
202        }
203
204        impl $crate::query::Filter for $name {}
205    };
206}
207
208/// Defines a query for a list route that takes free form terms, paging, and
209/// optionally a filter -- and nothing else.
210///
211/// `/works` is the only route with `sort`, `order`, `facet`, `select` and
212/// `sample`; `/funders`, `/members`, `/journals` and `/licenses` all answer
213/// those with a `400`, and only the first two take a `filter` on top of terms
214/// and paging.
215macro_rules! impl_list_query {
216    ($(#[$meta:meta])* $name:ident $(, filter = $filter:ident)?) => {
217        $(#[$meta])*
218        #[derive(Debug, Clone, Default, PartialEq, Eq)]
219        pub struct $name {
220            /// search by non specific query
221            pub queries: Vec<String>,
222            $(
223                /// filter to apply while querying
224                pub filter: Vec<$filter>,
225            )?
226            /// limit the returned items and set an offset
227            ///
228            /// Only `rows` and `offset` are supported by this route;
229            /// [`ResultControl::Sample`] is rejected by crossref with a `400`.
230            pub result_control: Option<ResultControl>,
231        }
232
233        impl $name {
234            $(
235                /// add a new filter to the query
236                pub fn filter(mut self, filter: $filter) -> Self {
237                    self.filter.push(filter);
238                    self
239                }
240            )?
241            /// alias for creating an empty default element
242            pub fn empty() -> Self {
243                Self::default()
244            }
245
246            /// Convenience method to create a new query with a term directly
247            pub fn new<T: ToString>(query: T) -> Self {
248                Self::empty().query(query)
249            }
250
251            /// add a new free form query
252            pub fn query<T: ToString>(mut self, query: T) -> Self {
253                self.queries.push(query.to_string());
254                self
255            }
256
257            /// add a bunch of free form query terms
258            pub fn queries<T: ToString>(mut self, queries: &[T]) -> Self {
259                self.queries.extend(queries.iter().map(T::to_string));
260                self
261            }
262
263            /// Limit the results, or take crossref's default page if given [`None`].
264            pub fn result_control(
265                mut self,
266                result_control: impl Into<Option<ResultControl>>,
267            ) -> Self {
268                self.result_control = result_control.into();
269                self
270            }
271        }
272
273        impl CrossrefRoute for $name {
274            fn route(&self) -> Result<String> {
275                let mut params: Vec<(Cow<'_, str>, Cow<'_, str>)> = Vec::new();
276                if !self.queries.is_empty() {
277                    params.push((
278                        Cow::Borrowed("query"),
279                        Cow::Owned(format_queries(&self.queries)),
280                    ));
281                }
282                $(
283                    let filters: &[$filter] = &self.filter;
284                    if !filters.is_empty() {
285                        $crate::query::reject_unsendable_filters(filters)?;
286                        params.extend(self.filter.params());
287                    }
288                )?
289                if let Some(rc) = &self.result_control {
290                    params.extend(rc.params());
291                }
292                Ok(encode::query_string(&params))
293            }
294        }
295    };
296}
297
298/// Defines an enum of crossref identifiers together with the list of them, so
299/// a coverage test can check the list against what the api reports.
300macro_rules! define_keyed_enum {
301    (
302        $(#[$meta:meta])*
303        $name:ident { $($(#[$doc:meta])* $variant:ident => $key:literal,)* }
304    ) => {
305        $(#[$meta])*
306        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
307        pub enum $name {
308            $(
309                #[doc = concat!("the `", $key, "` field")]
310                $(#[$doc])*
311                $variant,
312            )*
313        }
314
315        impl $name {
316            /// the identifier crossref knows this by
317            pub fn name(&self) -> &'static str {
318                match self { $($name::$variant => $key,)* }
319            }
320
321            /// Every variant, in declaration order.
322            pub const ALL: &'static [$name] = &[$($name::$variant,)*];
323        }
324    };
325}
326
327/// Defines [`FieldQuery`](works::FieldQuery), the queries that match against
328/// one field of a work's metadata rather than all of it.
329///
330/// Each entry names the variant, the field crossref knows it by, and the
331/// lower-case constructor that saves callers an `into`.
332macro_rules! define_field_queries {
333    ($($(#[$doc:meta])* $variant:ident => $key:literal / $ctor:ident,)*) => {
334        /// Matches against one field of a work's metadata rather than all of
335        /// it. Available on the `/works` route only.
336        ///
337        /// ```
338        /// # use crossref_client::FieldQuery;
339        /// assert_eq!("query.author", FieldQuery::author("feynman").name());
340        /// ```
341        ///
342        /// Covers all 21 field queries `/works` accepts, which
343        /// `every_field_query_is_accepted_by_the_api` pins against what the api
344        /// reports.
345        #[derive(Debug, Clone, PartialEq, Eq)]
346        pub enum FieldQuery {
347            $(
348                #[doc = concat!("matches against `", $key, "`: ")]
349                $(#[$doc])*
350                $variant(String),
351            )*
352        }
353
354        impl FieldQuery {
355            /// Every field `/works` can be queried against, in declaration
356            /// order -- the `author` of `query.author`.
357            pub const ALL_FIELDS: &'static [&'static str] = &[$($key,)*];
358
359            /// the key this renders under in the query string, e.g. `query.author`
360            pub fn name(&self) -> &'static str {
361                match self { $(FieldQuery::$variant(_) => concat!("query.", $key),)* }
362            }
363
364            /// the field crossref knows this by, e.g. `author`
365            pub fn field(&self) -> &'static str {
366                match self { $(FieldQuery::$variant(_) => $key,)* }
367            }
368
369            /// the term being matched
370            pub fn value(&self) -> &str {
371                match self { $(FieldQuery::$variant(value) => value,)* }
372            }
373
374            /// The query against the field crossref knows by this name, the
375            /// inverse of [`FieldQuery::field`], or [`None`] if `/works`
376            /// carries no such field. For callers that learn the field at
377            /// runtime -- a command line flag, a config file -- rather than
378            /// writing it out.
379            ///
380            /// ```
381            /// # use crossref_client::FieldQuery;
382            /// assert_eq!(
383            ///     Some(FieldQuery::author("feynman")),
384            ///     FieldQuery::from_field("author", "feynman")
385            /// );
386            /// assert_eq!(None, FieldQuery::from_field("query.author", "feynman"));
387            /// ```
388            pub fn from_field(field: &str, value: impl Into<String>) -> Option<Self> {
389                match field {
390                    $($key => Some(FieldQuery::$variant(value.into())),)*
391                    _ => None,
392                }
393            }
394
395            $(
396                #[doc = concat!("a query against `", $key, "`")]
397                pub fn $ctor(value: impl Into<String>) -> Self {
398                    FieldQuery::$variant(value.into())
399                }
400            )*
401        }
402    };
403}
404
405/// percent-encoding of the crossref query string
406pub(crate) mod encode;
407/// provides types to filter facets
408pub mod facet;
409/// provides support to query the `/funders` route
410pub mod funders;
411/// provides support to query the `/funders` route
412pub mod journals;
413/// provides support to query the `/licenses` route
414pub mod licenses;
415/// provides support to query the `/members` route
416pub mod members;
417/// provides support to query the `/members` route
418pub mod prefixes;
419/// provides support to query the `/prefixes` route
420pub mod types;
421/// provides support to query the `/types` route
422pub mod works;
423
424/// represents the visibility of an crossref item
425#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
426#[serde(rename_all = "kebab-case")]
427pub enum Visibility {
428    /// readable by anyone
429    Open,
430    /// readable by Metadata Plus subscribers
431    Limited,
432    /// not readable
433    Closed,
434}
435
436impl Visibility {
437    /// str identifier
438    pub fn as_str(&self) -> &str {
439        match self {
440            Visibility::Open => "open",
441            Visibility::Limited => "limited",
442            Visibility::Closed => "closed",
443        }
444    }
445}
446
447/// Determines how results should be sorted
448#[derive(Debug, PartialEq, Eq, Clone, Copy)]
449pub enum Order {
450    /// list results in ascending order
451    Asc,
452    /// list results in descending order
453    Desc,
454}
455
456impl Order {
457    /// the key name for the order parameter
458    pub fn as_str(&self) -> &str {
459        match self {
460            Order::Asc => "asc",
461            Order::Desc => "desc",
462        }
463    }
464}
465
466impl FromStr for Order {
467    type Err = String;
468
469    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
470        match s {
471            "asc" => Ok(Order::Asc),
472            "desc" => Ok(Order::Desc),
473            other => Err(format!("Unable to convert {} to Order", other)),
474        }
475    }
476}
477
478impl CrossrefQueryParam for Order {
479    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
480        vec![(Cow::Borrowed("order"), Cow::Borrowed(self.as_str()))]
481    }
482}
483
484/// Results from a list response can be sorted by applying the sort and order parameters.
485#[derive(Debug, PartialEq, Eq, Clone, Copy)]
486pub enum Sort {
487    /// Sort by relevance score
488    Score,
489    /// Sort by date of most recent change to metadata. Currently the same as `Deposited`
490    Updated,
491    /// Sort by time of most recent deposit
492    Deposited,
493    /// Sort by time of most recent index
494    Indexed,
495    /// Sort by publication date
496    Published,
497    /// Sort by print publication date
498    PublishedPrint,
499    /// Sort by online publication date
500    PublishedOnline,
501    /// Sort by issued date (earliest known publication date)
502    Issued,
503    /// Sort by number of times this DOI is referenced by other Crossref DOIs
504    IsReferencedByCount,
505    /// Sort by number of references included in the references section of the document identified by this DOI
506    ReferenceCount,
507    /// Sort by date the record was created
508    Created,
509    /// Sort by relevance to the query terms
510    Relevance,
511}
512
513impl Sort {
514    /// Every field `/works` can be sorted by, in declaration order.
515    pub const ALL: &'static [Sort] = &[
516        Sort::Score,
517        Sort::Updated,
518        Sort::Deposited,
519        Sort::Indexed,
520        Sort::Published,
521        Sort::PublishedPrint,
522        Sort::PublishedOnline,
523        Sort::Issued,
524        Sort::IsReferencedByCount,
525        Sort::ReferenceCount,
526        Sort::Created,
527        Sort::Relevance,
528    ];
529
530    /// the key name for the filter element
531    pub fn as_str(&self) -> &str {
532        match self {
533            Sort::Score => "score",
534            Sort::Updated => "updated",
535            Sort::Deposited => "deposited",
536            Sort::Indexed => "indexed",
537            Sort::Published => "published",
538            Sort::PublishedPrint => "published-print",
539            Sort::PublishedOnline => "published-online",
540            Sort::Issued => "issued",
541            Sort::IsReferencedByCount => "is-referenced-by-count",
542            Sort::ReferenceCount => "references-count",
543            Sort::Created => "created",
544            Sort::Relevance => "relevance",
545        }
546    }
547}
548
549impl FromStr for Sort {
550    type Err = String;
551
552    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
553        match s {
554            "score" => Ok(Sort::Score),
555            "updated" => Ok(Sort::Updated),
556            "deposited" => Ok(Sort::Deposited),
557            "indexed" => Ok(Sort::Indexed),
558            "published" => Ok(Sort::Published),
559            "published-print" => Ok(Sort::PublishedPrint),
560            "published-online" => Ok(Sort::PublishedOnline),
561            "issued" => Ok(Sort::Issued),
562            "is-referenced-by-count" => Ok(Sort::IsReferencedByCount),
563            "references-count" => Ok(Sort::ReferenceCount),
564            "created" => Ok(Sort::Created),
565            "relevance" => Ok(Sort::Relevance),
566            other => Err(format!("Unable to convert {} to Sort", other)),
567        }
568    }
569}
570
571impl CrossrefQueryParam for Sort {
572    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
573        vec![(Cow::Borrowed("sort"), Cow::Borrowed(self.as_str()))]
574    }
575}
576
577/// tells crossref how many items shall be returned or where to start
578#[derive(Debug, Clone, Copy, PartialEq, Eq)]
579pub enum ResultControl {
580    /// limits the returned items per page
581    Rows(usize),
582    /// sets an offset where crossref begins to retrieve items
583    /// high offsets (~10k) result in long response times
584    Offset(usize),
585    /// combines rows and offset: limit returned items per page, starting at the offset
586    RowsOffset {
587        /// row limit
588        rows: usize,
589        /// where to start
590        offset: usize,
591    },
592    /// return random results
593    Sample(usize),
594}
595
596impl CrossrefQueryParam for ResultControl {
597    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
598        match self {
599            ResultControl::Rows(rows) => {
600                vec![(Cow::Borrowed("rows"), Cow::Owned(rows.to_string()))]
601            }
602            ResultControl::Offset(offset) => {
603                vec![(Cow::Borrowed("offset"), Cow::Owned(offset.to_string()))]
604            }
605            ResultControl::RowsOffset { rows, offset } => vec![
606                (Cow::Borrowed("rows"), Cow::Owned(rows.to_string())),
607                (Cow::Borrowed("offset"), Cow::Owned(offset.to_string())),
608            ],
609            ResultControl::Sample(sample) => {
610                vec![(Cow::Borrowed("sample"), Cow::Owned(sample.to_string()))]
611            }
612        }
613    }
614}
615
616/// Major resource components supported by the Crossref API
617#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
618#[serde(rename_all = "lowercase")]
619pub enum Component {
620    /// a list of all works (journal articles, conference proceedings, books, components, etc), 20 per page
621    Works,
622    /// a list of all funders in the [Funder Registry](https://github.com/Crossref/open-funder-registry)
623    Funders,
624    /// a list of DOI owner prefixes
625    Prefixes,
626    /// a list of all Crossref members (mostly publishers)
627    Members,
628    /// a list of valid work types
629    Types,
630    /// a list of journals in the Crossref database
631    Journals,
632    /// a list of the licenses works in the Crossref metadata are published under
633    Licenses,
634}
635
636impl Component {
637    /// identifier for the component route
638    pub fn as_str(&self) -> &str {
639        match self {
640            Component::Works => "works",
641            Component::Funders => "funders",
642            Component::Prefixes => "prefixes",
643            Component::Members => "members",
644            Component::Types => "types",
645            Component::Journals => "journals",
646            Component::Licenses => "licenses",
647        }
648    }
649}
650
651impl CrossrefRoute for Component {
652    fn route(&self) -> Result<String> {
653        Ok(format!("/{}", self.as_str()))
654    }
655}
656
657/// The components that also expose their works at `/{component}/{id}/works`.
658///
659/// A narrower [`Component`]: `/works` has no such sub-route of its own, and
660/// neither does `/licenses`.
661#[derive(Debug, Clone, Copy, PartialEq, Eq)]
662pub enum WorksComponent {
663    /// works of one funder, at `/funders/{id}/works`
664    Funders,
665    /// works of one DOI prefix, at `/prefixes/{id}/works`
666    Prefixes,
667    /// works of one member, at `/members/{id}/works`
668    Members,
669    /// works of one type, at `/types/{id}/works`
670    Types,
671    /// works of one journal, at `/journals/{issn}/works`
672    Journals,
673}
674
675impl WorksComponent {
676    /// the route this component owns
677    pub fn component(&self) -> Component {
678        match self {
679            WorksComponent::Funders => Component::Funders,
680            WorksComponent::Prefixes => Component::Prefixes,
681            WorksComponent::Members => Component::Members,
682            WorksComponent::Types => Component::Types,
683            WorksComponent::Journals => Component::Journals,
684        }
685    }
686}
687
688impl CrossrefRoute for WorksComponent {
689    fn route(&self) -> Result<String> {
690        self.component().route()
691    }
692}
693
694/// bundles all available crossref api endpoints
695#[derive(Debug, Clone)]
696pub enum ResourceComponent {
697    /// the `/works` route
698    Works(Works),
699    /// the `/funders` route
700    Funders(Funders),
701    /// the `/prefixes` route
702    Prefixes(Prefixes),
703    /// the `/members` route
704    Members(Members),
705    /// the `/types` route
706    Types(Types),
707    /// the `/journals` route
708    Journals(Journals),
709    /// the `/licenses` route
710    Licenses(Licenses),
711}
712
713impl ResourceComponent {
714    /// the starting crossref component that in the route `/{primary_component}/{id}/works`
715    pub fn primary_component(&self) -> Component {
716        match self {
717            ResourceComponent::Works(_) => Component::Works,
718            ResourceComponent::Funders(_) => Component::Funders,
719            ResourceComponent::Prefixes(_) => Component::Prefixes,
720            ResourceComponent::Members(_) => Component::Members,
721            ResourceComponent::Types(_) => Component::Types,
722            ResourceComponent::Journals(_) => Component::Journals,
723            ResourceComponent::Licenses(_) => Component::Licenses,
724        }
725    }
726}
727
728impl fmt::Display for ResourceComponent {
729    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
730        write!(f, "{}", self.route().map_err(|_| fmt::Error)?)
731    }
732}
733
734impl CrossrefRoute for ResourceComponent {
735    fn route(&self) -> Result<String> {
736        match self {
737            ResourceComponent::Works(c) => c.route(),
738            ResourceComponent::Funders(c) => c.route(),
739            ResourceComponent::Prefixes(c) => c.route(),
740            ResourceComponent::Members(c) => c.route(),
741            ResourceComponent::Types(c) => c.route(),
742            ResourceComponent::Journals(c) => c.route(),
743            ResourceComponent::Licenses(c) => c.route(),
744        }
745    }
746}
747
748impl CrossrefQuery for ResourceComponent {
749    fn resource_component(self) -> ResourceComponent {
750        self
751    }
752}
753
754/// Helper trait to mark filters in the query string
755pub trait Filter: ParamFragment {}
756
757impl<T: Filter> CrossrefQueryParam for Vec<T> {
758    /// filters share the `filter` key and are concat with `,`
759    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
760        vec![(
761            Cow::Borrowed("filter"),
762            Cow::Owned(
763                self.iter()
764                    .map(ParamFragment::fragment)
765                    .collect::<Vec<_>>()
766                    .join(","),
767            ),
768        )]
769    }
770}
771
772/// represents a key value pair inside a multi value query string parameter
773pub trait ParamFragment {
774    /// the key, or name, of the fragment
775    fn key(&self) -> Cow<'_, str>;
776
777    /// the value of the fragment, if any
778    fn value(&self) -> Option<Cow<'_, str>>;
779
780    /// key and value are concat using `:`
781    fn fragment(&self) -> Cow<'_, str> {
782        if let Some(val) = self.value() {
783            Cow::Owned(format!("{}:{}", self.key(), val))
784        } else {
785            self.key()
786        }
787    }
788}
789
790/// a trait used to capture parameters for the query string of the crossref api
791pub trait CrossrefQueryParam {
792    /// The key/value pairs this element contributes to the query string.
793    ///
794    /// Most elements contribute exactly one pair, but a few span two --
795    /// [`ResultControl::RowsOffset`] and [`works::WorkResultControl::Cursor`]
796    /// with a row limit. Yielding pairs rather than a rendered `key=value`
797    /// fragment is what lets the route builder percent-encode keys and values
798    /// separately.
799    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)>;
800}
801
802impl<T: AsRef<str>> CrossrefQueryParam for (T, T) {
803    fn params(&self) -> Vec<(Cow<'_, str>, Cow<'_, str>)> {
804        vec![(
805            Cow::Borrowed(self.0.as_ref()),
806            Cow::Borrowed(self.1.as_ref()),
807        )]
808    }
809}
810
811/// represents elements that constructs parts of the crossref request url
812pub trait CrossrefRoute {
813    /// constructs the route for the crossref api
814    fn route(&self) -> Result<String>;
815}
816
817/// root level trait to construct full crossref api request urls
818pub trait CrossrefQuery: CrossrefRoute + Clone {
819    /// the resource component endpoint this route targets
820    fn resource_component(self) -> ResourceComponent;
821
822    /// constructs the full request url by concating the `base_path` with the `route`
823    fn to_url(&self, base_path: &str) -> Result<String> {
824        Ok(format!("{}{}", base_path, self.route()?))
825    }
826}
827
828/// Refuses a filter value crossref would read as two filters.
829///
830/// Crossref splits the `filter` value on `,` *after* percent-decoding it, so a
831/// value carrying one arrives as two fragments -- `container-title:A, B`
832/// becomes the filter `container-title:A` plus a filter called ` B`, which the
833/// api answers with a `400`. Neither the encoded nor the literal form survives,
834/// so there is nothing to escape it with and the request is refused here
835/// instead, where the error can say which filter is at fault.
836pub(crate) fn reject_unsendable_filters<T: Filter>(filters: &[T]) -> Result<()> {
837    for filter in filters {
838        match filter.value() {
839            Some(value) if value.contains(',') => {
840                return Err(crate::Error::UnsendableFilterValue {
841                    filter: filter.key().into_owned(),
842                    value: value.into_owned(),
843                });
844            }
845            _ => (),
846        }
847    }
848    Ok(())
849}
850
851/// normalizes a query term by collapsing runs of whitespace into single spaces
852///
853/// Crossref reads the `query` value as a whitespace separated list of terms.
854/// The separator is a plain space rather than the `+` it renders as on the wire,
855/// because [`encode`] escapes the value afterwards and a literal `+` there would
856/// come back out as one.
857pub(crate) fn format_query<T: AsRef<str>>(topic: T) -> String {
858    topic
859        .as_ref()
860        .split_whitespace()
861        .collect::<Vec<_>>()
862        .join(" ")
863}
864
865/// combines the individual topics of a query into a single `query` value
866pub(crate) fn format_queries<T: AsRef<str>>(topics: &[T]) -> String {
867    topics
868        .iter()
869        .flat_map(|topic| topic.as_ref().split_whitespace())
870        .collect::<Vec<_>>()
871        .join(" ")
872}
873
874/// Pins this crate's idea of a route's vocabulary against crossref's.
875///
876/// Crossref answers an unrecognised filter, sort field, field query or `select`
877/// element with a `400` that lists the ones it does know, so the lists below
878/// are copied from those responses. Checking both directions catches a name
879/// this crate would send and crossref would reject, *and* one crossref accepts
880/// that this crate cannot express.
881#[cfg(test)]
882fn assert_matches_api(kind: &str, ours: &[&str], api: &[&str]) {
883    use std::collections::BTreeSet;
884
885    let mine: BTreeSet<&str> = ours.iter().copied().collect();
886    assert_eq!(ours.len(), mine.len(), "duplicate {kind} in this crate");
887
888    let theirs: BTreeSet<&str> = api.iter().copied().collect();
889    assert_eq!(api.len(), theirs.len(), "duplicate {kind} in the api list");
890
891    let rejected: Vec<_> = mine.difference(&theirs).collect();
892    assert!(
893        rejected.is_empty(),
894        "{kind} this crate sends that crossref answers with a 400: {rejected:?}"
895    );
896
897    let unreachable: Vec<_> = theirs.difference(&mine).collect();
898    assert!(
899        unreachable.is_empty(),
900        "{kind} crossref accepts that this crate cannot express: {unreachable:?}"
901    );
902}
903
904#[cfg(test)]
905mod tests {
906    use super::*;
907    use crate::query::funders::FundersFilter;
908    use crate::query::members::MembersFilter;
909    use crate::query::works::{FieldQuery, WorkElement, WorksFilter};
910
911    /// The set crossref reports in its `400` response for an unknown sort field.
912    const API_SORT_FIELDS: &[&str] = &[
913        "score",
914        "created",
915        "issued",
916        "indexed",
917        "is-referenced-by-count",
918        "relevance",
919        "published",
920        "published-print",
921        "published-online",
922        "updated",
923        "references-count",
924        "deposited",
925    ];
926
927    #[test]
928    fn every_sort_key_is_accepted_by_the_api() {
929        let names: Vec<&str> = Sort::ALL.iter().map(Sort::as_str).collect();
930
931        assert_matches_api("/works sort fields", &names, API_SORT_FIELDS);
932    }
933
934    #[test]
935    fn sort_round_trips_through_from_str() {
936        for sort in Sort::ALL {
937            assert_eq!(Ok(*sort), Sort::from_str(sort.as_str()));
938        }
939    }
940
941    #[test]
942    fn order_round_trips_through_from_str() {
943        for order in [Order::Asc, Order::Desc] {
944            assert_eq!(Ok(order), Order::from_str(order.as_str()));
945        }
946    }
947
948    /// The filters crossref reports for `/works`.
949    const API_WORKS_FILTERS: &[&str] = &[
950        "alternative-id",
951        "archive",
952        "article-number",
953        "assertion",
954        "assertion-group",
955        "award.funder",
956        "award.number",
957        "category-name",
958        "clinical-trial-number",
959        "container-title",
960        "content-domain",
961        "directory",
962        "doi",
963        "from-accepted-date",
964        "from-approved-date",
965        "from-awarded-date",
966        "from-created-date",
967        "from-deposit-date",
968        "from-event-end-date",
969        "from-event-start-date",
970        "from-index-date",
971        "from-issued-date",
972        "from-online-pub-date",
973        "from-posted-date",
974        "from-print-pub-date",
975        "from-pub-date",
976        "from-update-date",
977        "full-text.application",
978        "full-text.type",
979        "full-text.version",
980        "funder",
981        "funder-doi-asserted-by",
982        "group-title",
983        "gte-award-amount",
984        "has-abstract",
985        "has-affiliation",
986        "has-affiliation-ror-id",
987        "has-alias",
988        "has-archive",
989        "has-assertion",
990        "has-authenticated-orcid",
991        "has-award",
992        "has-clinical-trial-number",
993        "has-content-domain",
994        "has-domain-restriction",
995        "has-event",
996        "has-full-text",
997        "has-funder",
998        "has-funder-doi",
999        "has-funder-ror-id",
1000        "has-license",
1001        "has-orcid",
1002        "has-prime-doi",
1003        "has-references",
1004        "has-relation",
1005        "has-ror-id",
1006        "has-update",
1007        "has-update-policy",
1008        "is-update",
1009        "isbn",
1010        "issn",
1011        "license.delay",
1012        "license.url",
1013        "license.version",
1014        "lte-award-amount",
1015        "member",
1016        "orcid",
1017        "prefix",
1018        "relation.object",
1019        "relation.object-type",
1020        "relation.type",
1021        "ror-id",
1022        "type",
1023        "type-name",
1024        "until-accepted-date",
1025        "until-approved-date",
1026        "until-awarded-date",
1027        "until-created-date",
1028        "until-deposit-date",
1029        "until-event-end-date",
1030        "until-event-start-date",
1031        "until-index-date",
1032        "until-issued-date",
1033        "until-online-pub-date",
1034        "until-posted-date",
1035        "until-print-pub-date",
1036        "until-pub-date",
1037        "until-update-date",
1038        "update-type",
1039        "updates",
1040    ];
1041
1042    /// The field queries crossref reports for `/works`.
1043    const API_FIELD_QUERIES: &[&str] = &[
1044        "affiliation",
1045        "author",
1046        "bibliographic",
1047        "chair",
1048        "container-title",
1049        "contributor",
1050        "degree",
1051        "description",
1052        "editor",
1053        "event-acronym",
1054        "event-location",
1055        "event-name",
1056        "event-sponsor",
1057        "event-theme",
1058        "funder-name",
1059        "publisher-location",
1060        "publisher-name",
1061        "standards-body-acronym",
1062        "standards-body-name",
1063        "title",
1064        "translator",
1065    ];
1066
1067    /// The `select` elements crossref reports for `/works`.
1068    const API_WORK_ELEMENTS: &[&str] = &[
1069        "DOI",
1070        "ISBN",
1071        "ISSN",
1072        "URL",
1073        "abstract",
1074        "accepted",
1075        "alternative-id",
1076        "approved",
1077        "archive",
1078        "article-number",
1079        "assertion",
1080        "author",
1081        "chair",
1082        "clinical-trial-number",
1083        "container-title",
1084        "content-created",
1085        "content-domain",
1086        "contributor",
1087        "created",
1088        "degree",
1089        "deposited",
1090        "editor",
1091        "event",
1092        "funder",
1093        "group-title",
1094        "indexed",
1095        "is-referenced-by-count",
1096        "issn-type",
1097        "issue",
1098        "issued",
1099        "license",
1100        "link",
1101        "member",
1102        "original-title",
1103        "page",
1104        "posted",
1105        "prefix",
1106        "published",
1107        "published-online",
1108        "published-print",
1109        "publisher",
1110        "publisher-location",
1111        "reference",
1112        "references-count",
1113        "relation",
1114        "resource",
1115        "score",
1116        "short-container-title",
1117        "short-title",
1118        "standards-body",
1119        "subject",
1120        "subtitle",
1121        "title",
1122        "translator",
1123        "type",
1124        "update-policy",
1125        "update-to",
1126        "updated-by",
1127        "volume",
1128    ];
1129
1130    /// The filters crossref reports for `/funders`.
1131    const API_FUNDERS_FILTERS: &[&str] = &["location"];
1132
1133    /// The filters crossref reports for `/members`.
1134    const API_MEMBERS_FILTERS: &[&str] = &["prefix", "backfile-doi-count", "current-doi-count"];
1135
1136    #[test]
1137    fn every_works_filter_is_accepted_by_the_api() {
1138        assert_matches_api("/works filters", WorksFilter::ALL_NAMES, API_WORKS_FILTERS);
1139    }
1140
1141    #[test]
1142    fn every_field_query_is_accepted_by_the_api() {
1143        assert_matches_api(
1144            "/works field queries",
1145            FieldQuery::ALL_FIELDS,
1146            API_FIELD_QUERIES,
1147        );
1148    }
1149
1150    #[test]
1151    fn every_selectable_element_is_accepted_by_the_api() {
1152        let names: Vec<&str> = WorkElement::ALL.iter().map(WorkElement::name).collect();
1153
1154        assert_matches_api("/works select elements", &names, API_WORK_ELEMENTS);
1155    }
1156
1157    #[test]
1158    fn every_funders_filter_is_accepted_by_the_api() {
1159        assert_matches_api(
1160            "/funders filters",
1161            FundersFilter::ALL_NAMES,
1162            API_FUNDERS_FILTERS,
1163        );
1164    }
1165
1166    #[test]
1167    fn every_members_filter_is_accepted_by_the_api() {
1168        assert_matches_api(
1169            "/members filters",
1170            MembersFilter::ALL_NAMES,
1171            API_MEMBERS_FILTERS,
1172        );
1173    }
1174
1175    #[test]
1176    fn a_marker_filter_renders_as_true_and_a_value_filter_as_its_value() {
1177        let filters = vec![
1178            WorksFilter::HasOrcid,
1179            WorksFilter::AlternativeId("abc".to_string()),
1180            WorksFilter::LicenseDelay(30),
1181            WorksFilter::GteAwardAmount(1_000),
1182        ];
1183
1184        assert_eq!(
1185            vec![(
1186                Cow::Borrowed("filter"),
1187                Cow::Owned(
1188                    "has-orcid:true,alternative-id:abc,license.delay:30,gte-award-amount:1000"
1189                        .to_string()
1190                )
1191            )],
1192            filters.params()
1193        );
1194    }
1195}