progenitor-macro 0.14.0

An OpenAPI client generator - macros
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
// Copyright 2026 Oxide Computer Company

//! Macros for the progenitor OpenAPI client generator.

#![deny(missing_docs)]

use std::{collections::HashMap, fs::File, path::PathBuf};

use openapiv3::OpenAPI;
use proc_macro::TokenStream;
use progenitor_impl::{
    CrateVers, GenerationSettings, Generator, InterfaceStyle, TagStyle, TypePatch, UnknownPolicy,
};
use quote::{ToTokens, quote};
use schemars::schema::SchemaObject;
use serde::Deserialize;
use serde_tokenstream::{OrderedMap, ParseWrapper};
use syn::LitStr;
use token_utils::TypeAndImpls;

mod token_utils;

/// Where to resolve the spec path relative to.
#[derive(Debug, Clone, Copy, Deserialize)]
enum RelativeTo {
    /// Resolve relative to CARGO_MANIFEST_DIR (the default).
    ManifestDir,
    /// Resolve relative to OUT_DIR.
    OutDir,
}

/// Specification of where to find the OpenAPI document.
#[derive(Debug)]
struct SpecSource {
    /// The path to the spec file.
    path: LitStr,
    /// Where to resolve the path relative to.
    relative_to: RelativeTo,
}

impl syn::parse::Parse for SpecSource {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        /// Helper struct for deserializing the struct form of SpecSource.
        #[derive(Deserialize)]
        struct SpecSourceStruct {
            path: ParseWrapper<LitStr>,
            relative_to: RelativeTo,
        }

        let lookahead = input.lookahead1();
        if lookahead.peek(LitStr) {
            // spec = "path/to/spec.json"
            let path: LitStr = input.parse()?;
            Ok(SpecSource {
                path,
                relative_to: RelativeTo::ManifestDir,
            })
        } else if lookahead.peek(syn::token::Brace) {
            // spec = { path = "...", relative_to = ... }
            let content;
            let brace_token = syn::braced!(content in input);
            let stream: proc_macro2::TokenStream = content.parse()?;
            let helper: SpecSourceStruct =
                serde_tokenstream::from_tokenstream_spanned(&brace_token.span, &stream)?;
            Ok(SpecSource {
                path: helper.path.into_inner(),
                relative_to: helper.relative_to,
            })
        } else {
            Err(lookahead.error())
        }
    }
}

