zenodo-rs 0.1.3

Rust client for Zenodo deposition workflows, record retrieval, and artifact downloads.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
//! Published-record search, retrieval, and latest-version helpers.
//!
//! Use this module when you want to work with Zenodo's public record surface:
//!
//! - [`RecordQuery`] and [`RecordQueryBuilder`] for search
//! - [`RecordSelector`] for choosing a record by ID or DOI
//! - [`ArtifactSelector`] for naming a downloadable file or archive
//!
//! Most consumers start here for DOI lookup, latest-version resolution, and
//! artifact-oriented read flows.

use serde::Deserialize;
use url::Url;

use crate::client::ZenodoClient;
use crate::error::ZenodoError;
use crate::ids::{Doi, DoiError, RecordId};
use crate::model::{ArtifactInfo, Record, RecordFile};
use crate::pagination::Page;
use crate::serde_util::deserialize_u64ish;

/// Selector for a published record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RecordSelector {
    /// Select by Zenodo record ID.
    RecordId(
        /// Record identifier.
        RecordId,
    ),
    /// Select by DOI.
    Doi(
        /// DOI selector.
        Doi,
    ),
}

impl RecordSelector {
    /// Selects a record by record ID.
    #[must_use]
    pub fn record_id(id: RecordId) -> Self {
        Self::RecordId(id)
    }

    /// Selects a record by DOI string.
    ///
    /// # Examples
    ///
    /// ```
    /// use zenodo_rs::{RecordSelector, RecordId};
    ///
    /// assert_eq!(RecordSelector::record_id(RecordId(42)), RecordSelector::RecordId(RecordId(42)));
    /// assert!(matches!(
    ///     RecordSelector::doi("https://doi.org/10.5281/zenodo.42")?,
    ///     RecordSelector::Doi(_)
    /// ));
    /// # Ok::<(), zenodo_rs::DoiError>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the DOI string is invalid.
    pub fn doi(value: impl AsRef<str>) -> Result<Self, DoiError> {
        Ok(Self::Doi(Doi::new(value)?))
    }
}

impl From<RecordId> for RecordSelector {
    fn from(value: RecordId) -> Self {
        Self::RecordId(value)
    }
}

impl From<Doi> for RecordSelector {
    fn from(value: Doi) -> Self {
        Self::Doi(value)
    }
}

impl From<&Doi> for RecordSelector {
    fn from(value: &Doi) -> Self {
        Self::Doi(value.clone())
    }
}

/// High-level selector for a downloadable artifact.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ArtifactSelector {
    /// Select a named file from a record.
    FileByKey {
        /// Record or DOI selector.
        record: RecordSelector,
        /// Exact file key.
        key: String,
        /// Whether to resolve the latest version first.
        latest: bool,
    },
    /// Select the record archive.
    Archive {
        /// Record or DOI selector.
        record: RecordSelector,
        /// Whether to resolve the latest version first.
        latest: bool,
    },
}

impl ArtifactSelector {
    /// Selects a named file from a specific record or DOI.
    #[must_use]
    pub fn file(record: impl Into<RecordSelector>, key: impl Into<String>) -> Self {
        Self::FileByKey {
            record: record.into(),
            key: key.into(),
            latest: false,
        }
    }

    /// Selects a named file from the latest version of a record or DOI.
    ///
    /// # Examples
    ///
    /// ```
    /// use zenodo_rs::{ArtifactSelector, RecordId, RecordSelector};
    ///
    /// assert_eq!(
    ///     ArtifactSelector::latest_file(RecordId(42), "artifact.tar.gz"),
    ///     ArtifactSelector::FileByKey {
    ///         record: RecordSelector::RecordId(RecordId(42)),
    ///         key: "artifact.tar.gz".into(),
    ///         latest: true,
    ///     }
    /// );
    /// assert!(matches!(
    ///     ArtifactSelector::latest_file_by_doi("10.5281/zenodo.42", "artifact.tar.gz")?,
    ///     ArtifactSelector::FileByKey { latest: true, .. }
    /// ));
    /// # Ok::<(), zenodo_rs::DoiError>(())
    /// ```
    #[must_use]
    pub fn latest_file(record: impl Into<RecordSelector>, key: impl Into<String>) -> Self {
        Self::FileByKey {
            record: record.into(),
            key: key.into(),
            latest: true,
        }
    }

