doxa-docs 0.1.2

Ergonomic OpenAPI documentation and Scalar UI hosting for axum. Built on utoipa + utoipa-axum with minimal handler attributes and in-memory spec serving.
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
//! Autoref-specialized dispatch used by the method macro to
//! unconditionally emit a parameter-contribution entry for every
//! handler argument. Types that do not implement the relevant role
//! trait silently no-op; types that do delegate to the trait impl.
//!
//! Not part of the public API — the paths inside this module may
//! change between minor versions. The method macro references items
//! here behind the crate's `__private` re-export.
//!
//! ## How the dispatch works
//!
//! We rely on Rust's method resolution rules: when a call like
//! `x.__collect()` has candidate methods at multiple autoref /
//! autoderef depths, the compiler picks the one requiring the fewest
//! adjustments to the receiver.
//!
//! For each role we define two traits with the same method name:
//! - A "implemented" trait whose impl requires `T: DocX` and targets receiver
//!   `Contribution<T>` directly (depth 0).
//! - A "missing" trait whose impl is unbounded and targets receiver
//!   `&Contribution<T>` (depth 1 via autoref).
//!
//! The call site constructs `Contribution::<T>::new()` and invokes
//! `__collect()`. If `T: DocX` holds, the depth-0 candidate wins;
//! otherwise the depth-1 fallback is chosen. In either case the
//! source text is identical, so the macro can emit the same call for
//! every argument and let the compiler route it.
//!
//! This is the same pattern used by `anyhow` to dispatch between
//! `std::error::Error` and bare `Display + Debug` inputs to `anyhow!`.

use std::marker::PhantomData;

use utoipa::openapi::path::{OperationBuilder, Parameter};
use utoipa::openapi::schema::Schema;
use utoipa::openapi::RefOr;

use crate::doc_responses::DocResponseBody;
use crate::doc_traits::{
    DocHeaderParams, DocOperationSecurity, DocPathParams, DocPathScalar, DocQueryParams,
};
use crate::inner_schema::InnerToSchema;

// ---------------------------------------------------------------------------
// Query parameter contribution
// ---------------------------------------------------------------------------

/// Zero-sized probe referenced from a per-handler
/// [`utoipa::IntoParams`] impl emitted by the method macro. The probe
/// contributes parameters only when `T: DocQueryParams`.
pub struct QueryParamContribution<T: ?Sized>(PhantomData<T>);

