rustapi-openapi 0.1.450

Native OpenAPI 3.1 specification generator for RustAPI. Integrates Swagger UI.
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
//! Version extraction strategies
//!
//! Provides different strategies for extracting API versions from requests.

use super::version::ApiVersion;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Strategy for extracting API version from requests
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum VersionStrategy {
    /// Extract version from URL path (e.g., /v1/users)
    ///
    /// The pattern should include `{version}` placeholder
    /// Example: "/v{version}/" or "/{version}/"
    Path {
        /// Pattern for matching version in path
        pattern: String,
    },

    /// Extract version from HTTP header
    ///
    /// Example: X-API-Version: 1.0
    Header {
        /// Header name to read version from
        name: String,
    },

    /// Extract version from query parameter
    ///
    /// Example: ?version=1.0 or ?api-version=1.0
    Query {
        /// Query parameter name
        param: String,
    },

    /// Extract version from Accept header media type
    ///
    /// Example: Accept: application/vnd.api.v1+json
    Accept {
        /// Media type pattern with version placeholder
        /// Example: "application/vnd.{vendor}.v{version}+json"
        pattern: String,
    },

    /// Use a custom extractor function
    ///
    /// Uses a named custom extractor registered with the router
    Custom {
        /// Name of the custom extractor
        name: String,
    },
}

impl VersionStrategy {
    /// Create a path-based versioning strategy
    ///
    /// Default pattern: "/v{version}/"
    pub fn path() -> Self {
        Self::Path {
            pattern: "/v{version}/".to_string(),
        }
    }

    /// Create a path strategy with custom pattern
    pub fn path_with_pattern(pattern: impl Into<String>) -> Self {
        Self::Path {
            pattern: pattern.into(),
        }
    }

    /// Create a header-based versioning strategy
    ///
    /// Default header: "X-API-Version"
    pub fn header() -> Self {
        Self::Header {
            name: "X-API-Version".to_string(),
        }
    }

    /// Create a header strategy with custom header name
    pub fn header_with_name(name: impl Into<String>) -> Self {
        Self::Header { name: name.into() }
    }

    /// Create a query parameter versioning strategy
    ///
    /// Default parameter: "version"
    pub fn query() -> Self {
        Self::Query {
            param: "version".to_string(),
        }
    }

    /// Create a query strategy with custom parameter name
    pub fn query_with_param(param: impl Into<String>) -> Self {
        Self::Query {
            param: param.into(),
        }
    }

    /// Create an Accept header versioning strategy
    ///
    /// Default pattern: "application/vnd.api.v{version}+json"
    pub fn accept() -> Self {
        Self::Accept {
            pattern: "application/vnd.api.v{version}+json".to_string(),
        }
    }

    /// Create an Accept strategy with custom pattern
    pub fn accept_with_pattern(pattern: impl Into<String>) -> Self {
        Self::Accept {
            pattern: pattern.into(),
        }
    }

    /// Create a custom extraction strategy
    pub fn custom(name: impl Into<String>) -> Self {
        Self::Custom { name: name.into() }
    }
}

impl Default for VersionStrategy {
    fn default() -> Self {
        Self::path()
    }
}

/// Version extractor that can extract versions from request data
#[derive(Debug, Clone)]
pub struct VersionExtractor {
    /// Strategies to try in order
    strategies: Vec<VersionStrategy>,
    /// Default version if none can be extracted
    default: ApiVersion,
}

impl VersionExtractor {
    /// Create a new extractor with default settings
    pub fn new() -> Self {
        Self {
            strategies: vec![VersionStrategy::path()],
            default: ApiVersion::v1(),
        }
    }

    /// Create an extractor with a single strategy
    pub fn with_strategy(strategy: VersionStrategy) -> Self {
        Self {
            strategies: vec![strategy],
            default: ApiVersion::v1(),
        }
    }

    /// Create an extractor with multiple strategies (tried in order)
    pub fn with_strategies(strategies: Vec<VersionStrategy>) -> Self {
        Self {
            strategies,
            default: ApiVersion::v1(),
        }
    }

    /// Set the default version
    pub fn default_version(mut self, version: ApiVersion) -> Self {
        self.default = version;
        self
    }