    /// Selects a named file from a DOI string.
    ///
    /// # Errors
    ///
    /// Returns an error if the DOI string is invalid.
    pub fn file_by_doi(doi: impl AsRef<str>, key: impl Into<String>) -> Result<Self, DoiError> {
        Ok(Self::file(RecordSelector::doi(doi)?, key))
    }

    /// Selects a named file from the latest version resolved from a DOI string.
    ///
    /// # Errors
    ///
    /// Returns an error if the DOI string is invalid.
    pub fn latest_file_by_doi(
        doi: impl AsRef<str>,
        key: impl Into<String>,
    ) -> Result<Self, DoiError> {
        Ok(Self::latest_file(RecordSelector::doi(doi)?, key))
    }

    /// Selects the archive for a specific record or DOI.
    #[must_use]
    pub fn archive(record: impl Into<RecordSelector>) -> Self {
        Self::Archive {
            record: record.into(),
            latest: false,
        }
    }

    /// Selects the archive for the latest version of a record or DOI.
    #[must_use]
    pub fn latest_archive(record: impl Into<RecordSelector>) -> Self {
        Self::Archive {
            record: record.into(),
            latest: true,
        }
    }

    /// Selects the archive for a DOI string.
    ///
    /// # Errors
    ///
    /// Returns an error if the DOI string is invalid.
    pub fn archive_by_doi(doi: impl AsRef<str>) -> Result<Self, DoiError> {
        Ok(Self::archive(RecordSelector::doi(doi)?))
    }

    /// Selects the archive for the latest version resolved from a DOI string.
    ///
    /// # Errors
    ///
    /// Returns an error if the DOI string is invalid.
    pub fn latest_archive_by_doi(doi: impl AsRef<str>) -> Result<Self, DoiError> {
        Ok(Self::latest_archive(RecordSelector::doi(doi)?))
    }
}

/// Typed query parameters for the records search API.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct RecordQuery {
    /// Free-text query string.
    pub q: Option<String>,
    /// Record status filter.
    pub status: Option<RecordQueryStatus>,
    /// Sort order.
    pub sort: Option<RecordSort>,
    /// 1-based page number.
    pub page: Option<u32>,
    /// Page size.
    pub size: Option<u32>,
    /// Whether to include all versions in the search results.
    pub all_versions: bool,
    /// Community filters.
    pub communities: Vec<String>,
    /// Resource type filter.
    pub resource_type: Option<String>,
    /// Resource subtype filter.
    pub subtype: Option<String>,
    /// Extra raw query pairs for unsupported parameters.
    pub custom: Vec<(String, String)>,
}

impl RecordQuery {
    /// Starts building a typed record search query.
    ///
    /// # Examples
    ///
    /// ```
    /// use zenodo_rs::RecordQuery;
    ///
    /// let query = RecordQuery::builder()
    ///     .query("doi:\"10.5281/zenodo.42\"")
    ///     .published()
    ///     .most_recent()
    ///     .size(10)
    ///     .all_versions()
    ///     .build();
    ///
    /// assert_eq!(query.q.as_deref(), Some("doi:\"10.5281/zenodo.42\""));
    /// assert!(query.all_versions);
    /// ```
    #[must_use]
    pub fn builder() -> RecordQueryBuilder {
        RecordQueryBuilder::default()
    }