impl<T: ?Sized> QueryParamContribution<T> {
    /// Construct a zero-sized probe for `T`.
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: ?Sized> Default for QueryParamContribution<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Autoref-specialization: depth-0 candidate when `T: DocQueryParams`.
pub trait QueryParamsImplementedAdhoc: Sized {
    /// Collect query parameters via the specialized impl.
    fn __collect(self) -> Vec<Parameter>;
}

impl<T: DocQueryParams + ?Sized> QueryParamsImplementedAdhoc for QueryParamContribution<T> {
    fn __collect(self) -> Vec<Parameter> {
        let mut op = OperationBuilder::new().build();
        T::describe(&mut op);
        op.parameters.unwrap_or_default()
    }
}

/// Autoref-specialization: depth-1 fallback that applies to every
/// `T`. Chosen only when the depth-0 impl above is unavailable.
pub trait QueryParamsMissingAdhoc: Sized {
    /// No-op fallback — returns an empty parameter list.
    fn __collect(self) -> Vec<Parameter>;
}

impl<T: ?Sized> QueryParamsMissingAdhoc for &QueryParamContribution<T> {
    fn __collect(self) -> Vec<Parameter> {
        Vec::new()
    }
}

// ---------------------------------------------------------------------------
// Path parameter contribution (struct form only — scalar/tuple Path
// stays in the method macro's syntactic emission)
// ---------------------------------------------------------------------------

/// Path-parameter counterpart to [`QueryParamContribution`]. Used for
/// struct-form `Path<T>` only — scalar/tuple path extractors are
/// handled via the method macro's syntactic emission so their
/// URL-template parameter names are preserved.
pub struct PathParamContribution<T: ?Sized>(PhantomData<T>);

impl<T: ?Sized> PathParamContribution<T> {
    /// Construct a zero-sized probe for `T`.
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: ?Sized> Default for PathParamContribution<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Depth-0 specialization.
pub trait PathParamsImplementedAdhoc: Sized {
    /// Collect path parameters via the specialized impl.
    fn __collect(self, path_param_names: &[&'static str]) -> Vec<Parameter>;
}

impl<T: DocPathParams + ?Sized> PathParamsImplementedAdhoc for PathParamContribution<T> {
    fn __collect(self, path_param_names: &[&'static str]) -> Vec<Parameter> {
        let mut op = OperationBuilder::new().build();
        T::describe(&mut op, path_param_names);
        op.parameters.unwrap_or_default()
    }
}

/// Depth-1 fallback.
pub trait PathParamsMissingAdhoc: Sized {
    /// No-op fallback — returns an empty parameter list.
    fn __collect(self, path_param_names: &[&'static str]) -> Vec<Parameter>;
}

impl<T: ?Sized> PathParamsMissingAdhoc for &PathParamContribution<T> {
    fn __collect(self, _path_param_names: &[&'static str]) -> Vec<Parameter> {
        Vec::new()
    }
}

// ---------------------------------------------------------------------------
// Scalar / tuple path parameter contribution (parallel probe to the
// struct-form one above, routed through [`DocPathScalar`])
// ---------------------------------------------------------------------------

/// Scalar/tuple counterpart to [`PathParamContribution`]. The method
/// macro invokes both probes for every handler argument; at most one
/// impl applies for any given `T`.
pub struct PathScalarContribution<T: ?Sized>(PhantomData<T>);

impl<T: ?Sized> PathScalarContribution<T> {
    /// Construct a zero-sized probe for `T`.
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: ?Sized> Default for PathScalarContribution<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Depth-0 specialization.
pub trait PathScalarImplementedAdhoc: Sized {
    /// Collect scalar / tuple path parameters via the specialized impl.
    fn __collect(self, path_param_names: &[&'static str]) -> Vec<Parameter>;
}

impl<T: DocPathScalar + ?Sized> PathScalarImplementedAdhoc for PathScalarContribution<T> {
    fn __collect(self, path_param_names: &[&'static str]) -> Vec<Parameter> {
        let mut op = OperationBuilder::new().build();
        T::describe_scalar(&mut op, path_param_names);
        op.parameters.unwrap_or_default()
    }
}

/// Depth-1 fallback.
pub trait PathScalarMissingAdhoc: Sized {
    /// No-op fallback — returns an empty parameter list.
    fn __collect(self, path_param_names: &[&'static str]) -> Vec<Parameter>;
}

impl<T: ?Sized> PathScalarMissingAdhoc for &PathScalarContribution<T> {
    fn __collect(self, _path_param_names: &[&'static str]) -> Vec<Parameter> {
        Vec::new()
    }
}

// ---------------------------------------------------------------------------
// Header parameter contribution
// ---------------------------------------------------------------------------

/// Header-parameter counterpart to [`QueryParamContribution`].
pub struct HeaderParamContribution<T: ?Sized>(PhantomData<T>);

impl<T: ?Sized> HeaderParamContribution<T> {
    /// Construct a zero-sized probe for `T`.
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: ?Sized> Default for HeaderParamContribution<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Depth-0 specialization.
pub trait HeaderParamsImplementedAdhoc: Sized {
    /// Collect header parameters via the specialized impl.
    fn __collect(self) -> Vec<Parameter>;
}

impl<T: DocHeaderParams + ?Sized> HeaderParamsImplementedAdhoc for HeaderParamContribution<T> {
    fn __collect(self) -> Vec<Parameter> {
        let mut op = OperationBuilder::new().build();
        T::describe(&mut op);
        op.parameters.unwrap_or_default()
    }
}

/// Depth-1 fallback.
pub trait HeaderParamsMissingAdhoc: Sized {
    /// No-op fallback — returns an empty parameter list.
    fn __collect(self) -> Vec<Parameter>;
}

impl<T: ?Sized> HeaderParamsMissingAdhoc for &HeaderParamContribution<T> {
    fn __collect(self) -> Vec<Parameter> {
        Vec::new()
    }
}

// ---------------------------------------------------------------------------
// Schema registration probe
// ---------------------------------------------------------------------------

/// Zero-sized probe referenced from a per-handler
/// [`crate::ApidocHandlerSchemas`] impl emitted by the method macro.
/// Registers schemas for the arg's inner payload only when the type
/// implements [`InnerToSchema`]; silently no-ops otherwise.
///
/// Used for **extractor-wrapped** payloads (`Query<T>`, `Path<T>`,
/// `Json<T>`, and transparent wrappers thereof). For bare
/// `ToSchema` types (handler error types, success body types etc.),
/// use [`BareSchemaContribution`] instead — the two probes target
/// different trait receivers and together cover both shapes without
/// coherence conflicts.
pub struct InnerSchemaContribution<T: ?Sized>(PhantomData<T>);

impl<T: ?Sized> InnerSchemaContribution<T> {
    /// Construct a zero-sized probe for `T`.
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: ?Sized> Default for InnerSchemaContribution<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Depth-0 specialization.
pub trait InnerSchemaImplementedAdhoc: Sized {
    /// Append referenced schemas to `out` via the specialized impl.
    fn __collect(self, out: &mut Vec<(String, RefOr<Schema>)>);
}

impl<T: InnerToSchema + ?Sized> InnerSchemaImplementedAdhoc for InnerSchemaContribution<T> {
    fn __collect(self, out: &mut Vec<(String, RefOr<Schema>)>) {
        T::inner_schemas(out);
    }
}

/// Depth-1 fallback.
pub trait InnerSchemaMissingAdhoc: Sized {
    /// No-op fallback — registers nothing.
    fn __collect(self, _out: &mut Vec<(String, RefOr<Schema>)>);
}

impl<T: ?Sized> InnerSchemaMissingAdhoc for &InnerSchemaContribution<T> {
    fn __collect(self, _out: &mut Vec<(String, RefOr<Schema>)>) {}
}

// ---------------------------------------------------------------------------
// Bare ToSchema probe (for error types, success body types, etc.)
// ---------------------------------------------------------------------------

/// Probes `T: ToSchema` directly. Used by the per-handler
/// [`crate::ApidocHandlerSchemas`] impl to register the handler's
/// error type — utoipa's own `IntoResponses`-based schema collection
/// does not walk these.
pub struct BareSchemaContribution<T: ?Sized>(PhantomData<T>);

impl<T: ?Sized> BareSchemaContribution<T> {
    /// Construct a zero-sized probe for `T`.
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: ?Sized> Default for BareSchemaContribution<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Depth-0 specialization.
pub trait BareSchemaImplementedAdhoc: Sized {
    /// Append `T::schemas(out)` via the specialized impl.
    fn __collect(self, out: &mut Vec<(String, RefOr<Schema>)>);
}

impl<T: utoipa::ToSchema + ?Sized> BareSchemaImplementedAdhoc for BareSchemaContribution<T> {
    fn __collect(self, out: &mut Vec<(String, RefOr<Schema>)>) {
        <T as utoipa::ToSchema>::schemas(out);
    }
}

/// Depth-1 fallback.
pub trait BareSchemaMissingAdhoc: Sized {
    /// No-op fallback — registers nothing.
    fn __collect(self, _out: &mut Vec<(String, RefOr<Schema>)>);
}

impl<T: ?Sized> BareSchemaMissingAdhoc for &BareSchemaContribution<T> {
    fn __collect(self, _out: &mut Vec<(String, RefOr<Schema>)>) {}
}

// ---------------------------------------------------------------------------
// Generic-argument schema probe (for types buried inside generic wrappers)
// ---------------------------------------------------------------------------

/// Probe that registers a type by its [`utoipa::ToSchema::name`] plus
/// every schema transitively referenced by it, so `$ref`s resolve.
///
/// The method macro emits one of these probes per type argument
/// discovered anywhere inside the handler's return type. This closes
/// a gap in utoipa's derive: when a field's type is a generic
/// parameter (e.g. `items: Vec<T>` in a `Paginated<T: ToSchema>`),
/// the derive emits only a recursive `<T as ToSchema>::schemas(out)`
/// call and never pushes `T`'s own `(name, schema)` pair. For a
/// concrete instantiation like `Paginated<SourceSummary>` where
/// `SourceSummary` is never returned directly anywhere else, this
/// leaves a dangling `$ref: #/components/schemas/SourceSummary` in
/// the final spec. Walking the return type at macro-expansion time
/// and routing each generic argument through this probe registers
/// the missing roots.
///
/// Types that do not implement [`utoipa::ToSchema`] +
/// [`utoipa::PartialSchema`] route to the depth-1 fallback and
/// contribute nothing — so emitting probes for wrapper types like
/// `axum::Json`, `Result`, and `std::vec::Vec<T>` is safe.
pub struct GenericArgSchemaContribution<T: ?Sized>(PhantomData<T>);

impl<T: ?Sized> GenericArgSchemaContribution<T> {
    /// Construct a zero-sized probe for `T`.
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: ?Sized> Default for GenericArgSchemaContribution<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Depth-0 specialization — invokes the shared `register_named_schema`
/// helper so this probe and `register_schema`-for-response-body follow
/// the same dedupe rules.
pub trait GenericArgSchemaImplementedAdhoc: Sized {
    /// Register the type and its transitive dependencies.
    fn __collect(self, out: &mut Vec<(String, RefOr<Schema>)>);
}

impl<T> GenericArgSchemaImplementedAdhoc for GenericArgSchemaContribution<T>
where
    T: utoipa::PartialSchema + utoipa::ToSchema,
{
    fn __collect(self, out: &mut Vec<(String, RefOr<Schema>)>) {
        crate::doc_responses::register_named_schema::<T>(out);
    }
}

/// Depth-1 fallback — applies to every `T`. Chosen when the depth-0
/// impl above is unavailable (i.e. `T` does not implement
/// `ToSchema + PartialSchema`).
pub trait GenericArgSchemaMissingAdhoc: Sized {
    /// No-op fallback — registers nothing.
    fn __collect(self, _out: &mut Vec<(String, RefOr<Schema>)>);
}

impl<T: ?Sized> GenericArgSchemaMissingAdhoc for &GenericArgSchemaContribution<T> {
    fn __collect(self, _out: &mut Vec<(String, RefOr<Schema>)>) {}
}

// ---------------------------------------------------------------------------
// Per-operation security/permission contribution
// ---------------------------------------------------------------------------

/// Probe routed through [`DocOperationSecurity`]. Used by the
/// per-handler [`crate::ApidocHandlerOps`] impl to mutate operations
/// with security requirements declared by extractor types.
pub struct OpSecurityContribution<T: ?Sized>(PhantomData<T>);

impl<T: ?Sized> OpSecurityContribution<T> {
    /// Construct a zero-sized probe for `T`.
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: ?Sized> Default for OpSecurityContribution<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Depth-0 specialization.
pub trait OpSecurityImplementedAdhoc: Sized {
    /// Apply the specialized impl, mutating `op` in place.
    fn __describe(self, op: &mut utoipa::openapi::path::Operation);
}

impl<T: DocOperationSecurity + ?Sized> OpSecurityImplementedAdhoc for OpSecurityContribution<T> {
    fn __describe(self, op: &mut utoipa::openapi::path::Operation) {
        T::describe(op);
    }
}

/// Depth-1 fallback.
pub trait OpSecurityMissingAdhoc: Sized {
    /// No-op fallback — does not mutate `op`.
    fn __describe(self, op: &mut utoipa::openapi::path::Operation);
}

impl<T: ?Sized> OpSecurityMissingAdhoc for &OpSecurityContribution<T> {
    fn __describe(self, _op: &mut utoipa::openapi::path::Operation) {}
}

// ---------------------------------------------------------------------------
// Response body contribution
// ---------------------------------------------------------------------------

/// Probe routed through [`DocResponseBody`]. The per-handler
/// [`crate::ApidocHandlerOps`] and [`crate::ApidocHandlerSchemas`]
/// impls invoke this probe once with the handler's return type; the
/// depth-0 impl applies when the return type implements
/// [`DocResponseBody`] (covering [`axum::Json`], [`crate::SseStream`],
/// [`Result<Ok, Err>`] where `Ok: DocResponseBody`, and any
/// user-defined wrappers), and the depth-1 fallback no-ops otherwise.
pub struct ResponseBodyContribution<T: ?Sized>(PhantomData<T>);

impl<T: ?Sized> ResponseBodyContribution<T> {
    /// Construct a zero-sized probe for `T`.
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: ?Sized> Default for ResponseBodyContribution<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Depth-0 specialization.
pub trait ResponseBodyImplementedAdhoc: Sized {
    /// Apply [`DocResponseBody::describe`] via the specialized impl.
    fn __describe(
        self,
        op: &mut utoipa::openapi::path::Operation,
        schemas: &mut Vec<(String, RefOr<Schema>)>,
    );
}

impl<T: DocResponseBody + ?Sized> ResponseBodyImplementedAdhoc for ResponseBodyContribution<T> {
    fn __describe(
        self,
        op: &mut utoipa::openapi::path::Operation,
        schemas: &mut Vec<(String, RefOr<Schema>)>,
    ) {
        T::describe(op, schemas);
    }
}

/// Depth-1 fallback.
pub trait ResponseBodyMissingAdhoc: Sized {
    /// No-op fallback — does not mutate `op` or append schemas.
    fn __describe(
        self,
        op: &mut utoipa::openapi::path::Operation,
        schemas: &mut Vec<(String, RefOr<Schema>)>,
    );
}

impl<T: ?Sized> ResponseBodyMissingAdhoc for &ResponseBodyContribution<T> {
    fn __describe(
        self,
        _op: &mut utoipa::openapi::path::Operation,
        _schemas: &mut Vec<(String, RefOr<Schema>)>,
    ) {
    }
}