wscall-server 0.1.1

Server framework for WSCALL
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
#![allow(dead_code)]

use serde_json::{Map, Value, json};
use validator::{ValidationError, ValidationErrors, ValidationErrorsKind};

pub use validator::Validate;

pub fn required<T>(value: &Option<T>) -> Result<(), ValidationError> {
    if value.is_none() {
        return Err(simple_error("required", "value is required"));
    }
    Ok(())
}

pub fn assert_true(value: &bool) -> Result<(), ValidationError> {
    if !*value {
        return Err(simple_error("assert_true", "value must be true"));
    }
    Ok(())
}

pub fn assert_false(value: &bool) -> Result<(), ValidationError> {
    if *value {
        return Err(simple_error("assert_false", "value must be false"));
    }
    Ok(())
}

pub fn not_empty(value: &str) -> Result<(), ValidationError> {
    if value.is_empty() {
        return Err(simple_error("not_empty", "value cannot be empty"));
    }
    Ok(())
}

pub fn not_blank(value: &str) -> Result<(), ValidationError> {
    if value.trim().is_empty() {
        return Err(simple_error("not_blank", "value cannot be blank"));
    }
    Ok(())
}

pub fn no_whitespace(value: &str) -> Result<(), ValidationError> {
    if value.chars().any(char::is_whitespace) {
        return Err(simple_error(
            "no_whitespace",
            "value cannot contain whitespace",
        ));
    }
    Ok(())
}

pub fn alphabetic(value: &str) -> Result<(), ValidationError> {
    if !value.chars().all(char::is_alphabetic) {
        return Err(simple_error(
            "alphabetic",
            "value must contain only letters",
        ));
    }
    Ok(())
}

pub fn alphanumeric(value: &str) -> Result<(), ValidationError> {
    if !value.chars().all(char::is_alphanumeric) {
        return Err(simple_error(
            "alphanumeric",
            "value must contain only letters or digits",
        ));
    }
    Ok(())
}

pub fn ascii_alphanumeric(value: &str) -> Result<(), ValidationError> {
    if !value.chars().all(|ch| ch.is_ascii_alphanumeric()) {
        return Err(simple_error(
            "ascii_alphanumeric",
            "value must contain only ASCII letters or digits",
        ));
    }
    Ok(())
}

pub fn numeric_text(value: &str) -> Result<(), ValidationError> {
    if !value.chars().all(|ch| ch.is_ascii_digit()) {
        return Err(simple_error(
            "numeric_text",
            "value must contain only digits",
        ));
    }
    Ok(())
}

pub fn lowercase(value: &str) -> Result<(), ValidationError> {
    if value
        .chars()
        .any(|ch| ch.is_alphabetic() && !ch.is_lowercase())
    {
        return Err(simple_error("lowercase", "value must be lowercase"));
    }
    Ok(())
}

pub fn uppercase(value: &str) -> Result<(), ValidationError> {
    if value
        .chars()
        .any(|ch| ch.is_alphabetic() && !ch.is_uppercase())
    {
        return Err(simple_error("uppercase", "value must be uppercase"));
    }
    Ok(())
}

pub fn non_empty_vec<T>(value: &[T]) -> Result<(), ValidationError> {
    if value.is_empty() {
        return Err(simple_error("not_empty", "collection cannot be empty"));
    }
    Ok(())
}

pub fn non_empty_map<K, V, S>(
    value: &std::collections::HashMap<K, V, S>,
) -> Result<(), ValidationError> {
    if value.is_empty() {
        return Err(simple_error("not_empty", "map cannot be empty"));
    }
    Ok(())
}

pub fn positive_i32(value: i32) -> Result<(), ValidationError> {
    if value <= 0 {
        return Err(simple_error("positive", "value must be greater than 0"));
    }
    Ok(())
}

pub fn non_negative_i32(value: i32) -> Result<(), ValidationError> {
    if value < 0 {
        return Err(simple_error(
            "non_negative",
            "value must be greater than or equal to 0",
        ));
    }
    Ok(())
}

pub fn positive_i64(value: i64) -> Result<(), ValidationError> {
    if value <= 0 {
        return Err(simple_error("positive", "value must be greater than 0"));
    }
    Ok(())
}

pub fn non_negative_i64(value: i64) -> Result<(), ValidationError> {
    if value < 0 {
        return Err(simple_error(
            "non_negative",
            "value must be greater than or equal to 0",
        ));
    }
    Ok(())
}