    /// Serializes the query into Zenodo URL parameter pairs.
    ///
    /// # Examples
    ///
    /// ```
    /// use zenodo_rs::{RecordQuery, RecordQueryStatus, RecordSort};
    ///
    /// let pairs = RecordQuery {
    ///     q: Some("doi:\"10.5281/zenodo.123\"".into()),
    ///     status: Some(RecordQueryStatus::Published),
    ///     sort: Some(RecordSort::MostRecent),
    ///     page: Some(2),
    ///     size: Some(25),
    ///     all_versions: true,
    ///     ..RecordQuery::default()
    /// }
    /// .into_pairs();
    ///
    /// assert!(pairs.contains(&("q".into(), "doi:\"10.5281/zenodo.123\"".into())));
    /// assert!(pairs.contains(&("status".into(), "published".into())));
    /// assert!(pairs.contains(&("sort".into(), "mostrecent".into())));
    /// assert!(pairs.contains(&("all_versions".into(), "true".into())));
    /// ```
    #[must_use]
    pub fn into_pairs(self) -> Vec<(String, String)> {
        let mut pairs = Vec::new();

        if let Some(q) = self.q {
            pairs.push(("q".into(), q));
        }
        if let Some(status) = self.status {
            pairs.push(("status".into(), status.to_string()));
        }
        if let Some(sort) = self.sort {
            pairs.push(("sort".into(), sort.to_string()));
        }
        if let Some(page) = self.page {
            pairs.push(("page".into(), page.to_string()));
        }
        if let Some(size) = self.size {
            pairs.push(("size".into(), size.to_string()));
        }
        if self.all_versions {
            pairs.push(("all_versions".into(), "true".into()));
        }
        if !self.communities.is_empty() {
            pairs.push(("communities".into(), self.communities.join(",")));
        }
        if let Some(resource_type) = self.resource_type {
            pairs.push(("type".into(), resource_type));
        }
        if let Some(subtype) = self.subtype {
            pairs.push(("subtype".into(), subtype));
        }
        pairs.extend(self.custom);
        pairs
    }
}

/// Builder for [`RecordQuery`] values.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct RecordQueryBuilder {
    query: RecordQuery,
}

impl RecordQueryBuilder {
    /// Sets the free-text query string.
    #[must_use]
    pub fn query(mut self, query: impl Into<String>) -> Self {
        self.query.q = Some(query.into());
        self
    }

    /// Sets the records API status filter.
    #[must_use]
    pub fn status(mut self, status: RecordQueryStatus) -> Self {
        self.query.status = Some(status);
        self
    }

    /// Filters to published records.
    #[must_use]
    pub fn published(mut self) -> Self {
        self.query.status = Some(RecordQueryStatus::Published);
        self
    }

    /// Filters to draft records.
    #[must_use]
    pub fn draft(mut self) -> Self {
        self.query.status = Some(RecordQueryStatus::Draft);
        self
    }

    /// Sets the records API sort order.
    #[must_use]
    pub fn sort(mut self, sort: RecordSort) -> Self {
        self.query.sort = Some(sort);
        self
    }

    /// Sorts by most recent first.
    #[must_use]
    pub fn most_recent(mut self) -> Self {
        self.query.sort = Some(RecordSort::MostRecent);
        self
    }

    /// Sets the 1-based page number.
    #[must_use]
    pub fn page(mut self, page: u32) -> Self {
        self.query.page = Some(page);
        self
    }

    /// Sets the page size.
    #[must_use]
    pub fn size(mut self, size: u32) -> Self {
        self.query.size = Some(size);
        self
    }

    /// Includes all versions in the search results.
    #[must_use]
    pub fn all_versions(mut self) -> Self {
        self.query.all_versions = true;
        self
    }

    /// Replaces the full community filter list.
    #[must_use]
    pub fn communities(mut self, communities: Vec<String>) -> Self {
        self.query.communities = communities;
        self
    }

    /// Adds one community filter.
    #[must_use]
    pub fn community(mut self, community: impl Into<String>) -> Self {
        self.query.communities.push(community.into());
        self
    }

    /// Sets the top-level resource type filter.
    #[must_use]
    pub fn resource_type(mut self, resource_type: impl Into<String>) -> Self {
        self.query.resource_type = Some(resource_type.into());
        self
    }

    /// Sets the resource subtype filter.
    #[must_use]
    pub fn subtype(mut self, subtype: impl Into<String>) -> Self {
        self.query.subtype = Some(subtype.into());
        self
    }

