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
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![warn(clippy::pedantic, missing_docs)]
#![allow(clippy::wildcard_imports)]
use std::{
any::{type_name, TypeId},
cell::RefCell,
collections::{HashMap, VecDeque},
};
use async_trait::async_trait;
use axum::{
extract::{rejection::JsonRejection, FromRequest},
response::IntoResponse,
BoxError,
};
use http::{Request, StatusCode};
use jsonschema::{
output::{BasicOutput, ErrorDescription, OutputUnit},
JSONSchema,
};
use schemars::{
gen::{SchemaGenerator, SchemaSettings},
JsonSchema,
};
use serde::{de::DeserializeOwned, Serialize};
use serde_json::{Map, Value};
pub struct Json<T>(pub T);
#[async_trait]
impl<S, B, T> FromRequest<S, B> for Json<T>
where
B: http_body::Body + Send + 'static,
B::Data: Send,
B::Error: Into<BoxError>,
S: Send + Sync,
T: DeserializeOwned + JsonSchema + 'static,
{
type Rejection = JsonSchemaRejection;
async fn from_request(req: Request<B>, state: &S) -> Result<Self, Self::Rejection> {
let value: Value = match axum::Json::from_request(req, state).await {
Ok(j) => j.0,
Err(error) => {
return Err(JsonSchemaRejection::Json(error));
}
};
let validation_result = CONTEXT.with(|ctx| {
let ctx = &mut *ctx.borrow_mut();
let schema = ctx.schemas.entry(TypeId::of::<T>()).or_insert_with(|| {
match jsonschema::JSONSchema::compile(
&serde_json::to_value(ctx.generator.root_schema_for::<T>()).unwrap(),
) {
Ok(s) => s,
Err(error) => {
tracing::error!(
%error,
type_name = type_name::<T>(),
"invalid JSON schema for type"
);
JSONSchema::compile(&Value::Object(Map::default())).unwrap()
}
}
});
let out = schema.apply(&value).basic();
match out {
BasicOutput::Valid(_) => Ok(()),
BasicOutput::Invalid(v) => Err(v),
}
});
if let Err(errors) = validation_result {
return Err(JsonSchemaRejection::Schema(errors));
}
match serde_json::from_value(value) {
Ok(v) => Ok(Json(v)),
Err(error) => {
tracing::error!(
%error,
type_name = type_name::<T>(),
"schema validation passed but serde failed"
);
Err(JsonSchemaRejection::Serde(error))
}
}
}
}
impl<T> IntoResponse for Json<T>
where
T: Serialize,
{
fn into_response(self) -> axum::response::Response {
axum::Json(self.0).into_response()
}
}
thread_local! {
static CONTEXT: RefCell<SchemaContext> = RefCell::new(SchemaContext::new());
}
struct SchemaContext {
generator: SchemaGenerator,
schemas: HashMap<TypeId, JSONSchema>,
}
impl SchemaContext {
fn new() -> Self {
Self {
generator: SchemaSettings::draft07()
.with(|g| g.inline_subschemas = true)
.into_generator(),
schemas: HashMap::default(),
}
}
}
#[derive(Debug)]
pub enum JsonSchemaRejection {
Json(JsonRejection),
Serde(serde_json::Error),
Schema(VecDeque<OutputUnit<ErrorDescription>>),
}
#[derive(Debug, Serialize)]
struct JsonSchemaErrorResponse {
pub error: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub schema_validation: Option<VecDeque<OutputUnit<ErrorDescription>>>,
}
impl From<JsonSchemaRejection> for JsonSchemaErrorResponse {
fn from(rejection: JsonSchemaRejection) -> Self {
match rejection {
JsonSchemaRejection::Json(v) => Self {
error: v.to_string(),
schema_validation: None,
},
JsonSchemaRejection::Serde(_) => Self {
error: "invalid request".to_string(),
schema_validation: None,
},
JsonSchemaRejection::Schema(s) => Self {
error: "request schema validation failed".to_string(),
schema_validation: Some(s),
},
}
}
}
impl IntoResponse for JsonSchemaRejection {
fn into_response(self) -> axum::response::Response {
let mut res = axum::Json(JsonSchemaErrorResponse::from(self)).into_response();
*res.status_mut() = StatusCode::BAD_REQUEST;
res
}
}
#[cfg(feature = "aide")]
mod impl_aide {
use super::*;
impl<T> aide::OperationInput for Json<T>
where
T: JsonSchema,
{
fn operation_input(
ctx: &mut aide::gen::GenContext,
operation: &mut aide::openapi::Operation,
) {
axum::Json::<T>::operation_input(ctx, operation);
}
}
impl<T> aide::OperationOutput for Json<T>
where
T: JsonSchema,
{
type Inner = <axum::Json<T> as aide::OperationOutput>::Inner;
fn operation_response(
ctx: &mut aide::gen::GenContext,
op: &mut aide::openapi::Operation,
) -> Option<aide::openapi::Response> {
axum::Json::<T>::operation_response(ctx, op)
}
fn inferred_responses(
ctx: &mut aide::gen::GenContext,
operation: &mut aide::openapi::Operation,
) -> Vec<(Option<u16>, aide::openapi::Response)> {
axum::Json::<T>::inferred_responses(ctx, operation)
}
}
}