shaperail-codegen 0.8.0

YAML parser, validator, and code generator for Shaperail
Documentation
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
use shaperail_core::{FieldType, HttpMethod, ResourceDefinition, WASM_HOOK_PREFIX};

/// A semantic validation error for a resource definition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationError {
    pub message: String,
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

/// Validate a parsed `ResourceDefinition` for semantic correctness.
///
/// Returns a list of all validation errors found. An empty list means the
/// resource is valid.
pub fn validate_resource(rd: &ResourceDefinition) -> Vec<ValidationError> {
    let mut errors = Vec::new();
    let res = &rd.resource;

    // Resource name must not be empty
    if res.is_empty() {
        errors.push(err("resource name must not be empty"));
    }

    // Version must be >= 1
    if rd.version == 0 {
        errors.push(err(&format!("resource '{res}': version must be >= 1")));
    }

    // Schema must have at least one field
    if rd.schema.is_empty() {
        errors.push(err(&format!(
            "resource '{res}': schema must have at least one field"
        )));
    }

    // Must have exactly one primary key
    let primary_count = rd.schema.values().filter(|f| f.primary).count();
    if primary_count == 0 {
        errors.push(err(&format!(
            "resource '{res}': schema must have a primary key field"
        )));
    } else if primary_count > 1 {
        errors.push(err(&format!(
            "resource '{res}': schema must have exactly one primary key, found {primary_count}"
        )));
    }

    // Per-field validation
    for (name, field) in &rd.schema {
        // Enum type requires values
        if field.field_type == FieldType::Enum && field.values.is_none() {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' is type enum but has no values"
            )));
        }

        // Non-enum type should not have values
        if field.field_type != FieldType::Enum && field.values.is_some() {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' has values but is not type enum"
            )));
        }

        // Ref field must be uuid type
        if field.reference.is_some() && field.field_type != FieldType::Uuid {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' has ref but is not type uuid"
            )));
        }

        // Ref format must be "resource.field"
        if let Some(ref reference) = field.reference {
            if !reference.contains('.') {
                errors.push(err(&format!(
                    "resource '{res}': field '{name}' ref must be in 'resource.field' format, got '{reference}'"
                )));
            }
        }

        // Array type requires items
        if field.field_type == FieldType::Array && field.items.is_none() {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' is type array but has no items"
            )));
        }

        // Format only valid for string type
        if field.format.is_some() && field.field_type != FieldType::String {
            errors.push(err(&format!(
                "resource '{res}': field '{name}' has format but is not type string"
            )));
        }

        // Primary key should be generated or required
        if field.primary && !field.generated && !field.required {
            errors.push(err(&format!(
                "resource '{res}': primary key field '{name}' must be generated or required"
            )));
        }
    }

    // Tenant key validation (M18)
    if let Some(ref tenant_key) = rd.tenant_key {
        match rd.schema.get(tenant_key) {
            Some(field) => {
                if field.field_type != FieldType::Uuid {
                    errors.push(err(&format!(
                        "resource '{res}': tenant_key '{tenant_key}' must reference a uuid field, found {}",
                        field.field_type
                    )));
                }
            }
            None => {
                errors.push(err(&format!(
                    "resource '{res}': tenant_key '{tenant_key}' not found in schema"
                )));
            }
        }
    }

    // Endpoint validation
    if let Some(endpoints) = &rd.endpoints {
        for (action, ep) in endpoints {
            // method and path must be set (either explicitly or via convention defaults)
            if ep.method.is_none() {
                errors.push(err(&format!(
                    "resource '{res}': endpoint '{action}' has no method. Use a known action name (list, get, create, update, delete) or set method explicitly"
                )));
            }
            if ep.path.is_none() {
                errors.push(err(&format!(
                    "resource '{res}': endpoint '{action}' has no path. Use a known action name (list, get, create, update, delete) or set path explicitly"
                )));
            }

            if let Some(controller) = &ep.controller {
                if let Some(before) = &controller.before {
                    if before.is_empty() {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' has an empty controller.before name"
                        )));
                    }
                    validate_controller_name(res, action, "before", before, &mut errors);
                }
                if let Some(after) = &controller.after {
                    if after.is_empty() {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' has an empty controller.after name"
                        )));
                    }
                    validate_controller_name(res, action, "after", after, &mut errors);
                }
            }

            if let Some(events) = &ep.events {
                for event in events {
                    if event.is_empty() {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' has an empty event name"
                        )));
                    }
                }
            }

            if let Some(jobs) = &ep.jobs {
                for job in jobs {
                    if job.is_empty() {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' has an empty job name"
                        )));
                    }
                }
            }

            // Input fields must exist in schema
            if let Some(input) = &ep.input {
                for field_name in input {
                    if !rd.schema.contains_key(field_name) {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' input field '{field_name}' not found in schema"
                        )));
                    }
                }
            }

            // Filter fields must exist in schema
            if let Some(filters) = &ep.filters {
                for field_name in filters {
                    if !rd.schema.contains_key(field_name) {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' filter field '{field_name}' not found in schema"
                        )));
                    }
                }
            }

            // Search fields must exist in schema
            if let Some(search) = &ep.search {
                for field_name in search {
                    if !rd.schema.contains_key(field_name) {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' search field '{field_name}' not found in schema"
                        )));
                    }
                }
            }

            // Sort fields must exist in schema
            if let Some(sort) = &ep.sort {
                for field_name in sort {
                    if !rd.schema.contains_key(field_name) {
                        errors.push(err(&format!(
                            "resource '{res}': endpoint '{action}' sort field '{field_name}' not found in schema"
                        )));
                    }
                }
            }

            // soft_delete requires updated_at field in schema
            if ep.soft_delete && !rd.schema.contains_key("updated_at") {
                errors.push(err(&format!(
                    "resource '{res}': endpoint '{action}' has soft_delete but schema has no 'updated_at' field"
                )));
            }

            if let Some(upload) = &ep.upload {
                match ep.method.as_ref() {
                    Some(HttpMethod::Post | HttpMethod::Patch | HttpMethod::Put) => {}
                    Some(_) => errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' uses upload but method must be POST, PATCH, or PUT"
                    ))),
                    None => {} // already reported above
                }

                match rd.schema.get(&upload.field) {
                    Some(field) if field.field_type == FieldType::File => {}
                    Some(_) => errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' upload field '{}' must be type file",
                        upload.field
                    ))),
                    None => errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' upload field '{}' not found in schema",
                        upload.field
                    ))),
                }

                if !matches!(upload.storage.as_str(), "local" | "s3" | "gcs" | "azure") {
                    errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' upload storage '{}' is invalid",
                        upload.storage
                    )));
                }

                if !ep
                    .input
                    .as_ref()
                    .is_some_and(|fields| fields.iter().any(|field| field == &upload.field))
                {
                    errors.push(err(&format!(
                        "resource '{res}': endpoint '{action}' upload field '{}' must appear in input",
                        upload.field
                    )));
                }

                for (suffix, expected_types) in [
                    ("filename", &[FieldType::String][..]),
                    ("mime_type", &[FieldType::String][..]),
                    ("size", &[FieldType::Integer, FieldType::Bigint][..]),
                ] {
                    let companion = format!("{}_{}", upload.field, suffix);
                    if let Some(field) = rd.schema.get(&companion) {
                        if !expected_types.contains(&field.field_type) {
                            let expected = expected_types
                                .iter()
                                .map(ToString::to_string)
                                .collect::<Vec<_>>()
                                .join(" or ");
                            errors.push(err(&format!(
                                "resource '{res}': companion upload field '{companion}' must be type {expected}"
                            )));
                        }
                    }
                }
            }
        }
    }

    // Relation validation
    if let Some(relations) = &rd.relations {
        for (name, rel) in relations {
            use shaperail_core::RelationType;

            // belongs_to should have key
            if rel.relation_type == RelationType::BelongsTo && rel.key.is_none() {
                errors.push(err(&format!(
                    "resource '{res}': relation '{name}' is belongs_to but has no key"
                )));
            }

            // has_many/has_one should have foreign_key
            if matches!(
                rel.relation_type,
                RelationType::HasMany | RelationType::HasOne
            ) && rel.foreign_key.is_none()
            {
                errors.push(err(&format!(
                    "resource '{res}': relation '{name}' is {} but has no foreign_key",
                    rel.relation_type
                )));
            }

            // belongs_to key must exist in schema
            if let Some(key) = &rel.key {
                if !rd.schema.contains_key(key) {
                    errors.push(err(&format!(
                        "resource '{res}': relation '{name}' key '{key}' not found in schema"
                    )));
                }
            }
        }
    }

    // Index validation
    if let Some(indexes) = &rd.indexes {
        for (i, idx) in indexes.iter().enumerate() {
            if idx.fields.is_empty() {
                errors.push(err(&format!("resource '{res}': index {i} has no fields")));
            }
            for field_name in &idx.fields {
                if !rd.schema.contains_key(field_name) {
                    errors.push(err(&format!(
                        "resource '{res}': index {i} references field '{field_name}' not in schema"
                    )));
                }
            }
            if let Some(order) = &idx.order {
                if order != "asc" && order != "desc" {
                    errors.push(err(&format!(
                        "resource '{res}': index {i} has invalid order '{order}', must be 'asc' or 'desc'"
                    )));
                }
            }
        }
    }

    errors
}

