ploidy-core 0.12.0

IR and type graph for the Ploidy OpenAPI compiler
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
use indexmap::IndexMap;
use itertools::Itertools;
use rustc_hash::FxHashSet;

use crate::{
    arena::Arena,
    parse::{
        self, Document, Info, Method, Operation, Parameter, ParameterLocation,
        ParameterStyle as ParsedParameterStyle, RefOrParameter, RefOrRequestBody, RefOrResponse,
        RefOrSchema, RequestBody, Response,
        path::{PathFragment, PathSegment},
    },
};

use super::{
    error::IrError,
    transform::transform,
    types::{
        InlineTypePath, InlineTypePathRoot, InlineTypePathSegment,
        ParameterStyle as IrParameterStyle, SchemaTypeInfo, SpecInlineType, SpecOperation,
        SpecParameter, SpecParameterInfo, SpecRequest, SpecResponse, SpecSchemaType, SpecType,
        TypeInfo,
    },
};

/// The intermediate representation of an OpenAPI document.
///
/// A [`Spec`] is a type tree lowered from a parsed document, with references
/// still unresolved. Construct one with [`Spec::from_doc()`], then pass it to
/// [`RawGraph::new()`] to build the type graph.
///
/// [`RawGraph::new()`]: crate::ir::RawGraph::new
#[derive(Debug)]
pub struct Spec<'a> {
    /// The document's `info` section: title, OpenAPI version, etc.
    pub info: &'a Info,
    /// All operations extracted from the document's `paths` section.
    pub operations: Vec<SpecOperation<'a>>,
    /// Named schemas from `components/schemas`, keyed by name.
    pub schemas: IndexMap<&'a str, SpecType<'a>>,
}

