daedalus-data 0.1.1

Type/value model and serialization helpers for Daedalus node ports.
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
use serde::{Deserialize, Serialize};

use crate::errors::{DataError, DataErrorCode, DataResult};
use crate::model::{TypeExpr, Value, ValueType};

/// GPU-related hints carried on descriptors.
///
/// ```
/// use daedalus_data::descriptor::{GpuHints, MemoryLocation};
/// let hints = GpuHints { requires_gpu: false, preferred_memory: Some(MemoryLocation::Host) };
/// assert_eq!(hints.preferred_memory, Some(MemoryLocation::Host));
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct GpuHints {
    pub requires_gpu: bool,
    pub preferred_memory: Option<MemoryLocation>,
}

/// Memory location hint for GPU-aware values.
///
/// ```
/// use daedalus_data::descriptor::MemoryLocation;
/// let loc = MemoryLocation::Device;
/// assert_eq!(loc, MemoryLocation::Device);
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum MemoryLocation {
    Host,
    Device,
    Shared,
}

/// Descriptor for values/types.
///
/// ```
/// use daedalus_data::descriptor::{DataDescriptor, DescriptorId, DescriptorVersion};
/// let desc = DataDescriptor {
///     id: DescriptorId::new("example"),
///     version: DescriptorVersion::new("1.0.0"),
///     label: None,
///     settable: false,
///     default: None,
///     schema: None,
///     codecs: vec![],
///     converters: vec![],
///     feature_flags: vec![],
///     gpu: None,
///     type_expr: None,
/// };
/// assert_eq!(desc.id.0, "example");
/// ```
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataDescriptor {
    pub id: DescriptorId,
    pub version: DescriptorVersion,
    pub label: Option<String>,
    pub settable: bool,
    pub default: Option<Value>,
    pub schema: Option<String>,
    pub codecs: Vec<String>,
    pub converters: Vec<String>,
    pub feature_flags: Vec<String>,
    pub gpu: Option<GpuHints>,
    pub type_expr: Option<TypeExpr>,
}

impl DataDescriptor {
    /// Validate the descriptor, including type/default compatibility.
    ///
    /// ```
    /// use daedalus_data::descriptor::{DataDescriptor, DescriptorId, DescriptorVersion};
    /// let desc = DataDescriptor {
    ///     id: DescriptorId::new("example"),
    ///     version: DescriptorVersion::new("1.0"),
    ///     label: None,
    ///     settable: false,
    ///     default: None,
    ///     schema: None,
    ///     codecs: vec![],
    ///     converters: vec![],
    ///     feature_flags: vec![],
    ///     gpu: None,
    ///     type_expr: None,
    /// };
    /// desc.validate().unwrap();
    /// ```
    pub fn validate(&self) -> DataResult<()> {
        self.id.validate()?;
        self.version.validate()?;
        if let Some(default) = &self.default {
            if self.type_expr.is_none() {
                return Err(DataError::new(
                    DataErrorCode::InvalidDescriptor,
                    "type_expr is required when default is present",
                ));
            }
            validate_default(self.type_expr.as_ref().unwrap(), default)?;
        }
        Ok(())
    }

    /// Deterministic ordering for codecs/converters/feature flags.
    ///
    /// ```
    /// use daedalus_data::descriptor::{DataDescriptor, DescriptorId, DescriptorVersion};
    /// let desc = DataDescriptor {
    ///     id: DescriptorId::new("id"),
    ///     version: DescriptorVersion::new("1.0"),
    ///     label: None,
    ///     settable: false,
    ///     default: None,
    ///     schema: None,
    ///     codecs: vec!["b".into(), "a".into()],
    ///     converters: vec!["y".into(), "x".into()],
    ///     feature_flags: vec!["b".into(), "a".into()],
    ///     gpu: None,
    ///     type_expr: None,
    /// };
    /// let sorted = desc.normalize();
    /// assert_eq!(sorted.codecs, vec!["a", "b"]);
    /// ```
    pub fn normalize(mut self) -> Self {
        self.codecs.sort();
        self.converters.sort();
        self.feature_flags.sort();
        self
    }
}

