datafold 0.1.55

A personal database for data sovereignty with AI-powered ingestion
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
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
#[cfg(feature = "ts-bindings")]
use ts_rs::TS;

use crate::schema::SchemaError;

/// Represents the topology (structure) of a JSON field
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
pub struct JsonTopology {
    /// Root structure definition
    pub root: TopologyNode,
}

/// Represents a node in the JSON topology tree
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
#[serde(tag = "type")]
pub enum TopologyNode {
    /// Primitive type with optional classifications (required for index schemas)
    #[serde(rename = "Primitive")]
    Primitive {
        value: PrimitiveValueType,
        #[serde(skip_serializing_if = "Option::is_none")]
        classifications: Option<Vec<String>>,
    },
    /// Object with named fields and their topologies
    Object {
        value: HashMap<String, TopologyNode>,
    },
    /// Array of a specific type
    Array { value: Box<TopologyNode> },
    /// Any type (no validation)
    Any,
}

/// Primitive JSON value types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts-bindings", derive(TS))]
#[cfg_attr(feature = "ts-bindings", ts(export))]
pub enum PrimitiveValueType {
    String,
    Number,
    Boolean,
    Null,
}

/// Legacy type alias for backward compatibility
pub type PrimitiveType = PrimitiveValueType;

impl JsonTopology {
    /// Create a new topology with a root node
    pub fn new(root: TopologyNode) -> Self {
        Self { root }
    }

    /// Create a topology that accepts any structure
    pub fn any() -> Self {
        Self {
            root: TopologyNode::Any,
        }
    }

    /// Validate that a JSON value conforms to this topology
    pub fn validate(&self, value: &JsonValue) -> Result<(), SchemaError> {
        self.root.validate(value, "root")
    }

    /// Infer topology from a sample JSON value
    pub fn infer_from_value(value: &JsonValue) -> Self {
        Self {
            root: TopologyNode::infer_from_value(value),
        }
    }

    /// Compute a SHA256 hash of this topology
    /// This creates a unique fingerprint of the topology structure
    pub fn compute_hash(&self) -> String {
        let canonical = serde_json::to_string(&self.root).unwrap_or_else(|_| "{}".to_string());
        let mut hasher = Sha256::new();
        hasher.update(canonical.as_bytes());
        format!("{:x}", hasher.finalize())
    }
}

impl TopologyNode {
    /// Validate that a JSON value conforms to this topology node
    pub fn validate(&self, value: &JsonValue, path: &str) -> Result<(), SchemaError> {
        match self {
            // Any accepts everything
            TopologyNode::Any => Ok(()),

            // Primitive validations
            TopologyNode::Primitive {
                value: prim_type, ..
            } => {
                match (prim_type, value) {
                    (PrimitiveValueType::String, JsonValue::String(_)) => Ok(()),
                    (PrimitiveValueType::Number, JsonValue::Number(_)) => Ok(()),
                    (PrimitiveValueType::Boolean, JsonValue::Bool(_)) => Ok(()),
                    // Null is always acceptable for any primitive type (nullable fields)
                    (_, JsonValue::Null) => Ok(()),
                    _ => Err(SchemaError::InvalidData(format!(
                        "Topology validation failed at '{}': expected {:?}, got {:?}",
                        path,
                        prim_type,
                        value_type_name(value)
                    ))),
                }
            }

            // Object validation
            TopologyNode::Object {
                value: expected_fields,
            } => {
                if let JsonValue::Object(obj) = value {
                    for (field_name, field_topology) in expected_fields {
                        if let Some(field_value) = obj.get(field_name) {
                            let field_path = format!("{}.{}", path, field_name);
                            field_topology.validate(field_value, &field_path)?;
                        }
                        // Missing fields are allowed - this enables partial updates
                    }
                    Ok(())
                } else {
                    Err(SchemaError::InvalidData(format!(
                        "Topology validation failed at '{}': expected object, got {:?}",
                        path,
                        value_type_name(value)
                    )))
                }
            }

            // Array validation
            TopologyNode::Array {
                value: element_topology,
            } => {
                if let JsonValue::Array(arr) = value {
                    for (idx, element) in arr.iter().enumerate() {
                        let element_path = format!("{}[{}]", path, idx);
                        element_topology.validate(element, &element_path)?;
                    }
                    Ok(())
                } else {
                    Err(SchemaError::InvalidData(format!(
                        "Topology validation failed at '{}': expected array, got {:?}",
                        path,
                        value_type_name(value)
                    )))
                }
            }
        }
    }

