hyperlane_plugin_openapi/impl.rs
1use super::*;
2
3/// Builders for [`OpenApiOperation`].
4impl OpenApiOperation {
5 /// Creates an [`OpenApiOperation`] with a summary line.
6 ///
7 /// # Arguments
8 ///
9 /// - `S` - Short summary string.
10 ///
11 /// # Returns
12 ///
13 /// - `Self` - New operation descriptor.
14 pub fn new<S>(summary: S) -> Self
15 where
16 S: Into<String>,
17 {
18 Self {
19 summary: summary.into(),
20 description: None,
21 operation_id: None,
22 tags: Vec::new(),
23 parameters: Vec::new(),
24 responses: BTreeMap::new(),
25 }
26 }
27
28 /// Attaches a tag label to this operation.
29 ///
30 /// # Arguments
31 ///
32 /// - `S` - Tag name.
33 ///
34 /// # Returns
35 ///
36 /// - `Self` - Updated operation.
37 pub fn with_tag<S>(mut self, tag: S) -> Self
38 where
39 S: Into<String>,
40 {
41 self.get_mut_tags().push(tag.into());
42 self
43 }
44
45 /// Adds a parameter descriptor to this operation.
46 ///
47 /// # Arguments
48 ///
49 /// - `N` - Parameter name.
50 /// - `L` - Parameter location (`"path"`, `"query"`, `"header"`, `"cookie"`).
51 /// - `bool` - Whether the parameter is required.
52 ///
53 /// # Returns
54 ///
55 /// - `Self` - Updated operation.
56 pub fn with_parameter<N, L>(mut self, name: N, location: L, required: bool) -> Self
57 where
58 N: Into<String>,
59 L: Into<String>,
60 {
61 self.get_mut_parameters().push(OpenApiParameter {
62 name: name.into(),
63 location: location.into(),
64 required,
65 description: None,
66 });
67 self
68 }
69
70 /// Adds a status-code response description to this operation.
71 ///
72 /// # Arguments
73 ///
74 /// - `u16` - HTTP status code (for example `200`).
75 /// - `D` - Response description text.
76 ///
77 /// # Returns
78 ///
79 /// - `Self` - Updated operation.
80 pub fn with_response<D>(mut self, status: u16, description: D) -> Self
81 where
82 D: Into<String>,
83 {
84 let _: Option<OpenApiResponse> = self.get_mut_responses().insert(
85 status.to_string(),
86 OpenApiResponse {
87 description: description.into(),
88 content: BTreeMap::new(),
89 },
90 );
91 self
92 }
93}
94
95/// Default construction for [`OpenApiSpec`].
96impl Default for OpenApiSpec {
97 /// Constructs a minimal OpenAPI 3.1.0 specification.
98 ///
99 /// # Returns
100 ///
101 /// - `Self` - Empty OpenAPI 3.1.0 document.
102 fn default() -> Self {
103 Self::new(DEFAULT_API_TITLE, DEFAULT_API_VERSION)
104 }
105}
106
107/// Fluent specification builder methods for [`OpenApiSpec`].
108impl OpenApiSpec {
109 /// Creates an OpenAPI 3.1.0 specification with `title` and `version`.
110 ///
111 /// # Arguments
112 ///
113 /// - `T` - API title.
114 /// - `V` - API version.
115 ///
116 /// # Returns
117 ///
118 /// - `Self` - New OpenAPI 3.1.0 document.
119 pub fn new<T, V>(title: T, version: V) -> Self
120 where
121 T: Into<String>,
122 V: Into<String>,
123 {
124 Self {
125 openapi: OPENAPI_VERSION.to_owned(),
126 info: OpenApiInfo {
127 title: title.into(),
128 version: version.into(),
129 description: None,
130 },
131 servers: Vec::new(),
132 paths: BTreeMap::new(),
133 }
134 }
135
136 /// Sets the API description text.
137 ///
138 /// # Arguments
139 ///
140 /// - `D` - Markdown description.
141 ///
142 /// # Returns
143 ///
144 /// - `Self` - Updated specification.
145 pub fn with_description<D>(mut self, description: D) -> Self
146 where
147 D: Into<String>,
148 {
149 self.get_mut_info()
150 .set_description(Some(description.into()));
151 self
152 }
153
154 /// Adds a server URL entry.
155 ///
156 /// # Arguments
157 ///
158 /// - `U` - Server base URL.
159 ///
160 /// # Returns
161 ///
162 /// - `Self` - Updated specification.
163 pub fn with_server<U>(mut self, url: U) -> Self
164 where
165 U: Into<String>,
166 {
167 self.get_mut_servers().push(OpenApiServer {
168 url: url.into(),
169 description: None,
170 });
171 self
172 }
173
174 /// Registers an HTTP operation under `(path, method)`.
175 ///
176 /// # Arguments
177 ///
178 /// - `P` - OpenAPI path template (for example `"/users/{id}"`).
179 /// - `M` - HTTP method name (lowercased automatically).
180 /// - `OpenApiOperation` - Operation metadata.
181 ///
182 /// # Returns
183 ///
184 /// - `Self` - Updated specification.
185 pub fn with_operation<P, M>(mut self, path: P, method: M, operation: OpenApiOperation) -> Self
186 where
187 P: Into<String>,
188 M: AsRef<str>,
189 {
190 let entry: &mut BTreeMap<String, OpenApiOperation> =
191 self.get_mut_paths().entry(path.into()).or_default();
192 let _: Option<OpenApiOperation> =
193 entry.insert(method.as_ref().trim().to_ascii_lowercase(), operation);
194 self
195 }
196}
197
198/// Default construction for [`OpenApiConfig`].
199impl Default for OpenApiConfig {
200 /// Builds a default [`OpenApiConfig`] serving `/openapi.json` and `/docs`.
201 ///
202 /// # Returns
203 ///
204 /// - `Self` - Default configuration.
205 fn default() -> Self {
206 Self {
207 spec: OpenApiSpec::default(),
208 spec_path: DEFAULT_SPEC_PATH.to_owned(),
209 docs_path: Some(DEFAULT_DOCS_PATH.to_owned()),
210 cache_control: DEFAULT_OPENAPI_CACHE_CONTROL.to_owned(),
211 }
212 }
213}
214
215/// Fluent builder helpers for [`OpenApiConfig`].
216impl OpenApiConfig {
217 /// Constructs an [`OpenApiConfig`] from an [`OpenApiSpec`].
218 ///
219 /// # Arguments
220 ///
221 /// - `OpenApiSpec` - Specification document.
222 ///
223 /// # Returns
224 ///
225 /// - `Self` - New configuration with default `/openapi.json` and `/docs` endpoints.
226 pub fn from_spec(spec: OpenApiSpec) -> Self {
227 Self {
228 spec,
229 ..Self::default()
230 }
231 }
232
233 /// Sets the endpoint serving the JSON specification.
234 ///
235 /// # Arguments
236 ///
237 /// - `S` - Spec endpoint path.
238 ///
239 /// # Returns
240 ///
241 /// - `Self` - Updated configuration.
242 pub fn with_spec_path<S>(mut self, path: S) -> Self
243 where
244 S: Into<String>,
245 {
246 self.set_spec_path(path.into());
247 self
248 }
249
250 /// Sets or disables the interactive HTML docs endpoint.
251 ///
252 /// # Arguments
253 ///
254 /// - `Option<String>` - Docs endpoint path, or `None` to disable HTML docs.
255 ///
256 /// # Returns
257 ///
258 /// - `Self` - Updated configuration.
259 pub fn with_docs_path(mut self, path: Option<String>) -> Self {
260 self.set_docs_path(path);
261 self
262 }
263}
264
265/// Pre-serialized wire serving methods for [`OpenApiPlugin`].
266impl OpenApiPlugin {
267 /// Compiles `config`, pre-serializing JSON spec, ETag, `304`, and HTML docs wire responses once.
268 ///
269 /// # Arguments
270 ///
271 /// - `OpenApiConfig` - OpenAPI configuration.
272 ///
273 /// # Returns
274 ///
275 /// - `Self` - Compiled zero-allocation OpenAPI server.
276 pub fn new(config: OpenApiConfig) -> Self {
277 let spec_json: Vec<u8> = to_vec(config.get_spec()).unwrap_or_default();
278 let spec_etag: String = compute_strong_etag(&spec_json);
279 let mut spec_resp: Response = Response::default();
280 spec_resp
281 .set_status_code(HttpStatus::Ok.code())
282 .set_header(CONTENT_TYPE, CONTENT_TYPE_JSON)
283 .set_header(ETAG, spec_etag.clone())
284 .set_header(CACHE_CONTROL, config.get_cache_control())
285 .set_body(spec_json);
286 let spec_wire: Vec<u8> = spec_resp.build();
287 let mut not_mod_resp: Response = Response::default();
288 not_mod_resp
289 .set_status_code(HttpStatus::NotModified.code())
290 .set_header(ETAG, spec_etag.clone())
291 .set_header(CACHE_CONTROL, config.get_cache_control());
292 let spec_not_modified_wire: Vec<u8> = not_mod_resp.build();
293 let docs_html: String = render_docs_html(
294 config.get_spec().get_info().get_title(),
295 config.get_spec().get_info().get_version(),
296 config.get_spec_path(),
297 );
298 let mut docs_resp: Response = Response::default();
299 docs_resp
300 .set_status_code(HttpStatus::Ok.code())
301 .set_header(CONTENT_TYPE, CONTENT_TYPE_HTML)
302 .set_header(CACHE_CONTROL, config.get_cache_control())
303 .set_body(docs_html.into_bytes());
304 let docs_wire: Vec<u8> = docs_resp.build();
305 Self {
306 config,
307 spec_etag,
308 spec_wire,
309 spec_not_modified_wire,
310 docs_wire,
311 }
312 }
313
314 /// Initializes the global [`OpenApiPlugin`] singleton once.
315 ///
316 /// # Arguments
317 ///
318 /// - `OpenApiConfig` - OpenAPI configuration.
319 ///
320 /// # Returns
321 ///
322 /// - `&'static Self` - Reference to the global plugin.
323 pub fn init(config: OpenApiConfig) -> &'static Self {
324 OPENAPI_PLUGIN.get_or_init(|| Self::new(config))
325 }
326
327 /// Returns the initialized global [`OpenApiPlugin`], if configured.
328 ///
329 /// # Returns
330 ///
331 /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
332 #[inline(always)]
333 pub fn get() -> Option<&'static Self> {
334 OPENAPI_PLUGIN.get()
335 }
336
337 /// Returns the precomputed strong ETag for `/openapi.json`.
338 ///
339 /// # Returns
340 ///
341 /// - `&str` - Strong quoted ETag.
342 #[inline(always)]
343 pub fn get_spec_etag(&self) -> &str {
344 let Self { spec_etag, .. } = self;
345 spec_etag.as_str()
346 }
347
348 /// Returns the prebuilt wire bytes for `/openapi.json`.
349 ///
350 /// # Returns
351 ///
352 /// - `&[u8]` - Complete HTTP/1.1 wire bytes.
353 #[inline(always)]
354 pub fn get_spec_wire(&self) -> &[u8] {
355 let Self { spec_wire, .. } = self;
356 spec_wire
357 }
358
359 /// Returns the prebuilt wire bytes for `/docs`.
360 ///
361 /// # Returns
362 ///
363 /// - `&[u8]` - Complete HTTP/1.1 wire bytes.
364 #[inline(always)]
365 pub fn get_docs_wire(&self) -> &[u8] {
366 let Self { docs_wire, .. } = self;
367 docs_wire
368 }
369}
370
371/// Implements [`ServerHook`] for [`OpenapiHook`].
372impl ServerHook for OpenapiHook {
373 /// Constructs a per-request [`OpenapiHook`].
374 ///
375 /// # Arguments
376 ///
377 /// - `&mut Stream` - Connection stream.
378 /// - `&mut Context` - Request context.
379 ///
380 /// # Returns
381 ///
382 /// - `Self` - Hook instance.
383 #[inline(always)]
384 async fn new(_: &mut Stream, _: &mut Context) -> Self {
385 Self
386 }
387
388 /// Serves pre-serialized `/openapi.json` (with `304` support) and `/docs` with zero allocations.
389 ///
390 /// # Arguments
391 ///
392 /// - `Self` - Hook instance.
393 /// - `&mut Stream` - Connection stream.
394 /// - `&mut Context` - Request context.
395 ///
396 /// # Returns
397 ///
398 /// - `Status` - `Status::Continue` on other routes; `Status::Reject` after sending spec or docs.
399 #[inline(always)]
400 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
401 let Some(plugin) = OpenApiPlugin::get() else {
402 return Status::Continue;
403 };
404 let OpenApiPlugin {
405 config,
406 spec_etag,
407 spec_wire,
408 spec_not_modified_wire,
409 docs_wire,
410 ..
411 } = plugin;
412 let method: &Method = ctx.get_request().get_method();
413 if !method.is_get() && !method.is_head() {
414 return Status::Continue;
415 }
416 let path: &str = ctx.get_request().get_path();
417 if path == config.get_spec_path().as_str() {
418 let wire: &[u8] = if ctx.get_request().matches_if_none_match(spec_etag) {
419 spec_not_modified_wire
420 } else {
421 spec_wire
422 };
423 let _: Result<(), ResponseError> = stream.try_send(wire).await;
424 return Status::Reject;
425 }
426 if let Some(docs_path) = config.try_get_docs_path()
427 && path == docs_path.as_str()
428 {
429 let _: Result<(), ResponseError> = stream.try_send(docs_wire).await;
430 return Status::Reject;
431 }
432 Status::Continue
433 }
434}