/// Builder to construct descriptors with deterministic ordering.
///
/// ```
/// use daedalus_data::descriptor::{DescriptorBuilder, GpuHints, MemoryLocation};
/// use daedalus_data::errors::DataResult;
/// use daedalus_data::model::{TypeExpr, Value, ValueType};
///
/// fn build_descriptor() -> DataResult<()> {
///     let desc = DescriptorBuilder::new("example", "1.0.0")
///         .label("Example")
///         .settable(true)
///         .type_expr(TypeExpr::Scalar(ValueType::String))
///         .default(Value::String("hi".into()))
///         .codec("json")
///         .feature_flag("core")
///         .gpu_hints(GpuHints { requires_gpu: false, preferred_memory: Some(MemoryLocation::Host) })
///         .build()?;
///     assert_eq!(desc.codecs, vec!["json"]);
///     Ok(())
/// }
/// ```
pub struct DescriptorBuilder {
    inner: DataDescriptor,
}

impl DescriptorBuilder {
    pub fn new(id: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            inner: DataDescriptor {
                id: DescriptorId::new(id.into()),
                version: DescriptorVersion::new(version.into()),
                label: None,
                settable: false,
                default: None,
                schema: None,
                codecs: Vec::new(),
                converters: Vec::new(),
                feature_flags: Vec::new(),
                gpu: None,
                type_expr: None,
            },
        }
    }

    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.inner.label = Some(label.into());
        self
    }

    pub fn settable(mut self, settable: bool) -> Self {
        self.inner.settable = settable;
        self
    }

    pub fn default(mut self, default: Value) -> Self {
        self.inner.default = Some(default);
        self
    }

    pub fn schema(mut self, schema: impl Into<String>) -> Self {
        self.inner.schema = Some(schema.into());
        self
    }

    pub fn codec(mut self, codec: impl Into<String>) -> Self {
        self.inner.codecs.push(codec.into());
        self
    }

    pub fn converter(mut self, conv: impl Into<String>) -> Self {
        self.inner.converters.push(conv.into());
        self
    }

    pub fn feature_flag(mut self, flag: impl Into<String>) -> Self {
        self.inner.feature_flags.push(flag.into());
        self
    }

    pub fn gpu_hints(mut self, hints: GpuHints) -> Self {
        self.inner.gpu = Some(hints);
        self
    }

    pub fn type_expr(mut self, ty: TypeExpr) -> Self {
        self.inner.type_expr = Some(ty.normalize());
        self
    }

    pub fn build(self) -> DataResult<DataDescriptor> {
        let desc = self.inner.normalize();
        desc.validate()?;
        Ok(desc)
    }
}

/// Descriptor for a type expression with associated metadata.
///
/// ```
/// use daedalus_data::descriptor::{DataDescriptor, DescriptorId, DescriptorVersion, TypeDescriptor};
/// use daedalus_data::model::{TypeExpr, ValueType};
/// let desc = DataDescriptor {
///     id: DescriptorId::new("demo"),
///     version: DescriptorVersion::new("1.0.0"),
///     label: None,
///     settable: false,
///     default: None,
///     schema: None,
///     codecs: vec![],
///     converters: vec![],
///     feature_flags: vec![],
///     gpu: None,
///     type_expr: None,
/// };
/// let typed = TypeDescriptor { ty: TypeExpr::Scalar(ValueType::Int), descriptor: desc };
/// assert!(matches!(typed.ty, TypeExpr::Scalar(_)));
/// ```
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TypeDescriptor {
    pub ty: TypeExpr,
    pub descriptor: DataDescriptor,
}

/// Strongly typed descriptor id with basic namespace validation.
///
/// ```
/// use daedalus_data::descriptor::DescriptorId;
/// let id = DescriptorId::namespaced("sensor", "temp");
/// assert_eq!(id.0, "sensor.temp");
/// ```
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hash)]
pub struct DescriptorId(pub String);