/// Generates a client from the given OpenAPI document
///
/// `generate_api!` can be invoked in two ways. The simple form, takes a path
/// to the OpenAPI document:
/// ```ignore
/// generate_api!("path/to/spec.json");
/// ```
///
/// The more complex form accepts the following key-value pairs in any order:
/// ```ignore
/// generate_api!(
///     // spec can be a simple path string:
///     spec = "path/to/spec.json",
///     // Or a struct with path and relative_to:
///     spec = { path = "path/to/spec.json", relative_to = OutDir },
///     [ interface = ( Positional | Builder ), ]
///     [ tags = ( Merged | Separate ), ]
///     [ pre_hook = closure::or::path::to::function, ]
///     [ post_hook = closure::or::path::to::function, ]
///     [ pre_hook_async = closure::or::path::to::function, ]
///     [ post_hook_async = closure::or::path::to::function, ]
///
///     [ derives = [ path::to::DeriveMacro ], ]
///
///     [ unknown_crates = (Generate | Allow | Deny ), ]
///     [ crates = { "<crate-name>" = ("<version>" | "*" | "!" ) } ]
///
///     [ patch = { TypeName = { [rename = NewTypeName], [derives = []] }, } ]
///     [ replace = { TypeName = full_path::to::other::TypeName, }]
///     [ convert = { { <schema> } = full_path::to::TypeName, }]
///     [ timeout = u64 ]
/// );
/// ```
///
/// The `spec` key is required; it is the OpenAPI document (JSON or YAML) from
/// which the client is derived. It can be specified as a simple string path, or
/// as a struct with `path` and `relative_to` fields. The `relative_to`
/// field controls where the path is resolved from:
///
/// - `ManifestDir`: relative to `CARGO_MANIFEST_DIR`. This is the default when
///   the spec is provided as a string path.
/// - `OutDir`: relative to `OUT_DIR` (useful for build script outputs).
///
/// The optional `interface` lets you specify either a `Positional` argument or
/// `Builder` argument style; `Positional` is the default.
///
/// The optional `tags` may be `Merged` in which case all operations are
/// methods on the `Client` struct or `Separate` in which case each tag is
/// represented by an "extension trait" that `Client` implements. The default
/// is `Merged`.
///
/// The optional `inner_type` is for ancillary data, stored with the generated
/// client that can be used by the pre- and post-hooks.
///
/// The optional `pre_hook` is either a closure (that must be within
/// parentheses: `(fn |[inner,] request| { .. })`) or a path to a function. The
/// closure or function must take one or two parameters: the inner type (if one
/// is specified) and a `&reqwest::Request`. This allows clients to examine
/// requests before they're sent to the server, for example to log them. The
/// optional `pre_hook_async` is the `async` variant of the same.
///
/// The optional `post_hook` is either a closure (that must be within
/// parentheses: `(fn |[inner,] result| { .. })`) or a path to a function. The
/// closure or function must take one or two parameters: the inner type (if one
/// is specified) and a `&Result<reqwest::Response, reqwest::Error>`. This
/// allows clients to examine responses, for example to log them. The optional
/// `post_hook_async` is the `async` variant of the same.
///
/// Additional options control type generation:
/// - `derives`: optional array of derive macro paths; the derive macros to be
///   applied to all generated types
///
/// - `struct_builder`: optional boolean; (if true) generates a `::builder()`
///   method for each generated struct that can be used to specify each
///   property and construct the struct
///
/// - `unknown_crates`: optional policy regarding the handling of schemas that
///   contain the `x-rust-type` extension whose crates are not explicitly named
///   in the `crates` section. The options are `generate` to ignore the
///   extension and generate a *de novo* type, `allow` to use the named type
///   (which may require the addition of a new dependency to compile, and which
///   ignores version compatibility checks), or `deny` to produce a
///   compile-time error (requiring the user to specify the crate's disposition
///   in the `crates` section).
///
/// - `crates`: optional map from crate name to the version of the crate in
///   use. Types encountered with the Rust type extension (`x-rust-type`) will
///   use types from the specified crates rather than generating them (within
///   the constraints of type compatibility).
///
/// - `patch`: optional map from type to an object with the optional members
///   `rename` and `derives`. This may be used to rename generated types or
///   to apply additional (non-default) derive macros to them.
///
/// - `replace`: optional map from definition name to a replacement type. This
///   may be used to skip generation of the named type and use a existing Rust
///   type.
///
/// - `convert`: optional map from a JSON schema type defined in `$defs` to a
///   replacement type. This may be used to skip generation of the schema and
///   use an existing Rust type.
///
/// - `timeout`: the default connection timeout for the underlying reqwest
///   client (15s if not specified)
#[proc_macro]
pub fn generate_api(item: TokenStream) -> TokenStream {
    match do_generate_api(item) {
        Err(err) => err.to_compile_error().into(),
        Ok(out) => out,
    }
}

#[derive(Deserialize)]
struct MacroSettings {
    spec: ParseWrapper<SpecSource>,
    #[serde(default)]
    interface: InterfaceStyle,
    #[serde(default)]
    tags: TagStyle,

    inner_type: Option<ParseWrapper<syn::Type>>,
    pre_hook: Option<ParseWrapper<ClosureOrPath>>,
    pre_hook_async: Option<ParseWrapper<ClosureOrPath>>,
    post_hook: Option<ParseWrapper<ClosureOrPath>>,
    post_hook_async: Option<ParseWrapper<ClosureOrPath>>,

    map_type: Option<ParseWrapper<syn::Type>>,