pub fn positive_f64(value: f64) -> Result<(), ValidationError> {
    if value <= 0.0 {
        return Err(simple_error("positive", "value must be greater than 0"));
    }
    Ok(())
}

pub fn non_negative_f64(value: f64) -> Result<(), ValidationError> {
    if value < 0.0 {
        return Err(simple_error(
            "non_negative",
            "value must be greater than or equal to 0",
        ));
    }
    Ok(())
}

pub fn percentage(value: f64) -> Result<(), ValidationError> {
    if !(0.0..=100.0).contains(&value) {
        return Err(simple_error(
            "percentage",
            "value must be between 0 and 100",
        ));
    }
    Ok(())
}

pub fn errors_to_details(errors: &ValidationErrors) -> Value {
    let mut fields = Map::new();

    for (field, kind) in errors.errors() {
        fields.insert(field.to_string(), error_kind_to_value(kind));
    }

    Value::Object(fields)
}

fn error_kind_to_value(kind: &ValidationErrorsKind) -> Value {
    match kind {
        ValidationErrorsKind::Field(errors) => Value::Array(
            errors
                .iter()
                .map(|error| {
                    json!({
                        "code": error.code,
                        "message": error.message.as_ref().map(|message| message.to_string()),
                        "params": error.params,
                    })
                })
                .collect(),
        ),
        ValidationErrorsKind::List(items) => {
            let mut list = Map::new();
            for (index, nested) in items {
                list.insert(index.to_string(), errors_to_details(nested));
            }
            Value::Object(list)
        }
        ValidationErrorsKind::Struct(nested) => errors_to_details(nested),
    }
}

fn simple_error(code: &'static str, message: &'static str) -> ValidationError {
    let mut error = ValidationError::new(code);
    error.message = Some(message.into());
    error
}

#[macro_export]
macro_rules! wscall_regex_validator {
    ($name:ident, $pattern:literal, $code:literal) => {
        fn $name(value: &str) -> Result<(), ::validator::ValidationError> {
            static REGEX: ::std::sync::OnceLock<::regex::Regex> = ::std::sync::OnceLock::new();
            let regex = REGEX.get_or_init(|| {
                ::regex::Regex::new($pattern)
                    .expect("invalid regex pattern in wscall_regex_validator!")
            });

            if regex.is_match(value) {
                Ok(())
            } else {
                let mut error = ::validator::ValidationError::new($code);
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "value does not match pattern {}",
                    $pattern
                )));
                Err(error)
            }
        }
    };
}

#[macro_export]
macro_rules! wscall_min_length_validator {
    ($name:ident, $min:expr) => {
        fn $name(value: &str) -> Result<(), ::validator::ValidationError> {
            let len = value.chars().count();
            if len < $min {
                let mut error = ::validator::ValidationError::new("min_length");
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "length must be at least {}",
                    $min
                )));
                error.add_param(::std::borrow::Cow::Borrowed("min"), &$min);
                error.add_param(::std::borrow::Cow::Borrowed("actual"), &len);
                Err(error)
            } else {
                Ok(())
            }
        }
    };
}

#[macro_export]
macro_rules! wscall_max_length_validator {
    ($name:ident, $max:expr) => {
        fn $name(value: &str) -> Result<(), ::validator::ValidationError> {
            let len = value.chars().count();
            if len > $max {
                let mut error = ::validator::ValidationError::new("max_length");
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "length must be at most {}",
                    $max
                )));
                error.add_param(::std::borrow::Cow::Borrowed("max"), &$max);
                error.add_param(::std::borrow::Cow::Borrowed("actual"), &len);
                Err(error)
            } else {
                Ok(())
            }
        }
    };
}

#[macro_export]
macro_rules! wscall_length_range_validator {
    ($name:ident, $min:expr, $max:expr) => {
        fn $name(value: &str) -> Result<(), ::validator::ValidationError> {
            let len = value.chars().count();
            if !($min..=$max).contains(&len) {
                let mut error = ::validator::ValidationError::new("length_range");
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "length must be between {} and {}",
                    $min, $max
                )));
                error.add_param(::std::borrow::Cow::Borrowed("min"), &$min);
                error.add_param(::std::borrow::Cow::Borrowed("max"), &$max);
                error.add_param(::std::borrow::Cow::Borrowed("actual"), &len);
                Err(error)
            } else {
                Ok(())
            }
        }
    };
}

