arcly-http 0.3.0

Enterprise-grade NestJS-inspired web framework on axum: zero-lock DI, declarative controllers, multi-tenant data routing, transactional outbox, ABAC, and a self-documenting OpenAPI surface
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
//! OpenAPI 3.0 spec generation + a tiny Swagger UI page.
//!
//! Walks every [`RouteDescriptor`] collected via `inventory`, converts the
//! associated [`RouteSpec`](crate::core::engine::RouteSpec) into a `paths.<route>.<method>` entry, harvests
//! schemars `definitions` into `components.schemas`, and produces a spec
//! that's immediately browsable in Swagger UI.

use std::borrow::Cow;
use std::collections::BTreeMap;

use serde_json::{json, Map, Value};

use crate::core::engine::{HttpMethod, ParamLoc, RouteDescriptor};

const OPENAPI_VERSION: &str = "3.0.3";

/// HTTP authentication scheme exposed in `components.securitySchemes`.
///
/// Routes opt in to a scheme by name via `security("bearer")` on the route
/// macro. The exact spelling must match the key used in
/// [`OpenApiInfo::security_schemes`].
#[derive(Clone)]
pub enum SecurityScheme {
    /// `Authorization: Bearer <token>`. Optional `bearer_format` (e.g. "JWT").
    Bearer { bearer_format: Option<&'static str> },
    /// API key carried in a header, query, or cookie.
    ApiKey {
        location: ApiKeyIn,
        name: &'static str,
    },
    /// HTTP Basic auth.
    Basic,
}

#[derive(Clone, Copy)]
pub enum ApiKeyIn {
    Header,
    Query,
    Cookie,
}

impl SecurityScheme {
    fn to_value(&self) -> Value {
        match self {
            SecurityScheme::Bearer { bearer_format } => {
                let mut v = json!({ "type": "http", "scheme": "bearer" });
                if let Some(f) = bearer_format {
                    v.as_object_mut()
                        .unwrap()
                        .insert("bearerFormat".into(), Value::String((*f).into()));
                }
                v
            }
            SecurityScheme::ApiKey { location, name } => json!({
                "type": "apiKey",
                "in": match location { ApiKeyIn::Header => "header", ApiKeyIn::Query => "query", ApiKeyIn::Cookie => "cookie" },
                "name": *name,
            }),
            SecurityScheme::Basic => json!({ "type": "http", "scheme": "basic" }),
        }
    }
}

/// Top-level OpenAPI document configuration. Build at `main.rs` and pass to
/// [`crate::App::launch_with_info`].
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct OpenApiInfo {
    pub title: Cow<'static, str>,
    pub version: Cow<'static, str>,
    pub description: Option<Cow<'static, str>>,
    pub terms_of_service: Option<Cow<'static, str>>,
    pub contact_name: Option<Cow<'static, str>>,
    pub contact_url: Option<Cow<'static, str>>,
    pub contact_email: Option<Cow<'static, str>>,
    pub license_name: Option<Cow<'static, str>>,
    pub license_url: Option<Cow<'static, str>>,
    /// Each `(url, description)` pair becomes a server entry. The first is
    /// the default rendered by Swagger UI.
    pub servers: Vec<(Cow<'static, str>, Cow<'static, str>)>,
    /// Security schemes available to routes. Routes attach to a scheme by
    /// name via `security("name")` on the route macro.
    pub security_schemes: Vec<(Cow<'static, str>, SecurityScheme)>,
    /// Tag descriptions surfaced in the UI as section blurbs.
    pub tag_descriptions: Vec<(Cow<'static, str>, Cow<'static, str>)>,
}

impl OpenApiInfo {
    /// Start from a title + version; chain the optional fields. Values may
    /// be `&'static str` or runtime `String`s (config/env-driven services).
    /// (`OpenApiInfo` is `#[non_exhaustive]` — new spec fields can land
    /// without breaking downstream construction.)
    pub fn new(title: impl Into<Cow<'static, str>>, version: impl Into<Cow<'static, str>>) -> Self {
        Self {
            title: title.into(),
            version: version.into(),
            ..Default::default()
        }
    }
    pub fn description(mut self, v: impl Into<Cow<'static, str>>) -> Self {
        self.description = Some(v.into());
        self
    }
    pub fn terms_of_service(mut self, v: impl Into<Cow<'static, str>>) -> Self {
        self.terms_of_service = Some(v.into());
        self
    }
    pub fn contact_name(mut self, v: impl Into<Cow<'static, str>>) -> Self {
        self.contact_name = Some(v.into());
        self
    }
    pub fn contact_url(mut self, v: impl Into<Cow<'static, str>>) -> Self {
        self.contact_url = Some(v.into());
        self
    }
    pub fn contact_email(mut self, v: impl Into<Cow<'static, str>>) -> Self {
        self.contact_email = Some(v.into());
        self
    }
    pub fn license(
        mut self,
        name: impl Into<Cow<'static, str>>,
        url: impl Into<Cow<'static, str>>,
    ) -> Self {
        self.license_name = Some(name.into());
        self.license_url = Some(url.into());
        self
    }
    /// Add one server entry (`url`, human description — may be empty).
    pub fn server(
        mut self,
        url: impl Into<Cow<'static, str>>,
        description: impl Into<Cow<'static, str>>,
    ) -> Self {
        self.servers.push((url.into(), description.into()));
        self
    }
    /// Add one security scheme by name.
    pub fn security_scheme(
        mut self,
        name: impl Into<Cow<'static, str>>,
        scheme: SecurityScheme,
    ) -> Self {
        self.security_schemes.push((name.into(), scheme));
        self
    }
    /// Add one tag description.
    pub fn tag(
        mut self,
        name: impl Into<Cow<'static, str>>,
        description: impl Into<Cow<'static, str>>,
    ) -> Self {
        self.tag_descriptions
            .push((name.into(), description.into()));
        self
    }
}

/// Build a complete OpenAPI 3.0 document from all routes registered via
/// `inventory`.
pub fn build_spec(info: &OpenApiInfo) -> Value {
    build_spec_filtered(info, None)
}

/// `allowed_controllers = None` means "include every inventory-registered route"
/// (legacy / no module scoping). `Some(set)` filters to controllers reachable
/// from the root module's import DAG.
pub fn build_spec_filtered(
    info: &OpenApiInfo,
    allowed_controllers: Option<&std::collections::HashSet<&'static str>>,
) -> Value {
    let mut paths: Map<String, Value> = Map::new();
    let mut components: Map<String, Value> = Map::new();

    // Always emit ProblemDetails — it's the canonical 4xx/5xx body shape.
    components.insert("ProblemDetails".into(), problem_details_schema());

    for rt in inventory::iter::<&'static RouteDescriptor> {
        if let Some(allowed) = allowed_controllers {
            if !rt.controller.is_empty() && !allowed.contains(rt.controller) {
                continue;
            }
        }
        let oapi_path = axum_to_openapi_path(rt.path);
        let entry = paths
            .entry(oapi_path)
            .or_insert_with(|| Value::Object(Map::new()));

        // ── Parameters: path + header + flattened query DTO fields ──────
        let mut parameters: Vec<Value> = rt.spec.params.iter().map(|p| {
            json!({
                "name": p.name,
                "in": match p.loc { ParamLoc::Path => "path", ParamLoc::Query => "query", ParamLoc::Header => "header" },
                "required": p.required,
                "schema": (p.schema)(),
            })
        }).collect();

        if let Some(qfn) = rt.spec.query_schema {
            let mut schema = qfn();
            harvest_definitions(&mut schema, &mut components);
            rewrite_refs(&mut schema);
            if let Some(props) = schema.get("properties").and_then(Value::as_object) {
                let required: std::collections::HashSet<&str> = schema
                    .get("required")
                    .and_then(Value::as_array)
                    .map(|a| a.iter().filter_map(Value::as_str).collect())
                    .unwrap_or_default();
                for (name, prop_schema) in props {
                    parameters.push(json!({
                        "name": name,
                        "in": "query",
                        "required": required.contains(name.as_str()),
                        "schema": prop_schema,
                    }));
                }
            }
        }

        // ── Hardening attributes → first-class spec surface ─────────────
        if rt.spec.idempotent_ttl_secs > 0 {
            parameters.push(json!({
                "name": "Idempotency-Key",
                "in": "header",
                "required": false,
                "description": format!(
                    "Optional client-supplied key for safe retries. A repeat \
                     within {}s replays the stored response \
                     (`Idempotency-Replayed: true`); a concurrent duplicate \
                     gets 409.", rt.spec.idempotent_ttl_secs),
                "schema": { "type": "string", "maxLength": 255 },
            }));
        }

        // ── Default success status code (POST → 201, else 200) ──────────
        let status = rt
            .spec
            .status_code
            .unwrap_or_else(|| default_success(rt.method));
        let success_desc = if status == 204 {
            "No Content"
        } else {
            "Successful response"
        };
        let success = match (rt.spec.response_schema, status == 204) {
            (Some(f), false) => {
                let mut s = f();
                harvest_definitions(&mut s, &mut components);
                rewrite_refs(&mut s);
                json!({
                    "description": success_desc,
                    "content": { "application/json": { "schema": s } }
                })
            }
            _ => json!({ "description": success_desc }),
        };

        // Success-response headers contributed by the hardening attributes.
        let mut success = success;
        {
            let mut headers = Map::new();
            if rt.spec.idempotent_ttl_secs > 0 {
                headers.insert("Idempotency-Replayed".into(), json!({
                    "description": "Present (true) when this response was replayed from the idempotency store.",
                    "schema": { "type": "string", "enum": ["true"] },
                }));
            }
            if !rt.spec.sunset.is_empty() {
                headers.insert(
                    "Deprecation".into(),
                    json!({
                        "description": "RFC 8594 — this endpoint is deprecated.",
                        "schema": { "type": "string", "enum": ["true"] },
                    }),
                );
                headers.insert(
                    "Sunset".into(),
                    json!({
                        "description": "RFC 8594 — date after which this endpoint may be removed.",
                        "schema": { "type": "string" },
                    }),
                );
            }
            if !headers.is_empty() {
                success["headers"] = Value::Object(headers);
            }
        }

        // ── Default error responses all point at ProblemDetails ─────────
        let problem_ref = json!({
            "description": "",
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProblemDetails" } } }
        });
        let mut responses = Map::new();
        responses.insert(status.to_string(), success);
        let forbidden_desc = if rt.spec.policies.is_empty() {
            "Forbidden".to_string()
        } else {
            format!(
                "Forbidden — requires ABAC policies: {} (default-deny; rules hot-reload at runtime)",
                rt.spec.policies.join(", "),
            )
        };
        let mut error_codes: Vec<(String, String)> = vec![
            ("400".into(), "Bad request".into()),
            ("401".into(), "Unauthorized".into()),
            ("403".into(), forbidden_desc),
            ("404".into(), "Not found".into()),
            ("422".into(), "Validation failed".into()),
            ("500".into(), "Internal error".into()),
        ];
        if rt.spec.idempotent_ttl_secs > 0 {
            error_codes.push((
                "409".into(),
                "Conflict — a request with this Idempotency-Key is already in flight".into(),
            ));
        }
        if rt.spec.timeout_ms > 0 {
            error_codes.push((
                "504".into(),
                format!(
                    "Gateway Timeout — handler exceeded its {}ms deadline (work cancelled{})",
                    rt.spec.timeout_ms,
                    if rt.spec.transactional {
                        "; transaction rolled back"
                    } else {
                        ""
                    },
                ),
            ));
        }
        for (code, desc) in error_codes {
            let mut entry = problem_ref.clone();
            entry["description"] = Value::String(desc);
            responses.insert(code, entry);
        }

        let tags: Vec<&'static str> = if rt.spec.tags.is_empty() {
            default_tags_from_path(rt.path)
        } else {
            rt.spec.tags.to_vec()
        };

        let security: Vec<Value> = rt
            .spec
            .security
            .iter()
            .map(|s| {
                // {"<scheme>": []}  — empty scope list, OK for non-OAuth.
                let mut m = Map::new();
                m.insert((*s).into(), Value::Array(vec![]));
                Value::Object(m)
            })
            .collect();

        let mut op = json!({
            "summary": rt.spec.summary,
            "operationId": rt.spec.operation_id,
            "tags": tags,
            "parameters": parameters,
            "responses": responses,
            // A sunset date implies deprecation even without the route flag.
            "deprecated": rt.spec.deprecated || !rt.spec.sunset.is_empty(),
        });

        // Vendor extensions: machine-readable mirror of the hardening stack,
        // so gateways/linters/SDK generators can reason about behaviour.
        if !rt.spec.api_version.is_empty() {
            op["x-api-version"] = Value::String(rt.spec.api_version.into());
        }
        if !rt.spec.sunset.is_empty() {
            op["x-sunset"] = Value::String(rt.spec.sunset.into());
        }
        if rt.spec.idempotent_ttl_secs > 0 {
            op["x-arcly-idempotent-ttl-secs"] = json!(rt.spec.idempotent_ttl_secs);
        }
        if !rt.spec.policies.is_empty() {
            op["x-arcly-policies"] = json!(rt.spec.policies);
        }
        if !rt.spec.audit_action.is_empty() {
            op["x-arcly-audit"] = json!({
                "action": rt.spec.audit_action,
                "resource": rt.spec.audit_resource,
            });
        }
        if rt.spec.timeout_ms > 0 {
            op["x-arcly-timeout-ms"] = json!(rt.spec.timeout_ms);
        }
        if rt.spec.transactional {
            op["x-arcly-transactional"] = Value::Bool(true);
        }
        if !rt.spec.mask_fields.is_empty() {
            op["x-arcly-masked-fields"] = json!(rt.spec.mask_fields);
        }
        if !rt.spec.description.is_empty() {
            op["description"] = Value::String(rt.spec.description.to_string());
        }
        if !security.is_empty() {
            op["security"] = Value::Array(security);
        }

        if rt.spec.has_body {
            let schema_val = match rt.spec.body_schema {
                Some(f) => {
                    let mut s = f();
                    harvest_definitions(&mut s, &mut components);
                    rewrite_refs(&mut s);
                    s
                }
                None => json!({ "type": "object" }),
            };
            op.as_object_mut().unwrap().insert(
                "requestBody".into(),
                json!({
                    "required": true,
                    "content": { "application/json": { "schema": schema_val } }
                }),
            );
        }

        let method_key = method_str(rt.method);
        entry.as_object_mut().unwrap().insert(method_key.into(), op);
    }

