poolster-core 0.5.0-alpha.1

Language-neutral OpenAPI code generation primitives
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
use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// A normalized, language-neutral description of an API.
///
/// Adapters own the conversion from OpenAPI (or another input) into this
/// structure. Generator plugins never need to know which source format was
/// used. `SchemaValue` intentionally retains OpenAPI's compositional type
/// system instead of reducing it to target-language strings.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Api {
    pub name: String,
    pub version: String,
    #[serde(default)]
    pub schemas: Vec<Schema>,
    #[serde(default)]
    pub operations: Vec<Operation>,
    /// Adapter-specific source metadata that is safe for generic transforms to
    /// inspect without coupling the generator to OpenAPI.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub annotations: BTreeMap<String, Value>,
}

/// A named reusable schema, normally an OpenAPI component schema.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Schema {
    pub name: String,
    pub value: SchemaValue,
}

impl Schema {
    pub fn new(name: impl Into<String>, value: SchemaValue) -> Self {
        Self {
            name: name.into(),
            value,
        }
    }
}

/// A recursively composable API type. This is deliberately target neutral:
/// plugins decide whether (for example) `String { format: uuid }` becomes a
/// branded TypeScript string, a Python UUID, or a Rust `uuid::Uuid`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaValue {
    pub kind: SchemaKind,
    #[serde(default)]
    pub nullable: bool,
    /// A target-neutral schema wrapper for contexts which retain optionality
    /// on the value rather than on an enclosing object property.
    #[serde(default)]
    pub optional: bool,
    /// A target-neutral schema wrapper for values which accept either `null`
    /// or `undefined`. OpenAPI itself normally models this through a nullable,
    /// non-required property, but retaining it makes lossless adapters and
    /// schema generators possible.
    #[serde(default)]
    pub nullish: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub format: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub enum_values: Vec<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub const_value: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default)]
    pub deprecated: bool,
    #[serde(default)]
    pub read_only: bool,
    #[serde(default)]
    pub write_only: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discriminator: Option<Discriminator>,
    /// Validation keywords and vendor-neutral OpenAPI keywords which do not
    /// alter the structural shape. Keeping them here means an adapter does not
    /// throw away constraints that a target plugin may support later.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub constraints: BTreeMap<String, Value>,
    /// Unknown `x-*` and future schema keywords. This is a forward-compatible
    /// lossless escape hatch; core generators must not depend on it.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extensions: BTreeMap<String, Value>,
}

impl SchemaValue {
    pub fn new(kind: SchemaKind) -> Self {
        Self {
            kind,
            nullable: false,
            optional: false,
            nullish: false,
            format: None,
            enum_values: Vec::new(),
            const_value: None,
            default: None,
            title: None,
            description: None,
            deprecated: false,
            read_only: false,
            write_only: false,
            discriminator: None,
            constraints: BTreeMap::new(),
            extensions: BTreeMap::new(),
        }
    }

    pub fn unknown() -> Self {
        Self::new(SchemaKind::Any)
    }

    pub fn reference(reference: impl Into<String>) -> Self {
        Self::new(SchemaKind::Reference {
            reference: reference.into(),
        })
    }
}

/// The structural part of a [`SchemaValue`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SchemaKind {
    Any,
    Null,
    Boolean,
    Integer,
    Number,
    String,
    Array {
        items: Box<SchemaValue>,
    },
    Object {
        fields: Vec<Field>,
        additional_properties: AdditionalProperties,
    },
    /// The full OpenAPI/JSON Schema reference is retained to support local,
    /// external, and non-component references. Use `reference_name` when a
    /// target needs the conventional final JSON-pointer segment.
    Reference {
        reference: String,
    },
    OneOf {
        variants: Vec<SchemaValue>,
    },
    AnyOf {
        variants: Vec<SchemaValue>,
    },
    AllOf {
        variants: Vec<SchemaValue>,
    },
    Not {
        schema: Box<SchemaValue>,
    },
}

impl SchemaKind {
    pub fn reference_name(&self) -> Option<&str> {
        let Self::Reference { reference } = self else {
            return None;
        };
        Some(reference.rsplit('/').next().unwrap_or(reference))
    }
}

/// OpenAPI's `additionalProperties` has three semantically distinct states.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum AdditionalProperties {
    /// The keyword was omitted. A generator can apply the relevant OpenAPI
    /// version's default without confusing it with an explicit `true`.
    #[default]
    Unspecified,
    Any,
    Forbidden,
    Schema {
        value: Box<SchemaValue>,
    },
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Discriminator {
    pub property_name: String,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub mapping: BTreeMap<String, String>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Field {
    pub name: String,
    pub value: SchemaValue,
    #[serde(default)]
    pub required: bool,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub annotations: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HttpMethod {
    Get,
    Post,
    Put,
    Patch,
    Delete,
    Head,
    Options,
    Trace,
    Query,
    Custom(String),
}

impl HttpMethod {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Get => "GET",
            Self::Post => "POST",
            Self::Put => "PUT",
            Self::Patch => "PATCH",
            Self::Delete => "DELETE",
            Self::Head => "HEAD",
            Self::Options => "OPTIONS",
            Self::Trace => "TRACE",
            Self::Query => "QUERY",
            Self::Custom(method) => method,
        }
    }
}

