dpp-plugin-sdk 0.10.0

Guest-side SDK and ABI export macro for Odal Node Wasm sector plugins
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
//! Reusable field validation for sector plugins.
//!
//! [`Validator`] is a fluent collector: each `require_*` / `optional_*` method
//! records a [`PluginFieldError`] when a check fails and is chainable, so a
//! plugin's `validate_input` reads as a declarative list of field constraints.
//! [`Validator::finish`] reports *all* failures at once rather than stopping at
//! the first — better for surfacing form errors to a manufacturer.
//!
//! The free functions [`num`] and [`str_of`] are convenience readers for
//! `calculate_metrics` bodies.

use dpp_plugin_traits::{PluginError, PluginFieldError, PluginInput};
use serde_json::Value;

/// A present, non-null value for `key`, or `None` if absent/null.
fn present<'a>(input: &'a Value, key: &str) -> Option<&'a Value> {
    match input.get(key) {
        Some(Value::Null) | None => None,
        other => other,
    }
}

/// Read a finite number field (ignores absent/non-numeric/NaN/inf).
#[must_use]
pub fn num(input: &PluginInput, key: &str) -> Option<f64> {
    input
        .get(key)
        .and_then(Value::as_f64)
        .filter(|n| n.is_finite())
}

/// Read a string field.
#[must_use]
pub fn str_of<'a>(input: &'a PluginInput, key: &str) -> Option<&'a str> {
    input.get(key).and_then(Value::as_str)
}

/// Fluent per-field validator. See module docs.
pub struct Validator<'a> {
    input: &'a Value,
    errors: Vec<PluginFieldError>,
}

impl<'a> Validator<'a> {
    #[must_use]
    pub fn new(input: &'a PluginInput) -> Self {
        Self {
            input,
            errors: Vec::new(),
        }
    }

    fn push_opt(&mut self, key: &str, err: Option<(&str, String)>) {
        if let Some((code, message)) = err {
            self.errors.push(PluginFieldError {
                field: format!("/{key}"),
                code: code.to_owned(),
                message,
            });
        }
    }

    /// Require a present, non-empty string.
    pub fn require_str(&mut self, key: &str) -> &mut Self {
        let err = match present(self.input, key) {
            None => Some(("missing", format!("{key} is required"))),
            Some(v) => match v.as_str() {
                Some(s) if !s.trim().is_empty() => None,
                Some(_) => Some(("empty", format!("{key} must not be empty"))),
                None => Some(("type", format!("{key} must be a string"))),
            },
        };
        self.push_opt(key, err);
        self
    }

    /// Require a string field whose value is one of `allowed`.
    pub fn require_enum(&mut self, key: &str, allowed: &[&str]) -> &mut Self {
        let err = match present(self.input, key).and_then(Value::as_str) {
            None => Some(("missing", format!("{key} is required"))),
            Some(s) if allowed.contains(&s) => None,
            Some(_) => Some(("out_of_range", format!("{key} must be one of {allowed:?}"))),
        };
        self.push_opt(key, err);
        self
    }

    /// Require a 14-digit GS1 GTIN string with a valid check digit.
    pub fn require_gtin(&mut self, key: &str) -> &mut Self {
        let err = match present(self.input, key).and_then(Value::as_str) {
            None => Some(("missing", format!("{key} is required"))),
            Some(g) if g.len() == 14 && g.bytes().all(|b| b.is_ascii_digit()) => {
                if gs1_check_digit_valid(g) {
                    None
                } else {
                    Some(("checksum", format!("{key} has an invalid GS1 check digit")))
                }
            }
            Some(_) => Some(("format", format!("{key} must be 14 digits"))),
        };
        self.push_opt(key, err);
        self
    }

