use ash_domain::schema::{RelationshipSchema, ResourceSchema, SchemaType};
use ash_domain::value::{Record as DomainRecord, Value};
use crate::context::Context;
use crate::error::JsonApiError;
use crate::serialize::{Record, RelationshipDef, Schema, Serializer};
impl RelationshipDef for RelationshipSchema {
fn name(&self) -> &str {
&self.name
}
fn target(&self) -> &str {
&self.destination
}
fn is_to_many(&self) -> bool {
matches!(self.cardinality, "has_many" | "many_to_many")
}
}
#[derive(Debug, Clone, Copy)]
pub struct Mounted<'a> {
pub schema: &'a ResourceSchema,
pub base_path: &'a str,
}
impl<'a> Mounted<'a> {
pub fn new(schema: &'a ResourceSchema, base_path: &'a str) -> Self {
Self { schema, base_path }
}
pub fn record(&self, id: &str) -> Record<'_, Self> {
Serializer::new(self).record(id)
}
pub fn self_link(&self, id: &str) -> String {
Serializer::new(self).self_link(id)
}
pub fn record_from(&self, record: &DomainRecord) -> Record<'_, Self> {
let id = match record.get(&self.schema.primary_key) {
Some(Value::Str(s)) => s.clone(),
Some(other) => render(other).to_string(),
None => String::new(),
};
let hidden = |key: &String| {
key == &self.schema.primary_key
|| self
.schema
.relationships
.iter()
.any(|rel| &rel.source_attribute == key)
};
let attributes = record
.0
.iter()
.filter(|(key, _)| !hidden(key))
.map(|(key, value)| (key.clone(), render(value)));
self.record(&id).attrs(attributes)
}
}
fn render(value: &Value) -> serde_json::Value {
match value {
Value::Null => serde_json::Value::Null,
Value::Bool(b) => (*b).into(),
Value::Int(i) => (*i).into(),
Value::Float(f) => serde_json::Number::from_f64(*f)
.map(serde_json::Value::Number)
.unwrap_or(serde_json::Value::Null),
Value::Str(s) => s.clone().into(),
Value::Bytes(_) => serde_json::Value::Null,
Value::Timestamp(ms) => (*ms).into(),
Value::Map(map) => {
serde_json::Value::Object(map.iter().map(|(k, v)| (k.clone(), render(v))).collect())
}
Value::List(items) => serde_json::Value::Array(items.iter().map(render).collect()),
}
}
impl Schema for Mounted<'_> {
type Relationship = RelationshipSchema;
fn name(&self) -> &str {
&self.schema.name
}
fn relationships(&self) -> &[RelationshipSchema] {
&self.schema.relationships
}
fn base_path(&self) -> &str {
self.base_path
}
}
#[macro_export]
macro_rules! resource_schema {
($name:literal $({ $($member:tt)* })?) => {{
#[allow(unused_mut)]
let mut attributes: ::std::vec::Vec<
$crate::__ash_domain::schema::AttributeSchema,
> = ::std::vec::Vec::new();
#[allow(unused_mut)]
let mut relationships: ::std::vec::Vec<
$crate::__ash_domain::schema::RelationshipSchema,
> = ::std::vec::Vec::new();
$($crate::__schema_members!(attributes, relationships, $($member)*);)?
$crate::__ash_domain::schema::ResourceSchema {
name: ::std::string::String::from($name),
storage_name: ::std::string::String::from($name),
primary_key: ::std::string::String::from("id"),
version_attribute: ::std::option::Option::None,
tenant: ::std::option::Option::None,
attributes,
relationships,
aggregates: ::std::vec::Vec::new(),
computed: ::std::vec::Vec::new(),
actions: ::std::vec::Vec::new(),
}
}};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __schema_members {
($attrs:ident, $rels:ident $(,)?) => {};
($attrs:ident, $rels:ident, $name:ident : $ty:ident $(, $($rest:tt)*)?) => {
$attrs.extend([$crate::__ash_domain::schema::AttributeSchema {
name: ::std::string::String::from(::std::stringify!($name)),
ty: $crate::__ash_domain::schema::SchemaType::$ty,
default: ::std::option::Option::None,
primary_key: false,
attribute_policy: false,
}]);
$($crate::__schema_members!($attrs, $rels, $($rest)*);)?
};
($attrs:ident, $rels:ident, $name:ident -> $target:tt $(, $($rest:tt)*)?) => {
$rels.extend([$crate::__relationship_schema!($name -> $target)]);
$($crate::__schema_members!($attrs, $rels, $($rest)*);)?
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! __relationship_schema {
($name:ident -> [$target:literal]) => {
$crate::__relationship_schema!(@build $name, $target, "has_many")
};
($name:ident -> $target:literal) => {
$crate::__relationship_schema!(@build $name, $target, "belongs_to")
};
(@build $name:ident, $target:literal, $cardinality:literal) => {
$crate::__ash_domain::schema::RelationshipSchema {
name: ::std::string::String::from(::std::stringify!($name)),
destination: ::std::string::String::from($target),
cardinality: $cardinality,
source_attribute: ::std::string::String::from("id"),
destination_attribute: ::std::string::String::from("id"),
through: ::std::option::Option::None,
}
};
}
impl<'a> Mounted<'a> {
pub fn parse_create<R>(
&self,
document: &serde_json::Value,
ctx: &Context,
) -> Result<R, JsonApiError>
where
R: ash_domain::FromRecord + ash_domain::value::IntoRecord + Default,
{
self.parse_document(document, None, ctx)
}
pub fn parse_update<R>(
&self,
document: &serde_json::Value,
id: &str,
ctx: &Context,
) -> Result<R, JsonApiError>
where
R: ash_domain::FromRecord + ash_domain::value::IntoRecord + Default,
{
self.parse_document(document, Some(id), ctx)
}
fn parse_document<R>(
&self,
document: &serde_json::Value,
id: Option<&str>,
ctx: &Context,
) -> Result<R, JsonApiError>
where
R: ash_domain::FromRecord + ash_domain::value::IntoRecord + Default,
{
let mut record = R::default()
.into_record()
.map_err(|err| JsonApiError::internal(ctx).detail(err.to_string()))?;
let supplied = self.read_document(document, ctx)?;
record.0.extend(supplied.0);
if let Some(id) = id {
record
.0
.insert(self.schema.primary_key.clone(), Value::Str(id.to_string()));
}
R::from_record(&record).map_err(|err| {
JsonApiError::invalid(ctx, err.to_string(), "/data/attributes")
})
}
}
impl Mounted<'_> {
fn read_document(
&self,
document: &serde_json::Value,
ctx: &Context,
) -> Result<DomainRecord, JsonApiError> {
let invalid =
|detail: String, pointer: &str| JsonApiError::invalid(ctx, detail, pointer.to_string());
let data = document
.get("data")
.ok_or_else(|| invalid("`data` is required".into(), "/data"))?;
let mut record = DomainRecord::new();
if let Some(attributes) = data.get("attributes").and_then(|a| a.as_object()) {
for attribute in &self.schema.attributes {
if attribute.name == self.schema.primary_key {
continue;
}
let value = match attributes.get(&attribute.name) {
Some(json) => coerce(json, &attribute.ty).ok_or_else(|| {
invalid(
format!("`{}` is not of the declared type", attribute.name),
&format!("/data/attributes/{}", attribute.name),
)
})?,
None => continue,
};
record.0.insert(attribute.name.clone(), value);
}
}
if let Some(relationships) = data.get("relationships").and_then(|r| r.as_object()) {
for rel in &self.schema.relationships {
let Some(id) = relationships
.get(&rel.name)
.and_then(|r| r.get("data"))
.and_then(|d| d.get("id"))
.and_then(|id| id.as_str())
else {
continue;
};
record
.0
.insert(rel.source_attribute.clone(), Value::Str(id.to_string()));
}
}
Ok(record)
}
}
fn coerce(json: &serde_json::Value, ty: &SchemaType) -> Option<Value> {
if json.is_null() {
return Some(Value::Null);
}
match ty {
SchemaType::Boolean => json.as_bool().map(Value::Bool),
SchemaType::Integer => json.as_i64().map(Value::Int),
SchemaType::Number => json.as_f64().map(Value::Float),
SchemaType::String => json.as_str().map(|s| Value::Str(s.to_string())),
SchemaType::Reference { .. } => json.as_str().map(|s| Value::Str(s.to_string())),
SchemaType::Opaque { .. } => json.as_str().map(|s| Value::Str(s.to_string())),
SchemaType::Embed { .. } | SchemaType::EmbedList { .. } => {
serde_json::from_value(json.clone()).ok()
}
SchemaType::Bytes => None,
}
}
#[cfg(feature = "validation")]
#[cfg_attr(docsrs, doc(cfg(feature = "validation")))]
impl crate::validation::DocumentValidator {
pub fn for_create(schema: &ResourceSchema) -> Result<Self, crate::validation::BuildError> {
let hidden: Vec<&str> = std::iter::once(schema.primary_key.as_str())
.chain(
schema
.relationships
.iter()
.map(|rel| rel.source_attribute.as_str()),
)
.collect();
let mounted = Mounted::new(schema, "");
Self::builder(&mounted)
.attributes(required_on_create(schema))
.hide(hidden)
.build()
}
}
pub fn error_from(err: &ash_domain::Error, ctx: &Context) -> JsonApiError {
use ash_domain::Error;
let code = match err {
Error::NotFound(_) => crate::ErrorCode::NotFound,
Error::Forbidden(_) => crate::ErrorCode::Forbidden,
Error::PolicyError(_) => crate::ErrorCode::PolicyUnavailable,
Error::MissingTenant(_) => crate::ErrorCode::MissingTenant,
Error::Invalid { field, message } => {
let pointer = match field {
Some(field) => format!("/data/attributes/{}", field.replace('.', "/")),
None => "/data".to_string(),
};
return JsonApiError::invalid(ctx, message.clone(), pointer);
}
Error::Conflict { .. } => crate::ErrorCode::Conflict,
Error::Contention(_) => crate::ErrorCode::LockContention,
Error::Closing(_) => crate::ErrorCode::Closing,
Error::Unsupported(_) => crate::ErrorCode::Unsupported,
Error::UnknownResource(_) | Error::UnknownAction { .. } => crate::ErrorCode::Internal,
Error::DataLayer { .. } | Error::Serialization(_) => crate::ErrorCode::Internal,
};
let error = JsonApiError::in_request(code, ctx);
error.detail(err.to_string())
}
pub trait DomainState: Clone + Send + Sync + 'static {
type Backend: ash_domain::context::Store + Send + Sync + 'static;
fn domain(&self) -> &ash_domain::Domain;
fn domain_context(&self, ctx: &Context) -> ash_domain::Context<Self::Backend>;
fn mounted(&self, resource: &str) -> Option<Mounted<'_>>;
}
pub struct MountedSchemas {
schemas: std::collections::BTreeMap<String, (ResourceSchema, String)>,
}
impl MountedSchemas {
pub fn new<'a>(
domain: &ash_domain::Domain,
mounts: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> Result<Self, String> {
let schema = domain.schema();
let mut schemas = std::collections::BTreeMap::new();
for (name, base_path) in mounts {
let resource = schema
.resource(name)
.ok_or_else(|| format!("the domain registers no resource named `{name}`"))?;
schemas.insert(name.to_string(), (resource.clone(), base_path.to_string()));
}
Ok(Self { schemas })
}
pub fn get(&self, resource: &str) -> Option<Mounted<'_>> {
self.schemas
.get(resource)
.map(|(schema, base_path)| Mounted::new(schema, base_path))
}
}
#[derive(Debug, Clone)]
pub struct DomainInput(pub serde_json::Value);
#[macro_export]
macro_rules! domain_api {
(
$resource:ident as $name:literal at $base:literal,
state: $state:ident,
operations: [$($op:tt)+]
$(,)?
) => {
$crate::domain_resource! {
$resource as $name at $base,
state: $state,
}
$crate::api! {
operations: [$($op)+],
resource: $resource,
name: $name,
path: $base,
state: $state,
}
};
}
#[macro_export]
macro_rules! domain_resource {
(
$resource:ident as $name:literal at $base:literal,
state: $state:ident
$(,)?
) => {
impl $crate::crud::Resource<$state> for $resource {
type Create = $crate::domain::DomainInput;
type Update = $crate::domain::DomainInput;
const NAME: &'static str = $name;
const PATH: &'static str = $base;
fn to_resource(
&self,
state: &$state,
ctx: &$crate::context::Context,
) -> ::std::result::Result<
$crate::document::ResourceObject,
$crate::error::JsonApiError,
> {
use $crate::domain::DomainState as _;
use $crate::__ash_domain::value::IntoRecord as _;
let mounted = state.mounted($name).ok_or_else(|| {
$crate::error::JsonApiError::internal(ctx)
.detail(::std::format!("`{}` is not mounted", $name))
})?;
let record = ::std::clone::Clone::clone(self).into_record().map_err(|err| {
$crate::error::JsonApiError::internal(ctx).detail(err.to_string())
})?;
::std::result::Result::Ok(mounted.record_from(&record).build())
}
}
impl $crate::extract::FromRequest<$state> for $crate::domain::DomainInput {
async fn from_request(
request: ::axum::extract::Request,
state: &$state,
ctx: &$crate::context::Context,
) -> ::std::result::Result<Self, $crate::response::Errors> {
let validator = $crate::crud::validator(state, $name, ctx)?;
let document = $crate::extract::validated(request, ctx, validator).await?;
::std::result::Result::Ok($crate::domain::DomainInput(document))
}
}
impl $crate::crud::Create<$resource> for $state {
async fn create(
&self,
input: $crate::domain::DomainInput,
ctx: &$crate::context::Context,
) -> ::std::result::Result<$resource, Self::Error> {
use $crate::domain::DomainState as _;
let mounted = self.mounted($name).ok_or_else(|| {
$crate::__ash_domain::Error::UnknownResource($name.to_string())
})?;
let record: $crate::__ash_domain::value::Record = mounted
.record_for_create(&input.0, ctx)
.map_err(|err| $crate::__ash_domain::Error::invalid(err.to_string()))?;
let mut dctx = self.domain_context(ctx);
self.domain().bind(&mut dctx).create::<$resource>(record).await
}
}
impl $crate::crud::Read<$resource> for $state {
async fn get(
&self,
id: &str,
) -> ::std::result::Result<::std::option::Option<$resource>, Self::Error> {
use $crate::domain::DomainState as _;
let ctx = $crate::context::Context::new("");
let mut dctx = self.domain_context(&ctx);
self.domain().bind(&mut dctx).get::<$resource>(id).await
}
}
impl $crate::crud::Update<$resource> for $state {
async fn update(
&self,
id: &str,
input: $crate::domain::DomainInput,
ctx: &$crate::context::Context,
) -> ::std::result::Result<$resource, Self::Error> {
use $crate::domain::DomainState as _;
let mounted = self.mounted($name).ok_or_else(|| {
$crate::__ash_domain::Error::UnknownResource($name.to_string())
})?;
let record: $crate::__ash_domain::value::Record = mounted
.record_for_update(&input.0, id, ctx)
.map_err(|err| $crate::__ash_domain::Error::invalid(err.to_string()))?;
let mut dctx = self.domain_context(ctx);
self.domain().bind(&mut dctx).update::<$resource>(id, record).await
}
}
impl $crate::crud::Delete<$resource> for $state {
async fn destroy(&self, id: &str) -> ::std::result::Result<(), Self::Error> {
use $crate::domain::DomainState as _;
let ctx = $crate::context::Context::new("");
let mut dctx = self.domain_context(&ctx);
self.domain().bind(&mut dctx).destroy::<$resource>(id).await
}
}
impl $crate::crud::List<$resource> for $state {
async fn list(
&self,
query: &$crate::query::Query,
ctx: &$crate::context::Context,
) -> ::std::result::Result<$crate::crud::Listing<$resource>, Self::Error> {
use $crate::domain::DomainState as _;
let probed = $crate::domain::probe_query::<$resource>(query)?;
let mut dctx = self.domain_context(ctx);
let rows = self
.domain()
.bind(&mut dctx)
.read::<$resource>(probed.query)
.await?;
::std::result::Result::Ok($crate::domain::listing_from(rows, probed.size))
}
}
impl $crate::crud::Storage<$resource> for $state {
type Error = $crate::__ash_domain::Error;
fn classify(
&self,
err: &Self::Error,
ctx: &$crate::context::Context,
) -> ::std::option::Option<$crate::error::JsonApiError> {
::std::option::Option::Some($crate::domain::error_from(err, ctx))
}
}
};
}
#[cfg(feature = "validation")]
fn required_on_create(schema: &ResourceSchema) -> serde_json::Value {
let mut json = schema.to_json_schema();
let required: Vec<serde_json::Value> = schema
.attributes
.iter()
.filter(|attr| !attr.primary_key && attr.default.is_none())
.map(|attr| serde_json::Value::from(attr.name.as_str()))
.collect();
if let Some(object) = json.as_object_mut()
&& !required.is_empty()
{
object.insert("required".to_string(), serde_json::Value::Array(required));
}
json
}
pub fn page_query<R: ash_domain::Resource>(
query: &crate::query::Query,
) -> Result<ash_domain::Query, ash_domain::Error> {
let mut domain_query = ash_domain::Query::new(R::NAME);
for key in query.sort() {
domain_query = if key.descending() {
domain_query.sort_desc(key.field())
} else {
domain_query.sort_asc(key.field())
};
}
match query.page() {
crate::query::Page::Offset { offset, limit } => {
let mut domain_query = domain_query.limit(*limit as u32);
if *offset > 0 {
let offset = u32::try_from(*offset).map_err(|_| {
ash_domain::Error::invalid(format!(
"`page[offset]` of {offset} is larger than this API can \
address (the maximum is {})",
u32::MAX
))
})?;
if query.sort().is_empty() {
domain_query = domain_query.sort_asc(R::primary_key());
}
domain_query = domain_query.offset(offset);
}
Ok(domain_query)
}
crate::query::Page::Cursor { .. } => Err(ash_domain::Error::Unsupported(
"this resource pages by `page[offset]`/`page[limit]`; \
`page[cursor]` is not supported over ash-domain"
.to_string(),
)),
}
}
pub struct Probe {
pub query: ash_domain::Query,
pub size: usize,
}
pub fn probe_query<R: ash_domain::Resource>(
query: &crate::query::Query,
) -> Result<Probe, ash_domain::Error> {
let size = query.page().size();
let mut probed = page_query::<R>(query)?;
probed.limit = Some(probed.limit.unwrap_or(size as u32).saturating_add(1));
Ok(Probe {
query: probed,
size,
})
}
#[cfg(all(feature = "http", feature = "validation"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "http", feature = "validation"))))]
pub fn listing_from<R>(mut rows: Vec<R>, size: usize) -> crate::crud::Listing<R> {
let has_more = rows.len() > size;
rows.truncate(size);
crate::crud::Listing::new(rows).has_more(has_more)
}
impl Mounted<'_> {
pub fn record_for_create(
&self,
document: &serde_json::Value,
ctx: &Context,
) -> Result<DomainRecord, JsonApiError> {
self.read_document(document, ctx)
}
pub fn record_for_update(
&self,
document: &serde_json::Value,
id: &str,
ctx: &Context,
) -> Result<DomainRecord, JsonApiError> {
let mut record = self.read_document(document, ctx)?;
record
.0
.insert(self.schema.primary_key.clone(), Value::Str(id.to_string()));
Ok(record)
}
}