1use std::collections::HashMap;
10use std::sync::atomic::{AtomicU64, Ordering};
11
12use rkyv::{Archive, Deserialize, Serialize};
13
14use crate::graph::ProvenanceSubKind;
15
16pub type FrameLayoutNodeId = String;
25
26#[derive(
27 Debug,
28 Clone,
29 Copy,
30 PartialEq,
31 Eq,
32 Archive,
33 Serialize,
34 Deserialize,
35 serde::Serialize,
36 serde::Deserialize,
37)]
38#[rkyv(derive(Debug, PartialEq, Eq))]
39pub enum SplitOrientation {
40 Vertical,
41 Horizontal,
42}
43
44#[derive(
45 Debug,
46 Clone,
47 Copy,
48 PartialEq,
49 Eq,
50 Archive,
51 Serialize,
52 Deserialize,
53 serde::Serialize,
54 serde::Deserialize,
55)]
56#[rkyv(derive(Debug, PartialEq, Eq))]
57pub enum DominantEdge {
58 Left,
59 Right,
60 Top,
61 Bottom,
62}
63
64#[derive(
65 Debug,
66 Clone,
67 PartialEq,
68 Eq,
69 PartialOrd,
70 Ord,
71 Hash,
72 Default,
73 Archive,
74 Serialize,
75 Deserialize,
76 serde::Serialize,
77 serde::Deserialize,
78)]
79#[rkyv(derive(Debug, PartialEq, Eq))]
80pub enum GraphScope {
81 #[default]
82 Default,
83 Source,
84 User,
85 Agent,
86 Moot,
87 Custom(String),
88}
89
90static NEXT_LOCAL_STATEMENT_NONCE: AtomicU64 = AtomicU64::new(1);
91static STATEMENT_MINTER_SALT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
92
93pub fn seed_statement_minter(salt: u64) {
100 let _ = STATEMENT_MINTER_SALT.set(salt);
101}
102
103fn statement_minter_salt() -> u64 {
104 *STATEMENT_MINTER_SALT.get_or_init(|| {
105 #[cfg(not(target_arch = "wasm32"))]
106 {
107 let bytes = uuid::Uuid::new_v4();
108 u64::from_le_bytes(bytes.as_bytes()[..8].try_into().expect("8 bytes"))
109 }
110 #[cfg(target_arch = "wasm32")]
111 {
112 0
113 }
114 })
115}
116
117pub(crate) fn mint_local_statement_id() -> String {
131 let timestamp_ms = crate::time::unix_epoch_millis();
132 let salt = statement_minter_salt();
133 let nonce = NEXT_LOCAL_STATEMENT_NONCE.fetch_add(1, Ordering::Relaxed);
134 format!("{timestamp_ms:012x}-{salt:016x}-{nonce:016x}")
135}
136
137#[cfg(test)]
138mod minting_tests {
139 use super::*;
140
141 #[test]
145 fn statement_ids_carry_salt_and_stay_unique() {
146 let a = mint_local_statement_id();
147 let b = mint_local_statement_id();
148 assert_ne!(a, b);
149 let parts: Vec<&str> = a.split('-').collect();
150 assert_eq!(parts.len(), 3, "ts-salt-counter shape: {a}");
151 assert_eq!(parts[0].len(), 12);
152 assert_eq!(parts[1].len(), 16);
153 assert_eq!(parts[2].len(), 16);
154 assert_ne!(parts[1], "0000000000000000", "native salt self-seeds");
155 let b_parts: Vec<&str> = b.split('-').collect();
156 assert_eq!(parts[1], b_parts[1], "salt is per-process stable");
157 }
158}
159
160#[derive(
161 Debug,
162 Clone,
163 PartialEq,
164 Eq,
165 Archive,
166 Serialize,
167 Deserialize,
168 serde::Serialize,
169 serde::Deserialize,
170)]
171#[rkyv(derive(Debug, PartialEq, Eq))]
172pub enum FrameLayoutHint {
173 SplitHalf {
174 first: FrameLayoutNodeId,
175 second: FrameLayoutNodeId,
176 orientation: SplitOrientation,
177 },
178 SplitPamphlet {
179 members: [FrameLayoutNodeId; 3],
180 orientation: SplitOrientation,
181 },
182 SplitTriptych {
183 dominant: FrameLayoutNodeId,
184 dominant_edge: DominantEdge,
185 wings: [FrameLayoutNodeId; 2],
186 },
187 SplitQuartered {
188 top_left: FrameLayoutNodeId,
189 top_right: FrameLayoutNodeId,
190 bottom_left: FrameLayoutNodeId,
191 bottom_right: FrameLayoutNodeId,
192 },
193}
194
195#[derive(
200 Debug,
201 Clone,
202 PartialEq,
203 Eq,
204 PartialOrd,
205 Ord,
206 Archive,
207 Serialize,
208 Deserialize,
209 serde::Serialize,
210 serde::Deserialize,
211)]
212pub struct NodeImportProvenance {
213 pub source_id: String,
214 pub source_label: String,
215}
216
217#[derive(
228 Debug,
229 Clone,
230 PartialEq,
231 Eq,
232 Archive,
233 Serialize,
234 Deserialize,
235 serde::Serialize,
236 serde::Deserialize,
237)]
238pub struct NodeDerivation {
239 pub sub_kind: ProvenanceSubKind,
241 pub source_node: String,
245 pub source_graph: Option<String>,
248}
249
250#[derive(
251 Debug,
252 Clone,
253 PartialEq,
254 Eq,
255 PartialOrd,
256 Ord,
257 Hash,
258 Default,
259 Archive,
260 Serialize,
261 Deserialize,
262 serde::Serialize,
263 serde::Deserialize,
264)]
265pub struct ImportRecordMembership {
266 pub node_id: String,
267 pub suppressed: bool,
268}
269
270#[derive(
271 Debug,
272 Clone,
273 PartialEq,
274 Eq,
275 PartialOrd,
276 Ord,
277 Hash,
278 Default,
279 Archive,
280 Serialize,
281 Deserialize,
282 serde::Serialize,
283 serde::Deserialize,
284)]
285pub struct ImportRecord {
286 pub record_id: String,
287 pub source_id: String,
288 pub source_label: String,
289 pub imported_at_secs: u64,
290 pub memberships: Vec<ImportRecordMembership>,
291}
292
293#[derive(Debug, Clone, PartialEq, Eq)]
294pub struct NodeImportRecordSummary {
295 pub record_id: String,
296 pub source_id: String,
297 pub source_label: String,
298 pub imported_at_secs: u64,
299}
300
301pub fn format_imported_at_secs(imported_at_secs: u64) -> String {
302 time::OffsetDateTime::from_unix_timestamp(imported_at_secs as i64)
303 .ok()
304 .and_then(|timestamp| {
305 timestamp
306 .format(&time::format_description::well_known::Rfc3339)
307 .ok()
308 })
309 .unwrap_or_else(|| format!("{}s", imported_at_secs))
310}
311
312#[derive(
318 Debug,
319 Clone,
320 PartialEq,
321 Eq,
322 PartialOrd,
323 Ord,
324 Hash,
325 Default,
326 Archive,
327 Serialize,
328 Deserialize,
329 serde::Serialize,
330 serde::Deserialize,
331)]
332pub enum ClassificationScheme {
333 #[default]
335 Udc,
336 ContentKind,
338 Custom(String),
340}
341
342#[derive(
344 Debug,
345 Clone,
346 PartialEq,
347 Eq,
348 PartialOrd,
349 Ord,
350 Hash,
351 Default,
352 Archive,
353 Serialize,
354 Deserialize,
355 serde::Serialize,
356 serde::Deserialize,
357)]
358pub enum ClassificationProvenance {
359 #[default]
361 UserAuthored,
362 Imported,
364 InheritedFromSource,
366 RegistryDerived,
368 AgentSuggested,
370 CommunitySynced,
372}
373
374#[derive(
376 Debug,
377 Clone,
378 PartialEq,
379 Eq,
380 PartialOrd,
381 Ord,
382 Hash,
383 Default,
384 Archive,
385 Serialize,
386 Deserialize,
387 serde::Serialize,
388 serde::Deserialize,
389)]
390pub enum ClassificationStatus {
391 Accepted,
393 #[default]
395 Suggested,
396 Rejected,
398 Verified,
400 Imported,
402}
403
404#[derive(
408 Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
409)]
410pub struct NodeClassification {
411 pub scheme: ClassificationScheme,
412 pub value: String,
414 pub label: Option<String>,
416 pub confidence: f32,
418 pub provenance: ClassificationProvenance,
419 pub status: ClassificationStatus,
420 pub primary: bool,
422}
423
424#[derive(
428 Debug,
429 Clone,
430 PartialEq,
431 Eq,
432 Archive,
433 Serialize,
434 Deserialize,
435 serde::Serialize,
436 serde::Deserialize,
437)]
438pub struct NodeProperty {
439 #[serde(default = "mint_local_statement_id")]
441 pub statement_id: String,
442 pub predicate: String,
444 pub value: String,
446 #[serde(default)]
448 pub datatype: Option<String>,
449 #[serde(default)]
451 pub lang: Option<String>,
452 #[serde(default)]
454 pub graph_scope: GraphScope,
455 #[serde(default)]
457 pub provenance_iri: Option<String>,
458 #[serde(default)]
460 pub asserted_at_ms: Option<u64>,
461}
462
463impl NodeProperty {
464 pub fn new(predicate: String, value: String) -> Self {
465 Self {
466 statement_id: mint_local_statement_id(),
467 predicate,
468 value,
469 datatype: None,
470 lang: None,
471 graph_scope: GraphScope::Default,
472 provenance_iri: None,
473 asserted_at_ms: None,
474 }
475 }
476
477 pub fn with_graph_scope(mut self, graph_scope: GraphScope) -> Self {
478 self.graph_scope = graph_scope;
479 self
480 }
481
482 pub fn with_metadata(
483 mut self,
484 provenance_iri: Option<String>,
485 asserted_at_ms: Option<u64>,
486 ) -> Self {
487 self.provenance_iri = provenance_iri;
488 self.asserted_at_ms = asserted_at_ms;
489 self
490 }
491
492 pub fn content_eq(&self, other: &Self) -> bool {
493 self.predicate == other.predicate
494 && self.value == other.value
495 && self.datatype == other.datatype
496 && self.lang == other.lang
497 && self.graph_scope == other.graph_scope
498 }
499}
500
501#[derive(
512 Debug,
513 Clone,
514 Copy,
515 PartialEq,
516 Eq,
517 Hash,
518 PartialOrd,
519 Ord,
520 Archive,
521 Serialize,
522 Deserialize,
523 serde::Serialize,
524 serde::Deserialize,
525)]
526#[rkyv(
527 compare(PartialEq, PartialOrd),
528 derive(Debug, PartialEq, Eq, PartialOrd, Ord)
529)]
530pub enum ImageRole {
531 Favicon,
532 Preview,
533 Snapshot,
534}
535
536#[derive(
544 Debug,
545 Clone,
546 Copy,
547 PartialEq,
548 Eq,
549 Hash,
550 Archive,
551 Serialize,
552 Deserialize,
553 serde::Serialize,
554 serde::Deserialize,
555)]
556#[rkyv(derive(Debug, PartialEq, Eq))]
557pub struct ImageRef {
558 #[serde(with = "digest_hex")]
561 pub digest: [u8; 32],
562 pub width: u32,
564 pub height: u32,
566}
567
568impl ImageRef {
569 pub fn new(digest: [u8; 32], width: u32, height: u32) -> Self {
570 Self {
571 digest,
572 width,
573 height,
574 }
575 }
576
577 pub fn hex(&self) -> String {
581 use std::fmt::Write;
582 let mut out = String::with_capacity(64);
583 for byte in &self.digest {
584 let _ = write!(out, "{byte:02x}");
585 }
586 out
587 }
588}
589
590mod digest_hex {
592 use serde::{Deserialize, Deserializer, Serializer, de::Error};
593
594 pub fn serialize<S: Serializer>(digest: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error> {
595 use std::fmt::Write;
596 let mut hex = String::with_capacity(64);
597 for byte in digest {
598 let _ = write!(hex, "{byte:02x}");
599 }
600 serializer.serialize_str(&hex)
601 }
602
603 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<[u8; 32], D::Error> {
604 let hex = String::deserialize(deserializer)?;
605 let bytes = hex.as_bytes();
606 if bytes.len() != 64 {
607 return Err(D::Error::invalid_length(bytes.len(), &"64 hex characters"));
608 }
609 let nibble = |b: u8| -> Result<u8, D::Error> {
610 (b as char)
611 .to_digit(16)
612 .map(|d| d as u8)
613 .ok_or_else(|| D::Error::custom("digest is not valid hex"))
614 };
615 let mut out = [0u8; 32];
616 for (i, pair) in bytes.chunks_exact(2).enumerate() {
617 out[i] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
618 }
619 Ok(out)
620 }
621}
622
623#[derive(
628 Debug,
629 Clone,
630 PartialEq,
631 Eq,
632 Archive,
633 Serialize,
634 Deserialize,
635 serde::Serialize,
636 serde::Deserialize,
637)]
638#[rkyv(derive(Debug, PartialEq, Eq))]
639pub enum BadgeIcon {
640 Emoji(String),
641 Lucide(String),
642 None,
643}
644
645#[derive(
646 Debug,
647 Clone,
648 Default,
649 PartialEq,
650 Eq,
651 Archive,
652 Serialize,
653 Deserialize,
654 serde::Serialize,
655 serde::Deserialize,
656)]
657#[rkyv(derive(Debug, PartialEq, Eq))]
658pub struct NodeTagPresentationState {
659 pub ordered_tags: Vec<String>,
660 pub icon_overrides: HashMap<String, BadgeIcon>,
661}