linkrs-core 0.1.0

Core data structures, types, and errors for Linkrs
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
//! JSON/JSONB Types - Graph Database JSON Support
//!
//! This module provides JSON and JSONB types for storing semi-structured data.
//!
//! ## JSON vs JSONB
//!
//! - JSON: Text format, preserves original formatting (whitespace, key order)
//! - JSONB: Binary format, parsed and normalized for better query performance

use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use std::hash::{Hash, Hasher};

/// JSON Error Type
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JsonError {
    InvalidJson(String),
    InvalidPath(String),
    TypeMismatch { expected: String, actual: String },
}

impl std::fmt::Display for JsonError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            JsonError::InvalidJson(msg) => write!(f, "Invalid JSON: {}", msg),
            JsonError::InvalidPath(path) => write!(f, "Invalid JSON path: {}", path),
            JsonError::TypeMismatch { expected, actual } => {
                write!(f, "Type mismatch: expected {}, got {}", expected, actual)
            }
        }
    }
}

impl std::error::Error for JsonError {}

/// JSON Type - Text Storage Format
///
/// Features:
/// - Preserves original text format (including whitespace, key order)
/// - No parsing required on write, better write performance
/// - Parsing required on query
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Json {
    /// Original JSON text
    text: String,
    /// Cached parse result (optional, for improved query performance)
    #[serde(skip)]
    cached_value: Option<JsonValue>,
}

/// JSONB Type - Binary Storage Format
///
/// Features:
/// - Stores parsed binary format
/// - Parsing and validation required on write
/// - Better query performance
/// - Supports GIN index creation
///
/// Serialization note: `JsonValue` (`serde_json::Value`) is a content-tagged
/// enum that postcard (used by WAL/undo persistence) cannot decode. JsonB is
/// therefore serialized as its JSON string, which round-trips losslessly.
#[derive(Debug, Clone)]
pub struct JsonB {
    value: JsonValue,
}

impl Serialize for JsonB {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.value.to_string())
    }
}

impl<'de> Deserialize<'de> for JsonB {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        serde_json::from_str(&text)
            .map(Self::from_value)
            .map_err(serde::de::Error::custom)
    }
}

impl Json {
    /// Create JSON from string
    pub fn parse(text: &str) -> Result<Self, JsonError> {
        // Optional: Validate JSON format
        let value: JsonValue =
            serde_json::from_str(text).map_err(|e| JsonError::InvalidJson(e.to_string()))?;

        Ok(Self {
            text: text.to_string(),
            cached_value: Some(value),
        })
    }

    /// Create from JsonValue
    pub fn from_value(value: JsonValue) -> Self {
        let text = value.to_string();
        Self {
            text,
            cached_value: Some(value),
        }
    }

    /// Get raw text
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Get parsed value (with caching)
    pub fn to_value(&self) -> Result<JsonValue, JsonError> {
        if let Some(ref value) = self.cached_value {
            return Ok(value.clone());
        }

        serde_json::from_str(&self.text).map_err(|e| JsonError::InvalidJson(e.to_string()))
    }

    /// Get value at specified path
    /// Path format: "key1.key2[0].key3"
    pub fn get_path(&self, path: &str) -> Result<Option<JsonValue>, JsonError> {
        let value = self.to_value()?;
        Ok(get_json_path(&value, path))
    }

    /// Convert to JsonB
    pub fn to_jsonb(&self) -> Result<JsonB, JsonError> {
        let value = self.to_value()?;
        Ok(JsonB::from_value(value))
    }

    /// Extract JSON path value, return new Json
    pub fn extract(&self, path: &str) -> Result<Json, JsonError> {
        let json_value = self.get_path(path)?;
        Ok(Json::from_value(json_value.unwrap_or(JsonValue::Null)))
    }

    /// Estimate memory usage
    pub fn estimated_size(&self) -> usize {
        std::mem::size_of::<Self>() + self.text.capacity()
    }
}

impl PartialEq for Json {
    fn eq(&self, other: &Self) -> bool {
        // Compare parsed values, not text
        match (self.to_value(), other.to_value()) {
            (Ok(a), Ok(b)) => a == b,
            _ => false,
        }
    }
}

impl Eq for Json {}

impl Hash for Json {
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Use parsed value for hashing
        if let Ok(value) = self.to_value() {
            hash_json_value(&value, state);
        }
    }
}

// Json and JsonB use serde for serialization, postcard will use serde integration

impl JsonB {
    /// Create JSONB from string (must validate)
    pub fn parse(text: &str) -> Result<Self, JsonError> {
        let value: JsonValue =
            serde_json::from_str(text).map_err(|e| JsonError::InvalidJson(e.to_string()))?;

        Ok(Self::from_value(value))
    }