impl HttpMethod {
    /// HTTP methods are case-sensitive ASCII tokens. Unknown methods default to
    /// unsafe retry semantics; callers must explicitly supply idempotency policy.
    pub fn parse(method: &str) -> Result<Self, String> {
        if method.is_empty()
            || method.len() > 256
            || !method
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
        {
            return Err("HTTP method must be an ASCII token of 1..=256 bytes".into());
        }
        if method != method.to_ascii_uppercase()
            && matches!(
                method.to_ascii_uppercase().as_str(),
                "GET"
                    | "POST"
                    | "PUT"
                    | "PATCH"
                    | "DELETE"
                    | "HEAD"
                    | "OPTIONS"
                    | "TRACE"
                    | "QUERY"
            )
        {
            return Err("standard HTTP methods must use canonical uppercase tokens".into());
        }
        Ok(match method {
            "GET" => Self::Get,
            "POST" => Self::Post,
            "PUT" => Self::Put,
            "PATCH" => Self::Patch,
            "DELETE" => Self::Delete,
            "HEAD" => Self::Head,
            "OPTIONS" => Self::Options,
            "TRACE" => Self::Trace,
            "QUERY" => Self::Query,
            other => Self::Custom(other.to_owned()),
        })
    }
}
impl Serialize for HttpMethod {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}
impl<'de> Deserialize<'de> for HttpMethod {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let method = String::deserialize(deserializer)?;
        Self::parse(&method).map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Operation {
    pub id: String,
    pub method: HttpMethod,
    pub path: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parameters: Vec<OperationParameter>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_body: Option<OperationRequestBody>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub responses: Vec<OperationResponse>,
    /// OpenAPI security requirements, preserving its OR-of-AND structure.
    /// Each entry is an alternative; every named scheme inside an entry is
    /// required together. Values are OAuth/OpenID scopes where applicable.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub security: Vec<SecurityRequirement>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub annotations: BTreeMap<String, Value>,
}

impl Default for Operation {
    fn default() -> Self {
        Self {
            id: String::new(),
            method: HttpMethod::Get,
            path: String::new(),
            parameters: Vec::new(),
            request_body: None,
            responses: Vec::new(),
            security: Vec::new(),
            annotations: BTreeMap::new(),
        }
    }
}

/// A path, query, header, or cookie input accepted by an operation. `location`
/// intentionally remains a string so the neutral AST can preserve future or
/// vendor-defined OpenAPI locations instead of rejecting an otherwise valid
/// source document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OperationParameter {
    pub name: String,
    pub location: String,
    #[serde(default)]
    pub required: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<SchemaValue>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub annotations: BTreeMap<String, Value>,
}

impl Operation {
    /// The preferred request schema, favoring JSON when multiple media types exist.
    pub fn request_schema(&self) -> Option<&SchemaValue> {
        preferred_schema(&self.request_body.as_ref()?.media_types)
    }

    /// The first declared successful response's schema, favoring JSON media.
    /// Error and default responses are not treated as successful responses.
    pub fn success_schema(&self) -> Option<&SchemaValue> {
        preferred_schema(
            &self
                .responses
                .iter()
                .find(|response| response.status.starts_with('2'))?
                .media_types,
        )
    }
}

fn preferred_schema(media_types: &[OperationMediaType]) -> Option<&SchemaValue> {
    media_types
        .iter()
        .find(|media| {
            media.content_type == "application/json" || media.content_type.ends_with("+json")
        })
        .or_else(|| media_types.first())?
        .schema
        .as_ref()
}

/// An operation request body, retaining the schemas for each media type.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OperationRequestBody {
    #[serde(default)]
    pub required: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub media_types: Vec<OperationMediaType>,
}

/// A response grouped by OpenAPI status code (or `default`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OperationResponse {
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub media_types: Vec<OperationMediaType>,
}

impl OperationRequestBody {
    pub fn json(schema: SchemaValue, required: bool) -> Self {
        Self {
            required,
            description: None,
            media_types: vec![OperationMediaType {
                content_type: "application/json".into(),
                schema: Some(schema),
            }],
        }
    }
}

impl OperationResponse {
    pub fn json(status: impl Into<String>, schema: SchemaValue) -> Self {
        Self {
            status: status.into(),
            description: None,
            media_types: vec![OperationMediaType {
                content_type: "application/json".into(),
                schema: Some(schema),
            }],
        }
    }
}