#[macro_export]
macro_rules! wscall_contains_validator {
    ($name:ident, $needle:literal, $code:literal) => {
        fn $name(value: &str) -> Result<(), ::validator::ValidationError> {
            if value.contains($needle) {
                Ok(())
            } else {
                let mut error = ::validator::ValidationError::new($code);
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "value must contain {}",
                    $needle
                )));
                Err(error)
            }
        }
    };
}

#[macro_export]
macro_rules! wscall_not_contains_validator {
    ($name:ident, $needle:literal, $code:literal) => {
        fn $name(value: &str) -> Result<(), ::validator::ValidationError> {
            if value.contains($needle) {
                let mut error = ::validator::ValidationError::new($code);
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "value cannot contain {}",
                    $needle
                )));
                Err(error)
            } else {
                Ok(())
            }
        }
    };
}

#[macro_export]
macro_rules! wscall_one_of_validator {
    ($name:ident, [$($value:expr),+ $(,)?], $code:literal) => {
        fn $name(value: &str) -> Result<(), ::validator::ValidationError> {
            const ALLOWED: &[&str] = &[$($value),+];
            if ALLOWED.contains(&value) {
                Ok(())
            } else {
                let mut error = ::validator::ValidationError::new($code);
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "value must be one of {:?}",
                    ALLOWED
                )));
                Err(error)
            }
        }
    };
}

#[macro_export]
macro_rules! wscall_numeric_min_validator {
    ($name:ident, $ty:ty, $min:expr) => {
        fn $name(value: $ty) -> Result<(), ::validator::ValidationError> {
            if value < $min {
                let mut error = ::validator::ValidationError::new("min");
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "value must be greater than or equal to {}",
                    $min
                )));
                error.add_param(::std::borrow::Cow::Borrowed("min"), &$min);
                Err(error)
            } else {
                Ok(())
            }
        }
    };
}

#[macro_export]
macro_rules! wscall_numeric_max_validator {
    ($name:ident, $ty:ty, $max:expr) => {
        fn $name(value: $ty) -> Result<(), ::validator::ValidationError> {
            if value > $max {
                let mut error = ::validator::ValidationError::new("max");
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "value must be less than or equal to {}",
                    $max
                )));
                error.add_param(::std::borrow::Cow::Borrowed("max"), &$max);
                Err(error)
            } else {
                Ok(())
            }
        }
    };
}

#[macro_export]
macro_rules! wscall_numeric_range_validator {
    ($name:ident, $ty:ty, $min:expr, $max:expr) => {
        fn $name(value: $ty) -> Result<(), ::validator::ValidationError> {
            if !($min..=$max).contains(&value) {
                let mut error = ::validator::ValidationError::new("range");
                error.message = Some(::std::borrow::Cow::Owned(format!(
                    "value must be between {} and {}",
                    $min, $max
                )));
                error.add_param(::std::borrow::Cow::Borrowed("min"), &$min);
                error.add_param(::std::borrow::Cow::Borrowed("max"), &$max);
                Err(error)
            } else {
                Ok(())
            }
        }
    };
}

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

    wscall_min_length_validator!(validate_min_len_3, 3);
    wscall_max_length_validator!(validate_max_len_5, 5);
    wscall_length_range_validator!(validate_len_2_to_4, 2, 4);
    wscall_numeric_range_validator!(validate_age_range, i32, 1, 150);
    wscall_one_of_validator!(validate_env, ["dev", "test", "prod"], "invalid_env");

    #[test]
    fn built_in_string_validators_work() {
        assert!(not_blank("hello").is_ok());
        assert!(not_blank("   ").is_err());
        assert!(ascii_alphanumeric("abc123").is_ok());
        assert!(ascii_alphanumeric("abc-123").is_err());
        assert!(numeric_text("123456").is_ok());
        assert!(numeric_text("12a456").is_err());
    }

    #[test]
    fn macro_validators_work() {
        assert!(validate_min_len_3("abc").is_ok());
        assert!(validate_min_len_3("ab").is_err());
        assert!(validate_max_len_5("abcde").is_ok());
        assert!(validate_max_len_5("abcdef").is_err());
        assert!(validate_len_2_to_4("abc").is_ok());
        assert!(validate_len_2_to_4("a").is_err());
        assert!(validate_age_range(42).is_ok());
        assert!(validate_age_range(151).is_err());
        assert!(validate_env("prod").is_ok());
        assert!(validate_env("stage").is_err());
    }
}