    // ── /info block ──
    let mut info_obj = Map::new();
    info_obj.insert(
        "title".into(),
        Value::String(info.title.clone().into_owned()),
    );
    info_obj.insert(
        "version".into(),
        Value::String(info.version.clone().into_owned()),
    );
    if let Some(d) = &info.description {
        info_obj.insert("description".into(), Value::String(d.clone().into_owned()));
    }
    if let Some(t) = &info.terms_of_service {
        info_obj.insert(
            "termsOfService".into(),
            Value::String(t.clone().into_owned()),
        );
    }
    let mut contact = Map::new();
    if let Some(n) = &info.contact_name {
        contact.insert("name".into(), Value::String(n.clone().into_owned()));
    }
    if let Some(u) = &info.contact_url {
        contact.insert("url".into(), Value::String(u.clone().into_owned()));
    }
    if let Some(e) = &info.contact_email {
        contact.insert("email".into(), Value::String(e.clone().into_owned()));
    }
    if !contact.is_empty() {
        info_obj.insert("contact".into(), Value::Object(contact));
    }
    let mut license = Map::new();
    if let Some(n) = &info.license_name {
        license.insert("name".into(), Value::String(n.clone().into_owned()));
    }
    if let Some(u) = &info.license_url {
        license.insert("url".into(), Value::String(u.clone().into_owned()));
    }
    if !license.is_empty() {
        info_obj.insert("license".into(), Value::Object(license));
    }