impl DescriptorId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn namespaced(namespace: impl Into<String>, name: impl Into<String>) -> Self {
        let ns = namespace.into();
        let name = name.into();
        if ns.is_empty() {
            return Self(name);
        }
        Self(format!("{ns}.{name}"))
    }
    pub fn validate(&self) -> DataResult<()> {
        if self.0.is_empty() {
            return Err(DataError::new(
                DataErrorCode::InvalidDescriptor,
                "id must not be empty",
            ));
        }
        if !self.0.chars().all(|c| {
            c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' || c == '_' || c == '-'
        }) {
            return Err(DataError::new(
                DataErrorCode::InvalidDescriptor,
                "id must be lowercase/digit/._-",
            ));
        }
        Ok(())
    }
}

/// Strongly typed semantic version string.
///
/// ```
/// use daedalus_data::descriptor::DescriptorVersion;
/// let ver = DescriptorVersion::new("1.2.3");
/// assert_eq!(ver.0, "1.2.3");
/// ```
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hash)]
pub struct DescriptorVersion(pub String);

impl DescriptorVersion {
    pub fn new(v: impl Into<String>) -> Self {
        Self(v.into())
    }
    pub fn validate(&self) -> DataResult<()> {
        let parts: Vec<_> = self.0.split('.').collect();
        if parts.len() < 2 {
            return Err(DataError::new(
                DataErrorCode::InvalidDescriptor,
                "version must be at least major.minor",
            ));
        }
        if parts
            .iter()
            .any(|p| p.is_empty() || p.chars().any(|c| !c.is_ascii_digit()))
        {
            return Err(DataError::new(
                DataErrorCode::InvalidDescriptor,
                "version segments must be numeric",
            ));
        }
        Ok(())
    }
}

