rson-schema 1.0.0

Schema validation for RSON
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
# ๐Ÿ›ก๏ธ rson-schema

**Schema validation and type safety for RSON (Rust Serialized Object Notation)**

[![Crates.io](https://img.shields.io/crates/v/rson-schema.svg)](https://crates.io/crates/rson-schema)
[![Documentation](https://docs.rs/rson-schema/badge.svg)](https://docs.rs/rson-schema)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

---

## ๐ŸŽฏ **What is rson-schema?**

`rson-schema` provides powerful schema validation for RSON data, ensuring your configuration files and data structures conform to expected formats and constraints.

**Key Features:**
- **Type validation** - Ensure structs, enums, and fields match expected types
- **Constraint checking** - Validate ranges, lengths, patterns, and custom rules
- **Schema generation** - Auto-generate schemas from Rust types
- **JSON Schema compatible** - Leverage existing JSON Schema tooling
- **Developer-friendly errors** - Clear validation error messages

---

## ๐Ÿš€ **Quick Start**

### Installation

```toml
[dependencies]
rson-schema = "0.1.0"
serde = { version = "1.0", features = ["derive"] }
```

### Basic Usage

```rust
use rson_schema::{Schema, validate, SchemaBuilder};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    #[schema(min_length = 1, max_length = 50)]
    name: String,
    
    #[schema(minimum = 1, maximum = 65535)]
    port: u16,
    
    #[schema(pattern = "^[a-z0-9]+$")]
    database_name: String,
    
    features: Vec<String>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Generate schema from Rust type
    let schema = Schema::from_type::<Config>()?;
    
    // Validate RSON data against schema
    let rson_text = r#"
        Config(
            name: "my-app",
            port: 8080,
            database_name: "mydb123",
            features: ["auth", "logging"],
        )
    "#;
    
    // Validate returns detailed errors if validation fails
    match validate(&schema, rson_text) {
        Ok(_) => println!("โœ… Valid RSON data"),
        Err(errors) => {
            for error in errors {
                println!("โŒ {}", error);
            }
        }
    }
    
    Ok(())
}
```

---

## ๐Ÿ“š **Schema Definition**

### **Using Attributes**

Add validation constraints directly to your Rust types:

```rust
use serde::{Deserialize, Serialize};
use rson_schema::schema;

#[derive(Serialize, Deserialize)]
struct User {
    #[schema(min_length = 2, max_length = 50)]
    name: String,
    
    #[schema(minimum = 13, maximum = 120)]
    age: u8,
    
    #[schema(pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")]
    email: String,
    
    #[schema(items = "String", min_items = 1, max_items = 10)]
    roles: Vec<String>,
    
    #[schema(optional)]
    phone: Option<String>,
}
```

### **Programmatic Schema Building**

```rust
use rson_schema::{SchemaBuilder, SchemaType, Constraint};

let schema = SchemaBuilder::new()
    .struct_type("Config")
    .field("name", SchemaType::String)
        .constraint(Constraint::MinLength(1))
        .constraint(Constraint::MaxLength(100))
    .field("port", SchemaType::Integer)
        .constraint(Constraint::Minimum(1))
        .constraint(Constraint::Maximum(65535))
    .field("enabled", SchemaType::Boolean)
    .field("tags", SchemaType::Array(Box::new(SchemaType::String)))
        .constraint(Constraint::MinItems(0))
        .constraint(Constraint::MaxItems(20))
    .build()?;
```

---

## ๐Ÿ”ง **Validation Constraints**

### **String Constraints**

```rust
#[derive(Serialize, Deserialize)]
struct StringValidation {
    #[schema(min_length = 5, max_length = 50)]
    name: String,
    
    #[schema(pattern = r"^[A-Z][a-z]+$")]
    title: String,
    
    #[schema(format = "email")]
    email: String,
    
    #[schema(format = "uri")]
    website: String,
    
    #[schema(enum_values = ["dev", "staging", "prod"])]
    environment: String,
}
```

### **Numeric Constraints**

```rust
#[derive(Serialize, Deserialize)]
struct NumericValidation {
    #[schema(minimum = 0, maximum = 100)]
    percentage: u8,
    
    #[schema(exclusive_minimum = 0.0)]
    price: f64,
    
    #[schema(multiple_of = 5)]
    step: u32,
}
```

### **Array Constraints**

```rust
#[derive(Serialize, Deserialize)]
struct ArrayValidation {
    #[schema(min_items = 1, max_items = 10)]
    tags: Vec<String>,
    
    #[schema(unique_items = true)]
    ids: Vec<u32>,
    
    #[schema(items = "Integer", min_value = 1, max_value = 100)]
    scores: Vec<u8>,
}
```

### **Object Constraints**

```rust
#[derive(Serialize, Deserialize)]
struct ObjectValidation {
    #[schema(min_properties = 1, max_properties = 50)]
    metadata: std::collections::HashMap<String, String>,
    
    #[schema(required = ["host", "port"])]
    config: DatabaseConfig,
}
```

---

## ๐ŸŽจ **Schema Formats**

### **RSON Schema Format**

```rson
// config.rschema
Schema(
    type: "struct",
    name: "Config",
    fields: {
        "name": FieldSchema(
            type: "string",
            constraints: [
                MinLength(1),
                MaxLength(50),
            ],
        ),
        "port": FieldSchema(
            type: "integer",
            constraints: [
                Minimum(1),
                Maximum(65535),
            ],
        ),
        "features": FieldSchema(
            type: "array",
            items: "string",
            constraints: [
                MinItems(0),
                MaxItems(20),
            ],
        ),
    },
)
```

### **JSON Schema Compatible**

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "properties": {
    "name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 50
    },
    "port": {
      "type": "integer",
      "minimum": 1,
      "maximum": 65535
    },
    "features": {
      "type": "array",
      "items": { "type": "string" },
      "minItems": 0,
      "maxItems": 20
    }
  },
  "required": ["name", "port", "features"]
}
```

---

## ๐Ÿ” **Advanced Validation**

### **Custom Validators**

```rust
use rson_schema::{Validator, ValidationResult, ValidationError};

struct EmailValidator;

impl Validator for EmailValidator {
    fn validate(&self, value: &str) -> ValidationResult {
        if value.contains('@') && value.contains('.') {
            Ok(())
        } else {
            Err(ValidationError::new("Invalid email format"))
        }
    }
}

// Use custom validator
#[derive(Serialize, Deserialize)]
struct User {
    #[schema(custom = EmailValidator)]
    email: String,
}
```

### **Conditional Validation**

```rust
#[derive(Serialize, Deserialize)]
struct ConditionalConfig {
    #[schema(required_if = "ssl_enabled == true")]
    ssl_cert: Option<String>,
    
    ssl_enabled: bool,
    
    #[schema(min_value_if = "environment == 'prod'", min_value = 8080)]
    port: u16,
    
    environment: String,
}
```

### **Cross-Field Validation**

```rust
use rson_schema::cross_field_validator;

#[derive(Serialize, Deserialize)]
#[schema(cross_field = "validate_password_confirmation")]
struct RegisterUser {
    password: String,
    password_confirmation: String,
}

#[cross_field_validator]
fn validate_password_confirmation(data: &RegisterUser) -> ValidationResult {
    if data.password == data.password_confirmation {
        Ok(())
    } else {
        Err(ValidationError::new("Passwords do not match"))
    }
}
```

---

## ๐Ÿ› ๏ธ **CLI Integration**

### **Schema Generation**

```bash
# Generate schema from Rust code
rsonc schema generate --type Config --output config.rschema src/config.rs

# Generate JSON Schema
rsonc schema generate --type Config --format json-schema --output config.schema.json src/config.rs
```

### **Validation**

```bash
# Validate RSON file against schema
rsonc validate --schema config.rschema config.rson

# Validate multiple files
rsonc validate --schema config.rschema configs/*.rson
```

---

## ๐Ÿ“Š **Performance**

Schema validation is designed to be fast:

| Operation | Speed | Memory Usage |
|-----------|-------|--------------|
| **Schema compile** | ~1ms | Low |
| **Validate small file** | ~100ฮผs | Minimal |
| **Validate large file** | ~10MB/s | Low |

*Benchmarks on typical configuration files*

---

## ๐ŸŽฏ **Use Cases**

### **Configuration Validation**

```rust
// Validate server configuration
#[derive(Serialize, Deserialize)]
struct ServerConfig {
    #[schema(format = "ipv4")]
    host: String,
    
    #[schema(minimum = 1024, maximum = 65535)]
    port: u16,
    
    #[schema(minimum = 1, maximum = 100)]
    worker_threads: u8,
    
    #[schema(enum_values = ["debug", "info", "warn", "error"])]
    log_level: String,
}
```

### **API Request Validation**

```rust
// Validate incoming API requests
#[derive(Serialize, Deserialize)]
struct CreateUserRequest {
    #[schema(min_length = 2, max_length = 50, pattern = r"^[a-zA-Z\s]+$")]
    name: String,
    
    #[schema(format = "email")]
    email: String,
    
    #[schema(minimum = 13, maximum = 120)]
    age: u8,
    
    #[schema(items = "String", enum_values = ["user", "admin", "moderator"])]
    roles: Vec<String>,
}
```

### **Data Pipeline Validation**

```rust
// Validate data transformation outputs
#[derive(Serialize, Deserialize)]
struct ProcessedData {
    #[schema(format = "iso8601")]
    timestamp: String,
    
    #[schema(minimum = 0.0)]
    value: f64,
    
    #[schema(pattern = r"^[A-Z]{2,4}$")]
    currency_code: String,
    
    #[schema(min_properties = 1)]
    metadata: std::collections::HashMap<String, serde_json::Value>,
}
```

---

## ๐Ÿงช **Testing**

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use rson_schema::{validate, Schema};

    #[test]
    fn test_valid_config() {
        let schema = Schema::from_type::<Config>().unwrap();
        let rson = r#"Config(name: "test", port: 8080, features: ["auth"])"#;
        
        assert!(validate(&schema, rson).is_ok());
    }

    #[test]
    fn test_invalid_port() {
        let schema = Schema::from_type::<Config>().unwrap();
        let rson = r#"Config(name: "test", port: 70000, features: ["auth"])"#;
        
        let result = validate(&schema, rson);
        assert!(result.is_err());
        
        let errors = result.unwrap_err();
        assert!(errors.iter().any(|e| e.field == "port"));
    }
}
```

---

## ๐Ÿ“– **Documentation**

- **[API Documentation]https://docs.rs/rson-schema** - Complete API reference
- **[Schema Guide]https://rson.org/docs/schema** - Schema definition guide
- **[Examples]https://github.com/RSON-Rust-Serialized-Object-Notation/RSON-core/tree/main/rson-schema/examples** - Usage examples

---

## ๐Ÿค **Contributing**

We welcome contributions! Please see our [Contributing Guide](https://github.com/RSON-Rust-Serialized-Object-Notation/RSON-core/blob/main/CONTRIBUTING.md).

**Areas we need help with:**
- Additional constraint types
- Performance optimizations
- Better error messages
- Schema migration tools

---

## ๐Ÿ“„ **License**

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

## ๐Ÿ”— **Related Projects**

- **[rson-core]https://crates.io/crates/rson-core** - Core RSON parsing library
- **[serde_rson]https://crates.io/crates/serde_rson** - Serde integration for RSON
- **[rson-cli]https://crates.io/crates/rson-cli** - Command-line tools
- **[RSON Website]https://rson.org** - Documentation and playground

---

**Made with ๐Ÿ›ก๏ธ by the RSON community**