    #[serde(default)]
    derives: Vec<ParseWrapper<syn::Path>>,

    #[serde(default)]
    unknown_crates: UnknownPolicy,
    #[serde(default)]
    crates: HashMap<CrateName, MacroCrateSpec>,

    #[serde(default)]
    patch: HashMap<ParseWrapper<syn::Ident>, MacroPatch>,
    #[serde(default)]
    replace: HashMap<ParseWrapper<syn::Ident>, ParseWrapper<TypeAndImpls>>,
    #[serde(default)]
    convert: OrderedMap<SchemaObject, ParseWrapper<TypeAndImpls>>,
    timeout: Option<u64>,
}

#[derive(Deserialize)]
struct MacroPatch {
    #[serde(default)]
    rename: Option<String>,
    #[serde(default)]
    derives: Vec<ParseWrapper<syn::Path>>,
}

impl From<MacroPatch> for TypePatch {
    fn from(a: MacroPatch) -> Self {
        let mut s = Self::default();
        a.rename.iter().for_each(|rename| {
            s.with_rename(rename);
        });
        a.derives.iter().for_each(|derive| {
            s.with_derive(derive.to_token_stream().to_string());
        });
        s
    }
}

#[derive(Debug)]
struct ClosureOrPath(proc_macro2::TokenStream);

impl syn::parse::Parse for ClosureOrPath {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let lookahead = input.lookahead1();

        if lookahead.peek(syn::token::Paren) {
            let group: proc_macro2::Group = input.parse()?;
            return syn::parse2::<Self>(group.stream());
        }

        if let Ok(closure) = input.parse::<syn::ExprClosure>() {
            return Ok(Self(closure.to_token_stream()));
        }

        input
            .parse::<syn::Path>()
            .map(|path| Self(path.to_token_stream()))
    }
}

struct MacroCrateSpec {
    original: Option<String>,
    version: CrateVers,
}

impl<'de> Deserialize<'de> for MacroCrateSpec {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let ss = String::deserialize(deserializer)?;

        let (original, vers_str) = if let Some(ii) = ss.find('@') {
            let original_str = &ss[..ii];
            let rest = &ss[ii + 1..];
            if !is_crate(original_str) {
                return Err(<D::Error as serde::de::Error>::invalid_value(
                    serde::de::Unexpected::Str(&ss),
                    &"valid crate name",
                ));
            }

            (Some(original_str.to_string()), rest)
        } else {
            (None, ss.as_ref())
        };

        let Some(version) = CrateVers::parse(vers_str) else {
            return Err(<D::Error as serde::de::Error>::invalid_value(
                serde::de::Unexpected::Str(&ss),
                &"valid version",
            ));
        };

        Ok(Self { original, version })
    }
}

#[derive(Hash, PartialEq, Eq)]
struct CrateName(String);
impl<'de> Deserialize<'de> for CrateName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let ss = String::deserialize(deserializer)?;

        if is_crate(&ss) {
            Ok(Self(ss))
        } else {
            Err(<D::Error as serde::de::Error>::invalid_value(
                serde::de::Unexpected::Str(&ss),
                &"valid crate name",
            ))
        }
    }
}

fn is_crate(s: &str) -> bool {
    !s.contains(|cc: char| !cc.is_alphanumeric() && cc != '_' && cc != '-')
}

fn open_file(path: PathBuf, span: proc_macro2::Span) -> Result<File, syn::Error> {
    File::open(path.clone()).map_err(|e| {
        let path_str = path.to_string_lossy();
        syn::Error::new(span, format!("couldn't read file {}: {}", path_str, e))
    })
}