/// Validates a controller name — either a Rust function name or a `wasm:` prefixed path.
fn validate_controller_name(
    res: &str,
    action: &str,
    phase: &str,
    name: &str,
    errors: &mut Vec<ValidationError>,
) {
    if let Some(wasm_path) = name.strip_prefix(WASM_HOOK_PREFIX) {
        if wasm_path.is_empty() {
            errors.push(err(&format!(
                "resource '{res}': endpoint '{action}' controller.{phase} has 'wasm:' prefix but no path"
            )));
        } else if !wasm_path.ends_with(".wasm") {
            errors.push(err(&format!(
                "resource '{res}': endpoint '{action}' controller.{phase} WASM path must end with '.wasm', got '{wasm_path}'"
            )));
        }
    }
}

fn err(message: &str) -> ValidationError {
    ValidationError {
        message: message.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::parse_resource;

    #[test]
    fn valid_resource_passes() {
        let yaml = include_str!("../../resources/users.yaml");
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.is_empty(), "Expected no errors, got: {errors:?}");
    }

    #[test]
    fn enum_without_values() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  status: { type: enum, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("type enum but has no values")));
    }

    #[test]
    fn ref_field_not_uuid() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  org_id: { type: string, ref: organizations.id }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("has ref but is not type uuid")));
    }

    #[test]
    fn missing_primary_key() {
        let yaml = r#"
resource: items
version: 1
schema:
  name: { type: string, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("must have a primary key")));
    }

    #[test]
    fn soft_delete_without_updated_at() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  delete:
    method: DELETE
    path: /items/:id
    auth: [admin]
    soft_delete: true
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("soft_delete but schema has no 'updated_at'")));
    }

    #[test]
    fn input_field_not_in_schema() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /items
    auth: [admin]
    input: [name, nonexistent]
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("input field 'nonexistent' not found in schema")));
    }

    #[test]
    fn belongs_to_without_key() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