    /// Infer topology from a sample JSON value
    pub fn infer_from_value(value: &JsonValue) -> Self {
        match value {
            JsonValue::String(_) => TopologyNode::Primitive {
                value: PrimitiveValueType::String,
                classifications: None,
            },
            JsonValue::Number(_) => TopologyNode::Primitive {
                value: PrimitiveValueType::Number,
                classifications: None,
            },
            JsonValue::Bool(_) => TopologyNode::Primitive {
                value: PrimitiveValueType::Boolean,
                classifications: None,
            },
            // Null values don't provide type information - use Any to accept any type later
            JsonValue::Null => TopologyNode::Any,
            JsonValue::Array(arr) => {
                // Infer from first element, or use Any if empty
                let element_topology = arr
                    .first()
                    .map(Self::infer_from_value)
                    .unwrap_or(TopologyNode::Any);
                TopologyNode::Array {
                    value: Box::new(element_topology),
                }
            }
            JsonValue::Object(obj) => {
                let mut fields = HashMap::new();
                for (key, val) in obj {
                    fields.insert(key.clone(), Self::infer_from_value(val));
                }
                TopologyNode::Object { value: fields }
            }
        }
    }
}

/// Get a human-readable name for a JSON value type
fn value_type_name(value: &JsonValue) -> &'static str {
    match value {
        JsonValue::String(_) => "string",
        JsonValue::Number(_) => "number",
        JsonValue::Bool(_) => "boolean",
        JsonValue::Null => "null",
        JsonValue::Array(_) => "array",
        JsonValue::Object(_) => "object",
    }
}

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

    #[test]
    fn test_primitive_validation() {
        let topology = JsonTopology::new(TopologyNode::Primitive {
            value: PrimitiveValueType::String,
            classifications: None,
        });

        assert!(topology.validate(&json!("hello")).is_ok());
        assert!(topology.validate(&json!(42)).is_err());
        assert!(topology.validate(&json!(true)).is_err());
    }

    #[test]
    fn test_object_validation() {
        let mut fields = HashMap::new();
        fields.insert(
            "name".to_string(),
            TopologyNode::Primitive {
                value: PrimitiveValueType::String,
                classifications: None,
            },
        );
        fields.insert(
            "age".to_string(),
            TopologyNode::Primitive {
                value: PrimitiveValueType::Number,
                classifications: None,
            },
        );

        let topology = JsonTopology::new(TopologyNode::Object { value: fields });

        // Valid object
        assert!(topology
            .validate(&json!({"name": "Alice", "age": 30}))
            .is_ok());

        // Partial object (missing fields allowed)
        assert!(topology.validate(&json!({"name": "Bob"})).is_ok());

        // Wrong type
        assert!(topology
            .validate(&json!({"name": "Alice", "age": "thirty"}))
            .is_err());

        // Not an object
        assert!(topology.validate(&json!("string")).is_err());
    }

    #[test]
    fn test_array_validation() {
        let topology = JsonTopology::new(TopologyNode::Array {
            value: Box::new(TopologyNode::Primitive {
                value: PrimitiveValueType::Number,
                classifications: None,
            }),
        });

        assert!(topology.validate(&json!([1, 2, 3])).is_ok());
        assert!(topology.validate(&json!([])).is_ok());
        assert!(topology.validate(&json!([1, "two", 3])).is_err());
    }

    #[test]
    fn test_nested_validation() {
        let mut user_fields = HashMap::new();
        user_fields.insert(
            "id".to_string(),
            TopologyNode::Primitive {
                value: PrimitiveValueType::Number,
                classifications: None,
            },
        );
        user_fields.insert(
            "name".to_string(),
            TopologyNode::Primitive {
                value: PrimitiveValueType::String,
                classifications: None,
            },
        );

        let mut root_fields = HashMap::new();
        root_fields.insert(
            "user".to_string(),
            TopologyNode::Object { value: user_fields },
        );
        root_fields.insert(
            "active".to_string(),
            TopologyNode::Primitive {
                value: PrimitiveValueType::Boolean,
                classifications: None,
            },
        );

        let topology = JsonTopology::new(TopologyNode::Object { value: root_fields });

        // Valid nested structure
        assert!(topology
            .validate(&json!({
                "user": {"id": 1, "name": "Alice"},
                "active": true
            }))
            .is_ok());

        // Invalid nested field
        assert!(topology
            .validate(&json!({
                "user": {"id": "not a number", "name": "Alice"},
                "active": true
            }))
            .is_err());
    }

    #[test]
    fn test_any_topology() {
        let topology = JsonTopology::any();

        assert!(topology.validate(&json!("string")).is_ok());
        assert!(topology.validate(&json!(42)).is_ok());
        assert!(topology.validate(&json!({"any": "structure"})).is_ok());
        assert!(topology.validate(&json!([1, "two", true])).is_ok());
    }

    #[test]
    fn test_infer_from_value() {
        let value = json!({
            "name": "Alice",
            "age": 30,
            "active": true,
            "tags": ["rust", "database"]
        });

        let topology = JsonTopology::infer_from_value(&value);

        // Should validate the original value
        assert!(topology.validate(&value).is_ok());

        // Should validate similar structure
        assert!(topology
            .validate(&json!({
                "name": "Bob",
                "age": 25,
                "active": false,
                "tags": ["python"]
            }))
            .is_ok());

        // Should reject different structure
        assert!(topology
            .validate(&json!({
                "name": "Charlie",
                "age": "thirty"
            }))
            .is_err());
    }

    #[test]
    fn test_nullable_primitives() {
        // All primitive types should accept null values
        let string_topology = JsonTopology::new(TopologyNode::Primitive {
            value: PrimitiveValueType::String,
            classifications: None,
        });
        assert!(string_topology.validate(&json!(null)).is_ok());
        assert!(string_topology.validate(&json!("hello")).is_ok());

        let number_topology = JsonTopology::new(TopologyNode::Primitive {
            value: PrimitiveValueType::Number,
            classifications: None,
        });
        assert!(number_topology.validate(&json!(null)).is_ok());
        assert!(number_topology.validate(&json!(42)).is_ok());

        let bool_topology = JsonTopology::new(TopologyNode::Primitive {
            value: PrimitiveValueType::Boolean,
            classifications: None,
        });
        assert!(bool_topology.validate(&json!(null)).is_ok());
        assert!(bool_topology.validate(&json!(true)).is_ok());
    }

    #[test]
    fn test_nullable_fields_in_object() {
        let mut fields = HashMap::new();
        fields.insert(
            "thread_position".to_string(),
            TopologyNode::Primitive {
                value: PrimitiveValueType::Number,
                classifications: None,
            },
        );
        fields.insert(
            "reply_to".to_string(),
            TopologyNode::Primitive {
                value: PrimitiveValueType::String,
                classifications: None,
            },
        );

        let topology = JsonTopology::new(TopologyNode::Object { value: fields });

        // Should accept null for numeric field
        assert!(topology
            .validate(&json!({"thread_position": null, "reply_to": "tweet_123"}))
            .is_ok());

        // Should accept null for string field
        assert!(topology
            .validate(&json!({"thread_position": 1, "reply_to": null}))
            .is_ok());

        // Should accept proper types
        assert!(topology
            .validate(&json!({"thread_position": 1, "reply_to": "tweet_123"}))
            .is_ok());
    }

    #[test]
    fn test_infer_from_null_uses_any() {
        // When inferring from null, should use Any type (not Null type)
        let topology = JsonTopology::infer_from_value(&json!(null));

        // Should accept any value type
        assert!(topology.validate(&json!(null)).is_ok());
        assert!(topology.validate(&json!("string")).is_ok());
        assert!(topology.validate(&json!(42)).is_ok());
        assert!(topology.validate(&json!(true)).is_ok());
        assert!(topology.validate(&json!({"key": "value"})).is_ok());
        assert!(topology.validate(&json!([1, 2, 3])).is_ok());
    }

    #[test]
    fn test_infer_from_object_with_null_fields() {
        // Object with null field should infer that field as Any
        let sample = json!({
            "name": "Alice",
            "optional_field": null
        });

        let topology = JsonTopology::infer_from_value(&sample);

        // Should accept the original
        assert!(topology.validate(&sample).is_ok());

        // Should accept when optional_field becomes a string
        assert!(topology
            .validate(&json!({
                "name": "Bob",
                "optional_field": "now a string"
            }))
            .is_ok());

        // Should accept when optional_field becomes a number
        assert!(topology
            .validate(&json!({
                "name": "Charlie",
                "optional_field": 42
            }))
            .is_ok());
    }
}