hyperlane-plugin-openapi 23.3.1

An OpenAPI 3.1.0 specification builder and zero-allocation interactive API docs plugin for the Hyperlane framework serving ETag-cached /openapi.json (with 304 support) and a self-contained zero-CDN /docs explorer.
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
use super::*;

/// Builders for [`OpenApiOperation`].
impl OpenApiOperation {
    /// Creates an [`OpenApiOperation`] with a summary line.
    ///
    /// # Arguments
    ///
    /// - `S` - Short summary string.
    ///
    /// # Returns
    ///
    /// - `Self` - New operation descriptor.
    pub fn new<S>(summary: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            summary: summary.into(),
            description: None,
            operation_id: None,
            tags: Vec::new(),
            parameters: Vec::new(),
            responses: BTreeMap::new(),
        }
    }

    /// Attaches a tag label to this operation.
    ///
    /// # Arguments
    ///
    /// - `S` - Tag name.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated operation.
    pub fn with_tag<S>(mut self, tag: S) -> Self
    where
        S: Into<String>,
    {
        self.get_mut_tags().push(tag.into());
        self
    }

    /// Adds a parameter descriptor to this operation.
    ///
    /// # Arguments
    ///
    /// - `N` - Parameter name.
    /// - `L` - Parameter location (`"path"`, `"query"`, `"header"`, `"cookie"`).
    /// - `bool` - Whether the parameter is required.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated operation.
    pub fn with_parameter<N, L>(mut self, name: N, location: L, required: bool) -> Self
    where
        N: Into<String>,
        L: Into<String>,
    {
        self.get_mut_parameters().push(OpenApiParameter {
            name: name.into(),
            location: location.into(),
            required,
            description: None,
        });
        self
    }

    /// Adds a status-code response description to this operation.
    ///
    /// # Arguments
    ///
    /// - `u16` - HTTP status code (for example `200`).
    /// - `D` - Response description text.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated operation.
    pub fn with_response<D>(mut self, status: u16, description: D) -> Self
    where
        D: Into<String>,
    {
        let _: Option<OpenApiResponse> = self.get_mut_responses().insert(
            status.to_string(),
            OpenApiResponse {
                description: description.into(),
                content: BTreeMap::new(),
            },
        );
        self
    }
}

/// Default construction for [`OpenApiSpec`].
impl Default for OpenApiSpec {
    /// Constructs a minimal OpenAPI 3.1.0 specification.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty OpenAPI 3.1.0 document.
    fn default() -> Self {
        Self::new(DEFAULT_API_TITLE, DEFAULT_API_VERSION)
    }
}

/// Fluent specification builder methods for [`OpenApiSpec`].
impl OpenApiSpec {
    /// Creates an OpenAPI 3.1.0 specification with `title` and `version`.
    ///
    /// # Arguments
    ///
    /// - `T` - API title.
    /// - `V` - API version.
    ///
    /// # Returns
    ///
    /// - `Self` - New OpenAPI 3.1.0 document.
    pub fn new<T, V>(title: T, version: V) -> Self
    where
        T: Into<String>,
        V: Into<String>,
    {
        Self {
            openapi: OPENAPI_VERSION.to_owned(),
            info: OpenApiInfo {
                title: title.into(),
                version: version.into(),
                description: None,
            },
            servers: Vec::new(),
            paths: BTreeMap::new(),
        }
    }

    /// Sets the API description text.
    ///
    /// # Arguments
    ///
    /// - `D` - Markdown description.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated specification.
    pub fn with_description<D>(mut self, description: D) -> Self
    where
        D: Into<String>,
    {
        self.get_mut_info()
            .set_description(Some(description.into()));
        self
    }

    /// Adds a server URL entry.
    ///
    /// # Arguments
    ///
    /// - `U` - Server base URL.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated specification.
    pub fn with_server<U>(mut self, url: U) -> Self
    where
        U: Into<String>,
    {
        self.get_mut_servers().push(OpenApiServer {
            url: url.into(),
            description: None,
        });
        self
    }

    /// Registers an HTTP operation under `(path, method)`.
    ///
    /// # Arguments
    ///
    /// - `P` - OpenAPI path template (for example `"/users/{id}"`).
    /// - `M` - HTTP method name (lowercased automatically).
    /// - `OpenApiOperation` - Operation metadata.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated specification.
    pub fn with_operation<P, M>(mut self, path: P, method: M, operation: OpenApiOperation) -> Self
    where
        P: Into<String>,
        M: AsRef<str>,
    {
        let entry: &mut BTreeMap<String, OpenApiOperation> =
            self.get_mut_paths().entry(path.into()).or_default();
        let _: Option<OpenApiOperation> =
            entry.insert(method.as_ref().trim().to_ascii_lowercase(), operation);
        self
    }
}

/// Default construction for [`OpenApiConfig`].
impl Default for OpenApiConfig {
    /// Builds a default [`OpenApiConfig`] serving `/openapi.json` and `/docs`.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            spec: OpenApiSpec::default(),
            spec_path: DEFAULT_SPEC_PATH.to_owned(),
            docs_path: Some(DEFAULT_DOCS_PATH.to_owned()),
            cache_control: DEFAULT_OPENAPI_CACHE_CONTROL.to_owned(),
        }
    }
}