    /// Require a recognized ISO 3166-1 alpha-2 country code.
    pub fn require_country(&mut self, key: &str) -> &mut Self {
        let err = match present(self.input, key).and_then(Value::as_str) {
            None => Some(("missing", format!("{key} is required"))),
            Some(c) if c.len() == 2 && c.bytes().all(|b| b.is_ascii_uppercase()) => {
                if ISO_3166_1_A2.binary_search(&c).is_ok() {
                    None
                } else {
                    Some((
                        "invalid",
                        format!("{key} is not a recognized ISO 3166-1 alpha-2 code"),
                    ))
                }
            }
            Some(_) => Some((
                "format",
                format!("{key} must be a 2-letter uppercase country code"),
            )),
        };
        self.push_opt(key, err);
        self
    }

    /// Require a present, finite number greater than 0.
    pub fn require_positive(&mut self, key: &str) -> &mut Self {
        let err = match num(self.input, key) {
            None => Some((
                "missing",
                format!("{key} is required and must be a finite number"),
            )),
            Some(v) if v <= 0.0 => Some(("out_of_range", format!("{key} must be greater than 0"))),
            Some(_) => None,
        };
        self.push_opt(key, err);
        self
    }

    /// Require a present, finite number greater than or equal to 0.
    pub fn require_non_negative(&mut self, key: &str) -> &mut Self {
        let err = match num(self.input, key) {
            None => Some((
                "missing",
                format!("{key} is required and must be a finite number"),
            )),
            Some(v) if v < 0.0 => Some(("out_of_range", format!("{key} must be 0 or greater"))),
            Some(_) => None,
        };
        self.push_opt(key, err);
        self
    }

    /// Require a present, finite number in `[0, 100]`.
    pub fn require_pct(&mut self, key: &str) -> &mut Self {
        let err = match num(self.input, key) {
            None => Some((
                "missing",
                format!("{key} is required and must be a number in 0..=100"),
            )),
            Some(v) if !(0.0..=100.0).contains(&v) => {
                Some(("out_of_range", format!("{key} must be in 0..=100")))
            }
            Some(_) => None,
        };
        self.push_opt(key, err);
        self
    }

    /// Require a present non-negative integer that is at least 1.
    pub fn require_positive_int(&mut self, key: &str) -> &mut Self {
        let err = match present(self.input, key).and_then(Value::as_u64) {
            None => Some((
                "missing",
                format!("{key} is required and must be a non-negative integer"),
            )),
            Some(0) => Some(("out_of_range", format!("{key} must be at least 1"))),
            Some(_) => None,
        };
        self.push_opt(key, err);
        self
    }

    /// Require a present boolean.
    pub fn require_bool(&mut self, key: &str) -> &mut Self {
        let err = match present(self.input, key) {
            None => Some(("missing", format!("{key} is required"))),
            Some(v) if v.is_boolean() => None,
            Some(_) => Some(("type", format!("{key} must be a boolean"))),
        };
        self.push_opt(key, err);
        self
    }

    /// Require a present, non-empty array.
    pub fn require_non_empty_array(&mut self, key: &str) -> &mut Self {
        let err = match present(self.input, key).and_then(Value::as_array) {
            None => Some(("missing", format!("{key} is required and must be an array"))),
            Some(a) if a.is_empty() => Some(("empty", format!("{key} must not be empty"))),
            Some(_) => None,
        };
        self.push_opt(key, err);
        self
    }

    /// If present (and non-null), the value must be a finite number in `[0, 100]`.
    pub fn optional_pct(&mut self, key: &str) -> &mut Self {
        let err = match present(self.input, key) {
            None => None,
            Some(v) => match v.as_f64().filter(|n| n.is_finite()) {
                Some(n) if (0.0..=100.0).contains(&n) => None,
                _ => Some(("out_of_range", format!("{key} must be a number in 0..=100"))),
            },
        };
        self.push_opt(key, err);
        self
    }