    /// Add a strategy to try
    pub fn add_strategy(mut self, strategy: VersionStrategy) -> Self {
        self.strategies.push(strategy);
        self
    }

    /// Extract version from path
    pub fn extract_from_path(&self, path: &str) -> Option<ApiVersion> {
        for strategy in &self.strategies {
            if let VersionStrategy::Path { pattern } = strategy {
                if let Some(version) = Self::extract_path_version(path, pattern) {
                    return Some(version);
                }
            }
        }
        None
    }

    /// Extract version from headers
    pub fn extract_from_headers(&self, headers: &HashMap<String, String>) -> Option<ApiVersion> {
        for strategy in &self.strategies {
            match strategy {
                VersionStrategy::Header { name } => {
                    if let Some(value) = headers.get(&name.to_lowercase()) {
                        if let Ok(version) = value.parse() {
                            return Some(version);
                        }
                    }
                }
                VersionStrategy::Accept { pattern } => {
                    if let Some(accept) = headers.get("accept") {
                        if let Some(version) = Self::extract_accept_version(accept, pattern) {
                            return Some(version);
                        }
                    }
                }
                _ => {}
            }
        }
        None
    }

    /// Extract version from query string
    pub fn extract_from_query(&self, query: &str) -> Option<ApiVersion> {
        let params: HashMap<_, _> = query
            .split('&')
            .filter_map(|pair| {
                let mut parts = pair.splitn(2, '=');
                Some((parts.next()?.to_string(), parts.next()?.to_string()))
            })
            .collect();

        for strategy in &self.strategies {
            if let VersionStrategy::Query { param } = strategy {
                if let Some(value) = params.get(param) {
                    if let Ok(version) = value.parse() {
                        return Some(version);
                    }
                }
            }
        }
        None
    }

    /// Get the default version
    pub fn get_default(&self) -> ApiVersion {
        self.default
    }

    /// Extract version from path using pattern
    fn extract_path_version(path: &str, pattern: &str) -> Option<ApiVersion> {
        // Find the version placeholder position
        let before = pattern.split("{version}").next()?;
        let after = pattern.split("{version}").nth(1)?;

        // Find the version segment in the path
        if let Some(start) = path.find(before) {
            let version_start = start + before.len();
            let remaining = &path[version_start..];

            // Find the end of the version segment
            let version_end = if after.is_empty() {
                remaining.len()
            } else {
                remaining.find(after).unwrap_or(remaining.len())
            };

            let version_str = &remaining[..version_end];
            version_str.parse().ok()
        } else {
            None
        }
    }

    /// Extract version from Accept header
    fn extract_accept_version(accept: &str, pattern: &str) -> Option<ApiVersion> {
        // Parse the pattern
        let before = pattern.split("{version}").next()?;
        let after = pattern.split("{version}").nth(1)?;

        // Find in accept header
        for media_type in accept.split(',').map(|s| s.trim()) {
            if let Some(start) = media_type.find(before) {
                let version_start = start + before.len();
                let remaining = &media_type[version_start..];

                let version_end = if after.is_empty() {
                    remaining.len()
                } else {
                    remaining.find(after).unwrap_or(remaining.len())
                };

                let version_str = &remaining[..version_end];
                if let Ok(version) = version_str.parse() {
                    return Some(version);
                }
            }
        }
        None
    }

    /// Remove version from path, returning the path without version prefix/suffix
    pub fn strip_version_from_path(&self, path: &str) -> String {
        for strategy in &self.strategies {
            if let VersionStrategy::Path { pattern } = strategy {
                if let Some(stripped) = Self::strip_path_version(path, pattern) {
                    return stripped;
                }
            }
        }
        path.to_string()
    }