    /// Adds one unsupported raw query pair.
    #[must_use]
    pub fn custom(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.query.custom.push((key.into(), value.into()));
        self
    }

    /// Builds the query value.
    #[must_use]
    pub fn build(self) -> RecordQuery {
        self.query
    }
}

/// Filter values for the records `status` query parameter.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecordQueryStatus {
    /// Draft records.
    Draft,
    /// Published records.
    Published,
    /// Arbitrary server value not modeled directly by the crate.
    Custom(
        /// Raw server value.
        String,
    ),
}

impl std::fmt::Display for RecordQueryStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Draft => write!(f, "draft"),
            Self::Published => write!(f, "published"),
            Self::Custom(value) => value.fmt(f),
        }
    }
}

/// Sort values for the records `sort` query parameter.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RecordSort {
    /// Relevance descending.
    BestMatch,
    /// Most recent first.
    MostRecent,
    /// Relevance ascending.
    AscBestMatch,
    /// Oldest first.
    AscMostRecent,
    /// Arbitrary server value not modeled directly by the crate.
    Custom(
        /// Raw server value.
        String,
    ),
}

impl std::fmt::Display for RecordSort {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::BestMatch => write!(f, "bestmatch"),
            Self::MostRecent => write!(f, "mostrecent"),
            Self::AscBestMatch => write!(f, "-bestmatch"),
            Self::AscMostRecent => write!(f, "-mostrecent"),
            Self::Custom(value) => value.fmt(f),
        }
    }
}

#[derive(Deserialize)]
#[serde(bound(deserialize = "T: Deserialize<'de>"))]
struct SearchEnvelope<T> {
    hits: SearchHits<T>,
    #[serde(default)]
    links: SearchLinks,
}

#[derive(Deserialize)]
#[serde(bound(deserialize = "T: Deserialize<'de>"))]
struct SearchHits<T> {
    #[serde(default)]
    hits: Vec<T>,
    #[serde(default)]
    total: Option<SearchTotal>,
}

#[derive(Deserialize)]
#[serde(untagged)]
enum SearchTotal {
    Number(#[serde(deserialize_with = "deserialize_u64ish")] u64),
    Object {
        #[serde(deserialize_with = "deserialize_u64ish")]
        value: u64,
    },
}

impl SearchTotal {
    fn into_u64(self) -> u64 {
        match self {
            Self::Number(value) | Self::Object { value } => value,
        }
    }
}

#[derive(Default, Deserialize)]
struct SearchLinks {
    #[serde(default)]
    next: Option<Url>,
    #[serde(default)]
    prev: Option<Url>,
}

impl<T> From<SearchEnvelope<T>> for Page<T> {
    fn from(value: SearchEnvelope<T>) -> Self {
        Self {
            hits: value.hits.hits,
            total: value.hits.total.map(SearchTotal::into_u64),
            next: value.links.next,
            prev: value.links.prev,
        }
    }
}

impl ZenodoClient {
    /// Searches published records using Zenodo's records API.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zenodo_rs::{Auth, RecordQuery, ZenodoClient};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = ZenodoClient::new(Auth::new("token"))?;
    ///     let page = client
    ///         .search_records(
    ///             &RecordQuery::builder()
    ///                 .query("doi:\"10.5281/zenodo.123\"")
    ///                 .published()
    ///                 .most_recent()
    ///                 .size(10)
    ///                 .build(),
    ///         )
    ///         .await?;
    ///     let _ = page.hits;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or Zenodo returns malformed
    /// search data.
    pub async fn search_records(&self, query: &RecordQuery) -> Result<Page<Record>, ZenodoError> {
        let pairs = query.clone().into_pairs();
        self.execute_json::<SearchEnvelope<Record>>(
            self.request(reqwest::Method::GET, "records")?.query(&pairs),
        )
        .await
        .map(Into::into)
    }

    /// Fetches a published record by record ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or Zenodo returns a non-success
    /// response.
    pub async fn get_record(&self, id: RecordId) -> Result<Record, ZenodoError> {
        self.execute_json(self.request(reqwest::Method::GET, &format!("records/{id}"))?)
            .await
    }