    /// If present (and non-null), the value must be a finite number in `[min, max]`.
    ///
    /// For a field that is optional (its absence is meaningful) but must be
    /// bounded when supplied — e.g. a 0–10 repairability score that gates a
    /// verdict only when present.
    pub fn optional_range(&mut self, key: &str, min: f64, max: f64) -> &mut Self {
        let err = match present(self.input, key) {
            None => None,
            Some(v) => match v.as_f64().filter(|n| n.is_finite()) {
                Some(n) if (min..=max).contains(&n) => None,
                _ => Some((
                    "out_of_range",
                    format!("{key} must be a number in {min}..={max}"),
                )),
            },
        };
        self.push_opt(key, err);
        self
    }

    /// If present (and non-null), the value must be a finite number ≥ 0.
    pub fn optional_non_negative(&mut self, key: &str) -> &mut Self {
        let err = match present(self.input, key) {
            None => None,
            Some(v) => match v.as_f64().filter(|n| n.is_finite()) {
                Some(n) if n >= 0.0 => None,
                _ => Some(("out_of_range", format!("{key} must be a finite number ≥ 0"))),
            },
        };
        self.push_opt(key, err);
        self
    }

    /// Finish validation, returning every collected error at once.
    pub fn finish(&mut self) -> Result<(), PluginError> {
        if self.errors.is_empty() {
            Ok(())
        } else {
            Err(PluginError::ValidationErrors(std::mem::take(
                &mut self.errors,
            )))
        }
    }
}

/// GS1 check-digit validation for GTIN-14.
///
/// Even-indexed positions (0, 2, 4, … 12) are weighted ×3; odd-indexed ×1.
/// The check digit at position 13 must equal `(10 − sum mod 10) mod 10`.
fn gs1_check_digit_valid(gtin: &str) -> bool {
    let bytes = gtin.as_bytes();
    debug_assert_eq!(bytes.len(), 14, "caller must check length == 14 first");
    let sum: u32 = bytes[..13]
        .iter()
        .enumerate()
        .map(|(i, &b)| {
            let d = (b - b'0') as u32;
            if i % 2 == 0 { d * 3 } else { d }
        })
        .sum();
    let expected = (10 - sum % 10) % 10;
    expected == (bytes[13] - b'0') as u32
}