    /// Create from JsonValue
    pub fn from_value(value: JsonValue) -> Self {
        // Normalize JSON (sort keys, remove whitespace)
        let normalized = normalize_json(value);

        Self { value: normalized }
    }

    /// Get parsed value
    pub fn as_value(&self) -> &JsonValue {
        &self.value
    }

    /// Convert to text format
    pub fn to_json_string(&self) -> String {
        self.value.to_string()
    }

    /// Get value at specified path
    pub fn get_path(&self, path: &str) -> Option<&JsonValue> {
        get_json_path_ref(&self.value, path)
    }

    /// Convert to Json
    pub fn to_json(&self) -> Json {
        Json::from_value(self.value.clone())
    }

    /// Check if contains specified key
    pub fn contains_key(&self, key: &str) -> bool {
        matches!(self.value, JsonValue::Object(ref map) if map.contains_key(key))
    }

    /// Get object key count
    pub fn key_count(&self) -> usize {
        match self.value {
            JsonValue::Object(ref map) => map.len(),
            _ => 0,
        }
    }

    /// Get array length
    pub fn array_len(&self) -> Option<usize> {
        match self.value {
            JsonValue::Array(ref arr) => Some(arr.len()),
            _ => None,
        }
    }

    /// Extract JSON path value, return new JsonB
    pub fn extract(&self, path: &str) -> JsonB {
        let json_value = self.get_path(path).cloned().unwrap_or(JsonValue::Null);
        JsonB::from_value(json_value)
    }

    /// Estimate memory usage
    pub fn estimated_size(&self) -> usize {
        std::mem::size_of::<Self>() + estimate_json_size(&self.value)
    }
}

impl PartialEq for JsonB {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl Eq for JsonB {}

impl Hash for JsonB {
    fn hash<H: Hasher>(&self, state: &mut H) {
        hash_json_value(&self.value, state);
    }
}

impl Ord for JsonB {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // JSONB comparison rules: by type priority, then by value
        compare_json_values(&self.value, &other.value)
    }
}

impl PartialOrd for JsonB {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

// Json and JsonB use serde for serialization, postcard will use serde integration

/// Normalize JSON value (for JSONB)
fn normalize_json(value: JsonValue) -> JsonValue {
    match value {
        JsonValue::Object(map) => {
            // Sort keys and recursively normalize
            let mut entries: Vec<_> = map.into_iter().collect();
            entries.sort_by(|a, b| a.0.cmp(&b.0));
            let normalized: serde_json::Map<String, JsonValue> = entries
                .into_iter()
                .map(|(k, v)| (k, normalize_json(v)))
                .collect();
            JsonValue::Object(normalized)
        }
        JsonValue::Array(arr) => JsonValue::Array(arr.into_iter().map(normalize_json).collect()),
        // Other types remain unchanged
        other => other,
    }
}

/// Get JSON path value
fn get_json_path(value: &JsonValue, path: &str) -> Option<JsonValue> {
    let parts: Vec<&str> = path.split('.').collect();
    let mut current = value;

    for part in parts {
        // Handle array index, e.g., "items[0]"
        if let Some(idx_start) = part.find('[') {
            let key = &part[..idx_start];
            let idx_end = part.find(']').unwrap_or(part.len());
            let idx: usize = part[idx_start + 1..idx_end].parse().ok()?;

            if !key.is_empty() {
                current = current.get(key)?;
            }
            current = current.get(idx)?;
        } else {
            current = current.get(part)?;
        }
    }

    Some(current.clone())
}

/// Get JSON path value (reference version)
fn get_json_path_ref<'a>(value: &'a JsonValue, path: &str) -> Option<&'a JsonValue> {
    let parts: Vec<&str> = path.split('.').collect();
    let mut current = value;

    for part in parts {
        if let Some(idx_start) = part.find('[') {
            let key = &part[..idx_start];
            let idx_end = part.find(']').unwrap_or(part.len());
            let idx: usize = part[idx_start + 1..idx_end].parse().ok()?;

            if !key.is_empty() {
                current = current.get(key)?;
            }
            current = current.get(idx)?;
        } else {
            current = current.get(part)?;
        }
    }

    Some(current)
}

/// Hash JSON value
fn hash_json_value<H: Hasher>(value: &JsonValue, state: &mut H) {
    match value {
        JsonValue::Null => 0u8.hash(state),
        JsonValue::Bool(b) => {
            1u8.hash(state);
            b.hash(state);
        }
        JsonValue::Number(n) => {
            2u8.hash(state);
            n.to_string().hash(state);
        }
        JsonValue::String(s) => {
            3u8.hash(state);
            s.hash(state);
        }
        JsonValue::Array(arr) => {
            4u8.hash(state);
            for item in arr {
                hash_json_value(item, state);
            }
        }
        JsonValue::Object(map) => {
            5u8.hash(state);
            for (k, v) in map {
                k.hash(state);
                hash_json_value(v, state);
            }
        }
    }
}