    /// Resolves a DOI to a published record.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zenodo_rs::{Auth, ZenodoClient};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = ZenodoClient::new(Auth::new("token"))?;
    ///     let record = client
    ///         .get_record_by_doi_str("https://doi.org/10.5281/zenodo.123")
    ///         .await?;
    ///     let _ = record.id;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the search fails or no record matches the DOI.
    pub async fn get_record_by_doi(&self, doi: &Doi) -> Result<Record, ZenodoError> {
        let mut page = self
            .search_records(
                &RecordQuery::builder()
                    .query(format!("doi:\"{doi}\" OR conceptdoi:\"{doi}\""))
                    .size(25)
                    .all_versions()
                    .build(),
            )
            .await?;

        loop {
            if let Some(record) = page
                .hits
                .into_iter()
                .find(|record| record_matches_doi(record, doi))
            {
                return Ok(record);
            }

            let Some(next) = page.next else {
                break;
            };
            page = self
                .execute_json::<SearchEnvelope<Record>>(
                    self.request_url(reqwest::Method::GET, next)?,
                )
                .await?
                .into();
        }

        Err(ZenodoError::UnsupportedSelector(format!(
            "no exact record found for DOI {doi}"
        )))
    }

    /// Parses a DOI string and resolves it to a published record.
    ///
    /// # Errors
    ///
    /// Returns an error if the DOI string is invalid, if the search fails, or
    /// if no record matches the DOI.
    pub async fn get_record_by_doi_str(&self, doi: impl AsRef<str>) -> Result<Record, ZenodoError> {
        let doi = Doi::new(doi).map_err(|error| {
            ZenodoError::UnsupportedSelector(format!("invalid DOI selector: {error}"))
        })?;
        self.get_record_by_doi(&doi).await
    }

    /// Resolves a DOI and then follows the latest-version link when present.
    ///
    /// # Errors
    ///
    /// Returns an error if DOI resolution fails or the latest record cannot be
    /// fetched.
    pub async fn resolve_latest_by_doi(&self, doi: &Doi) -> Result<Record, ZenodoError> {
        let record = self.get_record_by_doi(doi).await?;
        self.resolve_latest_from_record(record).await
    }

    /// Parses a DOI string and resolves the latest version in that record family.
    ///
    /// # Errors
    ///
    /// Returns an error if the DOI string is invalid, if DOI resolution fails,
    /// or if the latest record cannot be fetched.
    pub async fn resolve_latest_by_doi_str(
        &self,
        doi: impl AsRef<str>,
    ) -> Result<Record, ZenodoError> {
        let doi = Doi::new(doi).map_err(|error| {
            ZenodoError::UnsupportedSelector(format!("invalid DOI selector: {error}"))
        })?;
        self.resolve_latest_by_doi(&doi).await
    }

    /// Fetches the latest record version for a record family.
    ///
    /// # Errors
    ///
    /// Returns an error if record lookup fails or the latest record cannot be
    /// fetched.
    pub async fn get_latest_record(&self, id: RecordId) -> Result<Record, ZenodoError> {
        self.resolve_latest_version(id).await
    }

    /// Resolves the latest record version starting from a record ID.
    ///
    /// # Errors
    ///
    /// Returns an error if record lookup fails or the latest record cannot be
    /// fetched.
    pub async fn resolve_latest_version(&self, id: RecordId) -> Result<Record, ZenodoError> {
        let record = self.get_record(id).await?;
        self.resolve_latest_from_record(record).await
    }

    /// Lists the versions associated with a record family.
    ///
    /// # Errors
    ///
    /// Returns an error if the record lookup fails or the versions query cannot
    /// be completed.
    pub async fn list_record_versions(&self, id: RecordId) -> Result<Page<Record>, ZenodoError> {
        let record = self.get_record(id).await?;
        if let Some(versions_url) = record.links.versions.clone() {
            return self
                .execute_json::<SearchEnvelope<Record>>(
                    self.request_url(reqwest::Method::GET, versions_url)?,
                )
                .await
                .map(Into::into);
        }

        if let Some(conceptrecid) = record.conceptrecid {
            return self
                .search_records(
                    &RecordQuery::builder()
                        .query(format!("conceptrecid:{}", conceptrecid.0))
                        .all_versions()
                        .most_recent()
                        .build(),
                )
                .await;
        }

        Ok(Page {
            hits: vec![record],
            total: Some(1),
            next: None,
            prev: None,
        })
    }