impl<'a> Spec<'a> {
    /// Builds a [`Spec`] from a parsed OpenAPI [`Document`].
    ///
    /// Lowers each schema and operation to IR types, allocating all
    /// long-lived data in the `arena`. Returns an error if the document is
    /// malformed.
    pub fn from_doc(arena: &'a Arena, doc: &'a Document) -> Result<Self, IrError> {
        let schemas = match &doc.components {
            Some(components) => components
                .schemas
                .iter()
                .map(|(name, schema)| {
                    let ty = transform(
                        arena,
                        doc,
                        TypeInfo::Schema(SchemaTypeInfo {
                            name,
                            resource: schema.extension("x-resourceId"),
                        }),
                        schema,
                    );
                    (name.as_str(), ty)
                })
                .collect(),
            None => IndexMap::new(),
        };

        let operations = doc
            .paths
            .iter()
            .map(|(path, item)| {
                let segments: &_ =
                    arena.alloc_slice_copy(&parse::path::parse(arena, path.as_str())?);
                Ok(item.operations().map(move |(method, op)| PathOperation {
                    path: segments,
                    method,
                    params: &item.parameters,
                    op,
                }))
            })
            .flatten_ok()
            .map_ok(|item| -> Result<_, IrError> {
                let resource = item.op.extension("x-resource-name");
                let id = item
                    .op
                    .operation_id
                    .as_deref()
                    .ok_or(IrError::NoOperationId)?;

                let params = {
                    enum Source<'a> {
                        Declared(&'a Parameter),
                        Synthesized(&'a str),
                    }

                    // Merge path item and operation parameters.
                    // Operation parameters override path item ones.
                    let mut declared = IndexMap::new();
                    for param in item
                        .params
                        .iter()
                        .chain(item.op.parameters.iter())
                        .filter_map(|p| match p {
                            RefOrParameter::Other(p) => Some(p),
                            RefOrParameter::Ref(r) => {
                                r.path.pointer().follow::<&Parameter>(doc).ok()
                            }
                        })
                    {
                        declared.insert((param.name.as_str(), param.location), param);
                    }

                    // Walk the path template to produce path parameters in
                    // template order. Each template parameter name pulls its
                    // declaration from the merged map; undeclared names get
                    // a synthesized string parameter.
                    let mut sources = {
                        let mut seen = FxHashSet::default();
                        item.path
                            .iter()
                            .flat_map(|segment| segment.fragments())
                            .filter_map(|fragment| match fragment {
                                &PathFragment::Param(name) => Some(name),
                                _ => None,
                            })
                            .filter(|&name| seen.insert(name))
                            .map(|name| {
                                match declared.shift_remove(&(name, ParameterLocation::Path)) {
                                    Some(param) => Source::Declared(param),
                                    None => Source::Synthesized(name),
                                }
                            })
                            .collect_vec()
                    };

                    // Append remaining parameters in declaration order.
                    sources.extend(declared.into_iter().filter_map(|((_, location), param)| {
                        match location {
                            // Drop declared path parameters that are
                            // absent from the template.
                            ParameterLocation::Path => None,
                            _ => Some(Source::Declared(param)),
                        }
                    }));

                    // Lower all sources to spec parameters.
                    let params = sources.into_iter().filter_map(|source| match source {
                        Source::Declared(param) => {
                            let ty: &_ = match &param.schema {
                                Some(RefOrSchema::Ref(r)) => arena.alloc(SpecType::Ref(&r.path)),
                                Some(RefOrSchema::Other(schema)) => arena.alloc(transform(
                                    arena,
                                    doc,
                                    InlineTypePath {
                                        root: InlineTypePathRoot::Resource(resource),
                                        segments: arena.alloc_slice_copy(&[
                                            InlineTypePathSegment::Operation(id),
                                            InlineTypePathSegment::Parameter(param.name.as_str()),
                                        ]),
                                    },
                                    schema,
                                )),
                                None => arena.alloc(
                                    SpecInlineType::Any(InlineTypePath {
                                        root: InlineTypePathRoot::Resource(resource),
                                        segments: arena.alloc_slice_copy(&[
                                            InlineTypePathSegment::Operation(id),
                                            InlineTypePathSegment::Parameter(param.name.as_str()),
                                        ]),
                                    })
                                    .into(),
                                ),
                            };
                            let style = match (param.style, param.explode) {
                                (Some(ParsedParameterStyle::DeepObject), Some(true) | None) => {
                                    Some(IrParameterStyle::DeepObject)
                                }
                                (
                                    Some(ParsedParameterStyle::SpaceDelimited),
                                    Some(false) | None,
                                ) => Some(IrParameterStyle::SpaceDelimited),
                                (Some(ParsedParameterStyle::PipeDelimited), Some(false) | None) => {
                                    Some(IrParameterStyle::PipeDelimited)
                                }
                                (None, None) => None,
                                (Some(ParsedParameterStyle::Form) | None, Some(true) | None) => {
                                    Some(IrParameterStyle::Form { exploded: true })
                                }
                                (Some(ParsedParameterStyle::Form) | None, Some(false)) => {
                                    Some(IrParameterStyle::Form { exploded: false })
                                }
                                _ => None,
                            };
                            let info = SpecParameterInfo {
                                name: param.name.as_str(),
                                ty,
                                required: param.required,
                                description: param.description.as_deref(),
                                style,
                            };
                            Some(match param.location {
                                ParameterLocation::Path => SpecParameter::Path(info),
                                ParameterLocation::Query => SpecParameter::Query(info),
                                _ => return None,
                            })
                        }
                        Source::Synthesized(name) => {
                            let ty: &_ = arena.alloc(
                                SpecInlineType::Any(InlineTypePath {
                                    root: InlineTypePathRoot::Resource(resource),
                                    segments: arena.alloc_slice_copy(&[
                                        InlineTypePathSegment::Operation(id),
                                        InlineTypePathSegment::Parameter(name),
                                    ]),
                                })
                                .into(),
                            );
                            Some(SpecParameter::Path(SpecParameterInfo {
                                name,
                                ty,
                                required: true,
                                description: None,
                                style: None,
                            }))
                        }
                    });

                    arena.alloc_slice(params)
                };

                let request = item
                    .op
                    .request_body
                    .as_ref()
                    .and_then(|request_or_ref| {
                        let request = match request_or_ref {
                            RefOrRequestBody::Other(rb) => rb,
                            RefOrRequestBody::Ref(r) => {
                                r.path.pointer().follow::<&RequestBody>(doc).ok()?
                            }
                        };

                        Some(if request.content.contains_key("multipart/form-data") {
                            RequestContent::Multipart
                        } else if let Some(content) = request.content.get("application/json")
                            && let Some(schema) = &content.schema
                        {
                            RequestContent::Json(schema)
                        } else if let Some(content) = request.content.get("*/*")
                            && let Some(schema) = &content.schema
                        {
                            RequestContent::Json(schema)
                        } else {
                            RequestContent::Any
                        })
                    })
                    .map(|content| match content {
                        RequestContent::Multipart => SpecRequest::Multipart,
                        RequestContent::Json(RefOrSchema::Ref(r)) => {
                            SpecRequest::Json(arena.alloc(SpecType::Ref(&r.path)))
                        }
                        RequestContent::Json(RefOrSchema::Other(schema)) => {
                            SpecRequest::Json(arena.alloc(transform(
                                arena,
                                doc,
                                InlineTypePath {
                                    root: InlineTypePathRoot::Resource(resource),
                                    segments: arena.alloc_slice_copy(&[
                                        InlineTypePathSegment::Operation(id),
                                        InlineTypePathSegment::Request,
                                    ]),
                                },
                                schema,
                            )))
                        }
                        RequestContent::Any => SpecRequest::Json(
                            arena.alloc(
                                SpecInlineType::Any(InlineTypePath {
                                    root: InlineTypePathRoot::Resource(resource),
                                    segments: arena.alloc_slice_copy(&[
                                        InlineTypePathSegment::Operation(id),
                                        InlineTypePathSegment::Request,
                                    ]),
                                })
                                .into(),
                            ),
                        ),
                    });

                let response = {
                    let mut statuses = item
                        .op
                        .responses
                        .keys()
                        .filter_map(|status| Some((status.as_str(), status.parse::<u16>().ok()?)))
                        .collect_vec();
                    statuses.sort_unstable_by_key(|&(_, code)| code);
                    let key = statuses
                        .iter()
                        .find(|&(_, code)| matches!(code, 200..300))
                        .map(|&(key, _)| key)
                        .unwrap_or("default");

                    item.op
                        .responses
                        .get(key)
                        .and_then(|response_or_ref| {
                            let response = match response_or_ref {
                                RefOrResponse::Other(r) => r,
                                RefOrResponse::Ref(r) => {
                                    r.path.pointer().follow::<&Response>(doc).ok()?
                                }
                            };
                            response.content.as_ref()
                        })
                        .map(|content| {
                            if let Some(content) = content.get("application/json")
                                && let Some(schema) = &content.schema
                            {
                                ResponseContent::Json(schema)
                            } else if let Some(content) = content.get("*/*")
                                && let Some(schema) = &content.schema
                            {
                                ResponseContent::Json(schema)
                            } else {
                                ResponseContent::Any
                            }
                        })
                        .map(|content| match content {
                            ResponseContent::Json(RefOrSchema::Ref(r)) => {
                                SpecResponse::Json(arena.alloc(SpecType::Ref(&r.path)))
                            }
                            ResponseContent::Json(RefOrSchema::Other(schema)) => {
                                SpecResponse::Json(arena.alloc(transform(
                                    arena,
                                    doc,
                                    InlineTypePath {
                                        root: InlineTypePathRoot::Resource(resource),
                                        segments: arena.alloc_slice_copy(&[
                                            InlineTypePathSegment::Operation(id),
                                            InlineTypePathSegment::Response,
                                        ]),
                                    },
                                    schema,
                                )))
                            }
                            ResponseContent::Any => SpecResponse::Json(
                                arena.alloc(
                                    SpecInlineType::Any(InlineTypePath {
                                        root: InlineTypePathRoot::Resource(resource),
                                        segments: arena.alloc_slice_copy(&[
                                            InlineTypePathSegment::Operation(id),
                                            InlineTypePathSegment::Response,
                                        ]),
                                    })
                                    .into(),
                                ),
                            ),
                        })
                };

                Ok(SpecOperation {
                    resource,
                    id,
                    method: item.method,
                    path: item.path,
                    description: item.op.description.as_deref(),
                    params,
                    request,
                    response,
                })
            })
            .flatten_ok()
            .collect::<Result<_, IrError>>()?;

        Ok(Spec {
            info: &doc.info,
            operations,
            schemas,
        })
    }

    /// Resolves a [`SpecType`], following type references through the spec.
    #[inline]
    pub(super) fn resolve(&'a self, mut ty: &'a SpecType<'a>) -> ResolvedSpecType<'a> {
        loop {
            match ty {
                SpecType::Schema(ty) => return ResolvedSpecType::Schema(ty),
                SpecType::Inline(ty) => return ResolvedSpecType::Inline(ty),
                SpecType::Ref(r) => ty = &self.schemas[&*r.name()],
            }
        }
    }
}

/// A dereferenced type in the spec.
///
/// The derived [`Eq`] and [`Hash`][std::hash::Hash] implementations
/// use structural equality, not pointer identity. Multiple [`SpecType`]s
/// in a [`Spec`] may resolve to the same logical type, so value-based
/// comparison is necessary.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(super) enum ResolvedSpecType<'a> {
    Schema(&'a SpecSchemaType<'a>),
    Inline(&'a SpecInlineType<'a>),
}

#[derive(Clone, Copy, Debug)]
enum RequestContent<'a> {
    Multipart,
    Json(&'a RefOrSchema),
    Any,
}

#[derive(Clone, Copy, Debug)]
enum ResponseContent<'a> {
    Json(&'a RefOrSchema),
    Any,
}

#[derive(Clone, Copy, Debug)]
struct PathOperation<'a> {
    path: &'a [PathSegment<'a>],
    method: Method,
    params: &'a [RefOrParameter],
    op: &'a Operation,
}