    let servers: Vec<Value> = info
        .servers
        .iter()
        .map(|(url, desc)| {
            let mut m = Map::new();
            m.insert("url".into(), Value::String(url.clone().into_owned()));
            if !desc.is_empty() {
                m.insert(
                    "description".into(),
                    Value::String(desc.clone().into_owned()),
                );
            }
            Value::Object(m)
        })
        .collect();

    let tags_section: Vec<Value> = info
        .tag_descriptions
        .iter()
        .map(|(name, desc)| json!({ "name": name.as_ref(), "description": desc.as_ref() }))
        .collect();

    let mut components_obj = Map::new();
    components_obj.insert("schemas".into(), Value::Object(components));
    if !info.security_schemes.is_empty() {
        let mut schemes: BTreeMap<String, Value> = BTreeMap::new();
        for (name, sch) in &info.security_schemes {
            schemes.insert(name.clone().into_owned(), sch.to_value());
        }
        components_obj.insert(
            "securitySchemes".into(),
            Value::Object(schemes.into_iter().collect()),
        );
    }

    let mut doc = Map::new();
    doc.insert("openapi".into(), Value::String(OPENAPI_VERSION.into()));
    doc.insert("info".into(), Value::Object(info_obj));
    if !servers.is_empty() {
        doc.insert("servers".into(), Value::Array(servers));
    }
    if !tags_section.is_empty() {
        doc.insert("tags".into(), Value::Array(tags_section));
    }
    doc.insert("paths".into(), Value::Object(paths));
    doc.insert("components".into(), Value::Object(components_obj));
    Value::Object(doc)
}

