1use std::collections::HashMap;
13use std::sync::atomic::{AtomicU64, Ordering};
14
15use rkyv::{Archive, Deserialize, Serialize};
16
17use crate::graph::ProvenanceSubKind;
18
19pub type FrameLayoutNodeId = String;
28
29#[derive(
30 Debug,
31 Clone,
32 Copy,
33 PartialEq,
34 Eq,
35 Archive,
36 Serialize,
37 Deserialize,
38 serde::Serialize,
39 serde::Deserialize,
40)]
41#[rkyv(derive(Debug, PartialEq, Eq))]
42pub enum SplitOrientation {
43 Vertical,
44 Horizontal,
45}
46
47#[derive(
48 Debug,
49 Clone,
50 Copy,
51 PartialEq,
52 Eq,
53 Archive,
54 Serialize,
55 Deserialize,
56 serde::Serialize,
57 serde::Deserialize,
58)]
59#[rkyv(derive(Debug, PartialEq, Eq))]
60pub enum DominantEdge {
61 Left,
62 Right,
63 Top,
64 Bottom,
65}
66
67#[derive(
68 Debug,
69 Clone,
70 PartialEq,
71 Eq,
72 PartialOrd,
73 Ord,
74 Hash,
75 Default,
76 Archive,
77 Serialize,
78 Deserialize,
79 serde::Serialize,
80 serde::Deserialize,
81)]
82#[rkyv(derive(Debug, PartialEq, Eq))]
83pub enum GraphScope {
84 #[default]
85 Default,
86 Source,
87 User,
88 Agent,
89 Moot,
90 Custom(String),
91}
92
93#[derive(
95 Debug,
96 Clone,
97 PartialEq,
98 Eq,
99 Archive,
100 Serialize,
101 Deserialize,
102 serde::Serialize,
103 serde::Deserialize,
104)]
105#[rkyv(derive(Debug, PartialEq, Eq))]
106pub struct AssertionWithdrawal {
107 pub at_ms: Option<u64>,
110 pub by: Option<String>,
112}
113
114#[derive(
117 Debug,
118 Clone,
119 PartialEq,
120 Eq,
121 Default,
122 Archive,
123 Serialize,
124 Deserialize,
125 serde::Serialize,
126 serde::Deserialize,
127)]
128#[rkyv(derive(Debug, PartialEq, Eq))]
129pub struct AssertionBasis {
130 #[serde(default)]
132 pub note: Option<String>,
133 #[serde(default)]
134 pub method: Option<AssertionMethod>,
135 #[serde(default)]
137 pub evidence: Vec<String>,
138}
139
140#[derive(
141 Debug,
142 Clone,
143 PartialEq,
144 Eq,
145 Archive,
146 Serialize,
147 Deserialize,
148 serde::Serialize,
149 serde::Deserialize,
150)]
151#[rkyv(derive(Debug, PartialEq, Eq))]
152pub struct AssertionMethod {
153 pub iri: String,
154 #[serde(default)]
155 pub version: Option<String>,
156}
157
158impl AssertionBasis {
159 pub fn same_reason_as(&self, other: &Self) -> bool {
162 if self.method.as_ref().map(|method| method.iri.as_str())
163 != other.method.as_ref().map(|method| method.iri.as_str())
164 {
165 return false;
166 }
167 let mut left = self.evidence.iter().map(String::as_str).collect::<Vec<_>>();
168 let mut right = other
169 .evidence
170 .iter()
171 .map(String::as_str)
172 .collect::<Vec<_>>();
173 left.sort_unstable();
174 right.sort_unstable();
175 left.dedup();
176 right.dedup();
177 left == right
178 }
179
180 pub fn is_empty(&self) -> bool {
181 self.note.is_none() && self.method.is_none() && self.evidence.is_empty()
182 }
183}
184
185static NEXT_LOCAL_STATEMENT_NONCE: AtomicU64 = AtomicU64::new(1);
186static STATEMENT_MINTER_SALT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
187
188pub fn seed_statement_minter(salt: u64) {
195 let _ = STATEMENT_MINTER_SALT.set(salt);
196}
197
198fn statement_minter_salt() -> u64 {
199 *STATEMENT_MINTER_SALT.get_or_init(|| {
200 #[cfg(not(target_arch = "wasm32"))]
201 {
202 let bytes = uuid::Uuid::new_v4();
203 u64::from_le_bytes(bytes.as_bytes()[..8].try_into().expect("8 bytes"))
204 }
205 #[cfg(target_arch = "wasm32")]
206 {
207 0
208 }
209 })
210}
211
212pub(crate) fn mint_local_statement_id() -> String {
226 let timestamp_ms = crate::time::unix_epoch_millis();
227 let salt = statement_minter_salt();
228 let nonce = NEXT_LOCAL_STATEMENT_NONCE.fetch_add(1, Ordering::Relaxed);
229 format!("{timestamp_ms:012x}-{salt:016x}-{nonce:016x}")
230}
231
232#[cfg(test)]
233mod minting_tests {
234 use super::*;
235
236 #[test]
240 fn statement_ids_carry_salt_and_stay_unique() {
241 let a = mint_local_statement_id();
242 let b = mint_local_statement_id();
243 assert_ne!(a, b);
244 let parts: Vec<&str> = a.split('-').collect();
245 assert_eq!(parts.len(), 3, "ts-salt-counter shape: {a}");
246 assert_eq!(parts[0].len(), 12);
247 assert_eq!(parts[1].len(), 16);
248 assert_eq!(parts[2].len(), 16);
249 assert_ne!(parts[1], "0000000000000000", "native salt self-seeds");
250 let b_parts: Vec<&str> = b.split('-').collect();
251 assert_eq!(parts[1], b_parts[1], "salt is per-process stable");
252 }
253}
254
255#[derive(
256 Debug,
257 Clone,
258 PartialEq,
259 Eq,
260 Archive,
261 Serialize,
262 Deserialize,
263 serde::Serialize,
264 serde::Deserialize,
265)]
266#[rkyv(derive(Debug, PartialEq, Eq))]
267pub enum FrameLayoutHint {
268 SplitHalf {
269 first: FrameLayoutNodeId,
270 second: FrameLayoutNodeId,
271 orientation: SplitOrientation,
272 },
273 SplitPamphlet {
274 members: [FrameLayoutNodeId; 3],
275 orientation: SplitOrientation,
276 },
277 SplitTriptych {
278 dominant: FrameLayoutNodeId,
279 dominant_edge: DominantEdge,
280 wings: [FrameLayoutNodeId; 2],
281 },
282 SplitQuartered {
283 top_left: FrameLayoutNodeId,
284 top_right: FrameLayoutNodeId,
285 bottom_left: FrameLayoutNodeId,
286 bottom_right: FrameLayoutNodeId,
287 },
288}
289
290#[derive(
295 Debug,
296 Clone,
297 PartialEq,
298 Eq,
299 PartialOrd,
300 Ord,
301 Archive,
302 Serialize,
303 Deserialize,
304 serde::Serialize,
305 serde::Deserialize,
306)]
307pub struct NodeImportProvenance {
308 pub source_id: String,
309 pub source_label: String,
310}
311
312#[derive(
323 Debug,
324 Clone,
325 PartialEq,
326 Eq,
327 Archive,
328 Serialize,
329 Deserialize,
330 serde::Serialize,
331 serde::Deserialize,
332)]
333pub struct NodeDerivation {
334 pub sub_kind: ProvenanceSubKind,
336 pub source_node: String,
340 pub source_graph: Option<String>,
343}
344
345#[derive(
346 Debug,
347 Clone,
348 PartialEq,
349 Eq,
350 PartialOrd,
351 Ord,
352 Hash,
353 Default,
354 Archive,
355 Serialize,
356 Deserialize,
357 serde::Serialize,
358 serde::Deserialize,
359)]
360pub struct ImportRecordMembership {
361 pub node_id: String,
362 pub suppressed: bool,
363}
364
365#[derive(
366 Debug,
367 Clone,
368 PartialEq,
369 Eq,
370 PartialOrd,
371 Ord,
372 Hash,
373 Default,
374 Archive,
375 Serialize,
376 Deserialize,
377 serde::Serialize,
378 serde::Deserialize,
379)]
380pub struct ImportRecord {
381 pub record_id: String,
382 pub source_id: String,
383 pub source_label: String,
384 pub imported_at_secs: u64,
385 pub memberships: Vec<ImportRecordMembership>,
386}
387
388#[derive(Debug, Clone, PartialEq, Eq)]
389pub struct NodeImportRecordSummary {
390 pub record_id: String,
391 pub source_id: String,
392 pub source_label: String,
393 pub imported_at_secs: u64,
394}
395
396pub fn format_imported_at_secs(imported_at_secs: u64) -> String {
397 time::OffsetDateTime::from_unix_timestamp(imported_at_secs as i64)
398 .ok()
399 .and_then(|timestamp| {
400 timestamp
401 .format(&time::format_description::well_known::Rfc3339)
402 .ok()
403 })
404 .unwrap_or_else(|| format!("{}s", imported_at_secs))
405}
406
407#[derive(
413 Debug,
414 Clone,
415 PartialEq,
416 Eq,
417 PartialOrd,
418 Ord,
419 Hash,
420 Default,
421 Archive,
422 Serialize,
423 Deserialize,
424 serde::Serialize,
425 serde::Deserialize,
426)]
427pub enum ClassificationScheme {
428 #[default]
430 Udc,
431 ContentKind,
433 Custom(String),
435}
436
437#[derive(
439 Debug,
440 Clone,
441 PartialEq,
442 Eq,
443 PartialOrd,
444 Ord,
445 Hash,
446 Default,
447 Archive,
448 Serialize,
449 Deserialize,
450 serde::Serialize,
451 serde::Deserialize,
452)]
453pub enum ClassificationProvenance {
454 #[default]
456 UserAuthored,
457 Imported,
459 InheritedFromSource,
461 RegistryDerived,
463 AgentSuggested,
465 CommunitySynced,
467}
468
469#[derive(
471 Debug,
472 Clone,
473 PartialEq,
474 Eq,
475 PartialOrd,
476 Ord,
477 Hash,
478 Default,
479 Archive,
480 Serialize,
481 Deserialize,
482 serde::Serialize,
483 serde::Deserialize,
484)]
485pub enum ClassificationStatus {
486 Accepted,
488 #[default]
490 Suggested,
491 Rejected,
493 Verified,
495 Imported,
497}
498
499impl ClassificationStatus {
500 pub fn is_affirmative(&self) -> bool {
502 matches!(self, Self::Accepted | Self::Verified | Self::Imported)
503 }
504}
505
506#[derive(
510 Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
511)]
512pub struct NodeClassification {
513 pub scheme: ClassificationScheme,
514 pub value: String,
516 pub label: Option<String>,
518 pub confidence: f32,
520 pub provenance: ClassificationProvenance,
521 pub status: ClassificationStatus,
522 pub primary: bool,
524}
525
526#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, serde::Deserialize)]
530pub struct NodeProperty {
531 #[serde(default = "mint_local_statement_id")]
533 pub statement_id: String,
534 pub predicate: String,
536 pub value: String,
538 #[serde(default)]
540 pub datatype: Option<String>,
541 #[serde(default)]
543 pub lang: Option<String>,
544 #[serde(default)]
546 pub graph_scope: GraphScope,
547 #[serde(default)]
549 pub provenance_iri: Option<String>,
550 #[serde(default)]
552 pub asserted_at_ms: Option<u64>,
553}
554
555impl serde::Serialize for NodeProperty {
556 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
557 use serde::ser::SerializeStruct;
558
559 let human = serializer.is_human_readable();
560 let scoped = self.graph_scope != GraphScope::Default;
561 let fields = if human {
562 3 + usize::from(self.datatype.is_some())
563 + usize::from(self.lang.is_some())
564 + usize::from(scoped)
565 + usize::from(self.provenance_iri.is_some())
566 + usize::from(self.asserted_at_ms.is_some())
567 } else {
568 8
569 };
570 let mut state = serializer.serialize_struct("NodeProperty", fields)?;
572 state.serialize_field("statement_id", &self.statement_id)?;
573 state.serialize_field("predicate", &self.predicate)?;
574 state.serialize_field("value", &self.value)?;
575 if !human || self.datatype.is_some() {
576 state.serialize_field("datatype", &self.datatype)?;
577 }
578 if !human || self.lang.is_some() {
579 state.serialize_field("lang", &self.lang)?;
580 }
581 if !human || scoped {
582 state.serialize_field("graph_scope", &self.graph_scope)?;
583 }
584 if !human || self.provenance_iri.is_some() {
585 state.serialize_field("provenance_iri", &self.provenance_iri)?;
586 }
587 if !human || self.asserted_at_ms.is_some() {
588 state.serialize_field("asserted_at_ms", &self.asserted_at_ms)?;
589 }
590 state.end()
591 }
592}
593
594impl NodeProperty {
595 pub fn new(predicate: String, value: String) -> Self {
596 Self {
597 statement_id: mint_local_statement_id(),
598 predicate,
599 value,
600 datatype: None,
601 lang: None,
602 graph_scope: GraphScope::Default,
603 provenance_iri: None,
604 asserted_at_ms: None,
605 }
606 }
607
608 pub fn with_graph_scope(mut self, graph_scope: GraphScope) -> Self {
609 self.graph_scope = graph_scope;
610 self
611 }
612
613 pub fn with_metadata(
614 mut self,
615 provenance_iri: Option<String>,
616 asserted_at_ms: Option<u64>,
617 ) -> Self {
618 self.provenance_iri = provenance_iri;
619 self.asserted_at_ms = asserted_at_ms;
620 self
621 }
622
623 pub fn content_eq(&self, other: &Self) -> bool {
624 self.predicate == other.predicate
625 && self.value == other.value
626 && self.datatype == other.datatype
627 && self.lang == other.lang
628 && self.graph_scope == other.graph_scope
629 && self.provenance_iri == other.provenance_iri
630 }
631}
632
633#[derive(
644 Debug,
645 Clone,
646 Copy,
647 PartialEq,
648 Eq,
649 Hash,
650 PartialOrd,
651 Ord,
652 Archive,
653 Serialize,
654 Deserialize,
655 serde::Serialize,
656 serde::Deserialize,
657)]
658#[rkyv(
659 compare(PartialEq, PartialOrd),
660 derive(Debug, PartialEq, Eq, PartialOrd, Ord)
661)]
662pub enum ImageRole {
663 Favicon,
664 Preview,
665 Snapshot,
666}
667
668#[derive(
676 Debug,
677 Clone,
678 Copy,
679 PartialEq,
680 Eq,
681 Hash,
682 Archive,
683 Serialize,
684 Deserialize,
685 serde::Serialize,
686 serde::Deserialize,
687)]
688#[rkyv(derive(Debug, PartialEq, Eq))]
689pub struct ImageRef {
690 #[serde(with = "digest_hex")]
693 pub digest: [u8; 32],
694 pub width: u32,
696 pub height: u32,
698}
699
700impl ImageRef {
701 pub fn new(digest: [u8; 32], width: u32, height: u32) -> Self {
702 Self {
703 digest,
704 width,
705 height,
706 }
707 }
708
709 pub fn hex(&self) -> String {
713 use std::fmt::Write;
714 let mut out = String::with_capacity(64);
715 for byte in &self.digest {
716 let _ = write!(out, "{byte:02x}");
717 }
718 out
719 }
720}
721
722mod digest_hex {
724 use serde::{Deserialize, Deserializer, Serializer, de::Error};
725
726 pub fn serialize<S: Serializer>(digest: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error> {
727 use std::fmt::Write;
728 let mut hex = String::with_capacity(64);
729 for byte in digest {
730 let _ = write!(hex, "{byte:02x}");
731 }
732 serializer.serialize_str(&hex)
733 }
734
735 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<[u8; 32], D::Error> {
736 let hex = String::deserialize(deserializer)?;
737 let bytes = hex.as_bytes();
738 if bytes.len() != 64 {
739 return Err(D::Error::invalid_length(bytes.len(), &"64 hex characters"));
740 }
741 let nibble = |b: u8| -> Result<u8, D::Error> {
742 (b as char)
743 .to_digit(16)
744 .map(|d| d as u8)
745 .ok_or_else(|| D::Error::custom("digest is not valid hex"))
746 };
747 let mut out = [0u8; 32];
748 for (i, pair) in bytes.chunks_exact(2).enumerate() {
749 out[i] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
750 }
751 Ok(out)
752 }
753}
754
755#[derive(
760 Debug,
761 Clone,
762 PartialEq,
763 Eq,
764 Archive,
765 Serialize,
766 Deserialize,
767 serde::Serialize,
768 serde::Deserialize,
769)]
770#[rkyv(derive(Debug, PartialEq, Eq))]
771pub enum BadgeIcon {
772 Emoji(String),
773 Lucide(String),
774 None,
775}
776
777#[derive(
778 Debug,
779 Clone,
780 Default,
781 PartialEq,
782 Eq,
783 Archive,
784 Serialize,
785 Deserialize,
786 serde::Serialize,
787 serde::Deserialize,
788)]
789#[rkyv(derive(Debug, PartialEq, Eq))]
790pub struct NodeTagPresentationState {
791 pub ordered_tags: Vec<String>,
792 pub icon_overrides: HashMap<String, BadgeIcon>,
793}
794
795#[cfg(test)]
796mod property_serialization_tests {
797 use super::*;
798
799 fn cases() -> Vec<NodeProperty> {
800 let mut plain = NodeProperty::new("urn:predicate:value".into(), "held value".into());
801 plain.statement_id = "held\nproperty".into();
802 plain.provenance_iri = Some("https://author.test/".into());
803 let mut legacy = plain.clone();
804 legacy.provenance_iri = None;
805 let mut marker = plain.clone();
806 marker.provenance_iri = Some(crate::graph::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI.into());
807 let mut rich = plain.clone();
808 rich.statement_id = String::new();
809 rich.datatype = Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString".into());
810 rich.lang = Some("fr".into());
811 rich.graph_scope = GraphScope::Custom("urn:graph:held".into());
812 rich.provenance_iri = Some(String::new());
813 rich.asserted_at_ms = Some(0);
814 let mut explicit = plain.clone();
815 explicit.datatype = Some("http://www.w3.org/2001/XMLSchema#string".into());
816 explicit.lang = Some(String::new());
817 vec![plain, legacy, marker, rich, explicit]
818 }
819
820 #[test]
821 fn property_json_omits_absent_metadata_and_preserves_explicit_values() {
822 let cases = cases();
823 let plain = serde_json::to_value(&cases[0]).unwrap();
824 assert_eq!(plain.as_object().unwrap().len(), 4);
825 assert_eq!(plain["statement_id"], "held\nproperty");
826 assert_eq!(plain["provenance_iri"], "https://author.test/");
827 for absent in ["datatype", "lang", "graph_scope", "asserted_at_ms"] {
828 assert!(plain.get(absent).is_none());
829 }
830 let legacy = serde_json::to_value(&cases[1]).unwrap();
831 assert!(legacy.get("provenance_iri").is_none());
832 let decoded: NodeProperty = serde_json::from_value(legacy).unwrap();
833 assert_eq!(decoded, cases[1], "missing metadata keeps legacy defaults");
834 let marker = serde_json::to_value(&cases[2]).unwrap();
835 assert_eq!(
836 marker["provenance_iri"],
837 crate::graph::edge_data::UNKNOWN_LEGACY_ASSERTER_IRI
838 );
839 let rich = serde_json::to_value(&cases[3]).unwrap();
840 assert_eq!(rich.as_object().unwrap().len(), 8);
841 assert_eq!(rich["statement_id"], "");
842 assert_eq!(rich["provenance_iri"], "");
843 assert_eq!(rich["asserted_at_ms"], 0);
844 assert_eq!(rich["lang"], "fr");
845 let explicit = serde_json::to_value(&cases[4]).unwrap();
846 assert_eq!(
847 explicit["datatype"],
848 "http://www.w3.org/2001/XMLSchema#string"
849 );
850 assert_eq!(explicit["lang"], "");
851 for value in cases {
852 let bytes = serde_json::to_vec(&value).unwrap();
853 assert_eq!(
854 serde_json::from_slice::<NodeProperty>(&bytes).unwrap(),
855 value
856 );
857 }
858 }
859
860 #[test]
861 fn property_binary_bytes_match_the_complete_legacy_shape() {
862 #[derive(serde::Serialize)]
863 struct Complete<'a> {
864 statement_id: &'a String,
865 predicate: &'a String,
866 value: &'a String,
867 datatype: &'a Option<String>,
868 lang: &'a Option<String>,
869 graph_scope: &'a GraphScope,
870 provenance_iri: &'a Option<String>,
871 asserted_at_ms: &'a Option<u64>,
872 }
873 for value in cases() {
874 let old = Complete {
875 statement_id: &value.statement_id,
876 predicate: &value.predicate,
877 value: &value.value,
878 datatype: &value.datatype,
879 lang: &value.lang,
880 graph_scope: &value.graph_scope,
881 provenance_iri: &value.provenance_iri,
882 asserted_at_ms: &value.asserted_at_ms,
883 };
884 let bytes = postcard::to_allocvec(&value).unwrap();
885 assert_eq!(bytes, postcard::to_allocvec(&old).unwrap());
886 assert_eq!(postcard::from_bytes::<NodeProperty>(&bytes).unwrap(), value);
887 let archive = rkyv::to_bytes::<rkyv::rancor::Error>(&value).unwrap();
888 assert_eq!(
889 rkyv::from_bytes::<NodeProperty, rkyv::rancor::Error>(&archive).unwrap(),
890 value
891 );
892 }
893 }
894}