1use shaperail_core::{FieldType, HttpMethod, ResourceDefinition, WASM_HOOK_PREFIX};
2
3#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
5pub struct Diagnostic {
6 pub code: &'static str,
8 pub error: String,
10 pub fix: String,
12 pub example: String,
14}
15
16impl std::fmt::Display for Diagnostic {
17 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
18 write!(f, "[{}] {}", self.code, self.error)
19 }
20}
21
22pub fn diagnose_resource(rd: &ResourceDefinition) -> Vec<Diagnostic> {
25 let mut diags = Vec::new();
26 let res = &rd.resource;
27
28 if res.is_empty() {
29 diags.push(Diagnostic {
30 code: "SR001",
31 error: "resource name must not be empty".into(),
32 fix: "add a snake_case plural name to the 'resource' key".into(),
33 example: "resource: users".into(),
34 });
35 }
36
37 if rd.version == 0 {
38 diags.push(Diagnostic {
39 code: "SR002",
40 error: format!("resource '{res}': version must be >= 1"),
41 fix: "set version to 1 or higher".into(),
42 example: "version: 1".into(),
43 });
44 }
45
46 if rd.schema.is_empty() {
47 diags.push(Diagnostic {
48 code: "SR003",
49 error: format!("resource '{res}': schema must have at least one field"),
50 fix: "add at least an id field to the schema section".into(),
51 example: "schema:\n id: { type: uuid, primary: true, generated: true }".into(),
52 });
53 }
54
55 let primary_count = rd.schema.values().filter(|f| f.primary).count();
56 if primary_count == 0 && !rd.schema.is_empty() {
57 diags.push(Diagnostic {
58 code: "SR004",
59 error: format!("resource '{res}': schema must have a primary key field"),
60 fix: "add 'primary: true' to one field (typically 'id')".into(),
61 example: "id: { type: uuid, primary: true, generated: true }".into(),
62 });
63 } else if primary_count > 1 {
64 diags.push(Diagnostic {
65 code: "SR005",
66 error: format!(
67 "resource '{res}': schema must have exactly one primary key, found {primary_count}"
68 ),
69 fix: "remove 'primary: true' from all fields except one".into(),
70 example: "id: { type: uuid, primary: true, generated: true }".into(),
71 });
72 }
73
74 for (name, field) in &rd.schema {
75 if field.field_type == FieldType::Enum && field.values.is_none() {
76 diags.push(Diagnostic {
77 code: "SR010",
78 error: format!("resource '{res}': field '{name}' is type enum but has no values"),
79 fix: format!("add 'values: [value1, value2]' to the '{name}' field"),
80 example: format!("{name}: {{ type: enum, values: [option_a, option_b] }}"),
81 });
82 }
83
84 if field.field_type != FieldType::Enum && field.values.is_some() {
85 diags.push(Diagnostic {
86 code: "SR011",
87 error: format!("resource '{res}': field '{name}' has values but is not type enum"),
88 fix: format!("change the type to 'enum' or remove 'values' from '{name}'"),
89 example: format!("{name}: {{ type: enum, values: [...] }}"),
90 });
91 }
92
93 if field.reference.is_some() && field.field_type != FieldType::Uuid {
94 diags.push(Diagnostic {
95 code: "SR012",
96 error: format!("resource '{res}': field '{name}' has ref but is not type uuid"),
97 fix: format!("change the type of '{name}' to uuid"),
98 example: format!(
99 "{name}: {{ type: uuid, ref: {}, required: true }}",
100 field.reference.as_deref().unwrap_or("resource.id")
101 ),
102 });
103 }
104
105 if let Some(ref reference) = field.reference {
106 if !reference.contains('.') {
107 diags.push(Diagnostic {
108 code: "SR013",
109 error: format!(
110 "resource '{res}': field '{name}' ref must be in 'resource.field' format, got '{reference}'"
111 ),
112 fix: "use 'resource_name.field_name' format for the ref value".into(),
113 example: format!("{name}: {{ type: uuid, ref: organizations.id }}"),
114 });
115 }
116 }
117
118 if field.field_type == FieldType::Array && field.items.is_none() {
119 diags.push(Diagnostic {
120 code: "SR014",
121 error: format!("resource '{res}': field '{name}' is type array but has no items"),
122 fix: format!("add 'items: <element_type>' to the '{name}' field"),
123 example: format!("{name}: {{ type: array, items: string }}"),
124 });
125 }
126
127 if let Some(items_spec) = &field.items {
128 if items_spec.field_type == FieldType::Array {
129 diags.push(Diagnostic {
130 code: "SR076",
131 error: format!("resource '{res}': field '{name}' has nested array items"),
132 fix: "change items to type: json (nested arrays are not supported)".to_string(),
133 example: format!("{name}: {{ type: json }}"),
134 });
135 }
136 if items_spec.field_type == FieldType::Enum && items_spec.values.is_none() {
137 diags.push(Diagnostic {
138 code: "SR077",
139 error: format!("resource '{res}': field '{name}' enum items missing values"),
140 fix: "add `values: [...]` to items".to_string(),
141 example: format!(
142 "{name}: {{ type: array, items: {{ type: enum, values: [a, b] }} }}"
143 ),
144 });
145 }
146 if items_spec.format.is_some() && items_spec.field_type != FieldType::String {
147 diags.push(Diagnostic {
148 code: "SR078",
149 error: format!(
150 "resource '{res}': field '{name}' items.format only valid on string"
151 ),
152 fix: "remove items.format or change items.type to string".to_string(),
153 example: format!(
154 "{name}: {{ type: array, items: {{ type: string, format: email }} }}"
155 ),
156 });
157 }
158 if items_spec.reference.is_some() && items_spec.field_type != FieldType::Uuid {
159 diags.push(Diagnostic {
160 code: "SR079",
161 error: format!(
162 "resource '{res}': field '{name}' items.ref requires items.type uuid"
163 ),
164 fix: "change items.type to uuid, or remove items.ref".to_string(),
165 example: format!(
166 "{name}: {{ type: array, items: {{ type: uuid, ref: organizations.id }} }}"
167 ),
168 });
169 }
170 if let Some(reference) = &items_spec.reference {
171 if !reference.contains('.') {
172 diags.push(Diagnostic {
173 code: "SR080",
174 error: format!(
175 "resource '{res}': field '{name}' items.ref must be 'resource.field'"
176 ),
177 fix: "write items.ref as 'resource_name.column_name'".to_string(),
178 example: "items: { type: uuid, ref: organizations.id }".to_string(),
179 });
180 }
181 }
182 }
183
184 if field.format.is_some() && field.field_type != FieldType::String {
185 diags.push(Diagnostic {
186 code: "SR015",
187 error: format!(
188 "resource '{res}': field '{name}' has format but is not type string"
189 ),
190 fix: format!("change the type of '{name}' to string, or remove 'format'"),
191 example: format!(
192 "{name}: {{ type: string, format: {} }}",
193 field.format.as_deref().unwrap_or("email")
194 ),
195 });
196 }
197
198 if field.primary && !field.generated && !field.required {
199 diags.push(Diagnostic {
200 code: "SR016",
201 error: format!(
202 "resource '{res}': primary key field '{name}' must be generated or required"
203 ),
204 fix: format!("add 'generated: true' or 'required: true' to '{name}'"),
205 example: format!("{name}: {{ type: uuid, primary: true, generated: true }}"),
206 });
207 }
208 }
209
210 if let Some(ref tenant_key) = rd.tenant_key {
212 match rd.schema.get(tenant_key) {
213 Some(field) => {
214 if field.field_type != FieldType::Uuid {
215 diags.push(Diagnostic {
216 code: "SR020",
217 error: format!(
218 "resource '{res}': tenant_key '{tenant_key}' must reference a uuid field, found {}",
219 field.field_type
220 ),
221 fix: format!("change the type of '{tenant_key}' to uuid"),
222 example: format!(
223 "{tenant_key}: {{ type: uuid, ref: organizations.id, required: true }}"
224 ),
225 });
226 }
227 }
228 None => {
229 diags.push(Diagnostic {
230 code: "SR021",
231 error: format!(
232 "resource '{res}': tenant_key '{tenant_key}' not found in schema"
233 ),
234 fix: format!("add a '{tenant_key}' uuid field to the schema"),
235 example: format!(
236 "{tenant_key}: {{ type: uuid, ref: organizations.id, required: true }}"
237 ),
238 });
239 }
240 }
241 }
242
243 if let Some(endpoints) = &rd.endpoints {
245 for (action, ep) in endpoints {
246 if let Some(controller) = &ep.controller {
247 if let Some(before) = &controller.before {
248 if before.is_empty() {
249 diags.push(Diagnostic {
250 code: "SR030",
251 error: format!(
252 "resource '{res}': endpoint '{action}' has an empty controller.before name"
253 ),
254 fix: "provide a function name for controller.before".into(),
255 example: "controller: { before: validate_input }".into(),
256 });
257 }
258 diagnose_controller_name(res, action, "before", before, &mut diags);
259 }
260 if let Some(after) = &controller.after {
261 if after.is_empty() {
262 diags.push(Diagnostic {
263 code: "SR031",
264 error: format!(
265 "resource '{res}': endpoint '{action}' has an empty controller.after name"
266 ),
267 fix: "provide a function name for controller.after".into(),
268 example: "controller: { after: enrich_response }".into(),
269 });
270 }
271 diagnose_controller_name(res, action, "after", after, &mut diags);
272 }
273 }
274
275 if let Some(events) = &ep.events {
276 for event in events {
277 if event.is_empty() {
278 diags.push(Diagnostic {
279 code: "SR032",
280 error: format!(
281 "resource '{res}': endpoint '{action}' has an empty event name"
282 ),
283 fix: "use 'resource.action' format for event names".into(),
284 example: format!("events: [{res}.created]"),
285 });
286 }
287 }
288 }
289
290 if let Some(jobs) = &ep.jobs {
291 for job in jobs {
292 if job.is_empty() {
293 diags.push(Diagnostic {
294 code: "SR033",
295 error: format!(
296 "resource '{res}': endpoint '{action}' has an empty job name"
297 ),
298 fix: "provide a snake_case job name".into(),
299 example: "jobs: [send_notification]".into(),
300 });
301 }
302 }
303 }
304
305 for (field_kind, fields) in [
307 ("input", &ep.input),
308 ("filter", &ep.filters),
309 ("search", &ep.search),
310 ("sort", &ep.sort),
311 ] {
312 if let Some(fields) = fields {
313 for field_name in fields {
314 if !rd.schema.contains_key(field_name) {
315 diags.push(Diagnostic {
316 code: "SR040",
317 error: format!(
318 "resource '{res}': endpoint '{action}' {field_kind} field '{field_name}' not found in schema"
319 ),
320 fix: format!(
321 "add '{field_name}' to the schema, or remove it from {field_kind}"
322 ),
323 example: format!("{field_name}: {{ type: string, required: true }}"),
324 });
325 }
326 }
327 }
328 }
329
330 if ep.soft_delete && !rd.schema.contains_key("deleted_at") {
331 diags.push(Diagnostic {
332 code: "SR041",
333 error: format!(
334 "resource '{res}': endpoint '{action}' has soft_delete but schema has no 'deleted_at' field"
335 ),
336 fix: "add 'deleted_at: { type: timestamp, nullable: true }' to the schema".into(),
337 example: "deleted_at: { type: timestamp, nullable: true }".into(),
338 });
339 }
340
341 if let Some(upload) = &ep.upload {
342 if !matches!(
343 *ep.method(),
344 HttpMethod::Post | HttpMethod::Patch | HttpMethod::Put
345 ) {
346 diags.push(Diagnostic {
347 code: "SR050",
348 error: format!(
349 "resource '{res}': endpoint '{action}' uses upload but method must be POST, PATCH, or PUT"
350 ),
351 fix: "change the method to POST, PATCH, or PUT".into(),
352 example: "method: POST".into(),
353 });
354 }
355
356 match rd.schema.get(&upload.field) {
357 Some(field) if field.field_type == FieldType::File => {}
358 Some(_) => diags.push(Diagnostic {
359 code: "SR051",
360 error: format!(
361 "resource '{res}': endpoint '{action}' upload field '{}' must be type file",
362 upload.field
363 ),
364 fix: format!("change '{}' to type file in the schema", upload.field),
365 example: format!("{}: {{ type: file, required: true }}", upload.field),
366 }),
367 None => diags.push(Diagnostic {
368 code: "SR052",
369 error: format!(
370 "resource '{res}': endpoint '{action}' upload field '{}' not found in schema",
371 upload.field
372 ),
373 fix: format!("add '{}' as a file field in the schema", upload.field),
374 example: format!("{}: {{ type: file, required: true }}", upload.field),
375 }),
376 }
377
378 if !matches!(upload.storage.as_str(), "local" | "s3" | "gcs" | "azure") {
379 diags.push(Diagnostic {
380 code: "SR053",
381 error: format!(
382 "resource '{res}': endpoint '{action}' upload storage '{}' is invalid",
383 upload.storage
384 ),
385 fix: "use one of: local, s3, gcs, azure".into(),
386 example: "upload: { field: file, storage: s3, max_size: 5mb }".into(),
387 });
388 }
389
390 if !ep
391 .input
392 .as_ref()
393 .is_some_and(|fields| fields.iter().any(|field| field == &upload.field))
394 {
395 diags.push(Diagnostic {
396 code: "SR054",
397 error: format!(
398 "resource '{res}': endpoint '{action}' upload field '{}' must appear in input",
399 upload.field
400 ),
401 fix: format!("add '{}' to the input array", upload.field),
402 example: format!("input: [{}]", upload.field),
403 });
404 }
405 }
406
407 if let Some(subs) = &ep.subscribers {
409 for (i, sub) in subs.iter().enumerate() {
410 if sub.event.is_empty() {
411 diags.push(Diagnostic {
412 code: "SR073",
413 error: format!(
414 "resource '{res}': endpoint '{action}' subscriber[{i}] has an empty event pattern"
415 ),
416 fix: "provide a non-empty event pattern (e.g., \"user.created\" or \"*.deleted\")".into(),
417 example: format!(
418 "subscribers:\n - event: {res}.created\n handler: my_handler"
419 ),
420 });
421 }
422 if sub.handler.is_empty() {
423 diags.push(Diagnostic {
424 code: "SR074",
425 error: format!(
426 "resource '{res}': endpoint '{action}' subscriber[{i}] has an empty handler name"
427 ),
428 fix: "provide a non-empty handler name (e.g., \"send_welcome_email\")".into(),
429 example: "subscribers:\n - event: user.created\n handler: send_welcome_email".into(),
430 });
431 }
432 }
433 }
434
435 const CONVENTIONS: &[&str] = &["list", "get", "create", "update", "delete"];
437 if !CONVENTIONS.contains(&action.as_str()) && ep.handler.is_none() {
438 diags.push(Diagnostic {
439 code: "SR075",
440 error: format!(
441 "resource '{res}': endpoint '{action}' is not a standard action (list/get/create/update/delete) and has no 'handler:' declared",
442 ),
443 fix: "add a 'handler: <function_name>' field pointing to a function in resources/<resource>.controller.rs".into(),
444 example: format!(
445 "{action}:\n method: POST\n path: /{name}/{action}\n auth: [admin]\n handler: {action}_{name}",
446 action = action,
447 name = rd.resource
448 ),
449 });
450 }
451 }
452 }
453
454 if let Some(relations) = &rd.relations {
456 for (name, rel) in relations {
457 use shaperail_core::RelationType;
458
459 if rel.relation_type == RelationType::BelongsTo && rel.key.is_none() {
460 diags.push(Diagnostic {
461 code: "SR060",
462 error: format!(
463 "resource '{res}': relation '{name}' is belongs_to but has no key"
464 ),
465 fix: format!("add 'key: {res}_id' to the relation (the local FK field)"),
466 example: format!(
467 "{name}: {{ resource: {}, type: belongs_to, key: {}_id }}",
468 rel.resource, rel.resource
469 ),
470 });
471 }
472
473 if matches!(
474 rel.relation_type,
475 RelationType::HasMany | RelationType::HasOne
476 ) && rel.foreign_key.is_none()
477 {
478 diags.push(Diagnostic {
479 code: "SR061",
480 error: format!(
481 "resource '{res}': relation '{name}' is {} but has no foreign_key",
482 rel.relation_type
483 ),
484 fix: format!(
485 "add 'foreign_key: {res}_id' to the relation (the FK on the related table)"
486 ),
487 example: format!(
488 "{name}: {{ resource: {}, type: {}, foreign_key: {res}_id }}",
489 rel.resource, rel.relation_type
490 ),
491 });
492 }
493
494 if let Some(key) = &rel.key {
495 if !rd.schema.contains_key(key) {
496 diags.push(Diagnostic {
497 code: "SR062",
498 error: format!(
499 "resource '{res}': relation '{name}' key '{key}' not found in schema"
500 ),
501 fix: format!("add '{key}' as a uuid field in the schema"),
502 example: format!(
503 "{key}: {{ type: uuid, ref: {}.id, required: true }}",
504 rel.resource
505 ),
506 });
507 }
508 }
509 }
510 }
511
512 if let Some(indexes) = &rd.indexes {
514 for (i, idx) in indexes.iter().enumerate() {
515 if idx.fields.is_empty() {
516 diags.push(Diagnostic {
517 code: "SR070",
518 error: format!("resource '{res}': index {i} has no fields"),
519 fix: "add at least one field to the index".into(),
520 example: "- { fields: [field_name] }".into(),
521 });
522 }
523 for field_name in &idx.fields {
524 if !rd.schema.contains_key(field_name) {
525 diags.push(Diagnostic {
526 code: "SR071",
527 error: format!(
528 "resource '{res}': index {i} references field '{field_name}' not in schema"
529 ),
530 fix: format!("add '{field_name}' to the schema, or remove it from the index"),
531 example: format!("{field_name}: {{ type: string, required: true }}"),
532 });
533 }
534 }
535 if let Some(order) = &idx.order {
536 if order != "asc" && order != "desc" {
537 diags.push(Diagnostic {
538 code: "SR072",
539 error: format!(
540 "resource '{res}': index {i} has invalid order '{order}', must be 'asc' or 'desc'"
541 ),
542 fix: "use 'asc' or 'desc' for the index order".into(),
543 example: "- { fields: [created_at], order: desc }".into(),
544 });
545 }
546 }
547 }
548 }
549
550 diags
551}
552
553fn diagnose_controller_name(
554 res: &str,
555 action: &str,
556 phase: &str,
557 name: &str,
558 diags: &mut Vec<Diagnostic>,
559) {
560 if let Some(wasm_path) = name.strip_prefix(WASM_HOOK_PREFIX) {
561 if wasm_path.is_empty() {
562 diags.push(Diagnostic {
563 code: "SR035",
564 error: format!(
565 "resource '{res}': endpoint '{action}' controller.{phase} has 'wasm:' prefix but no path"
566 ),
567 fix: "provide a .wasm file path after the 'wasm:' prefix".into(),
568 example: format!("controller: {{ {phase}: \"wasm:./plugins/validator.wasm\" }}"),
569 });
570 } else if !wasm_path.ends_with(".wasm") {
571 diags.push(Diagnostic {
572 code: "SR036",
573 error: format!(
574 "resource '{res}': endpoint '{action}' controller.{phase} WASM path must end with '.wasm', got '{wasm_path}'"
575 ),
576 fix: "ensure the WASM plugin path ends with '.wasm'".into(),
577 example: format!("controller: {{ {phase}: \"wasm:./plugins/validator.wasm\" }}"),
578 });
579 }
580 }
581}
582
583#[cfg(test)]
584mod tests {
585 use super::*;
586 use crate::parser::parse_resource;
587
588 #[test]
589 fn valid_resource_produces_no_diagnostics() {
590 let yaml = include_str!("../../resources/users.yaml");
591 let rd = parse_resource(yaml).unwrap();
592 let diags = diagnose_resource(&rd);
593 assert!(diags.is_empty(), "Expected no diagnostics, got: {diags:?}");
594 }
595
596 #[test]
597 fn enum_without_values_has_fix_suggestion() {
598 let yaml = r#"
599resource: items
600version: 1
601schema:
602 id: { type: uuid, primary: true, generated: true }
603 status: { type: enum, required: true }
604"#;
605 let rd = parse_resource(yaml).unwrap();
606 let diags = diagnose_resource(&rd);
607 let d = diags.iter().find(|d| d.code == "SR010").unwrap();
608 assert!(d.fix.contains("values"));
609 assert!(d.example.contains("values:"));
610 }
611
612 #[test]
613 fn missing_primary_key_has_fix_suggestion() {
614 let yaml = r#"
615resource: items
616version: 1
617schema:
618 name: { type: string, required: true }
619"#;
620 let rd = parse_resource(yaml).unwrap();
621 let diags = diagnose_resource(&rd);
622 let d = diags.iter().find(|d| d.code == "SR004").unwrap();
623 assert!(d.fix.contains("primary: true"));
624 }
625
626 #[test]
627 fn diagnostics_serialize_to_json() {
628 let d = Diagnostic {
629 code: "SR010",
630 error: "field 'role' is type enum but has no values".into(),
631 fix: "add values".into(),
632 example: "role: { type: enum, values: [a, b] }".into(),
633 };
634 let json = serde_json::to_string(&d).unwrap();
635 assert!(json.contains("SR010"));
636 assert!(json.contains("fix"));
637 }
638
639 #[test]
640 fn subscriber_with_empty_event_has_fix_suggestion() {
641 let yaml = r#"
642resource: items
643version: 1
644schema:
645 id: { type: uuid, primary: true, generated: true }
646endpoints:
647 create:
648 auth: [admin]
649 subscribers:
650 - event: ""
651 handler: my_handler
652"#;
653 let rd = parse_resource(yaml).unwrap();
654 let diags = diagnose_resource(&rd);
655 let d = diags.iter().find(|d| d.code == "SR073");
656 assert!(
657 d.is_some(),
658 "Expected SR073 diagnostic for empty subscriber event"
659 );
660 assert!(d.unwrap().fix.contains("event"));
661 }
662
663 #[test]
664 fn subscriber_with_empty_handler_has_fix_suggestion() {
665 let yaml = r#"
666resource: items
667version: 1
668schema:
669 id: { type: uuid, primary: true, generated: true }
670endpoints:
671 create:
672 auth: [admin]
673 subscribers:
674 - event: items.created
675 handler: ""
676"#;
677 let rd = parse_resource(yaml).unwrap();
678 let diags = diagnose_resource(&rd);
679 let d = diags.iter().find(|d| d.code == "SR074");
680 assert!(
681 d.is_some(),
682 "Expected SR074 diagnostic for empty subscriber handler"
683 );
684 assert!(d.unwrap().fix.contains("handler"));
685 }
686
687 #[test]
688 fn non_convention_endpoint_without_handler_produces_sr075() {
689 let yaml = r#"
690resource: items
691version: 1
692schema:
693 id: { type: uuid, primary: true, generated: true }
694endpoints:
695 archive:
696 method: POST
697 path: /items/:id/archive
698 auth: [admin]
699"#;
700 let rd = parse_resource(yaml).unwrap();
701 let diags = diagnose_resource(&rd);
702 let d = diags.iter().find(|d| d.code == "SR075");
703 assert!(
704 d.is_some(),
705 "Expected SR075 for non-convention endpoint missing handler"
706 );
707 assert!(d.unwrap().fix.contains("handler"));
708 }
709
710 #[test]
711 fn non_convention_endpoint_with_handler_no_sr075() {
712 let yaml = r#"
713resource: items
714version: 1
715schema:
716 id: { type: uuid, primary: true, generated: true }
717endpoints:
718 archive:
719 method: POST
720 path: /items/:id/archive
721 auth: [admin]
722 handler: archive_item
723"#;
724 let rd = parse_resource(yaml).unwrap();
725 let diags = diagnose_resource(&rd);
726 let has_sr075 = diags.iter().any(|d| d.code == "SR075");
727 assert!(!has_sr075, "SR075 should not fire when handler is present");
728 }
729}