fn problem_details_schema() -> Value {
    json!({
        "type": "object",
        "description": "RFC 7807 ProblemDetails",
        "required": ["type", "title", "status", "detail"],
        "properties": {
            "type":   { "type": "string" },
            "title":  { "type": "string" },
            "status": { "type": "integer", "minimum": 100, "maximum": 599 },
            "detail": { "type": "string" },
            "errors": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["field", "code", "message"],
                    "properties": {
                        "field":   { "type": "string" },
                        "code":    { "type": "string" },
                        "message": { "type": "string" }
                    }
                }
            }
        }
    })
}

fn default_success(m: HttpMethod) -> u16 {
    match m {
        HttpMethod::POST => 201,
        HttpMethod::DELETE => 204,
        _ => 200,
    }
}

fn default_tags_from_path(p: &'static str) -> Vec<&'static str> {
    // Route paths submitted via inventory are always 'static literals from the
    // macro — so slicing them produces a valid 'static subslice.
    let seg = p.trim_start_matches('/').split('/').next().unwrap_or("");
    if seg.is_empty() || seg.starts_with(':') {
        Vec::new()
    } else {
        vec![seg]
    }
}

/// Move every entry from a schemars `definitions` map into the supplied
/// `components/schemas` registry, then strip it from the input schema.
fn harvest_definitions(schema: &mut Value, components: &mut Map<String, Value>) {
    let Value::Object(map) = schema else { return };
    if let Some(Value::Object(defs)) = map.remove("definitions") {
        for (k, mut v) in defs {
            rewrite_refs(&mut v);
            components.entry(k).or_insert(v);
        }
    }
}

/// Rewrite every `$ref: "#/definitions/X"` to `"#/components/schemas/X"`.
fn rewrite_refs(v: &mut Value) {
    match v {
        Value::Object(map) => {
            if let Some(Value::String(s)) = map.get_mut("$ref") {
                if let Some(name) = s.strip_prefix("#/definitions/") {
                    *s = format!("#/components/schemas/{name}");
                }
            }
            for (_, child) in map.iter_mut() {
                rewrite_refs(child);
            }
        }
        Value::Array(arr) => {
            for child in arr {
                rewrite_refs(child);
            }
        }
        _ => {}
    }
}

#[inline]
fn method_str(m: HttpMethod) -> &'static str {
    match m {
        HttpMethod::GET => "get",
        HttpMethod::POST => "post",
        HttpMethod::PUT => "put",
        HttpMethod::DELETE => "delete",
        HttpMethod::PATCH => "patch",
    }
}