/// Compare two JSON values
fn compare_json_values(a: &JsonValue, b: &JsonValue) -> std::cmp::Ordering {
    use std::cmp::Ordering;

    // Type priority: Null < Bool < Number < String < Array < Object
    let type_priority = |v: &JsonValue| match v {
        JsonValue::Null => 0,
        JsonValue::Bool(_) => 1,
        JsonValue::Number(_) => 2,
        JsonValue::String(_) => 3,
        JsonValue::Array(_) => 4,
        JsonValue::Object(_) => 5,
    };

    let priority_a = type_priority(a);
    let priority_b = type_priority(b);

    match priority_a.cmp(&priority_b) {
        Ordering::Equal => match (a, b) {
            (JsonValue::Null, JsonValue::Null) => Ordering::Equal,
            (JsonValue::Bool(a), JsonValue::Bool(b)) => a.cmp(b),
            (JsonValue::Number(a), JsonValue::Number(b)) => {
                // Try comparing as integers, otherwise as floats
                if let (Some(a_i), Some(b_i)) = (a.as_i64(), b.as_i64()) {
                    a_i.cmp(&b_i)
                } else if let (Some(a_f), Some(b_f)) = (a.as_f64(), b.as_f64()) {
                    a_f.partial_cmp(&b_f).unwrap_or(Ordering::Equal)
                } else {
                    a.to_string().cmp(&b.to_string())
                }
            }
            (JsonValue::String(a), JsonValue::String(b)) => a.cmp(b),
            (JsonValue::Array(a), JsonValue::Array(b)) => a
                .iter()
                .zip(b.iter())
                .map(|(x, y)| compare_json_values(x, y))
                .find(|&ord| ord != Ordering::Equal)
                .unwrap_or_else(|| a.len().cmp(&b.len())),
            (JsonValue::Object(a), JsonValue::Object(b)) => {
                let a_keys: Vec<_> = a.keys().collect();
                let b_keys: Vec<_> = b.keys().collect();

                match a_keys.cmp(&b_keys) {
                    Ordering::Equal => a_keys
                        .iter()
                        .map(|k| compare_json_values(&a[*k], &b[*k]))
                        .find(|&ord| ord != Ordering::Equal)
                        .unwrap_or(Ordering::Equal),
                    other => other,
                }
            }
            _ => Ordering::Equal, // Different types already handled by priority
        },
        other => other,
    }
}

/// Estimate JSON value memory usage
fn estimate_json_size(value: &JsonValue) -> usize {
    match value {
        JsonValue::Null => 0,
        JsonValue::Bool(_) => 1,
        JsonValue::Number(n) => n.to_string().len(),
        JsonValue::String(s) => s.len(),
        JsonValue::Array(arr) => {
            arr.iter().map(estimate_json_size).sum::<usize>()
                + arr.len() * std::mem::size_of::<JsonValue>()
        }
        JsonValue::Object(map) => {
            map.iter()
                .map(|(k, v)| k.len() + estimate_json_size(v))
                .sum::<usize>()
                + map.len() * std::mem::size_of::<(String, JsonValue)>()
        }
    }
}

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

    #[test]
    fn test_json_from_str() {
        let json = Json::parse(r#"{"name": "test", "value": 123}"#).unwrap();
        assert!(json.get_path("name").unwrap().is_some());
        assert!(json.get_path("value").unwrap().is_some());
    }

    #[test]
    fn test_jsonb_from_str() {
        let jsonb = JsonB::parse(r#"{"name": "test", "value": 123}"#).unwrap();
        assert!(jsonb.contains_key("name"));
        assert!(jsonb.contains_key("value"));
        assert_eq!(jsonb.key_count(), 2);
    }

    #[test]
    fn test_json_path() {
        let json = Json::parse(r#"{"items": [{"name": "a"}, {"name": "b"}]}"#).unwrap();
        let value = json.get_path("items[0].name").unwrap();
        assert!(value.is_some());
    }

    #[test]
    fn test_json_to_jsonb() {
        let json = Json::parse(r#"{"test": 123}"#).unwrap();
        let jsonb = json.to_jsonb().unwrap();
        assert!(jsonb.contains_key("test"));
    }

    #[test]
    fn test_jsonb_comparison() {
        let a = JsonB::parse("1").unwrap();
        let b = JsonB::parse("2").unwrap();
        assert!(a < b);
    }

    #[test]
    fn test_jsonb_equality() {
        let a = JsonB::parse(r#"{"b": 1, "a": 2}"#).unwrap();
        let b = JsonB::parse(r#"{"a": 2, "b": 1}"#).unwrap();
        // JSONB normalizes key order, so these should be equal
        assert_eq!(a, b);
    }
}