ng-gateway-sdk 0.1.0

SDK for building NG Gateway southward drivers and northward 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
use crate::{DriverError, DriverResult, NGValue, RuntimeParameter};
use std::sync::Arc;

/// Validate action parameters including required presence and numeric ranges.
///
/// This is the canonical validation used across the gateway and all drivers.
/// It ensures that required parameters exist with the correct container shape
/// and validates numeric values against `min_value` and `max_value` when
/// applicable. Error messages are human-readable and intended for RPC responses.
pub fn validate_action_parameters(
    inputs: &[Arc<dyn RuntimeParameter>],
    params: &Option<serde_json::Value>,
) -> DriverResult<()> {
    let params_value = params.as_ref();
    let params_obj = params_value.and_then(|v| v.as_object());
    let inputs_len = inputs.len();

    // Required presence check
    let required_keys: Vec<String> = inputs
        .iter()
        .filter(|input| input.required())
        .map(|input| input.key().to_string())
        .collect();

    if !required_keys.is_empty() {
        if required_keys.len() == 1 {
            if params_value.is_none() {
                return Err(DriverError::ValidationError(
                    "Parameters is required for required parameters".to_string(),
                ));
            }
            // Single-parameter actions allow scalar input; do NOT return early here because
            // we still want to perform range checks below when configured.
        } else if params_obj.is_none() {
            return Err(DriverError::ValidationError(
                "Parameters must be a JSON object for required parameters".to_string(),
            ));
        }
    }

    let missing_required: Vec<String> = match params_obj {
        Some(map) => required_keys
            .iter()
            .filter(|key| !map.contains_key(key.as_str()))
            .cloned()
            .collect(),
        None => {
            if inputs_len == 1 {
                match inputs.first() {
                    Some(input) if input.required() && params_value.is_none() => {
                        vec![input.key().to_string()]
                    }
                    _ => Vec::new(),
                }
            } else {
                required_keys
            }
        }
    };

    if !missing_required.is_empty() {
        return Err(DriverError::ValidationError(format!(
            "Missing required parameters: {}",
            missing_required.join(",")
        )));
    }

    // Numeric range validation
    let mut errors: Vec<String> = Vec::new();
    for input in inputs.iter() {
        let key = input.key();
        let value_opt: Option<&serde_json::Value> = match params_obj {
            Some(map) => map.get(key),
            None => {
                if inputs_len == 1 {
                    params_value
                } else {
                    None
                }
            }
        };

        let Some(value) = value_opt else { continue };

        // Numeric-like types only
        let expected = input.logical_data_type();
        if !expected.is_numeric() {
            continue;
        }

        let numeric_value: Option<f64> = value
            .as_f64()
            .or(value.as_i64().map(|v| v as f64))
            .or(value.as_u64().map(|v| v as f64))
            .or(value.as_str().and_then(|s| s.parse::<f64>().ok()));

        match numeric_value {
            Some(v) => {
                if let Some(min) = input.min_value() {
                    if v < min {
                        errors.push(format!("{key} < min_value ({min})"));
                    }
                }
                if let Some(max) = input.max_value() {
                    if v > max {
                        errors.push(format!("{key} > max_value ({max})"));
                    }
                }
            }
            None => {
                errors.push(format!("{key} is not a numeric value"));
            }
        }
    }

    if errors.is_empty() {
        Ok(())
    } else {
        Err(DriverError::ValidationError(format!(
            "Parameter validation failed: {}",
            errors.join("; ")
        )))
    }
}

