cinderblock_json_api/lib.rs
1//! JSON REST API extension for cinderblock resources.
2//!
3//! When a resource declares `cinderblock_json_api` in its `extensions { ... }`
4//! block, the [`resource!`](cinderblock_core::resource) macro generates Axum
5//! route handlers and endpoint registration code. At startup, all registered
6//! endpoints are automatically discovered via [`inventory`] and assembled into
7//! an [`axum::Router`].
8//!
9//! # Extension configuration
10//!
11//! Inside the `extensions` block of a [`resource!`](cinderblock_core::resource)
12//! invocation, declare routes and optional settings:
13//!
14//! ```rust,ignore
15//! extensions {
16//! cinderblock_json_api {
17//! // Each `route` maps an HTTP method + path to a resource action.
18//! route = { method = GET; path = "/"; action = all; };
19//! route = { method = POST; path = "/"; action = open; };
20//! route = { method = POST; path = "/assign"; action = assign; };
21//! route = { method = PATCH; path = "/{primary_key}"; action = close; };
22//! route = { method = DELETE; path = "/{primary_key}"; action = remove; };
23//!
24//! // Optional: override the auto-derived base path.
25//! // Default: kebab-case of resource name segments joined by `/`.
26//! // e.g. `Helpdesk.Support.Ticket` -> `/helpdesk/support/ticket`
27//! // base_path = "/api/v1/tickets";
28//!
29//! // Optional: disable OpenAPI spec generation. Default: true.
30//! // openapi = false;
31//! };
32//! }
33//! ```
34//!
35//! ## Route configuration
36//!
37//! | Field | Required | Description |
38//! |---|---|---|
39//! | `method` | yes | HTTP method: `GET`, `POST`, `PATCH`, `PUT`, or `DELETE` |
40//! | `path` | yes | Path relative to the base path. Use `/{primary_key}` for routes that operate on a single resource. |
41//! | `action` | yes | Name of a declared action on the resource. Must match the action kind (e.g. `GET` for `read`, `POST` for `create`). |
42//!
43//! The action name must refer to an action declared in the resource's `actions`
44//! block. Duplicate method + path combinations are rejected at compile time.
45//!
46//! ## Route behavior by action kind
47//!
48//! - **Read** (`GET`): query parameters are deserialized into the action's
49//! `Arguments` struct. Returns `{ "data": [...] }`.
50//! - **Create** (`POST`): JSON body is deserialized into the action's `Input`
51//! struct. Returns `{ "data": <resource> }`.
52//! - **Update** (`PATCH`/`PUT`): primary key is extracted from the URL path,
53//! JSON body is deserialized into the action's `Input` struct. Returns
54//! `{ "data": <resource> }`.
55//! - **Destroy** (`DELETE`): primary key is extracted from the URL path.
56//! Returns `{ "data": <resource> }` with the deleted resource.
57//!
58//! All responses are wrapped in a [`Response`] envelope (`{ "data": ... }`).
59//!
60//! ## OpenAPI and Swagger UI
61//!
62//! By default, the extension generates an OpenAPI spec fragment for each
63//! resource. These fragments are merged and served at `GET /openapi.json`.
64//!
65//! When the `swagger-ui` feature is enabled, a Swagger UI is mounted at
66//! `/swagger-ui`. This can be toggled off via [`RouterConfig::swagger_ui`].
67//!
68//! ## Custom types in OpenAPI schemas
69//!
70//! The generated OpenAPI schemas use the [`FieldSchema`] trait to produce
71//! schemas for each attribute type. Built-in types (`String`, integers, `bool`,
72//! `Uuid`) have implementations provided. For custom types (like enums),
73//! derive [`utoipa::ToSchema`] and bridge it with [`impl_field_schema!`]:
74//!
75//! ```rust,ignore
76//! #[derive(Debug, Clone, Serialize, Deserialize, cinderblock_json_api::utoipa::ToSchema)]
77//! enum TicketStatus {
78//! Open,
79//! Closed,
80//! }
81//!
82//! cinderblock_json_api::impl_field_schema!(TicketStatus);
83//! ```
84//!
85//! # Building the router
86//!
87//! Use [`router()`] for the common case, or [`RouterConfig`] for more control:
88//!
89//! ```rust,ignore
90//! let ctx = cinderblock_core::Context::new();
91//!
92//! // Simple — all defaults.
93//! let app = cinderblock_json_api::router(ctx);
94//!
95//! // Or configure options like Swagger UI.
96//! let app = cinderblock_json_api::RouterConfig::new(ctx)
97//! .swagger_ui(false)
98//! .build();
99//!
100//! let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
101//! axum::serve(listener, app).await?;
102//! ```
103//!
104//! # Full example
105//!
106//! ```rust,ignore
107//! use cinderblock_core::{Context, resource, serde::{Deserialize, Serialize}};
108//! use uuid::Uuid;
109//!
110//! resource! {
111//! name = Helpdesk.Support.Ticket;
112//!
113//! attributes {
114//! ticket_id Uuid {
115//! primary_key true;
116//! writable false;
117//! default || Uuid::new_v4();
118//! }
119//! subject String;
120//! status TicketStatus;
121//! }
122//!
123//! actions {
124//! read all {
125//! argument { status: Option<TicketStatus> };
126//! filter { status == arg(status) };
127//! };
128//! create open;
129//! update close {
130//! accept [];
131//! change_ref |ticket| { ticket.status = TicketStatus::Closed; };
132//! };
133//! destroy remove;
134//! }
135//!
136//! extensions {
137//! cinderblock_json_api {
138//! route = { method = GET; path = "/"; action = all; };
139//! route = { method = POST; path = "/"; action = open; };
140//! route = { method = PATCH; path = "/{primary_key}"; action = close; };
141//! route = { method = DELETE; path = "/{primary_key}"; action = remove; };
142//! };
143//! }
144//! }
145//!
146//! #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq,
147//! cinderblock_json_api::utoipa::ToSchema)]
148//! enum TicketStatus { #[default] Open, Closed }
149//! cinderblock_json_api::impl_field_schema!(TicketStatus);
150//!
151//! #[tokio::main]
152//! async fn main() -> cinderblock_core::Result<()> {
153//! let ctx = Context::new();
154//! let router = cinderblock_json_api::router(ctx);
155//! let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
156//! axum::serve(listener, router).await?;
157//! Ok(())
158//! }
159//! ```
160
161use std::sync::Arc;
162
163pub use serde;
164
165// Re-export dependencies for macro hygiene — the generated code from
166// `cinderblock-json-api-macros` references these through `cinderblock_json_api::axum`,
167// `cinderblock_json_api::tracing`, etc., so they must be available at the
168// call site without the user adding them as direct dependencies.
169pub use axum;
170pub use inventory;
171pub use tracing;
172pub use utoipa;
173
174// Re-export the extension proc macro so `resource!` can call
175// `cinderblock_json_api::__resource_extension!`.
176pub use cinderblock_json_api_macros::__resource_extension;
177
178/// Helper trait that provides OpenAPI schema generation for types used as
179/// resource attribute fields.
180///
181/// This exists because `utoipa::PartialSchema` is a foreign trait, so we
182/// can't impl it for foreign types like `uuid::Uuid` due to orphan rules.
183/// The extension macro generates calls to
184/// `<Type as cinderblock_json_api::FieldSchema>::field_schema()` instead of
185/// `<Type as utoipa::PartialSchema>::schema()`.
186///
187/// Types that derive `utoipa::ToSchema` (which implies `PartialSchema`)
188/// can use the blanket impl via the `partial_schema_field_schema!` macro.
189/// Common built-in types (`String`, integers, `bool`, `Uuid`) have
190/// explicit impls provided here.
191pub trait FieldSchema {
192 fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>;
193}
194
195/// Implements `FieldSchema` for types that already have `PartialSchema`.
196///
197/// Users call this for their own types that derive `ToSchema`:
198/// ```rust,ignore
199/// #[derive(utoipa::ToSchema)]
200/// enum TicketStatus { Open, Closed }
201/// cinderblock_json_api::impl_field_schema!(TicketStatus);
202/// ```
203#[macro_export]
204macro_rules! impl_field_schema {
205 ($ty:ty) => {
206 impl $crate::FieldSchema for $ty {
207 fn field_schema(
208 ) -> $crate::utoipa::openapi::RefOr<$crate::utoipa::openapi::schema::Schema> {
209 <$ty as $crate::utoipa::PartialSchema>::schema()
210 }
211 }
212 };
213}
214
215// # Built-in FieldSchema implementations
216//
217// These cover the common Rust types that appear as resource attribute
218// fields. The schemas match what utoipa's built-in `ComposeSchema` impls
219// would produce.
220
221macro_rules! impl_field_schema_string {
222 ($($ty:ty),*) => {
223 $(
224 impl FieldSchema for $ty {
225 fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
226 use utoipa::openapi::schema::{ObjectBuilder, SchemaType, Type};
227 ObjectBuilder::new()
228 .schema_type(SchemaType::new(Type::String))
229 .into()
230 }
231 }
232 )*
233 };
234}
235
236macro_rules! impl_field_schema_integer {
237 ($($ty:ty => $format:expr),*) => {
238 $(
239 impl FieldSchema for $ty {
240 fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
241 use utoipa::openapi::schema::{ObjectBuilder, SchemaType, SchemaFormat, Type};
242 ObjectBuilder::new()
243 .schema_type(SchemaType::new(Type::Integer))
244 .format(Some(SchemaFormat::KnownFormat($format)))
245 .into()
246 }
247 }
248 )*
249 };
250}
251
252macro_rules! impl_field_schema_number {
253 ($($ty:ty => $format:expr),*) => {
254 $(
255 impl FieldSchema for $ty {
256 fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
257 use utoipa::openapi::schema::{ObjectBuilder, SchemaType, SchemaFormat, Type};
258 ObjectBuilder::new()
259 .schema_type(SchemaType::new(Type::Number))
260 .format(Some(SchemaFormat::KnownFormat($format)))
261 .into()
262 }
263 }
264 )*
265 };
266}
267
268impl_field_schema_string!(String);
269
270impl FieldSchema for bool {
271 fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
272 use utoipa::openapi::schema::{ObjectBuilder, SchemaType, Type};
273 ObjectBuilder::new()
274 .schema_type(SchemaType::new(Type::Boolean))
275 .into()
276 }
277}
278
279impl_field_schema_integer!(
280 i8 => utoipa::openapi::KnownFormat::Int32,
281 i16 => utoipa::openapi::KnownFormat::Int32,
282 i32 => utoipa::openapi::KnownFormat::Int32,
283 i64 => utoipa::openapi::KnownFormat::Int64,
284 u8 => utoipa::openapi::KnownFormat::Int32,
285 u16 => utoipa::openapi::KnownFormat::Int32,
286 u32 => utoipa::openapi::KnownFormat::Int32,
287 u64 => utoipa::openapi::KnownFormat::Int64,
288 isize => utoipa::openapi::KnownFormat::Int64,
289 usize => utoipa::openapi::KnownFormat::Int64
290);
291
292impl_field_schema_number!(
293 f32 => utoipa::openapi::KnownFormat::Float,
294 f64 => utoipa::openapi::KnownFormat::Double
295);
296
297impl FieldSchema for uuid::Uuid {
298 fn field_schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
299 use utoipa::openapi::schema::{ObjectBuilder, SchemaFormat, SchemaType, Type};
300 ObjectBuilder::new()
301 .schema_type(SchemaType::new(Type::String))
302 .format(Some(SchemaFormat::KnownFormat(
303 utoipa::openapi::KnownFormat::Uuid,
304 )))
305 .into()
306 }
307}
308
309/// Generic JSON API response envelope.
310///
311/// Wraps all responses in a `{ "data": ... }` structure so the format is
312/// extensible with future fields like pagination, links, or errors.
313///
314/// For list endpoints `T` is `Vec<R>`, for single-resource endpoints it
315/// will be `R` directly.
316#[derive(Debug, serde::Serialize)]
317pub struct Response<T: serde::Serialize> {
318 pub data: T,
319}
320
321/// JSON API response envelope for paginated list endpoints.
322///
323/// Returns `{ "data": [...], "meta": { page, per_page, total, total_pages } }`.
324/// Used by paged read action handlers instead of the plain [`Response`] envelope.
325#[derive(Debug, serde::Serialize)]
326pub struct PaginatedResponse<T: serde::Serialize> {
327 pub data: Vec<T>,
328 pub meta: PaginationMeta,
329}
330
331/// Pagination metadata included in [`PaginatedResponse`].
332#[derive(Debug, serde::Serialize)]
333pub struct PaginationMeta {
334 pub page: u32,
335 pub per_page: u32,
336 pub total: u64,
337 pub total_pages: u32,
338}
339
340// # PartialSchema / ToSchema for Response<T>
341//
342// Manual implementations so the generated OpenAPI spec can describe the
343// `{ "data": ... }` envelope without requiring a derive on a struct that
344// has a generic type parameter. The schema delegates to `T`'s schema for
345// the `data` property.
346impl<T> utoipa::PartialSchema for Response<T>
347where
348 T: serde::Serialize + utoipa::PartialSchema,
349{
350 fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
351 use utoipa::openapi::schema::{ObjectBuilder, SchemaType, Type};
352
353 ObjectBuilder::new()
354 .schema_type(SchemaType::new(Type::Object))
355 .property("data", T::schema())
356 .required("data")
357 .into()
358 }
359}
360
361impl<T> utoipa::ToSchema for Response<T>
362where
363 T: serde::Serialize + utoipa::PartialSchema,
364{
365 fn name() -> std::borrow::Cow<'static, str> {
366 std::borrow::Cow::Borrowed("Response")
367 }
368}
369
370// # PartialSchema / ToSchema for PaginatedResponse<T>
371//
372// Describes the `{ "data": [...], "meta": {...} }` shape for OpenAPI specs.
373impl<T> utoipa::PartialSchema for PaginatedResponse<T>
374where
375 T: serde::Serialize + utoipa::PartialSchema,
376{
377 fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
378 use utoipa::openapi::schema::{
379 ArrayBuilder, ObjectBuilder, SchemaFormat, SchemaType, Type,
380 };
381
382 let meta_schema = ObjectBuilder::new()
383 .schema_type(SchemaType::new(Type::Object))
384 .property(
385 "page",
386 ObjectBuilder::new()
387 .schema_type(SchemaType::new(Type::Integer))
388 .format(Some(SchemaFormat::KnownFormat(
389 utoipa::openapi::KnownFormat::Int32,
390 ))),
391 )
392 .required("page")
393 .property(
394 "per_page",
395 ObjectBuilder::new()
396 .schema_type(SchemaType::new(Type::Integer))
397 .format(Some(SchemaFormat::KnownFormat(
398 utoipa::openapi::KnownFormat::Int32,
399 ))),
400 )
401 .required("per_page")
402 .property(
403 "total",
404 ObjectBuilder::new()
405 .schema_type(SchemaType::new(Type::Integer))
406 .format(Some(SchemaFormat::KnownFormat(
407 utoipa::openapi::KnownFormat::Int64,
408 ))),
409 )
410 .required("total")
411 .property(
412 "total_pages",
413 ObjectBuilder::new()
414 .schema_type(SchemaType::new(Type::Integer))
415 .format(Some(SchemaFormat::KnownFormat(
416 utoipa::openapi::KnownFormat::Int32,
417 ))),
418 )
419 .required("total_pages");
420
421 ObjectBuilder::new()
422 .schema_type(SchemaType::new(Type::Object))
423 .property("data", ArrayBuilder::new().items(T::schema()))
424 .required("data")
425 .property("meta", meta_schema)
426 .required("meta")
427 .into()
428 }
429}
430
431impl<T> utoipa::ToSchema for PaginatedResponse<T>
432where
433 T: serde::Serialize + utoipa::PartialSchema,
434{
435 fn name() -> std::borrow::Cow<'static, str> {
436 std::borrow::Cow::Borrowed("PaginatedResponse")
437 }
438}
439
440/// A registered resource endpoint. Extension macros generate instances of this
441/// struct and submit them via `inventory::submit!`. The `register` function
442/// takes an existing router and context, and returns a new router with the
443/// resource's endpoints added.
444///
445/// The optional `openapi` function returns an OpenAPI spec fragment for the
446/// resource's endpoints. When present, the router builder merges all fragments
447/// into a single spec served at `/openapi.json`.
448pub struct ResourceEndpoint {
449 pub register: fn(axum::Router, Arc<cinderblock_core::Context>) -> axum::Router,
450 pub openapi: Option<fn() -> utoipa::openapi::OpenApi>,
451}
452
453inventory::collect!(ResourceEndpoint);
454
455/// Configuration builder for the JSON API router.
456///
457/// Allows controlling optional features like Swagger UI before building
458/// the final `axum::Router`.
459///
460/// ```rust,ignore
461/// let router = cinderblock_json_api::RouterConfig::new(ctx)
462/// .swagger_ui(true)
463/// .build();
464/// ```
465pub struct RouterConfig {
466 ctx: Arc<cinderblock_core::Context>,
467 swagger_ui: bool,
468}
469
470impl RouterConfig {
471 pub fn new(ctx: impl Into<Arc<cinderblock_core::Context>>) -> Self {
472 Self {
473 ctx: ctx.into(),
474 swagger_ui: true,
475 }
476 }
477
478 /// Enable or disable the Swagger UI endpoint at `/swagger-ui`.
479 /// Only takes effect when the `utoipa-swagger-ui` feature is enabled.
480 /// Default: `true`.
481 pub fn swagger_ui(mut self, enabled: bool) -> Self {
482 self.swagger_ui = enabled;
483 self
484 }
485
486 pub fn build(self) -> axum::Router {
487 let mut router = axum::Router::new();
488
489 // # Endpoint registration + OpenAPI spec collection
490 //
491 // Each resource that declared `cinderblock_json_api` in its extensions block
492 // contributes both route handlers and an optional OpenAPI spec
493 // fragment. We collect the fragments and merge them afterward.
494 let mut openapi_specs: Vec<utoipa::openapi::OpenApi> = Vec::new();
495
496 for endpoint in inventory::iter::<ResourceEndpoint> {
497 router = (endpoint.register)(router, self.ctx.clone());
498
499 if let Some(openapi_fn) = endpoint.openapi {
500 openapi_specs.push(openapi_fn());
501 }
502 }
503
504 // # OpenAPI spec merging
505 //
506 // Build a base spec and merge each resource's fragment into it.
507 // The merged spec is served at GET /openapi.json.
508 if !openapi_specs.is_empty() {
509 let mut merged = utoipa::openapi::OpenApiBuilder::new()
510 .info(
511 utoipa::openapi::InfoBuilder::new()
512 .title("Cinderblock JSON API")
513 .version("0.1.0")
514 .build(),
515 )
516 .build();
517
518 for spec in openapi_specs {
519 merged.merge(spec);
520 }
521
522 // # Swagger UI
523 //
524 // When the `swagger-ui` feature is enabled and the user hasn't
525 // disabled it, mount the Swagger UI at `/swagger-ui`. The
526 // SwaggerUi widget also serves the spec at `/openapi.json`.
527 #[cfg(feature = "swagger-ui")]
528 if self.swagger_ui {
529 router = router.merge(
530 utoipa_swagger_ui::SwaggerUi::new("/swagger-ui").url("/openapi.json", merged),
531 );
532 }
533
534 #[cfg(not(feature = "swagger-ui"))]
535 let _ = self.swagger_ui;
536 }
537
538 router
539 }
540}
541
542/// Builds an `axum::Router` containing all auto-registered JSON API endpoints.
543///
544/// This is a convenience wrapper around `RouterConfig::new(ctx).build()`.
545/// Each resource that declared `cinderblock_json_api` in its `extensions` block will
546/// have its endpoints automatically included via `inventory` — no manual
547/// route construction is needed.
548pub fn router(ctx: impl Into<Arc<cinderblock_core::Context>>) -> axum::Router {
549 RouterConfig::new(ctx).build()
550}