Skip to main content

tsurara_sem/
model.rs

1//! IR of a whole definition. The IR stage of plugins rewrites it.
2
3use crate::Error;
4use crate::operation::{OpKind, Operation, OperationBuilder};
5use crate::options::Options;
6use crate::schema::{Converter, Mode, TypeDecl};
7use crate::warning::Warning;
8use serde_json::Value;
9use tsurara_loader::{DocumentSet, SpecVersion, detect_version};
10
11#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
12#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
13#[serde(rename_all = "camelCase")]
14pub struct ServerVariable {
15    pub name: String,
16    pub default: String,
17    pub values: Vec<String>,
18}
19
20#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
21#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
22#[serde(rename_all = "camelCase")]
23pub struct Server {
24    pub url: String,
25    pub description: Option<String>,
26    pub variables: Vec<ServerVariable>,
27}
28
29#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
30#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
31#[serde(rename_all = "camelCase")]
32pub struct Model {
33    /// Version of this JSON form (`SEM_VERSION`).
34    pub sem_version: u32,
35    pub version: SpecVersion,
36    pub title: Option<String>,
37    /// Named types, in the order of components, followed by the hoisted types.
38    pub schemas: Vec<TypeDecl>,
39    pub operations: Vec<Operation>,
40    pub webhooks: Vec<Operation>,
41    /// The channels of `x-event-channels`, in document order.
42    #[serde(default, skip_serializing_if = "Vec::is_empty")]
43    pub channels: Vec<crate::operation::Channel>,
44    pub servers: Vec<Server>,
45    /// The names in `components.securitySchemes`, in order.
46    #[serde(default, skip_serializing_if = "Vec::is_empty")]
47    pub security_schemes: Vec<String>,
48    pub warnings: Vec<Warning>,
49    /// Name requests, in the order backends must claim them (design.md 18.4.6).
50    pub names: Vec<crate::naming::NameRequest>,
51}
52
53pub fn build_model(set: &DocumentSet, opts: &Options) -> Result<Model, Error> {
54    let version = detect_version(set.root())?;
55    if version == SpecVersion::Swagger2 {
56        return Err(Error::Swagger2);
57    }
58    let mut conv = Converter::new(set, opts, version);
59    conv.find_multipart_only();
60    let components = conv.register_components();
61    if opts.filter.is_empty() {
62        for loc in &components {
63            conv.enqueue(loc, Mode::Read);
64        }
65    }
66
67    let mut builder = OperationBuilder {
68        conv: &mut conv,
69        incoming: false,
70    };
71    let mut selected = Vec::new();
72    let paths = if opts.operations {
73        builder.collect_paths()
74    } else {
75        Vec::new()
76    };
77    for (loc, method, path) in paths {
78        if !opts.filter.is_empty() {
79            let (id, tags) = builder.peek(&loc);
80            if !opts.filter.selects(id.as_deref(), &tags) {
81                continue;
82            }
83        }
84        let names = builder.name_operation(&loc, &method, &path, OpKind::Operation, None);
85        selected.push((loc, method, path, names));
86    }
87    let mut hooks = Vec::new();
88    if opts.filter.is_empty() {
89        for (loc, method, name) in builder.collect_webhooks() {
90            let names = builder.name_operation(&loc, &method, &name, OpKind::Webhook, None);
91            hooks.push((loc, method, name, names));
92        }
93    }
94    let operations: Vec<Operation> = selected
95        .into_iter()
96        .map(|(loc, method, path, (id, name_id))| {
97            let mut op = builder.build(&loc, &method, &path, id, name_id);
98            builder.check_path_template(&mut op);
99            op
100        })
101        .collect();
102    builder.incoming = true;
103    let webhooks: Vec<Operation> = hooks
104        .into_iter()
105        .map(|(loc, method, name, (id, name_id))| builder.build(&loc, &method, &name, id, name_id))
106        .collect();
107    builder.incoming = false;
108    let channels = if opts.filter.is_empty() {
109        builder.collect_channels()
110    } else {
111        Vec::new()
112    };
113    conv.drain();
114    break_alias_cycles(&mut conv.decls, &mut conv.warnings);
115
116    Ok(Model {
117        sem_version: crate::SEM_VERSION,
118        version,
119        title: set
120            .root()
121            .get("info")
122            .and_then(|i| i.get("title"))
123            .and_then(Value::as_str)
124            .map(str::to_owned),
125        schemas: conv.decls,
126        operations,
127        webhooks,
128        channels,
129        servers: servers(set.root()),
130        security_schemes: set
131            .root()
132            .get("components")
133            .and_then(|c| c.get("securitySchemes"))
134            .and_then(Value::as_object)
135            .map(|m| m.keys().cloned().collect())
136            .unwrap_or_default(),
137        warnings: conv.warnings,
138        names: conv.names,
139    })
140}
141
142/// A declaration that refers back to itself without an object, array or tuple in between
143/// (`A: { $ref: A }`, `A: { anyOf: [{ $ref: A }, { type: string }] }`, or `A` and `B` doing so through
144/// each other) is rejected by languages (TS2456 in TypeScript) and adds no values. Those references
145/// become `never`, so `A | string` is `string`; a declaration with nothing else becomes unknown. Both
146/// are warned about.
147fn break_alias_cycles(decls: &mut [TypeDecl], warnings: &mut Vec<Warning>) {
148    use crate::ir::Type;
149    use crate::naming::NameId;
150    use crate::warning::WarningKind;
151    use std::collections::{HashMap, HashSet};
152
153    /// References that are not inside an object, array or tuple.
154    fn direct(t: &Type, out: &mut Vec<NameId>) {
155        match t {
156            Type::Named(n) => out.push(n.id),
157            Type::Union(ts) | Type::Intersection(ts) => ts.iter().for_each(|t| direct(t, out)),
158            Type::Choice(c) => c.members.iter().for_each(|t| direct(t, out)),
159            Type::Inline(i) => direct(&i.ty, out),
160            _ => {}
161        }
162    }
163    fn cut(t: &Type, cyclic: &HashSet<NameId>) -> Type {
164        match t {
165            Type::Named(n) if cyclic.contains(&n.id) => Type::Never,
166            Type::Union(ts) => Type::Union(ts.iter().map(|t| cut(t, cyclic)).collect()),
167            Type::Intersection(ts) => {
168                Type::Intersection(ts.iter().map(|t| cut(t, cyclic)).collect())
169            }
170            Type::Choice(c) => {
171                let mut c = c.clone();
172                c.members = c.members.iter().map(|t| cut(t, cyclic)).collect();
173                Type::Choice(c)
174            }
175            Type::Inline(i) => {
176                let mut i = (**i).clone();
177                i.ty = cut(&i.ty, cyclic);
178                Type::Inline(Box::new(i))
179            }
180            other => other.clone(),
181        }
182    }
183    /// Whether nothing but `never` is left.
184    fn empty(t: &Type) -> bool {
185        match t {
186            Type::Never => true,
187            Type::Union(ts) | Type::Intersection(ts) => ts.iter().all(empty),
188            Type::Choice(c) => c.members.iter().all(empty),
189            Type::Inline(i) => empty(&i.ty),
190            _ => false,
191        }
192    }
193
194    let edges: HashMap<NameId, Vec<NameId>> = decls
195        .iter()
196        .map(|d| {
197            let mut out = Vec::new();
198            direct(&d.ty, &mut out);
199            (d.id, out)
200        })
201        .collect();
202    let reaches_itself = |start: NameId| {
203        let mut seen = HashSet::new();
204        let mut stack = edges.get(&start).cloned().unwrap_or_default();
205        while let Some(id) = stack.pop() {
206            if id == start {
207                return true;
208            }
209            if seen.insert(id) {
210                stack.extend(edges.get(&id).cloned().unwrap_or_default());
211            }
212        }
213        false
214    };
215    let cyclic: HashSet<NameId> = decls
216        .iter()
217        .map(|d| d.id)
218        .filter(|id| reaches_itself(*id))
219        .collect();
220    for d in decls.iter_mut().filter(|d| cyclic.contains(&d.id)) {
221        let ty = cut(&d.ty, &cyclic);
222        let message = if empty(&ty) {
223            d.ty = Type::Unknown;
224            format!(
225                "`{}` only refers to itself through references; its type is unknown",
226                d.preferred_name
227            )
228        } else {
229            d.ty = ty;
230            format!(
231                "`{}` refers to itself without an object or array in between; those references are left out",
232                d.preferred_name
233            )
234        };
235        warnings.push(Warning {
236            kind: WarningKind::InvalidDefinition,
237            loc: d.loc.clone(),
238            message,
239            language: None,
240        });
241    }
242}
243
244fn servers(root: &Value) -> Vec<Server> {
245    let Some(Value::Array(list)) = root.get("servers") else {
246        return Vec::new();
247    };
248    list.iter()
249        .filter_map(|s| {
250            let url = s.get("url")?.as_str()?.to_owned();
251            let variables = match s.get("variables") {
252                Some(Value::Object(vars)) => vars
253                    .iter()
254                    .map(|(name, v)| ServerVariable {
255                        name: name.clone(),
256                        default: v
257                            .get("default")
258                            .and_then(Value::as_str)
259                            .unwrap_or("")
260                            .to_owned(),
261                        values: v
262                            .get("enum")
263                            .and_then(Value::as_array)
264                            .map(|a| {
265                                a.iter()
266                                    .filter_map(Value::as_str)
267                                    .map(str::to_owned)
268                                    .collect()
269                            })
270                            .unwrap_or_default(),
271                    })
272                    .collect(),
273                _ => Vec::new(),
274            };
275            Some(Server {
276                url,
277                description: s
278                    .get("description")
279                    .and_then(Value::as_str)
280                    .map(str::to_owned),
281                variables,
282            })
283        })
284        .collect()
285}