1use std::{collections::BTreeMap, future::Future, marker::PhantomData, pin::Pin, sync::Arc};
2
3use axum::{Router, handler::Handler, http::StatusCode, routing};
4use serde_json::{Map, Value, json};
5
6use super::{ViewSet, router::ViewAction};
7use crate::{AppError, AppResult, AppState, CurrentPrincipal};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10pub enum HttpMethod {
11 Get,
12 Post,
13 Put,
14 Patch,
15 Delete,
16}
17
18impl HttpMethod {
19 pub fn openapi_key(self) -> &'static str {
20 match self {
21 Self::Get => "get",
22 Self::Post => "post",
23 Self::Put => "put",
24 Self::Patch => "patch",
25 Self::Delete => "delete",
26 }
27 }
28}
29
30#[derive(Debug, Clone)]
31pub struct ApiSchemaDefinition {
32 pub name: &'static str,
33 pub openapi: Value,
34 pub typescript: &'static str,
35}
36
37pub trait ApiSchema {
38 fn api_schema() -> ApiSchemaDefinition;
39}
40
41#[derive(Debug, Clone)]
42pub struct ClientMethod {
43 pub namespace: &'static str,
44 pub name: &'static str,
45}
46
47#[derive(Debug, Clone)]
48pub struct OperationSpec {
49 pub operation_id: String,
50 pub summary: Option<String>,
51 pub request: Option<ApiSchemaDefinition>,
52 pub response: Option<(u16, ApiSchemaDefinition)>,
53 pub errors: Vec<u16>,
54 pub authenticated: bool,
55 pub client: Option<ClientMethod>,
56 pub multipart: bool,
57 pub body_limit: Option<usize>,
58}
59
60impl OperationSpec {
61 pub fn new(operation_id: impl Into<String>) -> Self {
62 Self {
63 operation_id: operation_id.into(),
64 summary: None,
65 request: None,
66 response: None,
67 errors: Vec::new(),
68 authenticated: false,
69 client: None,
70 multipart: false,
71 body_limit: None,
72 }
73 }
74
75 pub fn summary(mut self, value: impl Into<String>) -> Self {
76 self.summary = Some(value.into());
77 self
78 }
79
80 pub fn request<T: ApiSchema>(mut self) -> Self {
81 self.request = Some(T::api_schema());
82 self
83 }
84
85 pub fn response<T: ApiSchema>(mut self, status: StatusCode) -> Self {
86 self.response = Some((status.as_u16(), T::api_schema()));
87 self
88 }
89
90 pub fn error(mut self, status: StatusCode) -> Self {
91 self.errors.push(status.as_u16());
92 self
93 }
94
95 pub fn authenticated(mut self) -> Self {
96 self.authenticated = true;
97 self
98 }
99
100 pub fn client(mut self, namespace: &'static str, name: &'static str) -> Self {
101 self.client = Some(ClientMethod { namespace, name });
102 self
103 }
104
105 pub fn multipart(mut self) -> Self {
106 self.multipart = true;
107 self
108 }
109
110 pub fn body_limit(mut self, limit: usize) -> Self {
111 self.body_limit = Some(limit);
112 self
113 }
114}
115
116#[derive(Debug, Clone)]
117pub struct ApiOperation {
118 pub extension_id: &'static str,
119 pub operation_id: String,
120 pub method: HttpMethod,
121 pub path: String,
122 pub request: Option<ApiSchemaDefinition>,
123 pub response: Option<(u16, ApiSchemaDefinition)>,
124 pub client: Option<ClientMethod>,
125 pub multipart: bool,
126 pub openapi: Value,
127}
128
129#[derive(Debug, Clone)]
130pub struct ApiExtension {
131 pub id: &'static str,
132 pub operations: Vec<ApiOperation>,
133}
134
135pub type MutationFuture<'a, T> = Pin<Box<dyn Future<Output = AppResult<T>> + Send + 'a>>;
136
137pub trait MutationBackend<V: ViewSet>: Send + Sync + 'static {
139 fn object_permissions(&self) -> bool {
141 false
142 }
143 fn filter_read(&self, queryset: V::QuerySet) -> V::QuerySet {
144 queryset
145 }
146 fn rest<'a>(
148 &'a self,
149 _state: &'a AppState,
150 _principal: Option<&'a CurrentPrincipal>,
151 _action: ViewAction,
152 _id: Option<<V::Model as che_orm::Model>::PrimaryKey>,
153 _headers: &'a axum::http::HeaderMap,
154 _data: Value,
155 ) -> MutationFuture<'a, Option<axum::response::Response>> {
156 Box::pin(async { Ok(None) })
157 }
158 fn save<'a>(
159 &'a self,
160 state: &'a AppState,
161 principal: Option<&'a CurrentPrincipal>,
162 write: crate::ValidatedWrite<V::Model>,
163 ) -> MutationFuture<'a, Option<V::Model>>;
164 fn delete<'a>(
165 &'a self,
166 state: &'a AppState,
167 principal: Option<&'a CurrentPrincipal>,
168 id: <V::Model as che_orm::Model>::PrimaryKey,
169 ) -> MutationFuture<'a, ()>;
170}
171
172pub trait MutationHook<V: ViewSet>: Send + Sync + 'static {
173 fn id(&self) -> &'static str;
174 fn installed(&self, _state: &AppState, _viewset: &V, _hooks: &[Arc<dyn MutationHook<V>>]) {}
175 fn backend(&self) -> Option<&dyn MutationBackend<V>> {
176 None
177 }
178 fn prepare_delete(&self, _model: &V::Model) -> serde_json::Value {
179 serde_json::Value::Null
180 }
181 fn prepare_delete_async<'a>(
182 &'a self,
183 _state: &'a AppState,
184 model: &'a V::Model,
185 ) -> Pin<Box<dyn Future<Output = AppResult<serde_json::Value>> + Send + 'a>> {
186 let value = self.prepare_delete(model);
187 Box::pin(async move { Ok(value) })
188 }
189 fn after_delete(&self, _state: &AppState, _payload: &serde_json::Value) -> AppResult<()> {
190 Ok(())
191 }
192 fn after_commit(
193 &self,
194 _state: &AppState,
195 _current: Option<&CurrentPrincipal>,
196 _action: ViewAction,
197 _model: &V::Model,
198 ) -> AppResult<()> {
199 Ok(())
200 }
201}
202
203pub trait ViewSetExtension<V>: Clone + Send + Sync + 'static
204where
205 V: ViewSet,
206{
207 const ID: &'static str;
208
209 fn install(self, context: &mut ExtensionContext<'_, V>) -> AppResult<()>;
210}
211
212pub struct ViewSetConfig<V: ViewSet> {
213 path: String,
214 router: Router,
215 extensions: Vec<ApiExtension>,
216 schemas: BTreeMap<&'static str, ApiSchemaDefinition>,
217 operation_keys: BTreeMap<(String, HttpMethod), String>,
218 client_keys: BTreeMap<(&'static str, &'static str), String>,
219 hooks: Vec<Arc<dyn MutationHook<V>>>,
220 _marker: PhantomData<fn() -> V>,
221}
222
223impl<V: ViewSet> ViewSetConfig<V> {
224 pub fn new(path: &str) -> Self {
225 Self {
226 path: path.trim_end_matches('/').to_owned(),
227 router: Router::new(),
228 extensions: Vec::new(),
229 schemas: BTreeMap::new(),
230 operation_keys: BTreeMap::new(),
231 client_keys: BTreeMap::new(),
232 hooks: Vec::new(),
233 _marker: PhantomData,
234 }
235 }
236
237 pub fn extend<E>(&mut self, extension: E) -> AppResult<()>
238 where
239 E: ViewSetExtension<V>,
240 {
241 let media = |id: &str| matches!(id, "image-field" | "image-create");
244 let journal_media =
245 |id: &str| matches!(id, "model-sync-image-field" | "model-sync-image-create");
246 let sync = |id: &str| matches!(id, "sync" | "model-sync" | "object-sync");
247 if sync(E::ID) && self.extensions.iter().any(|item| sync(item.id)) {
248 return Err(AppError::BadRequest(
249 "choose exactly one sync protocol per ViewSet".into(),
250 ));
251 }
252 if (sync(E::ID) && self.extensions.iter().any(|item| media(item.id)))
253 || (media(E::ID) && self.extensions.iter().any(|item| sync(item.id)))
254 {
255 return Err(AppError::BadRequest(
256 "sync and direct-write media endpoints cannot share a ViewSet".into(),
257 ));
258 }
259 if (journal_media(E::ID)
260 && self
261 .extensions
262 .iter()
263 .any(|item| sync(item.id) && item.id != "model-sync"))
264 || (sync(E::ID)
265 && E::ID != "model-sync"
266 && self.extensions.iter().any(|item| journal_media(item.id)))
267 {
268 return Err(AppError::BadRequest(
269 "journal-aware media requires protocol 2".into(),
270 ));
271 }
272 if !matches!(E::ID, "image-field" | "model-sync-image-field")
273 && self.extensions.iter().any(|item| item.id == E::ID)
274 {
275 return Err(AppError::BadRequest(format!(
276 "extension `{}` is already installed for {}",
277 E::ID,
278 self.path
279 )));
280 }
281 let mut extension_context = ExtensionContext {
282 config: self,
283 extension_id: E::ID,
284 operations: Vec::new(),
285 };
286 extension.install(&mut extension_context)?;
287 extension_context.config.extensions.push(ApiExtension {
288 id: E::ID,
289 operations: extension_context.operations,
290 });
291 Ok(())
292 }
293
294 pub fn mutation_hook<H: MutationHook<V>>(&mut self, hook: H) -> AppResult<()> {
295 if hook.id().starts_with('@') {
296 return Err(AppError::BadRequest(
297 "mutation hook IDs beginning with @ are reserved".into(),
298 ));
299 }
300 if hook.backend().is_some() && self.hooks.iter().any(|item| item.backend().is_some()) {
301 return Err(AppError::BadRequest("multiple mutation backends".into()));
302 }
303 if self.hooks.iter().any(|item| item.id() == hook.id()) {
304 return Err(AppError::BadRequest(format!(
305 "mutation hook `{}` is already installed for {}",
306 hook.id(),
307 self.path
308 )));
309 }
310 self.hooks.push(Arc::new(hook));
311 Ok(())
312 }
313
314 pub fn into_parts(
315 self,
316 ) -> (
317 Router,
318 Vec<ApiExtension>,
319 Vec<ApiSchemaDefinition>,
320 Vec<Arc<dyn MutationHook<V>>>,
321 ) {
322 (
323 self.router,
324 self.extensions,
325 self.schemas.into_values().collect(),
326 self.hooks,
327 )
328 }
329}
330
331pub struct ExtensionContext<'a, V: ViewSet> {
332 config: &'a mut ViewSetConfig<V>,
333 extension_id: &'static str,
334 operations: Vec<ApiOperation>,
335}
336
337impl<'a, V: ViewSet> ExtensionContext<'a, V> {
338 pub fn route<'route>(
339 &'route mut self,
340 relative_path: &str,
341 configure: impl FnOnce(&mut ExtensionRoute<'route, 'a, V>) -> AppResult<()>,
342 ) -> AppResult<()> {
343 let path = normalize_path(&self.config.path, relative_path)?;
344 let mut route = ExtensionRoute {
345 context: self,
346 path,
347 };
348 configure(&mut route)
349 }
350
351 pub fn mutation_hook<H: MutationHook<V>>(&mut self, hook: H) -> AppResult<()> {
352 self.config.mutation_hook(hook)
353 }
354
355 fn register_schema(&mut self, schema: ApiSchemaDefinition) -> AppResult<()> {
356 if let Some(existing) = self.config.schemas.get(schema.name) {
357 if existing.openapi != schema.openapi || existing.typescript != schema.typescript {
358 return Err(AppError::BadRequest(format!(
359 "conflicting API schema `{}`",
360 schema.name
361 )));
362 }
363 return Ok(());
364 }
365 self.config.schemas.insert(schema.name, schema);
366 Ok(())
367 }
368
369 fn register<H, T>(
370 &mut self,
371 path: String,
372 method: HttpMethod,
373 handler: H,
374 spec: OperationSpec,
375 ) -> AppResult<()>
376 where
377 H: Handler<T, ()> + Clone + Send + Sync + 'static,
378 T: 'static,
379 {
380 let key = (path.clone(), method);
381 if let Some(existing) = self.config.operation_keys.get(&key) {
382 return Err(AppError::BadRequest(format!(
383 "route conflict for {} {} between `{}` and `{}`",
384 method.openapi_key().to_ascii_uppercase(),
385 path,
386 existing,
387 spec.operation_id
388 )));
389 }
390 if let Some(client) = &spec.client {
391 let client_key = (client.namespace, client.name);
392 if let Some(existing) = self.config.client_keys.get(&client_key) {
393 return Err(AppError::BadRequest(format!(
394 "client method conflict for {}.{} between `{}` and `{}`",
395 client.namespace, client.name, existing, spec.operation_id
396 )));
397 }
398 self.config
399 .client_keys
400 .insert(client_key, spec.operation_id.clone());
401 }
402 if let Some(schema) = spec.request.clone() {
403 self.register_schema(schema)?;
404 }
405 if let Some((_, schema)) = spec.response.clone() {
406 self.register_schema(schema)?;
407 }
408 let openapi = operation_json(&spec, method);
409 let limit = spec.body_limit;
410 let router = |method: axum::routing::MethodRouter| match limit {
411 Some(limit) => method.layer(axum::extract::DefaultBodyLimit::max(limit)),
412 None => method,
413 };
414 self.config.router = match method {
415 HttpMethod::Get => self
416 .config
417 .router
418 .clone()
419 .route(&path, router(routing::get(handler))),
420 HttpMethod::Post => self
421 .config
422 .router
423 .clone()
424 .route(&path, router(routing::post(handler))),
425 HttpMethod::Put => self
426 .config
427 .router
428 .clone()
429 .route(&path, router(routing::put(handler))),
430 HttpMethod::Patch => self
431 .config
432 .router
433 .clone()
434 .route(&path, router(routing::patch(handler))),
435 HttpMethod::Delete => self
436 .config
437 .router
438 .clone()
439 .route(&path, router(routing::delete(handler))),
440 };
441 self.config
442 .operation_keys
443 .insert(key, spec.operation_id.clone());
444 self.operations.push(ApiOperation {
445 extension_id: self.extension_id,
446 operation_id: spec.operation_id,
447 method,
448 path,
449 request: spec.request,
450 response: spec.response,
451 client: spec.client,
452 multipart: spec.multipart,
453 openapi,
454 });
455 Ok(())
456 }
457}
458
459pub struct ExtensionRoute<'context, 'config, V: ViewSet> {
460 context: &'context mut ExtensionContext<'config, V>,
461 path: String,
462}
463
464macro_rules! route_method {
465 ($name:ident, $method:ident) => {
466 pub fn $name<H, T>(&mut self, handler: H, spec: OperationSpec) -> AppResult<()>
467 where
468 H: Handler<T, ()> + Clone + Send + Sync + 'static,
469 T: 'static,
470 {
471 self.context
472 .register(self.path.clone(), HttpMethod::$method, handler, spec)
473 }
474 };
475}
476
477impl<V: ViewSet> ExtensionRoute<'_, '_, V> {
478 route_method!(get, Get);
479 route_method!(post, Post);
480 route_method!(put, Put);
481 route_method!(patch, Patch);
482 route_method!(delete, Delete);
483}
484
485fn normalize_path(prefix: &str, relative: &str) -> AppResult<String> {
486 if relative.contains("..") {
487 return Err(AppError::BadRequest(
488 "extension paths may not contain `..`".into(),
489 ));
490 }
491 let relative = relative.trim_matches('/');
492 Ok(format!("{}/{}/", prefix.trim_end_matches('/'), relative))
493}
494
495fn operation_json(spec: &OperationSpec, method: HttpMethod) -> Value {
496 let mut operation = Map::new();
497 operation.insert(
498 "operationId".into(),
499 Value::String(spec.operation_id.clone()),
500 );
501 if let Some(summary) = &spec.summary {
502 operation.insert("summary".into(), Value::String(summary.clone()));
503 }
504 if spec.multipart {
505 let schema = if method == HttpMethod::Delete {
506 json!({"type": "object", "additionalProperties": {"type": "string"}})
507 } else {
508 json!({"type": "object", "properties": {"file": {"type": "string", "format": "binary"}}, "required": ["file"], "additionalProperties": {"type": "string"}})
509 };
510 operation.insert(
511 "requestBody".into(),
512 json!({"required": true, "content": {"multipart/form-data": {"schema": schema}}}),
513 );
514 } else if let Some(request) = &spec.request {
515 operation.insert(
516 "requestBody".into(),
517 json!({"required": true, "content": {"application/json": {"schema": {"$ref": format!("#/components/schemas/{}", request.name)}}}}),
518 );
519 }
520 let mut responses = Map::new();
521 if let Some((status, response)) = &spec.response {
522 responses.insert(
523 status.to_string(),
524 json!({"description": "OK", "content": {"application/json": {"schema": {"$ref": format!("#/components/schemas/{}", response.name)}}}}),
525 );
526 }
527 for status in &spec.errors {
528 responses.insert(status.to_string(), json!({"description": "Error"}));
529 }
530 operation.insert("responses".into(), Value::Object(responses));
531 if spec.authenticated {
532 operation.insert(
533 "security".into(),
534 json!([{"TokenAuth": []}, {"CsrfToken": [], "SessionCookie": []}]),
535 );
536 }
537 Value::Object(operation)
538}
539
540pub fn extension_openapi(extensions: &[ApiExtension]) -> Value {
541 extension_openapi_with_id_schema(extensions, json!({"type": "integer", "format": "int64"}))
542}
543
544pub(crate) fn extension_openapi_with_id_schema(
545 extensions: &[ApiExtension],
546 id_schema: Value,
547) -> Value {
548 let mut paths = Map::<String, Value>::new();
549 for extension in extensions {
550 for operation in &extension.operations {
551 let path = paths
552 .entry(operation.path.clone())
553 .or_insert_with(|| json!({}));
554 let object = path
555 .as_object_mut()
556 .expect("OpenAPI path must be an object");
557 if !object.contains_key("parameters") {
558 let parameters = path_parameters(&operation.path, &id_schema);
559 if !parameters.is_empty() {
560 object.insert("parameters".into(), Value::Array(parameters));
561 }
562 }
563 object.insert(
564 operation.method.openapi_key().into(),
565 operation.openapi.clone(),
566 );
567 }
568 }
569 json!({"paths": paths})
570}
571
572fn path_parameters(path: &str, id_schema: &Value) -> Vec<Value> {
573 path.split('{')
574 .skip(1)
575 .filter_map(|segment| segment.split('}').next())
576 .filter(|name| !name.is_empty())
577 .map(|name| {
578 let schema = if name == "id" {
579 id_schema.clone()
580 } else {
581 json!({"type": "string"})
582 };
583 json!({"in": "path", "name": name, "required": true, "schema": schema})
584 })
585 .collect()
586}
587
588#[cfg(test)]
589mod tests {
590 use super::*;
591
592 #[test]
593 fn uuid_extension_paths_preserve_id_type() {
594 let parameters = path_parameters(
595 "/rules/{id}/run/",
596 &json!({"type":"string","format":"uuid"}),
597 );
598 assert_eq!(
599 parameters[0]["schema"],
600 json!({"type":"string","format":"uuid"})
601 );
602 }
603 use crate::{
604 AllowAny,
605 auth::{AdminUserFilterSet, AdminUserSerializer},
606 };
607 use che_orm::{DatabaseQuery, Model};
608
609 #[derive(Clone, Copy, Default)]
610 struct TestViewSet;
611
612 impl ViewSet for TestViewSet {
613 type Model = crate::auth::User;
614 type Serializer = AdminUserSerializer;
615 type ListSerializer = Self::Serializer;
616 type QuerySet = DatabaseQuery<crate::auth::User>;
617 type FilterSet = AdminUserFilterSet;
618 type Permission = AllowAny;
619
620 fn path(&self) -> &'static str {
621 "/users"
622 }
623
624 fn get_queryset(&self) -> Self::QuerySet {
625 DatabaseQuery::new(crate::auth::User::query())
626 }
627 }
628
629 #[derive(Clone, Copy)]
630 struct PingExtension;
631
632 impl ViewSetExtension<TestViewSet> for PingExtension {
633 const ID: &'static str = "ping";
634
635 fn install(self, context: &mut ExtensionContext<'_, TestViewSet>) -> AppResult<()> {
636 context.route("/{id}/ping/", |route| {
637 route.get(
638 || async { "pong" },
639 OperationSpec::new("ping.retrieve")
640 .response::<PingResponse>(StatusCode::OK)
641 .client("ping", "retrieve"),
642 )
643 })
644 }
645 }
646
647 struct PingResponse;
648
649 impl ApiSchema for PingResponse {
650 fn api_schema() -> ApiSchemaDefinition {
651 ApiSchemaDefinition {
652 name: "PingResponse",
653 openapi: json!({"type": "string"}),
654 typescript: "export type PingResponse = string;",
655 }
656 }
657 }
658
659 #[test]
660 fn extension_operation_builds_openapi_from_registered_route() {
661 let mut config = ViewSetConfig::<TestViewSet>::new("/users");
662 config.extend(PingExtension).unwrap();
663 let (_, extensions, schemas, _) = config.into_parts();
664
665 assert_eq!(extensions[0].operations[0].path, "/users/{id}/ping/");
666 assert_eq!(extensions[0].operations[0].method, HttpMethod::Get);
667 assert_eq!(schemas[0].name, "PingResponse");
668 let openapi = extension_openapi(&extensions);
669 assert!(openapi["paths"]["/users/{id}/ping/"]["get"].is_object());
670 assert_eq!(
671 openapi["paths"]["/users/{id}/ping/"]["parameters"][0]["name"],
672 "id"
673 );
674 }
675
676 #[test]
677 fn duplicate_extension_is_rejected() {
678 let mut config = ViewSetConfig::<TestViewSet>::new("/users");
679 config.extend(PingExtension).unwrap();
680 assert!(config.extend(PingExtension).is_err());
681 }
682}