fn do_generate_api(item: TokenStream) -> Result<TokenStream, syn::Error> {
    let (spec_source, settings) = if let Ok(spec) = syn::parse::<LitStr>(item.clone()) {
        let spec_source = SpecSource {
            path: spec,
            relative_to: RelativeTo::ManifestDir,
        };
        (spec_source, GenerationSettings::default())
    } else {
        let MacroSettings {
            spec,
            interface,
            tags,
            inner_type,
            pre_hook,
            pre_hook_async,
            post_hook,
            post_hook_async,
            map_type,
            unknown_crates,
            crates,
            derives,
            patch,
            replace,
            convert,
            timeout,
        } = serde_tokenstream::from_tokenstream(&item.into())?;

        let spec = spec.into_inner();

        let mut settings = GenerationSettings::default();
        settings.with_interface(interface);
        settings.with_tag(tags);
        inner_type.map(|inner_type| settings.with_inner_type(inner_type.to_token_stream()));
        pre_hook.map(|pre_hook| settings.with_pre_hook(pre_hook.into_inner().0));
        pre_hook_async
            .map(|pre_hook_async| settings.with_pre_hook_async(pre_hook_async.into_inner().0));
        post_hook.map(|post_hook| settings.with_post_hook(post_hook.into_inner().0));
        post_hook_async
            .map(|post_hook_async| settings.with_post_hook_async(post_hook_async.into_inner().0));
        map_type.map(|map_type| settings.with_map_type(map_type.to_token_stream()));

        settings.with_unknown_crates(unknown_crates);
        crates.into_iter().for_each(
            |(CrateName(crate_name), MacroCrateSpec { original, version })| {
                if let Some(original_crate) = original {
                    settings.with_crate(original_crate, version, Some(&crate_name));
                } else {
                    settings.with_crate(crate_name, version, None);
                }
            },
        );

        derives.into_iter().for_each(|derive| {
            settings.with_derive(derive.to_token_stream());
        });
        patch.into_iter().for_each(|(type_name, patch)| {
            settings.with_patch(type_name.to_token_stream().to_string(), &patch.into());
        });
        replace.into_iter().for_each(|(type_name, type_and_impls)| {
            let type_name = type_name.to_token_stream();
            let (replace_name, impls) = type_and_impls.into_inner().into_name_and_impls();
            settings.with_replacement(type_name, replace_name, impls);
        });
        convert.into_iter().for_each(|(schema, type_and_impls)| {
            let (type_name, impls) = type_and_impls.into_inner().into_name_and_impls();
            settings.with_conversion(schema, type_name, impls);
        });
        if let Some(timeout) = timeout {
            settings.with_timeout(timeout);
        }
        (spec, settings)
    };

    let spec_path = spec_source.path;
    let base_dir = match spec_source.relative_to {
        RelativeTo::ManifestDir => std::env::var("CARGO_MANIFEST_DIR")
            .map_or_else(|_| std::env::current_dir().unwrap(), PathBuf::from),
        RelativeTo::OutDir => {
            let out_dir = std::env::var("OUT_DIR").map_err(|_| {
                syn::Error::new(
                    spec_path.span(),
                    "relative_to = OutDir requires OUT_DIR to be set \
                     (are you using this from a build script?)",
                )
            })?;
            PathBuf::from(out_dir)
        }
    };

    let path = base_dir.join(spec_path.value());
    let path_str = path.to_string_lossy();

    let mut f = open_file(path.clone(), spec_path.span())?;
    let oapi: OpenAPI = match serde_json::from_reader(f) {
        Ok(json_value) => json_value,
        _ => {
            f = open_file(path.clone(), spec_path.span())?;
            serde_yaml::from_reader(f).map_err(|e| {
                syn::Error::new(
                    spec_path.span(),
                    format!("failed to parse {}: {}", path_str, e),
                )
            })?
        }
    };

    let mut builder = Generator::new(&settings);

    let code = builder.generate_tokens(&oapi).map_err(|e| {
        syn::Error::new(
            spec_path.span(),
            format!("generation error for {}: {}", spec_path.value(), e),
        )
    })?;

    let output = quote! {
        // The progenitor_client is tautologically visible from macro
        // consumers.
        use progenitor::progenitor_client;

        #code

        // Force a rebuild when the given file is modified.
        const _: &str = include_str!(#path_str);
    };

    Ok(output.into())
}