/// Resolve input parameter values with defaulting semantics (unchecked variant).
///
/// This function assumes the caller has validated presence and container shape.
/// Optional parameters must supply `default_value()`, otherwise this function
/// returns a `ConfigurationError`.
pub fn resolve_action_inputs_typed<P>(
    inputs: &[Arc<dyn RuntimeParameter>],
    parameters: &Option<serde_json::Value>,
) -> DriverResult<Vec<(Arc<P>, serde_json::Value)>>
where
    P: RuntimeParameter + 'static,
{
    let total = inputs.len();
    let mut out: Vec<(Arc<P>, serde_json::Value)> = Vec::with_capacity(total);

    let required_keys: Vec<String> = inputs
        .iter()
        .filter(|input| input.required())
        .map(|input| input.key().to_string())
        .collect();

    let params_obj = parameters.as_ref().and_then(|v| v.as_object());

    for param in inputs.iter() {
        let required = param.required();
        let value: serde_json::Value = if !required {
            match params_obj {
                Some(map) => match map.get(param.key()) {
                    Some(v) => v.clone(),
                    None => match param.default_value() {
                        Some(v) => v,
                        None => {
                            return Err(DriverError::ConfigurationError(format!(
                                "Optional parameter '{}' missing default value",
                                param.key()
                            )));
                        }
                    },
                },
                None => match param.default_value() {
                    Some(v) => v,
                    None => {
                        return Err(DriverError::ConfigurationError(format!(
                            "Optional parameter '{}' missing default value",
                            param.key()
                        )));
                    }
                },
            }
        } else if total == 1 || required_keys.len() == 1 {
            match params_obj {
                Some(map) => match map.get(param.key()) {
                    Some(v) => v.clone(),
                    None => match parameters.as_ref() {
                        Some(v) => v.clone(),
                        None => {
                            return Err(DriverError::ConfigurationError(
                                "Missing parameters for required input".to_string(),
                            ));
                        }
                    },
                },
                None => match parameters.as_ref() {
                    Some(v) => v.clone(),
                    None => {
                        return Err(DriverError::ConfigurationError(
                            "Missing parameters for required input".to_string(),
                        ));
                    }
                },
            }
        } else {
            match params_obj.and_then(|m| m.get(param.key())) {
                Some(v) => v.clone(),
                None => {
                    return Err(DriverError::ConfigurationError(format!(
                        "Missing value for required parameter '{}'",
                        param.key()
                    )));
                }
            }
        };

        let p = match Arc::clone(param).downcast_arc::<P>() {
            Ok(p) => p,
            Err(_) => {
                return Err(DriverError::ConfigurationError(format!(
                    "Parameter type mismatch for key '{}' (expected {})",
                    param.key(),
                    std::any::type_name::<P>()
                )));
            }
        };

        out.push((p, value));
    }

    Ok(out)
}