relations:
  org: { resource: organizations, type: belongs_to }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("belongs_to but has no key")));
    }

    #[test]
    fn has_many_without_foreign_key() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
relations:
  orders: { resource: orders, type: has_many }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("has_many but has no foreign_key")));
    }

    #[test]
    fn index_references_missing_field() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
indexes:
  - fields: [missing_field]
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("references field 'missing_field' not in schema")));
    }

    #[test]
    fn error_message_format() {
        let yaml = r#"
resource: users
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  role: { type: enum }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert_eq!(
            errors[0].message,
            "resource 'users': field 'role' is type enum but has no values"
        );
    }

    #[test]
    fn wasm_controller_valid_path() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /items
    input: [name]
    controller: { before: "wasm:./plugins/my_validator.wasm" }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(
            errors.is_empty(),
            "Expected no errors for valid WASM controller, got: {errors:?}"
        );
    }

    #[test]
    fn wasm_controller_missing_extension() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /items
    input: [name]
    controller: { before: "wasm:./plugins/my_validator" }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("WASM path must end with '.wasm'")));
    }

    #[test]
    fn wasm_controller_empty_path() {
        let yaml = r#"
resource: items
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
endpoints:
  create:
    method: POST
    path: /items
    input: [name]
    controller: { before: "wasm:" }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors
            .iter()
            .any(|e| e.message.contains("'wasm:' prefix but no path")));
    }

    #[test]
    fn upload_endpoint_valid_when_file_field_declared() {
        let yaml = r#"
resource: assets
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  file: { type: file, required: true }
  file_filename: { type: string }
  file_mime_type: { type: string }
  file_size: { type: bigint }
  updated_at: { type: timestamp, generated: true }
endpoints:
  upload:
    method: POST
    path: /assets/upload
    input: [file]
    upload:
      field: file
      storage: local
      max_size: 5mb
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(
            errors.is_empty(),
            "Expected valid upload resource, got {errors:?}"
        );
    }

    #[test]
    fn upload_endpoint_requires_file_field() {
        let yaml = r#"
resource: assets
version: 1
schema:
  id: { type: uuid, primary: true, generated: true }
  file_path: { type: string, required: true }
endpoints:
  upload:
    method: POST
    path: /assets/upload
    input: [file_path]
    upload:
      field: file_path
      storage: local
      max_size: 5mb
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("upload field 'file_path' must be type file")));
    }

    #[test]
    fn tenant_key_valid_uuid_field() {
        let yaml = r#"
resource: projects
version: 1
tenant_key: org_id
schema:
  id: { type: uuid, primary: true, generated: true }
  org_id: { type: uuid, ref: organizations.id, required: true }
  name: { type: string, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.is_empty(), "Expected no errors, got: {errors:?}");
    }

    #[test]
    fn tenant_key_missing_field() {
        let yaml = r#"
resource: projects
version: 1
tenant_key: org_id
schema:
  id: { type: uuid, primary: true, generated: true }
  name: { type: string, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("tenant_key 'org_id' not found in schema")));
    }

    #[test]
    fn tenant_key_wrong_type() {
        let yaml = r#"
resource: projects
version: 1
tenant_key: org_name
schema:
  id: { type: uuid, primary: true, generated: true }
  org_name: { type: string, required: true }
"#;
        let rd = parse_resource(yaml).unwrap();
        let errors = validate_resource(&rd);
        assert!(errors.iter().any(|e| e
            .message
            .contains("tenant_key 'org_name' must reference a uuid field")));
    }
}