    /// Lists files attached to a specific record.
    ///
    /// # Errors
    ///
    /// Returns an error if the record lookup fails.
    pub async fn list_record_files(&self, id: RecordId) -> Result<Vec<RecordFile>, ZenodoError> {
        Ok(self.get_record(id).await?.files)
    }

    /// Returns a record together with its latest version and keyed files map.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use zenodo_rs::{Auth, RecordId, ZenodoClient};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = ZenodoClient::new(Auth::new("token"))?;
    ///     let info = client.get_artifact_info(RecordId(123)).await?;
    ///     let _ = info.files_by_key;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if record lookup or latest-version resolution fails.
    pub async fn get_artifact_info(&self, id: RecordId) -> Result<ArtifactInfo, ZenodoError> {
        let record = self.get_record(id).await?;
        let latest = self.resolve_latest_from_record(record.clone()).await?;
        let files_by_key = latest
            .files
            .iter()
            .cloned()
            .map(|file| (file.key.clone(), file))
            .collect();

        Ok(ArtifactInfo {
            record,
            latest,
            files_by_key,
        })
    }

    /// Resolves artifact information starting from a DOI.
    ///
    /// # Errors
    ///
    /// Returns an error if DOI resolution fails or latest-version resolution
    /// fails.
    pub async fn get_artifact_info_by_doi(&self, doi: &Doi) -> Result<ArtifactInfo, ZenodoError> {
        let record = self.get_record_by_doi(doi).await?;
        self.get_artifact_info(record.id).await
    }

    pub(crate) async fn resolve_record_selector(
        &self,
        selector: &RecordSelector,
    ) -> Result<Record, ZenodoError> {
        match selector {
            RecordSelector::RecordId(id) => self.get_record(*id).await,
            RecordSelector::Doi(doi) => self.get_record_by_doi(doi).await,
        }
    }

    pub(crate) async fn resolve_latest_from_record(
        &self,
        record: Record,
    ) -> Result<Record, ZenodoError> {
        match record.latest_url() {
            Some(latest_url) => self.get_record_by_url(latest_url).await,
            None => Ok(record),
        }
    }
}

fn record_matches_doi(record: &Record, doi: &Doi) -> bool {
    record.doi.as_ref() == Some(doi) || record.conceptdoi.as_ref() == Some(doi)
}

#[cfg(test)]
mod tests {
    use super::{
        record_matches_doi, ArtifactSelector, RecordQuery, RecordQueryStatus, RecordSelector,
        RecordSort, SearchEnvelope,
    };
    use crate::client::{Auth, ZenodoClient};
    use crate::{Doi, Endpoint, Record, RecordId, ZenodoError};
    use url::Url;

    #[test]
    fn query_serialization_uses_zenodo_parameter_names() {
        let pairs = RecordQuery {
            q: Some("title:test".into()),
            page: Some(2),
            size: Some(50),
            all_versions: true,
            communities: vec!["alpha".into(), "beta".into()],
            resource_type: Some("dataset".into()),
            subtype: Some("image".into()),
            custom: vec![("foo".into(), "bar".into())],
            ..RecordQuery::default()
        }
        .into_pairs();

        assert!(pairs.contains(&("q".into(), "title:test".into())));
        assert!(pairs.contains(&("page".into(), "2".into())));
        assert!(pairs.contains(&("size".into(), "50".into())));
        assert!(pairs.contains(&("all_versions".into(), "true".into())));
        assert!(pairs.contains(&("communities".into(), "alpha,beta".into())));
        assert!(pairs.contains(&("type".into(), "dataset".into())));
        assert!(pairs.contains(&("subtype".into(), "image".into())));
        assert!(pairs.contains(&("foo".into(), "bar".into())));
    }

