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
//! API Version provider service
include!(concat!(env!("OUT_DIR"), "/open_api.rs"));
use anyhow::anyhow;
use semver::{Version, VersionReq};
use std::collections::HashMap;
use std::sync::Arc;

use crate::era::EraChecker;
use crate::StdResult;

/// API Version provider
#[derive(Clone)]
pub struct APIVersionProvider {
    era_checker: Arc<EraChecker>,
    open_api_versions: HashMap<OpenAPIFileName, Version>,
}

impl APIVersionProvider {
    /// Version provider factory
    pub fn new(era_checker: Arc<EraChecker>) -> Self {
        Self {
            era_checker,
            open_api_versions: get_open_api_versions_mapping(),
        }
    }

    /// Compute the current api version
    pub fn compute_current_version(&self) -> StdResult<Version> {
        let current_era = self.era_checker.current_era();
        let open_api_spec_file_name_default = "openapi.yaml";
        let open_api_spec_file_name_era = &format!("openapi-{current_era}.yaml");
        let open_api_version = self
            .open_api_versions
            .get(open_api_spec_file_name_era)
            .unwrap_or(
                self.open_api_versions
                    .get(open_api_spec_file_name_default)
                    .ok_or_else(|| anyhow!("Missing default API version"))?,
            );

        Ok(open_api_version.clone())
    }

    /// Compute the current api version requirement
    pub fn compute_current_version_requirement(&self) -> StdResult<VersionReq> {
        let version = &self.compute_current_version()?;
        let version_req = if version.major > 0 {
            format!("={}", version.major)
        } else {
            format!("={}.{}", version.major, version.minor)
        };

        Ok(VersionReq::parse(&version_req)?)
    }

    /// Compute all the sorted list of all versions
    pub fn compute_all_versions_sorted() -> StdResult<Vec<Version>> {
        let mut versions: Vec<Version> = get_open_api_versions_mapping().into_values().collect();
        versions.sort();
        Ok(versions)
    }

    /// Update open api versions. Test only
    pub fn update_open_api_versions(
        &mut self,
        open_api_versions: HashMap<OpenAPIFileName, Version>,
    ) {
        self.open_api_versions = open_api_versions;
    }
}

#[cfg(test)]
mod test {
    use semver::Version;
    use std::{collections::HashMap, sync::Arc};

    use crate::{
        api_version::APIVersionProvider,
        entities::Epoch,
        era::{EraChecker, SupportedEra},
    };

    #[test]
    fn test_compute_current_version_default() {
        let era_checker = EraChecker::new(SupportedEra::dummy(), Epoch(1));
        let mut version_provider = APIVersionProvider::new(Arc::new(era_checker));
        let mut open_api_versions = HashMap::new();
        open_api_versions.insert("openapi.yaml".to_string(), Version::new(1, 2, 3));
        version_provider.update_open_api_versions(open_api_versions);
        let api_version_provider = Arc::new(version_provider);

        assert_eq!(
            "1.2.3".to_string(),
            api_version_provider
                .compute_current_version()
                .unwrap()
                .to_string()
        )
    }

    #[test]
    fn test_compute_current_version_era_specific() {
        let era_checker = EraChecker::new(SupportedEra::dummy(), Epoch(1));
        let mut version_provider = APIVersionProvider::new(Arc::new(era_checker));
        let mut open_api_versions = HashMap::new();
        open_api_versions.insert("openapi.yaml".to_string(), Version::new(1, 2, 3));
        open_api_versions.insert(
            format!("openapi-{}.yaml", SupportedEra::dummy()),
            Version::new(2, 1, 0),
        );
        version_provider.update_open_api_versions(open_api_versions);
        let api_version_provider = Arc::new(version_provider);

        assert_eq!(
            "2.1.0".to_string(),
            api_version_provider
                .compute_current_version()
                .unwrap()
                .to_string()
        )
    }

    #[test]
    fn test_compute_current_version_requirement_beta() {
        let era_checker = EraChecker::new(SupportedEra::dummy(), Epoch(1));
        let mut version_provider = APIVersionProvider::new(Arc::new(era_checker));
        let mut open_api_versions = HashMap::new();
        open_api_versions.insert("openapi.yaml".to_string(), Version::new(0, 2, 3));
        version_provider.update_open_api_versions(open_api_versions);
        let api_version_provider = Arc::new(version_provider);

        assert_eq!(
            "=0.2".to_string(),
            api_version_provider
                .compute_current_version_requirement()
                .unwrap()
                .to_string()
        )
    }

    #[test]
    fn test_compute_current_version_requirement_stable() {
        let era_checker = EraChecker::new(SupportedEra::dummy(), Epoch(1));
        let mut version_provider = APIVersionProvider::new(Arc::new(era_checker));
        let mut open_api_versions = HashMap::new();
        open_api_versions.insert("openapi.yaml".to_string(), Version::new(3, 2, 1));
        version_provider.update_open_api_versions(open_api_versions);
        let api_version_provider = Arc::new(version_provider);

        assert_eq!(
            "=3".to_string(),
            api_version_provider
                .compute_current_version_requirement()
                .unwrap()
                .to_string()
        )
    }

    #[test]
    fn test_compute_all_versions_sorted() {
        let all_versions_sorted = APIVersionProvider::compute_all_versions_sorted()
            .expect("Computing the list of all sorted versions should not fail");

        assert!(!all_versions_sorted.is_empty());
    }
}