fn validate_default(ty: &TypeExpr, value: &Value) -> DataResult<()> {
    match (ty, value) {
        (TypeExpr::Scalar(ValueType::Unit), Value::Unit) => Ok(()),
        (TypeExpr::Scalar(ValueType::Bool), Value::Bool(_)) => Ok(()),
        (TypeExpr::Scalar(ValueType::I32 | ValueType::U32 | ValueType::Int), Value::Int(_)) => {
            Ok(())
        }
        (TypeExpr::Scalar(ValueType::F32 | ValueType::Float), Value::Float(_)) => Ok(()),
        (TypeExpr::Scalar(ValueType::String), Value::String(_)) => Ok(()),
        (TypeExpr::Scalar(ValueType::Bytes), Value::Bytes(_)) => Ok(()),
        (TypeExpr::Optional(inner), v) => validate_default(inner, v),
        (TypeExpr::List(inner), Value::List(items)) => {
            for v in items {
                validate_default(inner, v)?;
            }
            Ok(())
        }
        (TypeExpr::Map(k_ty, v_ty), Value::Map(entries)) => {
            for (k, v) in entries {
                validate_default(k_ty, k)?;
                validate_default(v_ty, v)?;
            }
            Ok(())
        }
        (TypeExpr::Tuple(types), Value::Tuple(values)) => {
            if types.len() != values.len() {
                return Err(DataError::new(
                    DataErrorCode::InvalidType,
                    "tuple length mismatch",
                ));
            }
            for (t, v) in types.iter().zip(values.iter()) {
                validate_default(t, v)?;
            }
            Ok(())
        }
        (TypeExpr::Struct(fields), Value::Struct(values)) => {
            if fields.len() != values.len() {
                return Err(DataError::new(
                    DataErrorCode::InvalidType,
                    "struct field count mismatch",
                ));
            }
            for (field, val) in fields.iter().zip(values.iter()) {
                if field.name != val.name {
                    return Err(DataError::new(
                        DataErrorCode::InvalidType,
                        "struct field name mismatch",
                    ));
                }
                validate_default(&field.ty, &val.value)?;
            }
            Ok(())
        }
        (TypeExpr::Enum(variants), Value::Enum(ev)) => {
            let variant = variants.iter().find(|v| v.name == ev.name).ok_or_else(|| {
                DataError::new(DataErrorCode::InvalidType, "enum variant not found")
            })?;
            match (&variant.ty, &ev.value) {
                (None, None) => Ok(()),
                (Some(t), Some(v)) => validate_default(t, v),
                (None, Some(_)) | (Some(_), None) => Err(DataError::new(
                    DataErrorCode::InvalidType,
                    "enum payload mismatch",
                )),
            }
        }
        _ => Err(DataError::new(
            DataErrorCode::InvalidType,
            "default does not match type_expr",
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{StructField, StructFieldValue};

    #[test]
    fn normalize_sorts_fields() {
        let desc = DataDescriptor {
            id: DescriptorId::new("id"),
            version: DescriptorVersion::new("v1"),
            label: None,
            settable: true,
            default: None,
            schema: None,
            codecs: vec!["b".into(), "a".into()],
            converters: vec!["y".into(), "x".into()],
            feature_flags: vec!["f2".into(), "f1".into()],
            gpu: None,
            type_expr: None,
        }
        .normalize();
        assert_eq!(desc.codecs, vec!["a", "b"]);
        assert_eq!(desc.converters, vec!["x", "y"]);
        assert_eq!(desc.feature_flags, vec!["f1", "f2"]);
    }

    #[test]
    fn serde_preserves_sorted_order() {
        let desc = DescriptorBuilder::new("id", "1.0")
            .codec("z")
            .codec("a")
            .converter("b")
            .converter("a")
            .feature_flag("beta")
            .feature_flag("alpha")
            .build()
            .expect("build");
        let json = serde_json::to_string(&desc).unwrap();
        assert!(json.find("a").unwrap() < json.find("z").unwrap());
        assert!(json.find("alpha").unwrap() < json.find("beta").unwrap());
    }

    /// Minimal registry fixture showing `(id, version)` uniqueness and conflict diagnostics.
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use daedalus_data::descriptor::{DataDescriptor, DescriptorBuilder, DescriptorId, DescriptorVersion};
    ///
    /// #[derive(Default)]
    /// struct Registry {
    ///     entries: HashMap<(DescriptorId, DescriptorVersion), DataDescriptor>,
    /// }
    ///
    /// impl Registry {
    ///     fn register(&mut self, desc: DataDescriptor) -> Result<(), String> {
    ///         let key = (desc.id.clone(), desc.version.clone());
    ///         if self.entries.contains_key(&key) {
    ///             return Err(format!("duplicate descriptor {:?},{}", key.0, key.1));
    ///         }
    ///         self.entries.insert(key, desc);
    ///         Ok(())
    ///     }
    /// }
    ///
    /// let mut reg = Registry::default();
    /// let desc = DescriptorBuilder::new("sensor.temp", "1.0.0").build().unwrap();
    /// reg.register(desc.clone()).unwrap();
    /// assert!(reg.register(desc).is_err());
    /// ```
    #[test]
    fn registry_fixture_compiles() {
        // Doc-test above is the primary fixture; keep this test as a placeholder.
    }

    #[test]
    fn golden_descriptor_serialization_is_stable() {
        let desc = DescriptorBuilder::new("id", "1.0")
            .label("Example")
            .settable(true)
            .codec("json")
            .converter("int_to_string")
            .feature_flag("core")
            .build()
            .expect("build");
        let json = serde_json::to_string(&desc).unwrap();
        assert_eq!(
            json,
            r#"{"id":"id","version":"1.0","label":"Example","settable":true,"default":null,"schema":null,"codecs":["json"],"converters":["int_to_string"],"feature_flags":["core"],"gpu":null,"type_expr":null}"#
        );
    }

    #[test]
    fn validates_default_against_type() {
        let desc = DescriptorBuilder::new("id", "1.0")
            .type_expr(TypeExpr::Scalar(ValueType::String))
            .default(Value::String("ok".into()))
            .build()
            .unwrap();
        assert_eq!(desc.id.0, "id");

        let err = DescriptorBuilder::new("id2", "1.0")
            .type_expr(TypeExpr::Scalar(ValueType::Int))
            .default(Value::Bool(true))
            .build()
            .unwrap_err();
        assert_eq!(err.code(), DataErrorCode::InvalidType);

        let err = DescriptorBuilder::new("id3", "1.0")
            .type_expr(TypeExpr::Struct(vec![StructField {
                name: "a".into(),
                ty: TypeExpr::Scalar(ValueType::Int),
            }]))
            .default(Value::Struct(vec![StructFieldValue {
                name: "a".into(),
                value: Value::Int(1),
            }]))
            .build()
            .unwrap();
        assert_eq!(err.id.0, "id3");
    }
}