/// Validate, default and resolve action inputs into strongly-typed `NGValue`s.
///
/// This is the **single gateway entrypoint** for execute_action input handling:
/// - Compatible shape semantics:
///   - multi-parameter: `params` must be JSON object
///   - single-parameter: allow scalar or object containing the key
/// - Required checks and default-value fill
/// - Lenient scalar conversion (numeric strings, 0x hex, bool strings, RFC3339 timestamps, base64/hex binary)
/// - Stable output order: follows `inputs` order
pub fn validate_and_resolve_action_inputs(
    inputs: &[Arc<dyn RuntimeParameter>],
    params: &Option<serde_json::Value>,
) -> DriverResult<Vec<(Arc<dyn RuntimeParameter>, NGValue)>> {
    let total = inputs.len();
    let mut out: Vec<(Arc<dyn RuntimeParameter>, NGValue)> = Vec::with_capacity(total);

    let params_value = params.as_ref();
    let params_obj = params_value.and_then(|v| v.as_object());

    // Reuse existing required presence semantics to preserve behavior.
    let required_keys: Vec<String> = inputs
        .iter()
        .filter(|input| input.required())
        .map(|input| input.key().to_string())
        .collect();

    if !required_keys.is_empty() {
        if required_keys.len() == 1 {
            if params_value.is_none() {
                return Err(DriverError::ValidationError(
                    "Parameters is required for required parameters".to_string(),
                ));
            }
        } else if params_obj.is_none() {
            return Err(DriverError::ValidationError(
                "Parameters must be a JSON object for required parameters".to_string(),
            ));
        }
    }

    let missing_required: Vec<String> = match params_obj {
        Some(map) => required_keys
            .iter()
            .filter(|key| !map.contains_key(key.as_str()))
            .cloned()
            .collect(),
        None => {
            if total == 1 {
                match inputs.first() {
                    Some(input) if input.required() && params_value.is_none() => {
                        vec![input.key().to_string()]
                    }
                    _ => Vec::new(),
                }
            } else {
                required_keys.clone()
            }
        }
    };

    if !missing_required.is_empty() {
        return Err(DriverError::ValidationError(format!(
            "Missing required parameters: {}",
            missing_required.join(",")
        )));
    }

    // Range validation is aggregated to preserve error style.
    let mut range_errors: Vec<String> = Vec::new();

    for param in inputs.iter() {
        let required = param.required();
        let key = param.key();

        // Resolve JSON source value (borrowed) or default (owned for optional).
        let value_ref: Option<&serde_json::Value> = match params_obj {
            Some(map) => map.get(key),
            None => {
                if total == 1 {
                    params_value
                } else {
                    None
                }
            }
        };
        let expected = param.logical_data_type();

        let ng: NGValue = if !required {
            match value_ref {
                Some(v) => {
                    if v.is_null() {
                        return Err(DriverError::ValidationError(format!(
                            "Parameter '{}' is null",
                            key
                        )));
                    }
                    if v.is_array() || v.is_object() {
                        return Err(DriverError::ValidationError(format!(
                            "Parameter '{}' must be a JSON scalar",
                            key
                        )));
                    }
                    NGValue::try_from_json_scalar(expected, v).ok_or(
                        DriverError::ValidationError(format!(
                            "Parameter '{}' type conversion failed (expected {:?})",
                            key, expected
                        )),
                    )?
                }
                None => {
                    let dv = param
                        .default_value()
                        .ok_or(DriverError::ConfigurationError(format!(
                            "Optional parameter '{}' missing default value",
                            key
                        )))?;
                    if dv.is_null() {
                        return Err(DriverError::ValidationError(format!(
                            "Parameter '{}' default value is null",
                            key
                        )));
                    }
                    if dv.is_array() || dv.is_object() {
                        return Err(DriverError::ValidationError(format!(
                            "Parameter '{}' default value must be a JSON scalar",
                            key
                        )));
                    }
                    NGValue::try_from_json_scalar(expected, &dv).ok_or(
                        DriverError::ValidationError(format!(
                            "Parameter '{}' type conversion failed (expected {:?})",
                            key, expected
                        )),
                    )?
                }
            }
        } else {
            let chosen: &serde_json::Value = if total == 1 || required_keys.len() == 1 {
                match params_obj {
                    Some(map) => match map.get(key) {
                        Some(v) => v,
                        None => params_value.ok_or(DriverError::ConfigurationError(
                            "Missing parameters for required input".to_string(),
                        ))?,
                    },
                    None => params_value.ok_or(DriverError::ConfigurationError(
                        "Missing parameters for required input".to_string(),
                    ))?,
                }
            } else {
                params_obj
                    .and_then(|m| m.get(key))
                    .ok_or(DriverError::ConfigurationError(format!(
                        "Missing value for required parameter '{}'",
                        key
                    )))?
            };

            if chosen.is_null() {
                return Err(DriverError::ValidationError(format!(
                    "Parameter '{}' is null",
                    key
                )));
            }
            if chosen.is_array() || chosen.is_object() {
                return Err(DriverError::ValidationError(format!(
                    "Parameter '{}' must be a JSON scalar",
                    key
                )));
            }
            NGValue::try_from_json_scalar(expected, chosen).ok_or(DriverError::ValidationError(
                format!(
                    "Parameter '{}' type conversion failed (expected {:?})",
                    key, expected
                ),
            ))?
        };

        // Numeric range checks (only when declared on the parameter).
        let need_range = param.min_value().is_some() || param.max_value().is_some();
        if need_range {
            let numeric_value: Option<f64> = match &ng {
                NGValue::Int8(v) => Some(*v as f64),
                NGValue::UInt8(v) => Some(*v as f64),
                NGValue::Int16(v) => Some(*v as f64),
                NGValue::UInt16(v) => Some(*v as f64),
                NGValue::Int32(v) => Some(*v as f64),
                NGValue::UInt32(v) => Some(*v as f64),
                NGValue::Int64(v) => Some(*v as f64),
                NGValue::UInt64(v) => Some(*v as f64),
                NGValue::Float32(v) => Some(*v as f64),
                NGValue::Float64(v) => Some(*v),
                NGValue::Timestamp(ms) => Some(*ms as f64),
                _ => None,
            };

            if let Some(v) = numeric_value {
                if let Some(min) = param.min_value() {
                    if v < min {
                        range_errors.push(format!("{key} < min_value ({min})"));
                    }
                }
                if let Some(max) = param.max_value() {
                    if v > max {
                        range_errors.push(format!("{key} > max_value ({max})"));
                    }
                }
            }
        }

        out.push((Arc::clone(param), ng));
    }

    if range_errors.is_empty() {
        Ok(out)
    } else {
        Err(DriverError::ValidationError(format!(
            "Parameter validation failed: {}",
            range_errors.join("; ")
        )))
    }
}

/// Downcast resolved parameters to a concrete protocol parameter type.
pub fn downcast_parameters<P: RuntimeParameter + 'static>(
    params: Vec<(Arc<dyn RuntimeParameter>, NGValue)>,
) -> DriverResult<Vec<(Arc<P>, NGValue)>> {
    let mut out: Vec<(Arc<P>, NGValue)> = Vec::with_capacity(params.len());
    for (p, v) in params.into_iter() {
        let key = p.key().to_string();
        let p = p.downcast_arc::<P>().map_err(|_| {
            DriverError::ConfigurationError(format!(
                "Parameter type mismatch for key '{}' (expected {})",
                key,
                std::any::type_name::<P>()
            ))
        })?;
        out.push((p, v));
    }
    Ok(out)
}