    #[test]
    fn query_builder_covers_common_search_configuration() {
        let pairs = RecordQuery::builder()
            .query("doi:\"10.5281/zenodo.1\"")
            .published()
            .most_recent()
            .page(2)
            .size(25)
            .all_versions()
            .community("zenodo")
            .resource_type("dataset")
            .subtype("image")
            .custom("foo", "bar")
            .build()
            .into_pairs();

        assert!(pairs.contains(&("q".into(), "doi:\"10.5281/zenodo.1\"".into())));
        assert!(pairs.contains(&("status".into(), "published".into())));
        assert!(pairs.contains(&("sort".into(), "mostrecent".into())));
        assert!(pairs.contains(&("page".into(), "2".into())));
        assert!(pairs.contains(&("size".into(), "25".into())));
        assert!(pairs.contains(&("all_versions".into(), "true".into())));
        assert!(pairs.contains(&("communities".into(), "zenodo".into())));
        assert!(pairs.contains(&("type".into(), "dataset".into())));
        assert!(pairs.contains(&("subtype".into(), "image".into())));
        assert!(pairs.contains(&("foo".into(), "bar".into())));
    }

    #[test]
    fn selector_and_display_helpers_cover_custom_variants() {
        let doi = Doi::new("10.5281/zenodo.1").unwrap();
        assert!(matches!(
            RecordSelector::from(RecordId(1)),
            RecordSelector::RecordId(_)
        ));
        assert!(matches!(
            RecordSelector::from(doi.clone()),
            RecordSelector::Doi(_)
        ));
        assert!(matches!(RecordSelector::from(&doi), RecordSelector::Doi(_)));
        assert_eq!(RecordSort::BestMatch.to_string(), "bestmatch");
        assert_eq!(RecordQueryStatus::Draft.to_string(), "draft");
        assert_eq!(RecordQueryStatus::Custom("mine".into()).to_string(), "mine");
        assert_eq!(RecordSort::AscBestMatch.to_string(), "-bestmatch");
        assert_eq!(RecordSort::AscMostRecent.to_string(), "-mostrecent");
        assert_eq!(RecordSort::Custom("rank".into()).to_string(), "rank");
        assert!(matches!(
            RecordSelector::record_id(RecordId(1)),
            RecordSelector::RecordId(_)
        ));
        assert!(matches!(
            RecordSelector::doi("10.5281/zenodo.1").unwrap(),
            RecordSelector::Doi(_)
        ));
        assert_eq!(
            ArtifactSelector::file(RecordId(1), "artifact.bin"),
            ArtifactSelector::FileByKey {
                record: RecordSelector::RecordId(RecordId(1)),
                key: "artifact.bin".into(),
                latest: false,
            }
        );
        assert_eq!(
            ArtifactSelector::latest_archive_by_doi("10.5281/zenodo.1").unwrap(),
            ArtifactSelector::Archive {
                record: RecordSelector::Doi(Doi::new("10.5281/zenodo.1").unwrap()),
                latest: true,
            }
        );
        assert_eq!(
            ArtifactSelector::latest_file_by_doi("10.5281/zenodo.1", "artifact.bin").unwrap(),
            ArtifactSelector::FileByKey {
                record: RecordSelector::Doi(Doi::new("10.5281/zenodo.1").unwrap()),
                key: "artifact.bin".into(),
                latest: true,
            }
        );
        assert_eq!(
            ArtifactSelector::file_by_doi("10.5281/zenodo.1", "artifact.bin").unwrap(),
            ArtifactSelector::FileByKey {
                record: RecordSelector::Doi(Doi::new("10.5281/zenodo.1").unwrap()),
                key: "artifact.bin".into(),
                latest: false,
            }
        );
        assert_eq!(
            ArtifactSelector::archive(RecordId(9)),
            ArtifactSelector::Archive {
                record: RecordSelector::RecordId(RecordId(9)),
                latest: false,
            }
        );
        assert_eq!(
            ArtifactSelector::latest_archive(RecordId(9)),
            ArtifactSelector::Archive {
                record: RecordSelector::RecordId(RecordId(9)),
                latest: true,
            }
        );
        assert_eq!(
            ArtifactSelector::archive_by_doi("10.5281/zenodo.1").unwrap(),
            ArtifactSelector::Archive {
                record: RecordSelector::Doi(Doi::new("10.5281/zenodo.1").unwrap()),
                latest: false,
            }
        );
    }

