1use serde::{Deserialize, Serialize};
8use std::collections::{BTreeMap, HashMap};
9
10#[derive(Debug, Clone, Default, PartialEq)]
16pub struct Properties(pub HashMap<String, serde_json::Value>);
17
18impl From<HashMap<String, serde_json::Value>> for Properties {
19 fn from(map: HashMap<String, serde_json::Value>) -> Self {
20 Self(map)
21 }
22}
23
24impl std::ops::Deref for Properties {
25 type Target = HashMap<String, serde_json::Value>;
26 fn deref(&self) -> &Self::Target {
27 &self.0
28 }
29}
30
31impl std::ops::DerefMut for Properties {
32 fn deref_mut(&mut self) -> &mut Self::Target {
33 &mut self.0
34 }
35}
36
37impl Serialize for Properties {
38 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
39 let sorted: BTreeMap<&String, &serde_json::Value> = self.0.iter().collect();
45 if serializer.is_human_readable() {
46 sorted.serialize(serializer)
47 } else {
48 let json = serde_json::to_vec(&sorted).map_err(serde::ser::Error::custom)?;
49 json.serialize(serializer)
50 }
51 }
52}
53
54impl<'de> Deserialize<'de> for Properties {
55 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
56 if deserializer.is_human_readable() {
57 let map = HashMap::<String, serde_json::Value>::deserialize(deserializer)?;
58 Ok(Self(map))
59 } else {
60 let json = Vec::<u8>::deserialize(deserializer)?;
61 let map = serde_json::from_slice(&json).map_err(serde::de::Error::custom)?;
62 Ok(Self(map))
63 }
64 }
65}
66
67#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
73pub struct Node {
74 pub id: u64,
76 pub uuid: [u8; 16],
78 pub kind: String,
80 pub title: String,
82 pub body: String,
84 pub body_html: String,
86 pub created_at: i64,
88 pub updated_at: i64,
90 pub properties: Properties,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct NewNode {
99 pub kind: String,
101 pub title: String,
103 pub body: String,
105 pub body_html: String,
107 pub properties: Properties,
109}
110
111#[derive(Debug, Clone, Default, Serialize, Deserialize)]
115pub struct NodePatch {
116 pub kind: Option<String>,
118 pub title: Option<String>,
121 pub body: Option<String>,
123 pub body_html: Option<String>,
125 pub properties: Option<Properties>,
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
134pub struct Edge {
135 pub id: u64,
137 pub uuid: [u8; 16],
139 pub from_id: u64,
141 pub to_id: u64,
143 pub kind: String,
145 pub weight: f32,
147 pub created_at: i64,
149 pub properties: Properties,
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
157pub struct NewEdge {
158 pub from_id: u64,
160 pub to_id: u64,
162 pub kind: String,
164 pub weight: f32,
166 pub properties: Properties,
168}
169
170#[derive(Debug, Clone, Default, Serialize, Deserialize)]
174pub struct EdgePatch {
175 pub kind: Option<String>,
177 pub weight: Option<f32>,
179 pub properties: Option<Properties>,
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum Direction {
186 Outgoing,
188 Incoming,
190 Both,
192}
193
194#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
199pub struct ScoredNode {
200 pub node: Node,
202 pub score: f32,
204}
205
206#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
211pub struct ScoredEdge {
212 pub edge: Edge,
214 pub score: f32,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq)]
225pub enum FtsRanking {
226 Bm25 {
230 k1: f32,
234 b: f32,
238 },
239 TfIdf,
243}
244
245impl FtsRanking {
246 pub const fn bm25_default() -> Self {
249 FtsRanking::Bm25 { k1: 1.2, b: 0.75 }
250 }
251}
252
253impl Default for FtsRanking {
254 fn default() -> Self {
255 FtsRanking::bm25_default()
256 }
257}
258
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
265pub struct SubGraph {
266 pub nodes: Vec<Node>,
268 pub edges: Vec<Edge>,
270}
271
272#[cfg(not(target_arch = "wasm32"))]
274pub fn new_uuid_v7() -> [u8; 16] {
275 *uuid::Uuid::now_v7().as_bytes()
276}
277
278#[cfg(target_arch = "wasm32")]
286pub fn new_uuid_v7() -> [u8; 16] {
287 let ms = now_ms();
288 let secs = (ms / 1000) as u64;
289 let nanos = ((ms % 1000) * 1_000_000) as u32;
290 let ts = uuid::Timestamp::from_unix(uuid::NoContext, secs, nanos);
291 *uuid::Uuid::new_v7(ts).as_bytes()
292}
293
294#[cfg(not(target_arch = "wasm32"))]
302pub fn now_ms() -> i64 {
303 match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
304 Ok(dur) => dur.as_millis() as i64,
305 Err(err) => -(err.duration().as_millis() as i64),
306 }
307}
308
309#[cfg(target_arch = "wasm32")]
316pub fn now_ms() -> i64 {
317 js_sys::Date::now() as i64
318}
319
320impl Node {
321 pub fn apply_patch(&mut self, patch: NodePatch) {
324 if let Some(kind) = patch.kind {
325 self.kind = kind;
326 }
327 if let Some(title) = patch.title {
328 self.title = title;
329 }
330 if let Some(body) = patch.body {
331 self.body = body;
332 }
333 if let Some(body_html) = patch.body_html {
334 self.body_html = body_html;
335 }
336 if let Some(properties) = patch.properties {
337 self.properties = properties;
338 }
339 self.updated_at = now_ms();
340 }
341}
342
343impl Edge {
344 pub fn apply_patch(&mut self, patch: EdgePatch) {
346 if let Some(kind) = patch.kind {
347 self.kind = kind;
348 }
349 if let Some(weight) = patch.weight {
350 self.weight = weight;
351 }
352 if let Some(properties) = patch.properties {
353 self.properties = properties;
354 }
355 }
356}
357
358impl NewNode {
359 pub fn into_node(self, id: u64) -> Node {
361 let now = now_ms();
362 Node {
363 id,
364 uuid: new_uuid_v7(),
365 kind: self.kind,
366 title: self.title,
367 body: self.body,
368 body_html: self.body_html,
369 created_at: now,
370 updated_at: now,
371 properties: self.properties,
372 }
373 }
374}
375
376impl NewEdge {
377 pub fn into_edge(self, id: u64) -> Edge {
379 Edge {
380 id,
381 uuid: new_uuid_v7(),
382 from_id: self.from_id,
383 to_id: self.to_id,
384 kind: self.kind,
385 weight: self.weight,
386 created_at: now_ms(),
387 properties: self.properties,
388 }
389 }
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395 use serde_json::json;
396
397 fn sample_new_node() -> NewNode {
398 let mut props = HashMap::new();
399 props.insert("priority".to_string(), json!(1));
400 NewNode {
401 kind: "note".to_string(),
402 title: "Test Node".to_string(),
403 body: "# Hello\nWorld".to_string(),
404 body_html: "<h1>Hello</h1><p>World</p>".to_string(),
405 properties: Properties::from(props),
406 }
407 }
408
409 fn sample_new_edge() -> NewEdge {
410 let mut props = HashMap::new();
411 props.insert("label".to_string(), json!("related"));
412 NewEdge {
413 from_id: 1,
414 to_id: 2,
415 kind: "links_to".to_string(),
416 weight: 1.0,
417 properties: Properties::from(props),
418 }
419 }
420
421 #[test]
424 fn uuid_v7_is_valid() {
425 let bytes = new_uuid_v7();
426 let uuid = uuid::Uuid::from_bytes(bytes);
427 assert_eq!(uuid.get_version(), Some(uuid::Version::SortRand));
428 }
429
430 #[test]
431 fn uuid_v7_is_unique() {
432 let a = new_uuid_v7();
433 let b = new_uuid_v7();
434 assert_ne!(a, b);
435 }
436
437 #[test]
438 fn uuid_v7_is_sortable_by_time() {
439 let a = new_uuid_v7();
440 std::thread::sleep(std::time::Duration::from_millis(2));
442 let b = new_uuid_v7();
443 assert!(a < b, "UUID v7 should be time-sortable");
444 }
445
446 #[test]
449 fn now_ms_returns_reasonable_timestamp() {
450 let ts = now_ms();
451 assert!(ts > 1_704_067_200_000);
453 assert!(ts < 4_102_444_800_000);
455 }
456
457 #[test]
460 fn new_node_into_node_sets_id() {
461 let node = sample_new_node().into_node(42);
462 assert_eq!(node.id, 42);
463 }
464
465 #[test]
466 fn new_node_into_node_generates_uuid() {
467 let node = sample_new_node().into_node(1);
468 let uuid = uuid::Uuid::from_bytes(node.uuid);
469 assert_eq!(uuid.get_version(), Some(uuid::Version::SortRand));
470 }
471
472 #[test]
473 fn new_node_into_node_copies_fields() {
474 let input = sample_new_node();
475 let node = input.clone().into_node(1);
476 assert_eq!(node.kind, input.kind);
477 assert_eq!(node.title, input.title);
478 assert_eq!(node.body, input.body);
479 assert_eq!(node.body_html, input.body_html);
480 assert_eq!(node.properties, input.properties);
481 }
482
483 #[test]
484 fn new_node_into_node_sets_timestamps() {
485 let before = now_ms();
486 let node = sample_new_node().into_node(1);
487 let after = now_ms();
488 assert!(node.created_at >= before && node.created_at <= after);
489 assert_eq!(node.created_at, node.updated_at);
490 }
491
492 #[test]
495 fn new_edge_into_edge_sets_id() {
496 let edge = sample_new_edge().into_edge(99);
497 assert_eq!(edge.id, 99);
498 }
499
500 #[test]
501 fn new_edge_into_edge_copies_fields() {
502 let input = sample_new_edge();
503 let edge = input.clone().into_edge(1);
504 assert_eq!(edge.from_id, input.from_id);
505 assert_eq!(edge.to_id, input.to_id);
506 assert_eq!(edge.kind, input.kind);
507 assert_eq!(edge.weight, input.weight);
508 assert_eq!(edge.properties, input.properties);
509 }
510
511 #[test]
512 fn new_edge_into_edge_generates_uuid() {
513 let edge = sample_new_edge().into_edge(1);
514 let uuid = uuid::Uuid::from_bytes(edge.uuid);
515 assert_eq!(uuid.get_version(), Some(uuid::Version::SortRand));
516 }
517
518 #[test]
519 fn new_edge_into_edge_sets_timestamp() {
520 let before = now_ms();
521 let edge = sample_new_edge().into_edge(1);
522 let after = now_ms();
523 assert!(edge.created_at >= before && edge.created_at <= after);
524 }
525
526 #[test]
529 fn apply_patch_updates_only_some_fields() {
530 let mut node = sample_new_node().into_node(1);
531 let original_kind = node.kind.clone();
532 let original_body = node.body.clone();
533
534 node.apply_patch(NodePatch {
535 title: Some("Updated Title".to_string()),
536 ..Default::default()
537 });
538
539 assert_eq!(node.title, "Updated Title");
540 assert_eq!(node.kind, original_kind);
541 assert_eq!(node.body, original_body);
542 }
543
544 #[test]
545 fn apply_patch_updates_all_fields() {
546 let mut node = sample_new_node().into_node(1);
547 let mut new_props = HashMap::new();
548 new_props.insert("status".to_string(), json!("done"));
549 let new_props = Properties::from(new_props);
550
551 node.apply_patch(NodePatch {
552 kind: Some("task".to_string()),
553 title: Some("New Title".to_string()),
554 body: Some("New body".to_string()),
555 body_html: Some("<p>New body</p>".to_string()),
556 properties: Some(new_props.clone()),
557 });
558
559 assert_eq!(node.kind, "task");
560 assert_eq!(node.title, "New Title");
561 assert_eq!(node.body, "New body");
562 assert_eq!(node.body_html, "<p>New body</p>");
563 assert_eq!(node.properties, new_props);
564 }
565
566 #[test]
567 fn apply_patch_updates_timestamp() {
568 let mut node = sample_new_node().into_node(1);
569 let old_updated = node.updated_at;
570 std::thread::sleep(std::time::Duration::from_millis(2));
571
572 node.apply_patch(NodePatch {
573 title: Some("Changed".to_string()),
574 ..Default::default()
575 });
576
577 assert!(node.updated_at > old_updated);
578 }
579
580 #[test]
581 fn apply_empty_patch_only_updates_timestamp() {
582 let mut node = sample_new_node().into_node(1);
583 let original = node.clone();
584 std::thread::sleep(std::time::Duration::from_millis(2));
585
586 node.apply_patch(NodePatch::default());
587
588 assert_eq!(node.kind, original.kind);
589 assert_eq!(node.title, original.title);
590 assert!(node.updated_at > original.updated_at);
591 }
592
593 #[test]
596 fn edge_apply_patch_updates_some_fields() {
597 let mut edge = sample_new_edge().into_edge(1);
598 let original_kind = edge.kind.clone();
599
600 edge.apply_patch(EdgePatch {
601 weight: Some(2.5),
602 ..Default::default()
603 });
604
605 assert_eq!(edge.weight, 2.5);
606 assert_eq!(edge.kind, original_kind);
607 }
608
609 #[test]
610 fn edge_apply_patch_updates_all_fields() {
611 let mut edge = sample_new_edge().into_edge(1);
612 let mut new_props = HashMap::new();
613 new_props.insert("color".to_string(), json!("red"));
614 let new_props = Properties::from(new_props);
615
616 edge.apply_patch(EdgePatch {
617 kind: Some("blocks".to_string()),
618 weight: Some(0.5),
619 properties: Some(new_props.clone()),
620 });
621
622 assert_eq!(edge.kind, "blocks");
623 assert_eq!(edge.weight, 0.5);
624 assert_eq!(edge.properties, new_props);
625 }
626
627 #[test]
630 fn node_serializes_to_bincode_roundtrip() {
631 let node = sample_new_node().into_node(1);
632 let config = bincode::config::standard();
633 let bytes = bincode::serde::encode_to_vec(&node, config).unwrap();
634 let (decoded, _): (Node, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
635 assert_eq!(decoded, node);
636 }
637
638 #[test]
639 fn edge_serializes_to_bincode_roundtrip() {
640 let edge = sample_new_edge().into_edge(1);
641 let config = bincode::config::standard();
642 let bytes = bincode::serde::encode_to_vec(&edge, config).unwrap();
643 let (decoded, _): (Edge, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
644 assert_eq!(decoded, edge);
645 }
646
647 #[test]
648 fn node_serializes_to_json_roundtrip() {
649 let node = sample_new_node().into_node(1);
650 let json = serde_json::to_string(&node).unwrap();
651 let decoded: Node = serde_json::from_str(&json).unwrap();
652 assert_eq!(decoded, node);
653 }
654
655 #[test]
656 fn edge_serializes_to_json_roundtrip() {
657 let edge = sample_new_edge().into_edge(1);
658 let json = serde_json::to_string(&edge).unwrap();
659 let decoded: Edge = serde_json::from_str(&json).unwrap();
660 assert_eq!(decoded, edge);
661 }
662
663 #[test]
664 fn node_with_empty_properties_serializes() {
665 let node = NewNode {
666 kind: "note".to_string(),
667 title: "Empty".to_string(),
668 body: String::new(),
669 body_html: String::new(),
670 properties: Properties::default(),
671 }
672 .into_node(1);
673
674 let config = bincode::config::standard();
675 let bytes = bincode::serde::encode_to_vec(&node, config).unwrap();
676 let (decoded, _): (Node, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
677 assert_eq!(decoded, node);
678 }
679
680 #[test]
681 fn node_with_complex_properties_serializes() {
682 let mut props = HashMap::new();
683 props.insert("tags".to_string(), json!(["rust", "graph", "db"]));
684 props.insert("nested".to_string(), json!({"a": {"b": 42}}));
685 props.insert("flag".to_string(), json!(true));
686 props.insert("score".to_string(), json!(2.71));
687 props.insert("empty".to_string(), json!(null));
688
689 let node = NewNode {
690 kind: "note".to_string(),
691 title: "Complex".to_string(),
692 body: String::new(),
693 body_html: String::new(),
694 properties: Properties::from(props),
695 }
696 .into_node(1);
697
698 let config = bincode::config::standard();
699 let bytes = bincode::serde::encode_to_vec(&node, config).unwrap();
700 let (decoded, _): (Node, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
701 assert_eq!(decoded, node);
702 }
703
704 #[test]
707 fn direction_variants_are_distinct() {
708 assert_ne!(Direction::Outgoing, Direction::Incoming);
709 assert_ne!(Direction::Outgoing, Direction::Both);
710 assert_ne!(Direction::Incoming, Direction::Both);
711 }
712
713 #[test]
714 fn direction_clone_eq() {
715 let d = Direction::Outgoing;
716 let d2 = d;
717 assert_eq!(d, d2);
718 }
719
720 fn build_properties(pairs: &[(&str, serde_json::Value)]) -> Properties {
723 let mut props = HashMap::new();
724 for (k, v) in pairs {
725 props.insert((*k).to_string(), v.clone());
726 }
727 Properties::from(props)
728 }
729
730 #[test]
731 fn properties_bincode_is_deterministic_across_insertion_order() {
732 let a = build_properties(&[
736 ("alpha", json!(1)),
737 ("beta", json!("two")),
738 ("gamma", json!([3, 4, 5])),
739 ("delta", json!({"nested": true})),
740 ]);
741 let b = build_properties(&[
742 ("delta", json!({"nested": true})),
743 ("gamma", json!([3, 4, 5])),
744 ("alpha", json!(1)),
745 ("beta", json!("two")),
746 ]);
747
748 let config = bincode::config::standard();
749 let bytes_a = bincode::serde::encode_to_vec(&a, config).unwrap();
750 let bytes_b = bincode::serde::encode_to_vec(&b, config).unwrap();
751
752 assert_eq!(
753 bytes_a, bytes_b,
754 "Properties bincode must be byte-identical for equivalent contents \
755 irrespective of HashMap insertion order"
756 );
757 }
758
759 #[test]
760 fn node_bincode_is_deterministic_across_property_insertion_order() {
761 let make = |order_a: bool| {
764 let pairs: &[(&str, serde_json::Value)] = if order_a {
765 &[("k1", json!(1)), ("k2", json!(2)), ("k3", json!(3))]
766 } else {
767 &[("k3", json!(3)), ("k1", json!(1)), ("k2", json!(2))]
768 };
769 Node {
770 id: 7,
771 uuid: [0u8; 16],
772 kind: "note".to_string(),
773 title: "T".to_string(),
774 body: "B".to_string(),
775 body_html: String::new(),
776 created_at: 1,
777 updated_at: 1,
778 properties: build_properties(pairs),
779 }
780 };
781
782 let config = bincode::config::standard();
783 let bytes_a = bincode::serde::encode_to_vec(make(true), config).unwrap();
784 let bytes_b = bincode::serde::encode_to_vec(make(false), config).unwrap();
785 assert_eq!(bytes_a, bytes_b);
786 }
787
788 #[test]
791 fn now_ms_is_total_and_does_not_panic() {
792 for _ in 0..32 {
793 let _ = now_ms();
794 }
795 }
796
797 fn roundtrip_node_bincode(node: &Node) {
800 let config = bincode::config::standard();
801 let bytes = bincode::serde::encode_to_vec(node, config).unwrap();
802 let (decoded, _): (Node, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
803 assert_eq!(decoded, *node);
804 }
805
806 fn roundtrip_node_json(node: &Node) {
807 let s = serde_json::to_string(node).unwrap();
808 let decoded: Node = serde_json::from_str(&s).unwrap();
809 assert_eq!(decoded, *node);
810 }
811
812 #[test]
813 fn node_with_cjk_content_serializes_roundtrip() {
814 let node = NewNode {
815 kind: "note".to_string(),
816 title: "知识图谱・グラフノート・지식그래프".to_string(),
818 body: "# 标题\n本文。これは本文です。본문 내용입니다。".to_string(),
819 body_html: "<h1>标题</h1>".to_string(),
820 properties: Properties::default(),
821 }
822 .into_node(1);
823 roundtrip_node_bincode(&node);
824 roundtrip_node_json(&node);
825 }
826
827 #[test]
828 fn node_with_emoji_content_serializes_roundtrip() {
829 let node = NewNode {
830 kind: "note".to_string(),
831 title: "🚀 launch 🌍".to_string(),
832 body: "🔥 multi-codepoint: 👨👩👧👦 family ZWJ sequence".to_string(),
833 body_html: String::new(),
834 properties: Properties::default(),
835 }
836 .into_node(1);
837 roundtrip_node_bincode(&node);
838 roundtrip_node_json(&node);
839 }
840
841 #[test]
842 fn node_with_cyrillic_content_serializes_roundtrip() {
843 let node = NewNode {
844 kind: "заметка".to_string(),
845 title: "Привет, мир!".to_string(),
846 body: "Граф-база данных — производительная и надёжная.".to_string(),
847 body_html: String::new(),
848 properties: Properties::default(),
849 }
850 .into_node(1);
851 roundtrip_node_bincode(&node);
852 roundtrip_node_json(&node);
853 }
854
855 #[test]
856 fn properties_with_unicode_keys_and_values_roundtrip() {
857 let props = build_properties(&[
858 ("标签", json!("中文")),
859 ("emoji_🔑", json!("🌈")),
860 ("кириллица", json!({"вложенный": true})),
861 ]);
862 let config = bincode::config::standard();
863 let bytes = bincode::serde::encode_to_vec(&props, config).unwrap();
864 let (decoded, _): (Properties, _) =
865 bincode::serde::decode_from_slice(&bytes, config).unwrap();
866 assert_eq!(decoded, props);
867
868 let json = serde_json::to_string(&props).unwrap();
870 let from_json: Properties = serde_json::from_str(&json).unwrap();
871 assert_eq!(from_json, props);
872 }
873
874 #[test]
875 fn edge_with_cyrillic_kind_serializes_roundtrip() {
876 let edge = NewEdge {
877 from_id: 1,
878 to_id: 2,
879 kind: "связано_с".to_string(),
880 weight: 1.0,
881 properties: Properties::default(),
882 }
883 .into_edge(1);
884 let config = bincode::config::standard();
885 let bytes = bincode::serde::encode_to_vec(&edge, config).unwrap();
886 let (decoded, _): (Edge, _) = bincode::serde::decode_from_slice(&bytes, config).unwrap();
887 assert_eq!(decoded, edge);
888 }
889}