/// Fluent builder helpers for [`OpenApiConfig`].
impl OpenApiConfig {
    /// Constructs an [`OpenApiConfig`] from an [`OpenApiSpec`].
    ///
    /// # Arguments
    ///
    /// - `OpenApiSpec` - Specification document.
    ///
    /// # Returns
    ///
    /// - `Self` - New configuration with default `/openapi.json` and `/docs` endpoints.
    pub fn from_spec(spec: OpenApiSpec) -> Self {
        Self {
            spec,
            ..Self::default()
        }
    }

    /// Sets the endpoint serving the JSON specification.
    ///
    /// # Arguments
    ///
    /// - `S` - Spec endpoint path.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_spec_path<S>(mut self, path: S) -> Self
    where
        S: Into<String>,
    {
        self.set_spec_path(path.into());
        self
    }

    /// Sets or disables the interactive HTML docs endpoint.
    ///
    /// # Arguments
    ///
    /// - `Option<String>` - Docs endpoint path, or `None` to disable HTML docs.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_docs_path(mut self, path: Option<String>) -> Self {
        self.set_docs_path(path);
        self
    }
}

/// Pre-serialized wire serving methods for [`OpenApiPlugin`].
impl OpenApiPlugin {
    /// Compiles `config`, pre-serializing JSON spec, ETag, `304`, and HTML docs wire responses once.
    ///
    /// # Arguments
    ///
    /// - `OpenApiConfig` - OpenAPI configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Compiled zero-allocation OpenAPI server.
    pub fn new(config: OpenApiConfig) -> Self {
        let spec_json: Vec<u8> = to_vec(config.get_spec()).unwrap_or_default();
        let spec_etag: String = compute_strong_etag(&spec_json);
        let mut spec_resp: Response = Response::default();
        spec_resp
            .set_status_code(HttpStatus::Ok.code())
            .set_header(CONTENT_TYPE, CONTENT_TYPE_JSON)
            .set_header(ETAG, spec_etag.clone())
            .set_header(CACHE_CONTROL, config.get_cache_control())
            .set_body(spec_json);
        let spec_wire: Vec<u8> = spec_resp.build();
        let mut not_mod_resp: Response = Response::default();
        not_mod_resp
            .set_status_code(HttpStatus::NotModified.code())
            .set_header(ETAG, spec_etag.clone())
            .set_header(CACHE_CONTROL, config.get_cache_control());
        let spec_not_modified_wire: Vec<u8> = not_mod_resp.build();
        let docs_html: String = render_docs_html(
            config.get_spec().get_info().get_title(),
            config.get_spec().get_info().get_version(),
            config.get_spec_path(),
        );
        let mut docs_resp: Response = Response::default();
        docs_resp
            .set_status_code(HttpStatus::Ok.code())
            .set_header(CONTENT_TYPE, CONTENT_TYPE_HTML)
            .set_header(CACHE_CONTROL, config.get_cache_control())
            .set_body(docs_html.into_bytes());
        let docs_wire: Vec<u8> = docs_resp.build();
        Self {
            config,
            spec_etag,
            spec_wire,
            spec_not_modified_wire,
            docs_wire,
        }
    }

    /// Initializes the global [`OpenApiPlugin`] singleton once.
    ///
    /// # Arguments
    ///
    /// - `OpenApiConfig` - OpenAPI configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init(config: OpenApiConfig) -> &'static Self {
        OPENAPI_PLUGIN.get_or_init(|| Self::new(config))
    }

    /// Returns the initialized global [`OpenApiPlugin`], if configured.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        OPENAPI_PLUGIN.get()
    }

    /// Returns the precomputed strong ETag for `/openapi.json`.
    ///
    /// # Returns
    ///
    /// - `&str` - Strong quoted ETag.
    #[inline(always)]
    pub fn get_spec_etag(&self) -> &str {
        let Self { spec_etag, .. } = self;
        spec_etag.as_str()
    }

    /// Returns the prebuilt wire bytes for `/openapi.json`.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Complete HTTP/1.1 wire bytes.
    #[inline(always)]
    pub fn get_spec_wire(&self) -> &[u8] {
        let Self { spec_wire, .. } = self;
        spec_wire
    }

    /// Returns the prebuilt wire bytes for `/docs`.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Complete HTTP/1.1 wire bytes.
    #[inline(always)]
    pub fn get_docs_wire(&self) -> &[u8] {
        let Self { docs_wire, .. } = self;
        docs_wire
    }
}

/// Implements [`ServerHook`] for [`OpenapiHook`].
impl ServerHook for OpenapiHook {
    /// Constructs a per-request [`OpenapiHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Serves pre-serialized `/openapi.json` (with `304` support) and `/docs` with zero allocations.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Continue` on other routes; `Status::Reject` after sending spec or docs.
    #[inline(always)]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = OpenApiPlugin::get() else {
            return Status::Continue;
        };
        let OpenApiPlugin {
            config,
            spec_etag,
            spec_wire,
            spec_not_modified_wire,
            docs_wire,
            ..
        } = plugin;
        let method: &Method = ctx.get_request().get_method();
        if !method.is_get() && !method.is_head() {
            return Status::Continue;
        }
        let path: &str = ctx.get_request().get_path();
        if path == config.get_spec_path().as_str() {
            let wire: &[u8] = if ctx.get_request().matches_if_none_match(spec_etag) {
                spec_not_modified_wire
            } else {
                spec_wire
            };
            let _: Result<(), ResponseError> = stream.try_send(wire).await;
            return Status::Reject;
        }
        if let Some(docs_path) = config.try_get_docs_path()
            && path == docs_path.as_str()
        {
            let _: Result<(), ResponseError> = stream.try_send(docs_wire).await;
            return Status::Reject;
        }
        Status::Continue
    }
}