/// A named representation carried by a request or response.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OperationMediaType {
    pub content_type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema: Option<SchemaValue>,
}

/// One OpenAPI Security Requirement Object. Multiple values in
/// `Operation::security` are alternatives; the map entries in one value are
/// conjunctive scheme requirements.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecurityRequirement {
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub schemes: BTreeMap<String, Vec<String>>,
}

/// Reusable security-scheme metadata from OpenAPI components.
///
/// An operation's [`SecurityRequirement`] says which named schemes it needs;
/// this catalog says how an SDK supplies each credential. Keeping it separate
/// lets plugins opt into authentication support without parsing sidecar JSON.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecuritySchemeCatalog {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub schemes: Vec<SecurityScheme>,
}

/// A named OpenAPI component security scheme.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SecurityScheme {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub kind: SecuritySchemeKind,
}

/// The credential metadata a generator needs to materialize an OpenAPI
/// security scheme. Unsupported/future scheme kinds are retained as `Other`
/// rather than discarded at the sidecar boundary.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SecuritySchemeKind {
    ApiKey {
        name: Option<String>,
        location: Option<String>,
    },
    Http {
        scheme: Option<String>,
        bearer_format: Option<String>,
    },
    OAuth2 {
        flows: Vec<OAuthFlow>,
        metadata_url: Option<String>,
    },
    OpenIdConnect {
        discovery_url: Option<String>,
    },
    Other {
        type_name: String,
    },
}

/// One named OAuth2 flow, including its token endpoints and advertised scopes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OAuthFlow {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub device_authorization_url: Option<String>,
    pub flow_type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authorization_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_url: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub scopes: BTreeMap<String, String>,
}

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

    #[test]
    fn operation_schema_selection_uses_declared_json_media() {
        let mut operation = Operation {
            request_body: Some(OperationRequestBody::json(
                SchemaValue::reference("Input"),
                true,
            )),
            responses: vec![OperationResponse::json(
                "200",
                SchemaValue::reference("Output"),
            )],
            ..Operation::default()
        };
        operation.request_body.as_mut().unwrap().media_types.insert(
            0,
            OperationMediaType {
                content_type: "text/plain".into(),
                schema: Some(SchemaValue::new(SchemaKind::String)),
            },
        );
        operation.responses[0].media_types.insert(
            0,
            OperationMediaType {
                content_type: "text/plain".into(),
                schema: Some(SchemaValue::new(SchemaKind::String)),
            },
        );
        assert_eq!(
            operation.request_schema().unwrap().kind.reference_name(),
            Some("Input")
        );
        assert_eq!(
            operation.success_schema().unwrap().kind.reference_name(),
            Some("Output")
        );
    }

    #[test]
    fn missing_or_empty_success_never_uses_an_error_schema() {
        let mut operation = Operation {
            responses: vec![OperationResponse::json(
                "default",
                SchemaValue::reference("Error"),
            )],
            ..Operation::default()
        };
        assert!(operation.success_schema().is_none());
        operation.responses.insert(
            0,
            OperationResponse {
                status: "204".into(),
                description: None,
                media_types: vec![],
            },
        );
        assert!(operation.success_schema().is_none());
        assert!(operation.request_schema().is_none());
    }

    #[test]
    fn preserves_a_recursive_discriminated_union() {
        let value = SchemaValue {
            nullable: true,
            discriminator: Some(Discriminator {
                property_name: "kind".into(),
                mapping: BTreeMap::from([("cat".into(), "#/components/schemas/Cat".into())]),
            }),
            ..SchemaValue::new(SchemaKind::OneOf {
                variants: vec![SchemaValue::reference("#/components/schemas/Cat")],
            })
        };
        let round_trip: SchemaValue =
            serde_json::from_str(&serde_json::to_string(&value).unwrap()).unwrap();
        assert_eq!(round_trip, value);
        assert_eq!(value.kind.reference_name(), None);
    }
}

#[cfg(test)]
mod method_tests {
    use super::*;
    #[test]
    fn custom_methods_preserve_case_and_string_serialization() {
        for token in ["GET", "COPY", "x-Custom", "X!#$%&'*+-.^_`|~"] {
            let method = HttpMethod::parse(token).unwrap();
            assert_eq!(method.as_str(), token);
            let encoded = serde_json::to_string(&method).unwrap();
            assert_eq!(
                serde_json::from_str::<HttpMethod>(&encoded).unwrap(),
                method
            );
        }
        for token in [
            "",
            "BAD METHOD",
            "BAD\r\nMETHOD",
            "Méthod",
            "X/Path",
            "get",
            "pOst",
        ] {
            assert!(HttpMethod::parse(token).is_err());
        }
        assert!(HttpMethod::parse(&"X".repeat(257)).is_err());
    }
}