    /// Strip version from path using pattern
    fn strip_path_version(path: &str, pattern: &str) -> Option<String> {
        let before = pattern.split("{version}").next()?;
        let after = pattern.split("{version}").nth(1)?;

        if let Some(start) = path.find(before) {
            let version_start = start + before.len();
            let remaining = &path[version_start..];

            let version_end = if after.is_empty() {
                remaining.len()
            } else {
                remaining.find(after)?
            };

            // Verify it's a valid version
            let version_str = &remaining[..version_end];
            if version_str.parse::<ApiVersion>().is_ok() {
                let prefix = &path[..start];
                // The suffix starts after version_end + after.len() in remaining
                // But we want to keep the leading / for paths
                let suffix = &remaining[version_end + after.len()..];
                // Ensure result starts with / if original path did and prefix is empty
                if path.starts_with('/') && prefix.is_empty() && !suffix.starts_with('/') {
                    return Some(format!("/{}", suffix));
                }
                return Some(format!("{}{}", prefix, suffix));
            }
        }
        None
    }
}

impl Default for VersionExtractor {
    fn default() -> Self {
        Self::new()
    }
}

/// Result of version extraction
#[derive(Debug, Clone)]
pub struct ExtractedVersion {
    /// The extracted version
    pub version: ApiVersion,
    /// Source of the version
    pub source: VersionSource,
}

/// Source from which version was extracted
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VersionSource {
    /// Extracted from URL path
    Path,
    /// Extracted from HTTP header
    Header,
    /// Extracted from query parameter
    Query,
    /// Extracted from Accept header
    Accept,
    /// Default version was used
    Default,
    /// Custom extraction
    Custom,
}

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

    #[test]
    fn test_extract_from_path() {
        let extractor = VersionExtractor::new();

        assert_eq!(
            extractor.extract_from_path("/v1/users"),
            Some(ApiVersion::major(1))
        );
        assert_eq!(
            extractor.extract_from_path("/v2/products/123"),
            Some(ApiVersion::major(2))
        );
        assert_eq!(
            extractor.extract_from_path("/v1.2/items"),
            Some(ApiVersion::new(1, 2, 0))
        );
    }

    #[test]
    fn test_extract_from_header() {
        let extractor = VersionExtractor::with_strategy(VersionStrategy::header());
        let mut headers = HashMap::new();
        headers.insert("x-api-version".to_string(), "2.0".to_string());

        assert_eq!(
            extractor.extract_from_headers(&headers),
            Some(ApiVersion::new(2, 0, 0))
        );
    }

    #[test]
    fn test_extract_from_query() {
        let extractor = VersionExtractor::with_strategy(VersionStrategy::query());

        assert_eq!(
            extractor.extract_from_query("version=1&other=value"),
            Some(ApiVersion::major(1))
        );
        assert_eq!(
            extractor.extract_from_query("foo=bar&version=2.1"),
            Some(ApiVersion::new(2, 1, 0))
        );
    }

    #[test]
    fn test_extract_from_accept() {
        let extractor = VersionExtractor::with_strategy(VersionStrategy::accept());
        let mut headers = HashMap::new();
        headers.insert(
            "accept".to_string(),
            "application/vnd.api.v2+json".to_string(),
        );

        assert_eq!(
            extractor.extract_from_headers(&headers),
            Some(ApiVersion::major(2))
        );
    }

    #[test]
    fn test_strip_version_from_path() {
        let extractor = VersionExtractor::new();

        assert_eq!(extractor.strip_version_from_path("/v1/users"), "/users");
        assert_eq!(
            extractor.strip_version_from_path("/v2.0/products/123"),
            "/products/123"
        );
    }

    #[test]
    fn test_multiple_strategies() {
        let extractor = VersionExtractor::with_strategies(vec![
            VersionStrategy::path(),
            VersionStrategy::header(),
            VersionStrategy::query(),
        ])
        .default_version(ApiVersion::v1());

        // Path takes precedence
        assert_eq!(
            extractor.extract_from_path("/v2/test"),
            Some(ApiVersion::major(2))
        );

        // Falls back to query
        assert_eq!(
            extractor.extract_from_query("version=3"),
            Some(ApiVersion::major(3))
        );
    }

    #[test]
    fn test_custom_path_pattern() {
        let extractor =
            VersionExtractor::with_strategy(VersionStrategy::path_with_pattern("/api/{version}/"));

        assert_eq!(
            extractor.extract_from_path("/api/1/users"),
            Some(ApiVersion::major(1))
        );
        assert_eq!(
            extractor.extract_from_path("/api/2.0/products"),
            Some(ApiVersion::new(2, 0, 0))
        );
    }
}