fn axum_to_openapi_path(p: &str) -> String {
    // Canonical form: no trailing slash. The router serves both
    // `/products` and `/products/`, but generated clients should call the
    // bare form — advertising only `/products/` made SDKs needlessly
    // slash-sensitive.
    let p = if p.len() > 1 {
        p.trim_end_matches('/')
    } else {
        p
    };
    let mut out = String::with_capacity(p.len() + 4);
    let mut chars = p.chars().peekable();
    while let Some(c) = chars.next() {
        if c == ':' {
            out.push('{');
            while let Some(&n) = chars.peek() {
                if n == '/' {
                    break;
                }
                out.push(n);
                chars.next();
            }
            out.push('}');
        } else {
            out.push(c);
        }
    }
    out
}

/// Minimal Swagger UI page (CDN-hosted assets). No build step, no extra crate.
pub const SWAGGER_UI_HTML: &str = r##"<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>arcly-http — API docs</title>
  <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css">
</head>
<body>
  <div id="swagger-ui"></div>
  <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
  <script>
    window.onload = () => {
      window.ui = SwaggerUIBundle({
        url: '/openapi.json',
        dom_id: '#swagger-ui',
        deepLinking: true,
        persistAuthorization: true,
        layout: 'BaseLayout',
      });
    };
  </script>
</body>
</html>
"##;

#[cfg(test)]
mod path_tests {
    use super::axum_to_openapi_path;

    #[test]
    fn spec_paths_are_canonical() {
        assert_eq!(axum_to_openapi_path("/products/"), "/products");
        assert_eq!(axum_to_openapi_path("/products"), "/products");
        assert_eq!(axum_to_openapi_path("/users/:id"), "/users/{id}");
        assert_eq!(axum_to_openapi_path("/"), "/");
    }
}