ash_jsonapi/domain.rs
1//! Where `ash-domain` plugs in — **optional**, behind the `domain` feature.
2//!
3//! This crate stands alone: [`resource!`](crate::resource!) over your own
4//! structs and storage needs no `ash-*` crate in the tree at all. This module
5//! is the other way in, for a service whose resources the domain already
6//! owns.
7//!
8//! The division: the domain owns resources, policies and execution; this
9//! crate owns the JSON:API wire format. Nothing about a resource is declared
10//! twice — attributes, types, relationships and cardinality all come from
11//! `#[derive(Resource)]`, and the one thing supplied here is the base path,
12//! because the domain does not know it is being served over HTTP.
13//!
14//! ```text
15//! impl DomainState for App { /* domain, context, mounted schemas */ }
16//!
17//! ash_jsonapi::domain_resource! { Todo as "todo" at "/todos", state: App }
18//! ash_jsonapi::api! { operations: [ash_jsonapi::CRUD], resource: Todo, … }
19//! ```
20//!
21//! [`domain_resource!`](crate::domain_resource!) writes the same traits
22//! [`resource!`](crate::resource!) does, so [`api!`](crate::api!) serves both
23//! kinds of resource identically. Every action runs *through* the domain —
24//! [`Bound`](ash_domain::domain::Bound), not around it — so policies,
25//! extensions and validation all apply, and [`error_from`] turns what comes
26//! back into the right status: a denial is a `403`, not a `500`.
27
28use ash_domain::schema::{RelationshipSchema, ResourceSchema, SchemaType};
29use ash_domain::value::{Record as DomainRecord, Value};
30
31use crate::context::Context;
32use crate::error::JsonApiError;
33use crate::serialize::{Record, RelationshipDef, Schema, Serializer};
34
35impl RelationshipDef for RelationshipSchema {
36 fn name(&self) -> &str {
37 &self.name
38 }
39
40 fn target(&self) -> &str {
41 &self.destination
42 }
43
44 fn is_to_many(&self) -> bool {
45 // `RelationshipSchema` reports cardinality as a string rather than the
46 // `Cardinality` enum, so match the strings it documents.
47 matches!(self.cardinality, "has_many" | "many_to_many")
48 }
49}
50
51/// A resource schema paired with the path it is served under.
52///
53/// The base path is not a domain concept — the domain does not know it is
54/// being served over HTTP — so the router supplies it alongside the schema.
55#[derive(Debug, Clone, Copy)]
56pub struct Mounted<'a> {
57 pub schema: &'a ResourceSchema,
58 pub base_path: &'a str,
59}
60
61impl<'a> Mounted<'a> {
62 pub fn new(schema: &'a ResourceSchema, base_path: &'a str) -> Self {
63 Self { schema, base_path }
64 }
65
66 /// Start a resource object for `id`, in one step.
67 ///
68 /// ```text
69 /// Mounted::new(&schema, "/api/v1/todos")
70 /// .record("t_1")
71 /// .attr("message", "buy milk")
72 /// .rel("owner", "u_01H8X")
73 /// .build()
74 /// ```ignore
75 pub fn record(&self, id: &str) -> Record<'_, Self> {
76 Serializer::new(self).record(id)
77 }
78
79 /// The `self` link for one resource.
80 pub fn self_link(&self, id: &str) -> String {
81 Serializer::new(self).self_link(id)
82 }
83
84 /// Serialize an `ash_domain::Record` straight from the domain.
85 ///
86 /// Two things are dropped from `attributes`, because JSON:API carries
87 /// them elsewhere: the primary key, which becomes the envelope `id`, and
88 /// every relationship's source attribute — a foreign key belongs in
89 /// linkage, not beside the data. Everything else is converted as-is.
90 ///
91 /// Relationships are added afterwards, since a `Record` holds foreign
92 /// keys rather than linkage:
93 ///
94 /// ```ignore
95 /// mounted.record_from(&record).rel("owner", owner_id).build()
96 /// ```
97 pub fn record_from(&self, record: &DomainRecord) -> Record<'_, Self> {
98 // The primary key becomes the envelope `id`, which is always a string.
99 let id = match record.get(&self.schema.primary_key) {
100 Some(Value::Str(s)) => s.clone(),
101 Some(other) => render(other).to_string(),
102 None => String::new(),
103 };
104
105 let hidden = |key: &String| {
106 key == &self.schema.primary_key
107 || self
108 .schema
109 .relationships
110 .iter()
111 .any(|rel| &rel.source_attribute == key)
112 };
113
114 let attributes = record
115 .0
116 .iter()
117 .filter(|(key, _)| !hidden(key))
118 .map(|(key, value)| (key.clone(), render(value)));
119
120 self.record(&id).attrs(attributes)
121 }
122}
123
124/// `ash_domain::Value` → `serde_json::Value`.
125///
126/// Written out rather than delegated to `serde_json::to_value`: `Value`'s own
127/// `Serialize` is externally tagged, so a message would reach the client as
128/// `{"Str":"buy milk"}`. A JSON:API attribute is the bare value.
129fn render(value: &Value) -> serde_json::Value {
130 match value {
131 Value::Null => serde_json::Value::Null,
132 Value::Bool(b) => (*b).into(),
133 Value::Int(i) => (*i).into(),
134 Value::Float(f) => serde_json::Number::from_f64(*f)
135 .map(serde_json::Value::Number)
136 .unwrap_or(serde_json::Value::Null),
137 Value::Str(s) => s.clone().into(),
138 // Bytes have no JSON form; base64 is the caller's decision, so a
139 // resource that exposes them should use a computed attribute.
140 Value::Bytes(_) => serde_json::Value::Null,
141 // Milliseconds since the epoch, as the domain stores them.
142 Value::Timestamp(ms) => (*ms).into(),
143 Value::Map(map) => {
144 serde_json::Value::Object(map.iter().map(|(k, v)| (k.clone(), render(v))).collect())
145 }
146 Value::List(items) => serde_json::Value::Array(items.iter().map(render).collect()),
147 }
148}
149
150impl Schema for Mounted<'_> {
151 type Relationship = RelationshipSchema;
152
153 fn name(&self) -> &str {
154 &self.schema.name
155 }
156
157 fn relationships(&self) -> &[RelationshipSchema] {
158 &self.schema.relationships
159 }
160
161 fn base_path(&self) -> &str {
162 self.base_path
163 }
164}
165
166/// Build an [`ash_domain::schema::ResourceSchema`] literal.
167///
168/// `ResourceSchema` has ten fields, most of which serialization ignores.
169/// Writing one by hand is noise; this fills in the defaults.
170///
171/// **For tests, examples and fixtures only.** A real service takes its schema
172/// from `Domain::schema()` — a resource is declared once, with
173/// `#[derive(Resource)]`, and never restated.
174///
175/// ```ignore
176/// use ash_jsonapi::resource_schema;
177///
178/// let schema = resource_schema! {
179/// "todo" {
180/// message: String,
181/// owner -> "user",
182/// tags -> ["tag"],
183/// }
184/// };
185///
186/// assert_eq!(schema.name, "todo");
187/// assert_eq!(schema.attributes.len(), 1);
188/// assert_eq!(schema.relationships.len(), 2);
189/// ```
190///
191/// `name: Type` declares an attribute — `String`, `Integer`, `Number`,
192/// `Boolean` or `Bytes`. `-> "user"` declares a to-one relationship;
193/// `-> ["tag"]` a to-many, the brackets reading as "many of these".
194#[macro_export]
195macro_rules! resource_schema {
196 ($name:literal $({ $($member:tt)* })?) => {{
197 #[allow(unused_mut)]
198 let mut attributes: ::std::vec::Vec<
199 $crate::__ash_domain::schema::AttributeSchema,
200 > = ::std::vec::Vec::new();
201 #[allow(unused_mut)]
202 let mut relationships: ::std::vec::Vec<
203 $crate::__ash_domain::schema::RelationshipSchema,
204 > = ::std::vec::Vec::new();
205 $($crate::__schema_members!(attributes, relationships, $($member)*);)?
206
207 $crate::__ash_domain::schema::ResourceSchema {
208 name: ::std::string::String::from($name),
209 storage_name: ::std::string::String::from($name),
210 primary_key: ::std::string::String::from("id"),
211 version_attribute: ::std::option::Option::None,
212 tenant: ::std::option::Option::None,
213 attributes,
214 relationships,
215 aggregates: ::std::vec::Vec::new(),
216 computed: ::std::vec::Vec::new(),
217 actions: ::std::vec::Vec::new(),
218 }
219 }};
220}
221
222/// Walks the member list, sorting attributes from relationships.
223#[doc(hidden)]
224#[macro_export]
225macro_rules! __schema_members {
226 ($attrs:ident, $rels:ident $(,)?) => {};
227
228 ($attrs:ident, $rels:ident, $name:ident : $ty:ident $(, $($rest:tt)*)?) => {
229 $attrs.extend([$crate::__ash_domain::schema::AttributeSchema {
230 name: ::std::string::String::from(::std::stringify!($name)),
231 ty: $crate::__ash_domain::schema::SchemaType::$ty,
232 default: ::std::option::Option::None,
233 primary_key: false,
234 attribute_policy: false,
235 }]);
236 $($crate::__schema_members!($attrs, $rels, $($rest)*);)?
237 };
238
239 ($attrs:ident, $rels:ident, $name:ident -> $target:tt $(, $($rest:tt)*)?) => {
240 $rels.extend([$crate::__relationship_schema!($name -> $target)]);
241 $($crate::__schema_members!($attrs, $rels, $($rest)*);)?
242 };
243}
244
245#[doc(hidden)]
246#[macro_export]
247macro_rules! __relationship_schema {
248 ($name:ident -> [$target:literal]) => {
249 $crate::__relationship_schema!(@build $name, $target, "has_many")
250 };
251 ($name:ident -> $target:literal) => {
252 $crate::__relationship_schema!(@build $name, $target, "belongs_to")
253 };
254 (@build $name:ident, $target:literal, $cardinality:literal) => {
255 $crate::__ash_domain::schema::RelationshipSchema {
256 name: ::std::string::String::from(::std::stringify!($name)),
257 destination: ::std::string::String::from($target),
258 cardinality: $cardinality,
259 source_attribute: ::std::string::String::from("id"),
260 destination_attribute: ::std::string::String::from("id"),
261 through: ::std::option::Option::None,
262 }
263 };
264}
265
266impl<'a> Mounted<'a> {
267 /// Read a create document into the resource's own type.
268 ///
269 /// The document is expected to have passed
270 /// [`DocumentValidator`](crate::validation::DocumentValidator) already —
271 /// shape, required members and linkage are its job. What remains here is
272 /// the typed conversion, driven by the schema's declared attribute types.
273 pub fn parse_create<R>(
274 &self,
275 document: &serde_json::Value,
276 ctx: &Context,
277 ) -> Result<R, JsonApiError>
278 where
279 R: ash_domain::FromRecord + ash_domain::value::IntoRecord + Default,
280 {
281 self.parse_document(document, None, ctx)
282 }
283
284 /// Read an update document into the resource's own type.
285 ///
286 /// Same as [`Mounted::parse_create`], except the primary key comes from
287 /// the URL: a `PATCH` addresses a row that already exists, and the id in
288 /// the path is authoritative over anything the body says.
289 pub fn parse_update<R>(
290 &self,
291 document: &serde_json::Value,
292 id: &str,
293 ctx: &Context,
294 ) -> Result<R, JsonApiError>
295 where
296 R: ash_domain::FromRecord + ash_domain::value::IntoRecord + Default,
297 {
298 self.parse_document(document, Some(id), ctx)
299 }
300
301 fn parse_document<R>(
302 &self,
303 document: &serde_json::Value,
304 id: Option<&str>,
305 ctx: &Context,
306 ) -> Result<R, JsonApiError>
307 where
308 R: ash_domain::FromRecord + ash_domain::value::IntoRecord + Default,
309 {
310 // Start from the resource's own `Default`, so any attribute the body
311 // omits keeps the value the struct would have given it. That is the
312 // only source that knows a valid `ValueEnum` member — a schema
313 // records the type, not which variant is the default.
314 let mut record = R::default()
315 .into_record()
316 .map_err(|err| JsonApiError::internal(ctx).detail(err.to_string()))?;
317
318 let supplied = self.read_document(document, ctx)?;
319 record.0.extend(supplied.0);
320
321 // On an update the row already exists, so the path's id wins; on a
322 // create `Default` leaves it empty and the domain stamps one.
323 if let Some(id) = id {
324 record
325 .0
326 .insert(self.schema.primary_key.clone(), Value::Str(id.to_string()));
327 }
328
329 R::from_record(&record).map_err(|err| {
330 // The schema and the struct disagree, which is a bug in the
331 // resource declaration rather than in the request.
332 JsonApiError::invalid(ctx, err.to_string(), "/data/attributes")
333 })
334 }
335}
336
337impl Mounted<'_> {
338 /// `{"data":{"attributes":…,"relationships":…}}` → `Record`.
339 ///
340 /// Attributes are coerced to the types the schema declares; relationship
341 /// linkage is written back to the foreign key it stands for.
342 fn read_document(
343 &self,
344 document: &serde_json::Value,
345 ctx: &Context,
346 ) -> Result<DomainRecord, JsonApiError> {
347 let invalid =
348 |detail: String, pointer: &str| JsonApiError::invalid(ctx, detail, pointer.to_string());
349
350 let data = document
351 .get("data")
352 .ok_or_else(|| invalid("`data` is required".into(), "/data"))?;
353
354 let mut record = DomainRecord::new();
355
356 // Attributes, coerced to the types the schema declares. An attribute
357 // the schema does not know is ignored rather than passed through:
358 // the domain would reject it, and a clear message beats a 500.
359 //
360 // The primary key is skipped for the same reason `record_from` drops
361 // it on the way out: JSON:API carries it in the envelope, not among
362 // the attributes. `DocumentValidator::for_create` hides it from the
363 // *request schema*, but hiding a property only stops describing it —
364 // nothing sets `additionalProperties: false` — so without this the
365 // member would still be read, and a client could choose its own row
366 // id by sending `attributes.id`. A create lets the domain stamp the
367 // key; an update takes it from the path, which `parse_document` and
368 // `record_for_update` apply after this returns.
369 if let Some(attributes) = data.get("attributes").and_then(|a| a.as_object()) {
370 for attribute in &self.schema.attributes {
371 if attribute.name == self.schema.primary_key {
372 continue;
373 }
374
375 let value = match attributes.get(&attribute.name) {
376 Some(json) => coerce(json, &attribute.ty).ok_or_else(|| {
377 invalid(
378 format!("`{}` is not of the declared type", attribute.name),
379 &format!("/data/attributes/{}", attribute.name),
380 )
381 })?,
382 // Absent from the body: leave whatever the resource's
383 // own `Default` put there.
384 None => continue,
385 };
386
387 record.0.insert(attribute.name.clone(), value);
388 }
389 }
390
391 // Linkage → foreign keys. A relationship's `source_attribute` is the
392 // column the domain stores, so writing it here is what makes
393 // `{"owner":{"data":{"id":"alice"}}}` mean `owner_id = "alice"`.
394 if let Some(relationships) = data.get("relationships").and_then(|r| r.as_object()) {
395 for rel in &self.schema.relationships {
396 let Some(id) = relationships
397 .get(&rel.name)
398 .and_then(|r| r.get("data"))
399 .and_then(|d| d.get("id"))
400 .and_then(|id| id.as_str())
401 else {
402 continue;
403 };
404
405 record
406 .0
407 .insert(rel.source_attribute.clone(), Value::Str(id.to_string()));
408 }
409 }
410
411 Ok(record)
412 }
413}
414
415/// `serde_json::Value` → `ash_domain::Value`, against a declared type.
416///
417/// Returns `None` when the JSON does not fit, which becomes a 422 pointing at
418/// the attribute.
419fn coerce(json: &serde_json::Value, ty: &SchemaType) -> Option<Value> {
420 if json.is_null() {
421 return Some(Value::Null);
422 }
423
424 match ty {
425 SchemaType::Boolean => json.as_bool().map(Value::Bool),
426 SchemaType::Integer => json.as_i64().map(Value::Int),
427 SchemaType::Number => json.as_f64().map(Value::Float),
428 SchemaType::String => json.as_str().map(|s| Value::Str(s.to_string())),
429 // A reference is stored as the target's id.
430 SchemaType::Reference { .. } => json.as_str().map(|s| Value::Str(s.to_string())),
431 // `ValueEnum` and other consumer scalars reach storage as strings.
432 SchemaType::Opaque { .. } => json.as_str().map(|s| Value::Str(s.to_string())),
433 SchemaType::Embed { .. } | SchemaType::EmbedList { .. } => {
434 // Nested structures round-trip through the same JSON form the
435 // domain stores them in.
436 serde_json::from_value(json.clone()).ok()
437 }
438 // Bytes have no JSON form; a resource exposing them needs an explicit
439 // encoding, which is the resource's decision rather than ours.
440 SchemaType::Bytes => None,
441 }
442}
443
444#[cfg(feature = "validation")]
445#[cfg_attr(docsrs, doc(cfg(feature = "validation")))]
446impl crate::validation::DocumentValidator {
447 /// Derive a create-body validator from an `ash-domain` schema.
448 ///
449 /// The ash-domain shortcut for
450 /// [`DocumentValidator::builder`](crate::validation::DocumentValidator::builder):
451 /// attribute types come from `ResourceSchema::to_json_schema`, and the
452 /// members JSON:API carries elsewhere are hidden — the primary key, which
453 /// belongs in the envelope, and every relationship's foreign key, which
454 /// belongs in linkage.
455 ///
456 /// Note what hiding does and does not do. [`hide`](crate::validation::ValidatorBuilder::hide)
457 /// removes a property from the generated schema, so the member is no
458 /// longer *described*; it does not set `additionalProperties: false`, so
459 /// it is not *forbidden* either. Sending a hidden member is therefore not
460 /// an error — it is ignored. What keeps it from taking effect is the
461 /// reading side: `Mounted`'s document reader skips the primary key, so a
462 /// client cannot choose a row's id by sending `attributes.id`.
463 ///
464 /// Relationships are optional in the document: whether one is *required*
465 /// is a domain policy, not a question about the document's shape.
466 pub fn for_create(schema: &ResourceSchema) -> Result<Self, crate::validation::BuildError> {
467 let hidden: Vec<&str> = std::iter::once(schema.primary_key.as_str())
468 .chain(
469 schema
470 .relationships
471 .iter()
472 .map(|rel| rel.source_attribute.as_str()),
473 )
474 .collect();
475
476 // `Mounted` supplies the `Schema` impl; the base path is unused when
477 // building a validator, so any value does.
478 let mounted = Mounted::new(schema, "");
479
480 Self::builder(&mounted)
481 .attributes(required_on_create(schema))
482 .hide(hidden)
483 .build()
484 }
485}
486
487/// An `ash-domain` error, as a JSON:API error.
488///
489/// Most of what the domain returns is a legitimate outcome rather than a
490/// fault, and reporting all of it as `500` would tell a client to retry a
491/// request that will never succeed. The mapping:
492///
493/// | `ash_domain::Error` | Status |
494/// |---|---|
495/// | `NotFound` | `404` |
496/// | `Forbidden` | `403` |
497/// | `PolicyError` | `503` — an authorization *outage*, so retriable |
498/// | `MissingTenant` | `400` |
499/// | `Invalid` | `422`, with `source.pointer` at the named field |
500/// | `Conflict` | `409` |
501/// | `Contention` | `503` |
502/// | `Closing` | `503` |
503/// | `Unsupported` | `501` |
504/// | `UnknownResource`, `UnknownAction` | `500` — a wiring bug |
505/// | `DataLayer`, `Serialization` | `500`, message logged not sent |
506///
507/// The two `500`s stay opaque: a data-layer message can hold a connection
508/// string or a fragment of a query, so it is logged against the correlation
509/// id and never serialized.
510pub fn error_from(err: &ash_domain::Error, ctx: &Context) -> JsonApiError {
511 use ash_domain::Error;
512
513 let code = match err {
514 Error::NotFound(_) => crate::ErrorCode::NotFound,
515 Error::Forbidden(_) => crate::ErrorCode::Forbidden,
516 Error::PolicyError(_) => crate::ErrorCode::PolicyUnavailable,
517 Error::MissingTenant(_) => crate::ErrorCode::MissingTenant,
518 Error::Invalid { field, message } => {
519 // `field` is an attribute path, which is what a pointer into the
520 // document's `attributes` is built from.
521 let pointer = match field {
522 Some(field) => format!("/data/attributes/{}", field.replace('.', "/")),
523 None => "/data".to_string(),
524 };
525 return JsonApiError::invalid(ctx, message.clone(), pointer);
526 }
527 Error::Conflict { .. } => crate::ErrorCode::Conflict,
528 Error::Contention(_) => crate::ErrorCode::LockContention,
529 Error::Closing(_) => crate::ErrorCode::Closing,
530 Error::Unsupported(_) => crate::ErrorCode::Unsupported,
531 // A resource or action the router offers but the domain does not
532 // register is a wiring bug, not something a client can act on.
533 Error::UnknownResource(_) | Error::UnknownAction { .. } => crate::ErrorCode::Internal,
534 Error::DataLayer { .. } | Error::Serialization(_) => crate::ErrorCode::Internal,
535 };
536
537 let error = JsonApiError::in_request(code, ctx);
538
539 // `detail` is a no-op for the sanitized codes, so this cannot leak a
540 // data-layer message even though it is called unconditionally.
541 error.detail(err.to_string())
542}
543
544/// Your state, as the `ash-domain` bridge sees it.
545///
546/// Implement it once, and [`domain_resource!`](crate::domain_resource!)
547/// writes the [`Resource`](crate::crud::Resource) and per-operation impls for
548/// every resource you mount — so the same [`api!`](crate::api!) that serves a
549/// hand-rolled resource serves a domain-backed one.
550///
551/// ```ignore
552/// impl DomainState for App {
553/// type Backend = InMemoryDataLayer;
554///
555/// fn domain(&self) -> &Domain {
556/// &self.domain
557/// }
558///
559/// fn domain_context(&self, ctx: &Context) -> ash_domain::Context<Self::Backend> {
560/// let mut dctx = ash_domain::Context::new(self.store.clone());
561/// // Carry the request's principal and tenant into the domain, so
562/// // policies see who is asking.
563/// if let Some(tenant) = ctx.tenant() {
564/// dctx.set_tenant(tenant);
565/// }
566/// dctx
567/// }
568/// }
569/// ```
570///
571/// A fresh domain context per request is deliberate: it holds the actor and
572/// tenant the policies evaluate against, and those belong to one request, not
573/// to the process.
574pub trait DomainState: Clone + Send + Sync + 'static {
575 /// The data layer the domain reads and writes through.
576 type Backend: ash_domain::context::Store + Send + Sync + 'static;
577
578 /// The domain to run actions against.
579 fn domain(&self) -> &ash_domain::Domain;
580
581 /// A domain context for one request.
582 ///
583 /// Called once per action. Bind the request's principal and tenant here —
584 /// whatever a policy needs to make its decision — from the JSON:API
585 /// [`Context`], which carries them.
586 fn domain_context(&self, ctx: &Context) -> ash_domain::Context<Self::Backend>;
587
588 /// The mounted schema for one resource, by JSON:API type.
589 ///
590 /// Supplies the base path the domain does not know about. Written by
591 /// [`domain_resource!`](crate::domain_resource!) via
592 /// [`MountedSchemas`].
593 fn mounted(&self, resource: &str) -> Option<Mounted<'_>>;
594}
595
596/// The schemas a [`DomainState`] serves, resolved once at startup.
597///
598/// [`Domain::schema`](ash_domain::Domain::schema) allocates, so resolving a
599/// resource's schema per request would cost a full domain walk on every call.
600/// This holds them alongside the base path each is mounted at.
601///
602/// ```ignore
603/// let schemas = MountedSchemas::new(&domain, [("todo", "/todos")])?;
604/// ```
605pub struct MountedSchemas {
606 schemas: std::collections::BTreeMap<String, (ResourceSchema, String)>,
607}
608
609impl MountedSchemas {
610 /// Resolve each resource's schema and pair it with its base path.
611 ///
612 /// Fails naming the first resource the domain does not register, since a
613 /// route mounted on a resource that does not exist should stop startup
614 /// rather than 500 on its first request.
615 pub fn new<'a>(
616 domain: &ash_domain::Domain,
617 mounts: impl IntoIterator<Item = (&'a str, &'a str)>,
618 ) -> Result<Self, String> {
619 let schema = domain.schema();
620 let mut schemas = std::collections::BTreeMap::new();
621
622 for (name, base_path) in mounts {
623 let resource = schema
624 .resource(name)
625 .ok_or_else(|| format!("the domain registers no resource named `{name}`"))?;
626
627 schemas.insert(name.to_string(), (resource.clone(), base_path.to_string()));
628 }
629
630 Ok(Self { schemas })
631 }
632
633 /// The mounted schema for one resource.
634 pub fn get(&self, resource: &str) -> Option<Mounted<'_>> {
635 self.schemas
636 .get(resource)
637 .map(|(schema, base_path)| Mounted::new(schema, base_path))
638 }
639}
640
641/// A request body on its way to the domain.
642///
643/// The domain reads a document into its own types, so the bridge carries the
644/// validated JSON rather than a struct of its own — a second definition of
645/// the resource is exactly what this integration exists to avoid.
646#[derive(Debug, Clone)]
647pub struct DomainInput(pub serde_json::Value);
648
649/// Serve an `ash-domain` resource over JSON:API.
650///
651/// The ash-domain counterpart to [`resource!`](crate::resource!): where that
652/// derives everything from a field list you write, this derives it from the
653/// schema the domain already holds. Nothing about the resource is restated —
654/// attributes, types, relationships and their cardinality all come from
655/// `#[derive(Resource)]`.
656///
657/// ```ignore
658/// ash_jsonapi::domain_resource! {
659/// Todo as "todo" at "/todos",
660/// state: App,
661/// }
662///
663/// ash_jsonapi::api! {
664/// operations: [ash_jsonapi::CRUD],
665/// resource: Todo, name: "todo", path: "/todos", state: App,
666/// }
667/// ```
668///
669/// `App` implements [`DomainState`]; this writes
670/// [`Resource`](crate::crud::Resource), [`Storage`](crate::crud::Storage) and
671/// the five operation traits in terms of it, so [`api!`](crate::api!) serves a
672/// domain resource exactly as it serves a hand-rolled one.
673///
674/// Every action runs through [`Bound`](ash_domain::domain::Bound) rather than
675/// around it, so policies, extensions and domain validation all apply. A
676/// `Forbidden` becomes `403`, an `Invalid` a `422` pointing at the field, and
677/// a data-layer failure an opaque `500` — see [`error_from`].
678/// A domain resource and its routes, from one declaration.
679///
680/// [`domain_resource!`](crate::domain_resource!) writes the traits and
681/// [`api!`](crate::api!) the routes, and both need the same name, path and
682/// state. Writing them twice is three chances for the two to disagree — and a
683/// mismatched `name` is not a compile error, it is a resource that serializes
684/// as one type and validates as another.
685///
686/// ```ignore
687/// ash_jsonapi::domain_api! {
688/// Todo as "todo" at "/todos",
689/// state: App,
690/// operations: [ash_jsonapi::CRUD],
691/// }
692/// ```
693///
694/// Exactly equivalent to the two macros written out, with each fact stated
695/// once:
696///
697/// ```ignore
698/// ash_jsonapi::domain_resource! {
699/// Todo as "todo" at "/todos",
700/// state: App,
701/// }
702///
703/// ash_jsonapi::api! {
704/// operations: [ash_jsonapi::CRUD],
705/// resource: Todo, name: "todo", path: "/todos", state: App,
706/// }
707/// ```
708///
709/// Use the two directly when they need to diverge — a resource served at two
710/// paths, or one whose traits you write by hand.
711#[macro_export]
712macro_rules! domain_api {
713 (
714 $resource:ident as $name:literal at $base:literal,
715 state: $state:ident,
716 operations: [$($op:tt)+]
717 $(,)?
718 ) => {
719 $crate::domain_resource! {
720 $resource as $name at $base,
721 state: $state,
722 }
723
724 $crate::api! {
725 operations: [$($op)+],
726 resource: $resource,
727 name: $name,
728 path: $base,
729 state: $state,
730 }
731 };
732}
733
734#[macro_export]
735macro_rules! domain_resource {
736 (
737 $resource:ident as $name:literal at $base:literal,
738 state: $state:ident
739 $(,)?
740 ) => {
741 impl $crate::crud::Resource<$state> for $resource {
742 type Create = $crate::domain::DomainInput;
743 type Update = $crate::domain::DomainInput;
744
745 const NAME: &'static str = $name;
746 const PATH: &'static str = $base;
747
748 fn to_resource(
749 &self,
750 state: &$state,
751 ctx: &$crate::context::Context,
752 ) -> ::std::result::Result<
753 $crate::document::ResourceObject,
754 $crate::error::JsonApiError,
755 > {
756 use $crate::domain::DomainState as _;
757 use $crate::__ash_domain::value::IntoRecord as _;
758
759 let mounted = state.mounted($name).ok_or_else(|| {
760 $crate::error::JsonApiError::internal(ctx)
761 .detail(::std::format!("`{}` is not mounted", $name))
762 })?;
763
764 // Serialized from the domain's own `Record`, so the primary
765 // key and every foreign key land where JSON:API puts them
766 // rather than beside the attributes.
767 // Cloned because `IntoRecord` consumes the row, and
768 // serialization borrows it — a handler may still need it.
769 let record = ::std::clone::Clone::clone(self).into_record().map_err(|err| {
770 $crate::error::JsonApiError::internal(ctx).detail(err.to_string())
771 })?;
772
773 ::std::result::Result::Ok(mounted.record_from(&record).build())
774 }
775 }
776
777 impl $crate::extract::FromRequest<$state> for $crate::domain::DomainInput {
778 async fn from_request(
779 request: ::axum::extract::Request,
780 state: &$state,
781 ctx: &$crate::context::Context,
782 ) -> ::std::result::Result<Self, $crate::response::Errors> {
783 let validator = $crate::crud::validator(state, $name, ctx)?;
784 let document = $crate::extract::validated(request, ctx, validator).await?;
785
786 ::std::result::Result::Ok($crate::domain::DomainInput(document))
787 }
788 }
789
790 impl $crate::crud::Create<$resource> for $state {
791 async fn create(
792 &self,
793 input: $crate::domain::DomainInput,
794 ctx: &$crate::context::Context,
795 ) -> ::std::result::Result<$resource, Self::Error> {
796 use $crate::domain::DomainState as _;
797
798 let mounted = self.mounted($name).ok_or_else(|| {
799 $crate::__ash_domain::Error::UnknownResource($name.to_string())
800 })?;
801
802 // The domain's own conversion reads the document, so the
803 // resource is not described a second time here.
804 let record: $crate::__ash_domain::value::Record = mounted
805 .record_for_create(&input.0, ctx)
806 .map_err(|err| $crate::__ash_domain::Error::invalid(err.to_string()))?;
807
808 let mut dctx = self.domain_context(ctx);
809 self.domain().bind(&mut dctx).create::<$resource>(record).await
810 }
811 }
812
813 impl $crate::crud::Read<$resource> for $state {
814 async fn get(
815 &self,
816 id: &str,
817 ) -> ::std::result::Result<::std::option::Option<$resource>, Self::Error> {
818 use $crate::domain::DomainState as _;
819
820 // No request context reaches `get`, so the domain context is
821 // built from an empty one: a read still runs every policy,
822 // just without a principal bound.
823 let ctx = $crate::context::Context::new("");
824 let mut dctx = self.domain_context(&ctx);
825 self.domain().bind(&mut dctx).get::<$resource>(id).await
826 }
827 }
828
829 impl $crate::crud::Update<$resource> for $state {
830 async fn update(
831 &self,
832 id: &str,
833 input: $crate::domain::DomainInput,
834 ctx: &$crate::context::Context,
835 ) -> ::std::result::Result<$resource, Self::Error> {
836 use $crate::domain::DomainState as _;
837
838 let mounted = self.mounted($name).ok_or_else(|| {
839 $crate::__ash_domain::Error::UnknownResource($name.to_string())
840 })?;
841
842 let record: $crate::__ash_domain::value::Record = mounted
843 .record_for_update(&input.0, id, ctx)
844 .map_err(|err| $crate::__ash_domain::Error::invalid(err.to_string()))?;
845
846 let mut dctx = self.domain_context(ctx);
847 self.domain().bind(&mut dctx).update::<$resource>(id, record).await
848 }
849 }
850
851 impl $crate::crud::Delete<$resource> for $state {
852 async fn destroy(&self, id: &str) -> ::std::result::Result<(), Self::Error> {
853 use $crate::domain::DomainState as _;
854
855 let ctx = $crate::context::Context::new("");
856 let mut dctx = self.domain_context(&ctx);
857 self.domain().bind(&mut dctx).destroy::<$resource>(id).await
858 }
859 }
860
861 impl $crate::crud::List<$resource> for $state {
862 async fn list(
863 &self,
864 query: &$crate::query::Query,
865 ctx: &$crate::context::Context,
866 ) -> ::std::result::Result<$crate::crud::Listing<$resource>, Self::Error> {
867 use $crate::domain::DomainState as _;
868
869 // One row past the page, so `next` is a fact rather than a
870 // guess: `Paginator` would otherwise infer "there is more"
871 // from a full page and link the client into an empty one.
872 let probed = $crate::domain::probe_query::<$resource>(query)?;
873
874 let mut dctx = self.domain_context(ctx);
875 let rows = self
876 .domain()
877 .bind(&mut dctx)
878 .read::<$resource>(probed.query)
879 .await?;
880
881 ::std::result::Result::Ok($crate::domain::listing_from(rows, probed.size))
882 }
883 }
884
885 impl $crate::crud::Storage<$resource> for $state {
886 type Error = $crate::__ash_domain::Error;
887
888 fn classify(
889 &self,
890 err: &Self::Error,
891 ctx: &$crate::context::Context,
892 ) -> ::std::option::Option<$crate::error::JsonApiError> {
893 // Most domain outcomes are the client's business: a denial, a
894 // conflict, an invalid field. `error_from` decides which, and
895 // keeps the rest opaque.
896 ::std::option::Option::Some($crate::domain::error_from(err, ctx))
897 }
898 }
899 };
900}
901
902/// The domain's attribute schema, with a `required` list for a create body.
903///
904/// `ResourceSchema::to_json_schema` describes the attributes but marks none
905/// required — the domain records a default, not a nullability flag, so there
906/// is nothing for it to emit. Without a `required` list an empty `attributes`
907/// object passes validation and fails deeper down, where the failure is no
908/// longer attributable to a member.
909///
910/// The rule applied here: an attribute is required on create when it has no
911/// default and is not the primary key. That is what the domain would itself
912/// have to supply a value for.
913#[cfg(feature = "validation")]
914fn required_on_create(schema: &ResourceSchema) -> serde_json::Value {
915 let mut json = schema.to_json_schema();
916
917 let required: Vec<serde_json::Value> = schema
918 .attributes
919 .iter()
920 .filter(|attr| !attr.primary_key && attr.default.is_none())
921 .map(|attr| serde_json::Value::from(attr.name.as_str()))
922 .collect();
923
924 if let Some(object) = json.as_object_mut()
925 && !required.is_empty()
926 {
927 object.insert("required".to_string(), serde_json::Value::Array(required));
928 }
929
930 json
931}
932
933/// A JSON:API collection request as a domain [`Query`](ash_domain::Query).
934///
935/// Offset paging maps directly onto the domain's own offset paging:
936/// `page[offset]` becomes [`Query::offset`](ash_domain::Query::offset) and
937/// `page[limit]` its [`limit`](ash_domain::Query::limit). Cursor paging does
938/// not: the domain resumes from a [`Cursor`](ash_domain::query::Cursor) built
939/// from the sort key's values, not from an opaque string, so a `page[cursor]`
940/// this crate handed out cannot be turned back into one. Rather than
941/// mistranslate it, a cursor request is refused.
942///
943/// Sort keys pass through by name; the domain rejects an attribute the
944/// resource does not declare, which is where that check belongs.
945///
946/// # Why an offset implies a sort
947///
948/// The domain refuses an offset on an unsorted read, and it is right to:
949/// skipping rows of an order nothing pinned down skips *arbitrary* rows, so
950/// page 2 of an unsorted collection is not the page after page 1. But a bare
951/// `GET /todos?page[offset]=25` carries no `?sort=`, and refusing it would
952/// make the most ordinary paged request in JSON:API an error.
953///
954/// So a request that pages past the first row and names no sort is ordered by
955/// the resource's primary key — the one attribute every resource has, and a
956/// total order, which is what paging needs. A client that wants a different
957/// order says so with `?sort=`, and that wins.
958pub fn page_query<R: ash_domain::Resource>(
959 query: &crate::query::Query,
960) -> Result<ash_domain::Query, ash_domain::Error> {
961 let mut domain_query = ash_domain::Query::new(R::NAME);
962
963 for key in query.sort() {
964 domain_query = if key.descending() {
965 domain_query.sort_desc(key.field())
966 } else {
967 domain_query.sort_asc(key.field())
968 };
969 }
970
971 match query.page() {
972 crate::query::Page::Offset { offset, limit } => {
973 let mut domain_query = domain_query.limit(*limit as u32);
974
975 // Only a page past the first needs a position, and only a position
976 // needs an order — a first page keeps the layer's natural order,
977 // exactly as an unpaged read does.
978 if *offset > 0 {
979 // The domain counts offsets in `u32`. A larger one is past the
980 // end of anything the domain can address, and casting would
981 // wrap it into a small offset — silently serving some other
982 // page. Refuse instead.
983 let offset = u32::try_from(*offset).map_err(|_| {
984 ash_domain::Error::invalid(format!(
985 "`page[offset]` of {offset} is larger than this API can \
986 address (the maximum is {})",
987 u32::MAX
988 ))
989 })?;
990
991 if query.sort().is_empty() {
992 domain_query = domain_query.sort_asc(R::primary_key());
993 }
994 domain_query = domain_query.offset(offset);
995 }
996
997 Ok(domain_query)
998 }
999 crate::query::Page::Cursor { .. } => Err(ash_domain::Error::Unsupported(
1000 "this resource pages by `page[offset]`/`page[limit]`; \
1001 `page[cursor]` is not supported over ash-domain"
1002 .to_string(),
1003 )),
1004 }
1005}
1006
1007/// A [`page_query`] that reads one row past the page.
1008///
1009/// Returned by [`probe_query`], and paired with [`listing_from`], which drops
1010/// the extra row and reports it as [`Listing::has_more`](crate::crud::Listing).
1011pub struct Probe {
1012 /// The query to run: the client's page, plus one row.
1013 pub query: ash_domain::Query,
1014 /// The page size the client actually asked for.
1015 pub size: usize,
1016}
1017
1018/// A collection request as a domain query that reads **one row too many**.
1019///
1020/// `next` is otherwise a guess. A `Listing` that reports no total leaves the
1021/// [`Paginator`](crate::Paginator) inferring "there may be more" from a full
1022/// page, so the last full page links to an empty one and the client learns
1023/// the collection ended by fetching nothing. Reading one row past the page
1024/// answers it exactly, for the cost of one row rather than a `COUNT`.
1025///
1026/// This is the same trick ash-domain's
1027/// [`offset_page`](ash_domain::read::OffsetPage) plays, done here because the
1028/// erased read path returns rows rather than a page.
1029///
1030/// Pass the result to [`listing_from`], which puts the page back to the size
1031/// that was asked for.
1032pub fn probe_query<R: ash_domain::Resource>(
1033 query: &crate::query::Query,
1034) -> Result<Probe, ash_domain::Error> {
1035 let size = query.page().size();
1036 let mut probed = page_query::<R>(query)?;
1037
1038 // Saturating, so a page size at the domain's ceiling widens to the
1039 // ceiling rather than wrapping to nothing.
1040 probed.limit = Some(probed.limit.unwrap_or(size as u32).saturating_add(1));
1041
1042 Ok(Probe {
1043 query: probed,
1044 size,
1045 })
1046}
1047
1048/// The rows of a [`probe_query`] as a [`Listing`](crate::crud::Listing).
1049///
1050/// Drops the probe row the client did not ask for, and reports its presence
1051/// as [`has_more`](crate::crud::Listing::has_more) — so the `next` link is
1052/// emitted exactly when there is a next page.
1053///
1054/// Gated with [`crud`](crate::crud) itself, which is where `Listing` lives:
1055/// a `domain`-only build has no HTTP surface to page.
1056#[cfg(all(feature = "http", feature = "validation"))]
1057#[cfg_attr(docsrs, doc(cfg(all(feature = "http", feature = "validation"))))]
1058pub fn listing_from<R>(mut rows: Vec<R>, size: usize) -> crate::crud::Listing<R> {
1059 let has_more = rows.len() > size;
1060 rows.truncate(size);
1061 crate::crud::Listing::new(rows).has_more(has_more)
1062}
1063
1064impl Mounted<'_> {
1065 /// A create document as a domain [`Record`](ash_domain::value::Record).
1066 ///
1067 /// The document has already passed the validator, so what is left is the
1068 /// typed conversion the schema drives.
1069 pub fn record_for_create(
1070 &self,
1071 document: &serde_json::Value,
1072 ctx: &Context,
1073 ) -> Result<DomainRecord, JsonApiError> {
1074 self.read_document(document, ctx)
1075 }
1076
1077 /// An update document as a domain
1078 /// [`Record`](ash_domain::value::Record), with the path's id.
1079 ///
1080 /// A `PATCH` addresses a row that exists, so the URL's id wins over
1081 /// anything the body carries.
1082 pub fn record_for_update(
1083 &self,
1084 document: &serde_json::Value,
1085 id: &str,
1086 ctx: &Context,
1087 ) -> Result<DomainRecord, JsonApiError> {
1088 let mut record = self.read_document(document, ctx)?;
1089 record
1090 .0
1091 .insert(self.schema.primary_key.clone(), Value::Str(id.to_string()));
1092 Ok(record)
1093 }
1094}