    #[test]
    fn query_builder_exercises_remaining_methods() {
        let query = RecordQuery::builder()
            .query("title:test")
            .status(RecordQueryStatus::Custom("custom".into()))
            .sort(RecordSort::AscMostRecent)
            .draft()
            .page(3)
            .size(15)
            .communities(vec!["alpha".into(), "beta".into()])
            .community("gamma")
            .resource_type("software")
            .subtype("source-code")
            .build();

        assert_eq!(query.q.as_deref(), Some("title:test"));
        assert_eq!(query.status, Some(RecordQueryStatus::Draft));
        assert_eq!(query.sort, Some(RecordSort::AscMostRecent));
        assert_eq!(query.page, Some(3));
        assert_eq!(query.size, Some(15));
        assert_eq!(query.communities, vec!["alpha", "beta", "gamma"]);
        assert_eq!(query.resource_type.as_deref(), Some("software"));
        assert_eq!(query.subtype.as_deref(), Some("source-code"));
    }

    #[test]
    fn doi_matching_accepts_record_and_concept_doi_only() {
        let doi = Doi::new("https://doi.org/10.5281/ZENODO.1").unwrap();
        let record: Record = serde_json::from_value(serde_json::json!({
            "id": 1,
            "recid": 1,
            "doi": "10.5281/zenodo.1",
            "conceptdoi": "10.5281/zenodo.2",
            "metadata": { "title": "artifact" },
            "files": [],
            "links": {}
        }))
        .unwrap();
        let concept_only: Record = serde_json::from_value(serde_json::json!({
            "id": 2,
            "recid": 2,
            "conceptdoi": "10.5281/zenodo.1",
            "metadata": { "title": "artifact" },
            "files": [],
            "links": {}
        }))
        .unwrap();
        let mismatch: Record = serde_json::from_value(serde_json::json!({
            "id": 3,
            "recid": 3,
            "doi": "10.5281/zenodo.999",
            "metadata": { "title": "artifact" },
            "files": [],
            "links": {}
        }))
        .unwrap();

        assert!(record_matches_doi(&record, &doi));
        assert!(record_matches_doi(&concept_only, &doi));
        assert!(!record_matches_doi(&mismatch, &doi));
    }

    #[test]
    fn search_totals_accept_integer_like_numeric_shapes() {
        let from_number: SearchEnvelope<Record> = serde_json::from_value(serde_json::json!({
            "hits": {
                "hits": [],
                "total": 14.0
            }
        }))
        .unwrap();
        let from_object: SearchEnvelope<Record> = serde_json::from_value(serde_json::json!({
            "hits": {
                "hits": [],
                "total": {
                    "value": "15"
                }
            }
        }))
        .unwrap();

        assert_eq!(super::Page::from(from_number).total, Some(14));
        assert_eq!(super::Page::from(from_object).total, Some(15));
    }

    #[tokio::test]
    async fn doi_string_helpers_reject_invalid_selectors_before_requesting() {
        let client = ZenodoClient::builder(Auth::new("token"))
            .endpoint(Endpoint::Custom(
                Url::parse("http://localhost:9/api/").unwrap(),
            ))
            .build()
            .unwrap();

        let get_error = client
            .get_record_by_doi_str("definitely not a doi")
            .await
            .unwrap_err();
        let latest_error = client
            .resolve_latest_by_doi_str("still not a doi")
            .await
            .unwrap_err();

        assert!(matches!(
            get_error,
            ZenodoError::UnsupportedSelector(message)
            if message.starts_with("invalid DOI selector:")
        ));
        assert!(matches!(
            latest_error,
            ZenodoError::UnsupportedSelector(message)
            if message.starts_with("invalid DOI selector:")
        ));
    }
}