/// All 249 ISO 3166-1 alpha-2 country codes, sorted for binary search.
const ISO_3166_1_A2: &[&str] = &[
    "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ",
    "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS",
    "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN",
    "CO", "CR", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE",
    "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF",
    "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM",
    "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM",
    "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KP", "KR", "KW", "KY", "KZ", "LA", "LB", "LC",
    "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK",
    "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA",
    "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG",
    "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW",
    "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS",
    "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO",
    "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI",
    "VN", "VU", "WF", "WS", "YE", "YT", "ZA", "ZM", "ZW",
];

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

    #[test]
    fn collects_all_failures() {
        let input = json!({ "gtin": "12-34", "voltage": -1.0 });
        let err = Validator::new(&input)
            .require_gtin("gtin")
            .require_positive("voltage")
            .require_str("name")
            .finish()
            .unwrap_err();
        match err {
            PluginError::ValidationErrors(errs) => assert_eq!(errs.len(), 3),
            other => panic!("expected ValidationErrors, got {other:?}"),
        }
    }

    #[test]
    fn valid_input_passes() {
        let input = json!({
            "gtin": "12345678901231",
            "country": "DE",
            "pct": 42.0,
            "count": 3,
            "flag": true,
            "items": [1]
        });
        assert!(
            Validator::new(&input)
                .require_gtin("gtin")
                .require_country("country")
                .require_pct("pct")
                .require_positive_int("count")
                .require_bool("flag")
                .require_non_empty_array("items")
                .finish()
                .is_ok()
        );
    }

    #[test]
    fn enum_and_country_and_pct_bounds() {
        let input = json!({ "cls": "Z", "country": "de", "pct": 150.0 });
        let err = Validator::new(&input)
            .require_enum("cls", &["A", "B"])
            .require_country("country")
            .require_pct("pct")
            .finish()
            .unwrap_err();
        match err {
            PluginError::ValidationErrors(errs) => assert_eq!(errs.len(), 3),
            other => panic!("expected ValidationErrors, got {other:?}"),
        }
    }

    #[test]
    fn gtin_invalid_check_digit_is_rejected() {
        // "12345678901234" — correct digits, correct length, but check digit should be 1, not 4.
        let input = json!({ "gtin": "12345678901234" });
        let err = Validator::new(&input)
            .require_gtin("gtin")
            .finish()
            .unwrap_err();
        match err {
            PluginError::ValidationErrors(errs) => {
                assert_eq!(errs.len(), 1);
                assert_eq!(errs[0].code, "checksum");
            }
            other => panic!("expected ValidationErrors, got {other:?}"),
        }
    }

    #[test]
    fn gtin_valid_check_digit_passes() {
        // "12345678901231" — check digit = 1, matches GS1 calculation.
        let input = json!({ "gtin": "12345678901231" });
        assert!(Validator::new(&input).require_gtin("gtin").finish().is_ok());
    }

    #[test]
    fn country_not_in_iso_list_is_rejected() {
        // "XX" has the right format (2 uppercase letters) but is not an assigned code.
        let input = json!({ "country": "XX" });
        let err = Validator::new(&input)
            .require_country("country")
            .finish()
            .unwrap_err();
        match err {
            PluginError::ValidationErrors(errs) => {
                assert_eq!(errs.len(), 1);
                assert_eq!(errs[0].code, "invalid");
            }
            other => panic!("expected ValidationErrors, got {other:?}"),
        }
    }

    #[test]
    fn country_valid_iso_code_passes() {
        for code in ["DE", "NO", "FR", "US", "JP"] {
            let input = json!({ "country": code });
            assert!(
                Validator::new(&input)
                    .require_country("country")
                    .finish()
                    .is_ok(),
                "{code} should be a valid ISO 3166-1 alpha-2 code"
            );
        }
    }

    #[test]
    fn optional_pct_absent_is_ok_present_out_of_range_fails() {
        let ok = json!({});
        assert!(Validator::new(&ok).optional_pct("x").finish().is_ok());
        let bad = json!({ "x": 101.0 });
        assert!(Validator::new(&bad).optional_pct("x").finish().is_err());
    }

    #[test]
    fn optional_range_absent_ok_present_bounded() {
        // Absent → ok (the field's absence is meaningful).
        assert!(
            Validator::new(&json!({}))
                .optional_range("s", 0.0, 10.0)
                .finish()
                .is_ok()
        );
        // In range → ok.
        assert!(
            Validator::new(&json!({ "s": 6.0 }))
                .optional_range("s", 0.0, 10.0)
                .finish()
                .is_ok()
        );
        // Out of range → err (the fail-open case the plugins guard against).
        for bad in [json!({ "s": 999999.0 }), json!({ "s": -1.0 })] {
            assert!(
                Validator::new(&bad)
                    .optional_range("s", 0.0, 10.0)
                    .finish()
                    .is_err()
            );
        }
    }

    #[test]
    fn optional_non_negative_absent_ok_negative_fails() {
        assert!(
            Validator::new(&json!({}))
                .optional_non_negative("c")
                .finish()
                .is_ok()
        );
        assert!(
            Validator::new(&json!({ "c": 0.0 }))
                .optional_non_negative("c")
                .finish()
                .is_ok()
        );
        assert!(
            Validator::new(&json!({ "c": -999.0 }))
                .optional_non_negative("c")
                .finish()
                .is_err()
        );
    }

    #[test]
    fn readers_extract_values() {
        let input = json!({ "n": 3.5, "s": "hi", "bad": "x" });
        assert_eq!(num(&input, "n"), Some(3.5));
        assert_eq!(num(&input, "bad"), None);
        assert_eq!(str_of(&input, "s"), Some("hi"));
    }
}