1mod check;
7mod crud;
8mod custom;
9mod schema;
10
11pub use check::validate;
12
13use crate::{ServiceManifest, TableDefinition};
14use custom::Components;
15use schema::Nullable;
16use serde_json::{json, Map, Value};
17use std::fmt;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum PathStyle<'a> {
22 Absolute { tenant: &'a str },
25 ServerRelative { tenant: &'a str },
28}
29
30pub fn default_style<'a>(manifest: &ServiceManifest, tenant: &'a str) -> PathStyle<'a> {
33 let documented = manifest.openapi.is_some()
34 || manifest
35 .custom_routes
36 .iter()
37 .any(|route| route.doc.is_some());
38 if documented {
39 PathStyle::ServerRelative { tenant }
40 } else {
41 PathStyle::Absolute { tenant }
42 }
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct OpenApiError(pub String);
48
49impl fmt::Display for OpenApiError {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 f.write_str(&self.0)
52 }
53}
54
55impl std::error::Error for OpenApiError {}
56
57pub fn generate_openapi(
59 manifest: &ServiceManifest,
60 style: PathStyle<'_>,
61) -> Result<Value, OpenApiError> {
62 match style {
63 PathStyle::Absolute { tenant } => Ok(absolute(manifest, tenant)),
64 PathStyle::ServerRelative { tenant } => server_relative(manifest, tenant),
65 }
66}
67
68pub fn service_spec(manifest: &ServiceManifest, tenant: &str) -> Result<Value, OpenApiError> {
71 generate_openapi(manifest, default_style(manifest, tenant))
72}
73
74fn insert_operations(
75 paths: &mut Map<String, Value>,
76 operations: impl IntoIterator<Item = (String, String, Value)>,
77) {
78 for (path, method, operation) in operations {
79 if let Some(obj) = paths
80 .entry(path)
81 .or_insert_with(|| json!({}))
82 .as_object_mut()
83 {
84 obj.insert(method, operation);
85 }
86 }
87}
88
89fn absolute(manifest: &ServiceManifest, tenant_slug: &str) -> Value {
90 let mut paths: Map<String, Value> = manifest
91 .tables
92 .iter()
93 .flat_map(|table| {
94 let base = format!("/svc/{}/{}/{}", tenant_slug, manifest.name, table.name);
95 crud::table_paths(base.clone(), format!("{base}/:id"), table)
96 })
97 .collect();
98 insert_operations(
99 &mut paths,
100 manifest
101 .custom_routes
102 .iter()
103 .filter(|route| custom::published(route))
104 .map(|route| custom::route_operation(tenant_slug, &manifest.name, route)),
105 );
106 let schemas: Map<String, Value> = manifest
107 .tables
108 .iter()
109 .flat_map(|table| schema::table_schemas(table, Nullable::Flag))
110 .chain(std::iter::once(("Pagination".into(), schema::pagination())))
111 .collect();
112
113 json!({
114 "openapi": "3.1.0",
115 "info": {
116 "title": manifest.name,
117 "version": manifest.version.as_deref().unwrap_or("0.1.0")
118 },
119 "paths": Value::Object(paths),
120 "components": {
121 "schemas": Value::Object(schemas)
122 }
123 })
124}
125
126fn table_security(table: &TableDefinition, scheme: &str) -> Vec<Value> {
128 if table.auth_required {
129 vec![json!({ scheme: [] })]
130 } else {
131 Vec::new()
132 }
133}
134
135fn server_relative(manifest: &ServiceManifest, tenant: &str) -> Result<Value, OpenApiError> {
136 validate(manifest)?;
137 let options = manifest.openapi.clone().unwrap_or_default();
138 let scheme = options.security_scheme();
139 let components = Map::from_iter(manifest.components.clone());
140 let lookup = Components(&components);
141
142 let custom: Vec<(String, String, Value)> = manifest
143 .custom_routes
144 .iter()
145 .filter(|route| custom::published(route))
146 .map(|route| {
147 let security = check::route_security(route, scheme);
148 custom::relative_operation(manifest, route, &security, &lookup)
149 })
150 .collect();
151 let crud = manifest.tables.iter().flat_map(|table| {
152 let security = table_security(table, scheme);
153 crud::table_paths(
154 format!("/{}", table.name),
155 format!("/{}/{{id}}", table.name),
156 table,
157 )
158 .into_iter()
159 .map(move |(path, operations)| (path, with_security(operations, &security)))
160 });
161 let mut paths: Map<String, Value> = crud.collect();
162 insert_operations(&mut paths, custom);
163
164 let uses = |name: &str| {
165 paths.values().any(|operations| {
166 operations
167 .as_object()
168 .into_iter()
169 .flatten()
170 .any(|(_, operation)| {
171 operation["security"]
172 .as_array()
173 .is_some_and(|requirements| {
174 requirements.iter().any(|r| r.get(name).is_some())
175 })
176 })
177 })
178 };
179 let security_schemes: Map<String, Value> = [
180 uses(scheme).then(|| {
181 (
182 scheme.to_string(),
183 json!({ "type": "http", "scheme": "bearer" }),
184 )
185 }),
186 uses(check::API_KEY_SCHEME).then(|| {
187 (
188 check::API_KEY_SCHEME.to_string(),
189 json!({ "type": "apiKey", "in": "header", "name": "X-Api-Key" }),
190 )
191 }),
192 ]
193 .into_iter()
194 .flatten()
195 .collect();
196 let schemas: Map<String, Value> = manifest
197 .tables
198 .iter()
199 .flat_map(|table| schema::table_schemas(table, Nullable::TypeUnion))
200 .chain(
201 (!manifest.tables.is_empty()).then(|| ("Pagination".to_string(), schema::pagination())),
202 )
203 .chain(components)
204 .collect();
205 let mut component_map = Map::from_iter([("schemas".to_string(), Value::Object(schemas))]);
206 if !security_schemes.is_empty() {
207 component_map.insert("securitySchemes".into(), Value::Object(security_schemes));
208 }
209
210 let mut info = Map::from_iter([
211 (
212 "title".to_string(),
213 json!(options.title.as_deref().unwrap_or(&manifest.name)),
214 ),
215 (
216 "version".to_string(),
217 json!(options
218 .version
219 .as_deref()
220 .or(manifest.version.as_deref())
221 .unwrap_or("0.1.0")),
222 ),
223 ]);
224 if let Some(description) = &options.description {
225 info.insert("description".into(), json!(description));
226 }
227 let servers = if options.servers.is_empty() {
228 json!([{
229 "url": format!("{{origin}}/svc/{{tenant}}/{}", manifest.name),
230 "variables": {
231 "origin": { "default": "" },
232 "tenant": { "default": tenant },
233 },
234 }])
235 } else {
236 json!(options.servers)
237 };
238 let mut document = Map::from_iter([
239 ("openapi".to_string(), json!("3.1.0")),
240 ("info".to_string(), Value::Object(info)),
241 ("servers".to_string(), servers),
242 ("paths".to_string(), Value::Object(paths)),
243 ("components".to_string(), Value::Object(component_map)),
244 ]);
245 if !options.tags.is_empty() {
246 document.insert("tags".into(), json!(options.tags));
247 }
248 Ok(Value::Object(document))
249}
250
251fn with_security(mut operations: Value, security: &[Value]) -> Value {
253 if !security.is_empty() {
254 operations
255 .as_object_mut()
256 .into_iter()
257 .flat_map(|operations| operations.values_mut())
258 .filter_map(Value::as_object_mut)
259 .for_each(|operation| {
260 operation.insert("security".into(), json!(security));
261 });
262 }
263 operations
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269 use crate::{
270 ColumnDefinition, ColumnType, CustomRouteDefinition, ServiceManifest, ServiceMode,
271 TableDefinition,
272 };
273
274 fn test_manifest() -> ServiceManifest {
275 ServiceManifest {
276 name: "test-service".into(),
277 version: Some("1.0.0".into()),
278 tables: vec![TableDefinition {
279 name: "todos".into(),
280 columns: vec![
281 ColumnDefinition {
282 name: "id".into(),
283 column_type: ColumnType::Uuid,
284 primary_key: true,
285 nullable: false,
286 auto_generate: true,
287 default_value: None,
288 references: None,
289 on_delete: None,
290 unique: false,
291 validations: vec![],
292 },
293 ColumnDefinition {
294 name: "title".into(),
295 column_type: ColumnType::Text,
296 primary_key: false,
297 nullable: false,
298 auto_generate: false,
299 default_value: None,
300 references: None,
301 on_delete: None,
302 unique: false,
303 validations: vec![],
304 },
305 ColumnDefinition {
306 name: "done".into(),
307 column_type: ColumnType::Boolean,
308 primary_key: false,
309 nullable: false,
310 auto_generate: false,
311 default_value: Some("false".into()),
312 references: None,
313 on_delete: None,
314 unique: false,
315 validations: vec![],
316 },
317 ],
318 indexes: vec![],
319 soft_delete: false,
320 owner_field: None,
321 auth_required: false,
322 permission_area: None,
323 owner_self_service: false,
324 hooks: None,
325 scoped_by: None,
326 }],
327 cells: vec![],
328 events: vec![],
329 subscriptions: vec![],
330 custom_routes: vec![],
331 mode: ServiceMode::Crud,
332 authorization: None,
333 on_migrate: None,
334 publishes: None,
335 required_platform_features: vec![],
336 graphql: false,
337 ..Default::default()
338 }
339 }
340
341 #[test]
342 fn test_generates_valid_openapi() {
343 let manifest = test_manifest();
344 let spec = generate_openapi(
345 &manifest,
346 PathStyle::Absolute {
347 tenant: "test-tenant",
348 },
349 )
350 .expect("spec");
351
352 assert_eq!(spec["openapi"], "3.1.0");
353 assert_eq!(spec["info"]["title"], "test-service");
354 assert_eq!(spec["info"]["version"], "1.0.0");
355 }
356
357 #[test]
358 fn test_generates_crud_paths() {
359 let manifest = test_manifest();
360 let spec =
361 generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
362
363 let paths = spec["paths"].as_object().unwrap();
364 assert!(paths.contains_key("/svc/acme/test-service/todos"));
365 assert!(paths.contains_key("/svc/acme/test-service/todos/:id"));
366 }
367
368 #[test]
369 fn test_generates_schemas() {
370 let manifest = test_manifest();
371 let spec =
372 generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
373
374 let schemas = spec["components"]["schemas"].as_object().unwrap();
375 assert!(schemas.contains_key("Todos"));
376 assert!(schemas.contains_key("TodosCreate"));
377 assert!(schemas.contains_key("Pagination"));
378 }
379
380 #[test]
381 fn test_create_schema_excludes_auto_generated() {
382 let manifest = test_manifest();
383 let spec =
384 generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
385
386 let create_props = spec["components"]["schemas"]["TodosCreate"]["properties"]
387 .as_object()
388 .unwrap();
389 assert!(!create_props.contains_key("id"));
391 assert!(create_props.contains_key("title"));
392 }
393
394 #[test]
395 fn test_custom_routes() {
396 let mut manifest = test_manifest();
397 manifest.custom_routes.push(CustomRouteDefinition {
398 method: "POST".into(),
399 path: "/complete/:id".into(),
400 handler: "complete_todo".into(),
401 job: None,
402 posture: None,
403 forward_auth: false,
404 ..Default::default()
405 });
406
407 let spec =
408 generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
409 let paths = spec["paths"].as_object().unwrap();
410 assert!(paths.contains_key("/svc/acme/test-service/_fn/complete_todo"));
411 }
412
413 #[test]
414 fn test_default_version() {
415 let mut manifest = test_manifest();
416 manifest.version = None;
417 let spec =
418 generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
419 assert_eq!(spec["info"]["version"], "0.1.0");
420 }
421
422 #[test]
423 fn output_matches_the_golden_specs() {
424 for (manifest, golden) in [
425 (
426 include_str!("../../fixtures/starmoire_manifest.json"),
427 include_str!("../../fixtures/openapi/starmoire.json"),
428 ),
429 (
430 include_str!("../../fixtures/todo_manifest.json"),
431 include_str!("../../fixtures/openapi/todo.json"),
432 ),
433 (
434 include_str!("../../fixtures/blog_manifest.json"),
435 include_str!("../../fixtures/openapi/blog.json"),
436 ),
437 ] {
438 let manifest: ServiceManifest = serde_json::from_str(manifest).expect("manifest");
439 let golden: Value = serde_json::from_str(golden).expect("golden");
440 assert_eq!(
441 generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec"),
442 golden,
443 "{}",
444 manifest.name
445 );
446 }
447 }
448
449 #[test]
450 fn test_local_slug() {
451 let manifest = test_manifest();
452 let spec =
453 generate_openapi(&manifest, PathStyle::Absolute { tenant: "local" }).expect("spec");
454
455 let paths = spec["paths"].as_object().unwrap();
456 assert!(paths.contains_key("/svc/local/test-service/todos"));
457 }
458
459 fn documented_route(
460 method: &str,
461 path: &str,
462 handler: &str,
463 posture: Option<crate::RoutePosture>,
464 doc: crate::RouteDoc,
465 ) -> CustomRouteDefinition {
466 CustomRouteDefinition {
467 method: method.into(),
468 path: path.into(),
469 handler: handler.into(),
470 posture,
471 doc: Some(doc),
472 ..Default::default()
473 }
474 }
475
476 fn relative(manifest: &ServiceManifest) -> Value {
477 generate_openapi(manifest, PathStyle::ServerRelative { tenant: "acme" }).expect("spec")
478 }
479
480 #[test]
481 fn documented_services_default_to_server_relative_paths() {
482 let mut manifest = test_manifest();
483 assert_eq!(
484 default_style(&manifest, "acme"),
485 PathStyle::Absolute { tenant: "acme" }
486 );
487 manifest.custom_routes.push(documented_route(
488 "GET",
489 "/x",
490 "x",
491 None,
492 crate::RouteDoc::default(),
493 ));
494 assert_eq!(
495 default_style(&manifest, "acme"),
496 PathStyle::ServerRelative { tenant: "acme" }
497 );
498 }
499
500 #[test]
501 fn server_relative_specs_default_their_server_and_use_3_1_nullability() {
502 let mut manifest = test_manifest();
503 manifest.tables[0].columns[1].nullable = true;
504 manifest.openapi = Some(crate::OpenApiOptions::default());
505 let spec = relative(&manifest);
506 assert_eq!(
507 spec["servers"],
508 json!([{"url": "{origin}/svc/{tenant}/test-service",
509 "variables": {"origin": {"default": ""}, "tenant": {"default": "acme"}}}])
510 );
511 let paths = spec["paths"].as_object().expect("paths");
512 assert!(paths.contains_key("/todos") && paths.contains_key("/todos/{id}"));
513 assert_eq!(
514 spec["components"]["schemas"]["Todos"]["properties"]["title"],
515 json!({"type": ["string", "null"]})
516 );
517 assert!(spec.get("tags").is_none());
518 assert!(spec["components"].get("securitySchemes").is_none());
519
520 manifest.openapi = Some(crate::OpenApiOptions {
521 title: Some("Notes".into()),
522 version: Some("2.0.0".into()),
523 description: Some(String::new()),
524 servers: vec![crate::ServerDoc {
525 url: "https://api.example.com/api".into(),
526 description: Some("Production".into()),
527 }],
528 tags: vec![crate::TagDoc {
529 name: "Notes Service".into(),
530 description: Some("Notes Service API".into()),
531 }],
532 security_scheme: None,
533 });
534 let spec = relative(&manifest);
535 assert_eq!(
536 spec["info"],
537 json!({"title": "Notes", "version": "2.0.0", "description": ""})
538 );
539 assert_eq!(
540 spec["servers"],
541 json!([{"url": "https://api.example.com/api", "description": "Production"}])
542 );
543 assert_eq!(
544 spec["tags"],
545 json!([{"name": "Notes Service", "description": "Notes Service API"}])
546 );
547 }
548
549 #[test]
550 fn documented_routes_carry_parameters_bodies_responses_and_security() {
551 use crate::{BodyDoc, MediaDoc, ResponseDoc, RouteDoc, RoutePosture, RoutingMode};
552 let mut manifest = test_manifest();
553 manifest.tables.clear();
554 manifest.routing = RoutingMode::Strict;
555 manifest.components.insert(
556 "ApiNote".into(),
557 json!({"type": "object", "properties": {"id": {"type": "string"}}}),
558 );
559 let doc = RouteDoc {
560 tags: vec!["note".into()],
561 summary: Some("Update a note".into()),
562 deprecated: true,
563 path_params: Some(json!({"type": "object", "required": ["note_id"],
564 "properties": {"note_id": {"type": "string", "description": "Note identifier"}}})),
565 query: Some(
566 json!({"type": "object", "required": ["force"], "properties": {
567 "force": {"type": "boolean"}, "page": {"type": ["integer", "null"], "format": "int32"}}}),
568 ),
569 request: Some(BodyDoc {
570 content_type: "application/json".into(),
571 schema: Some(json!({"$ref": "#/components/schemas/ApiNote"})),
572 required: true,
573 }),
574 responses: [
575 (
576 200,
577 ResponseDoc {
578 description: "Updated".into(),
579 content: vec![MediaDoc {
580 content_type: "application/json".into(),
581 schema: Some(json!({"$ref": "#/components/schemas/ApiNote"})),
582 }],
583 },
584 ),
585 (
586 403,
587 ResponseDoc {
588 description: "Forbidden".into(),
589 content: vec![],
590 },
591 ),
592 ]
593 .into(),
594 ..Default::default()
595 };
596 manifest.custom_routes = vec![
597 documented_route(
598 "PUT",
599 "/notes/{note_id}",
600 "update_note",
601 Some(RoutePosture::Permission {
602 area: "notes".into(),
603 operation: "edit".into(),
604 }),
605 doc,
606 ),
607 documented_route(
608 "GET",
609 "/notes/{note_id}/pdf",
610 "note_pdf",
611 Some(RoutePosture::Public {
612 reason: "shared link".into(),
613 }),
614 RouteDoc {
615 responses: [(
616 200,
617 ResponseDoc {
618 description: "PDF".into(),
619 content: vec![MediaDoc {
620 content_type: "application/pdf".into(),
621 schema: None,
622 }],
623 },
624 )]
625 .into(),
626 ..Default::default()
627 },
628 ),
629 ];
630 let spec = relative(&manifest);
631 let update = &spec["paths"]["/notes/{note_id}"]["put"];
632 assert_eq!(update["operationId"], "update_note");
633 assert_eq!(update["tags"], json!(["note"]));
634 assert_eq!(update["summary"], "Update a note");
635 assert_eq!(update["deprecated"], true);
636 assert_eq!(
637 update["parameters"],
638 json!([
639 {"name": "note_id", "in": "path", "required": true, "schema": {"type": "string"},
640 "description": "Note identifier"},
641 {"name": "force", "in": "query", "required": true, "schema": {"type": "boolean"}},
642 {"name": "page", "in": "query", "required": false,
643 "schema": {"type": ["integer", "null"], "format": "int32"}},
644 ])
645 );
646 assert_eq!(
647 update["requestBody"],
648 json!({"content": {"application/json": {"schema": {"$ref": "#/components/schemas/ApiNote"}}}, "required": true})
649 );
650 assert_eq!(
651 update["responses"]["403"],
652 json!({"description": "Forbidden"})
653 );
654 assert_eq!(update["security"], json!([{"bearer_auth": []}]));
655
656 let pdf = &spec["paths"]["/notes/{note_id}/pdf"]["get"];
657 assert_eq!(pdf["tags"], json!(["test-service"]));
658 assert_eq!(pdf["parameters"][0]["schema"], json!({"type": "string"}));
659 assert_eq!(
660 pdf["responses"]["200"],
661 json!({"description": "PDF", "content": {"application/pdf": {}}})
662 );
663 assert!(
664 pdf.get("security").is_none(),
665 "public routes need no credentials"
666 );
667 assert!(pdf.get("requestBody").is_none());
668 assert_eq!(
669 spec["components"]["securitySchemes"],
670 json!({"bearer_auth": {"type": "http", "scheme": "bearer"}})
671 );
672 assert_eq!(spec["components"]["schemas"]["ApiNote"]["type"], "object");
673 }
674
675 #[test]
676 fn legacy_routes_of_a_documented_service_use_their_fn_alias() {
677 let mut manifest = test_manifest();
678 manifest.custom_routes.push(CustomRouteDefinition {
679 method: "POST".into(),
680 path: "/complete/:id".into(),
681 handler: "complete_todo".into(),
682 posture: Some(crate::RoutePosture::Authenticated),
683 ..Default::default()
684 });
685 manifest.openapi = Some(crate::OpenApiOptions::default());
686 let spec = relative(&manifest);
687 let operation = &spec["paths"]["/_fn/complete_todo"]["post"];
688 assert_eq!(operation["operationId"], "complete_todo");
689 assert_eq!(operation["requestBody"]["required"], false);
690 assert_eq!(operation["responses"]["200"]["description"], "Success");
691 assert_eq!(
692 spec["paths"]["/todos"]["get"]["operationId"], "list_todos",
693 "CRUD operations are server-relative too"
694 );
695 }
696
697 #[test]
698 fn internal_routes_are_left_out_of_both_specs() {
699 let mut manifest = test_manifest();
700 manifest.custom_routes.push(CustomRouteDefinition {
701 method: "POST".into(),
702 path: "/reprice".into(),
703 handler: "reprice".into(),
704 posture: Some(crate::RoutePosture::Internal {
705 callers: vec!["pricing".into()],
706 }),
707 ..Default::default()
708 });
709 let absolute =
710 generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).expect("spec");
711 assert!(absolute["paths"]
712 .get("/svc/acme/test-service/_fn/reprice")
713 .is_none());
714 manifest.openapi = Some(crate::OpenApiOptions::default());
715 assert!(relative(&manifest)["paths"].get("/_fn/reprice").is_none());
716 }
717
718 #[test]
719 fn api_key_routes_require_the_api_key_scheme() {
720 let mut manifest = test_manifest();
721 manifest.openapi = Some(crate::OpenApiOptions::default());
722 manifest.custom_routes.push(CustomRouteDefinition {
723 method: "POST".into(),
724 path: "/ingest".into(),
725 handler: "ingest_lead".into(),
726 posture: Some(crate::RoutePosture::ApiKey {
727 scope: "leads:ingest".into(),
728 }),
729 ..Default::default()
730 });
731 let spec = relative(&manifest);
732 assert_eq!(
733 spec["paths"]["/_fn/ingest_lead"]["post"]["security"],
734 json!([{"api_key": []}])
735 );
736 assert_eq!(
737 spec["components"]["securitySchemes"],
738 json!({"api_key": {"type": "apiKey", "in": "header", "name": "X-Api-Key"}})
739 );
740 }
741
742 #[test]
743 fn a_crud_operation_id_clash_is_a_generation_error() {
744 let mut manifest = test_manifest();
745 manifest.custom_routes.push(documented_route(
746 "GET",
747 "/x",
748 "list_todos",
749 None,
750 crate::RouteDoc::default(),
751 ));
752 assert_eq!(
753 generate_openapi(&manifest, PathStyle::ServerRelative { tenant: "acme" }),
754 Err(OpenApiError(
755 "operation id 'list_todos' is used more than once".into()
756 ))
757 );
758 assert!(
759 generate_openapi(&manifest, PathStyle::Absolute { tenant: "acme" }).is_ok(),
760 "the absolute spec is today's and never refused"
761 );
762 }
763}