Skip to main content

kernel/graph/
node_facets.rs

1// Copyright 2026 Mark Alan Boykin
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5// SPDX-License-Identifier: MPL-2.0
6
7//! Typed projections over the graph's atomic per-node facet store.
8//!
9//! The store remains JSON-shaped and unknown-forward at its boundary. These
10//! helpers give kernel consumers concrete types without putting optional
11//! metadata columns back on [`Node`](super::Node).
12
13use serde::{Serialize, de::DeserializeOwned};
14use uuid::Uuid;
15
16use super::snapshot::ResourceSnapshotError;
17use super::{Graph, NodeKey};
18use crate::types::{NodeClassification, NodeProperty, NodeTagPresentationState};
19
20pub const ARRANGEMENT_PIN: &str = "arrangement.pin";
21pub const ARRANGEMENT_FRAME_LAYOUT: &str = "arrangement.frame-layout";
22pub const ARRANGEMENT_SPLIT_OFFER_SUPPRESSED: &str = "arrangement.split-offer-suppressed";
23pub const PRESENTATION_TAGS: &str = "presentation.tags";
24pub const VISIT_HISTORY: &str = "visit.history";
25pub const PROVENANCE_IMPORT: &str = "provenance.import";
26pub const PROVENANCE_DERIVATIONS: &str = "provenance.derivations";
27pub const SEMANTIC_CLASSIFICATIONS: &str = "semantic.classifications";
28pub const SEMANTIC_PROPERTIES: &str = "semantic.properties";
29
30pub type NodeFacetStore = chartulary::FacetStore<Uuid>;
31
32/// The durable visit clocks formerly stored as two columns on `Node`.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, serde::Deserialize)]
34pub struct VisitHistoryFacet {
35    #[serde(default)]
36    pub last_visited_ms: Option<u64>,
37    #[serde(default)]
38    pub last_session_visited: u64,
39}
40
41impl Graph {
42    /// The graph's single live atomic-facet authority.
43    pub fn facets(&self) -> &NodeFacetStore {
44        &self.facets
45    }
46
47    /// Raw mutable access to the store, for kernel code and test fixtures.
48    ///
49    /// Outside the kernel a loaded store goes in through
50    /// [`install_facets`](Self::install_facets) or
51    /// [`overlay_facets`](Self::overlay_facets), which apply the handle rule
52    /// checked open applies; this skips it.
53    ///
54    /// A write through it may touch visit history, so taking it advances the
55    /// [visit revision](Graph::visit_revision).
56    pub(crate) fn facets_mut(&mut self) -> &mut NodeFacetStore {
57        self.bump_visit_revision();
58        &mut self.facets
59    }
60
61    /// Replace the facet store with `facets`, a sidecar loaded for this graph.
62    ///
63    /// Refused, with the previous store kept, when the result would fail
64    /// checked open: a retained Surface literal may not reuse a handle a
65    /// Resource holds ([`validate_active_resource_assertion_handles`]
66    /// (Graph::validate_active_resource_assertion_handles)).
67    pub fn install_facets(&mut self, facets: NodeFacetStore) -> Result<(), ResourceSnapshotError> {
68        let previous = std::mem::replace(&mut self.facets, facets);
69        if let Err(error) = self.validate_active_resource_assertion_handles() {
70            self.facets = previous;
71            return Err(ResourceSnapshotError::InvalidFacets(error));
72        }
73        self.bump_visit_revision();
74        Ok(())
75    }
76
77    /// Overlay a canonical sidecar after snapshot load.
78    ///
79    /// Legacy snapshot columns are imported while reconstructing the graph.
80    /// Existing `facets.json` values then win for matching keys, while both
81    /// stores preserve unrelated namespaces. Checked and kept as
82    /// [`install_facets`](Self::install_facets) is.
83    pub fn overlay_facets(&mut self, facets: NodeFacetStore) -> Result<(), ResourceSnapshotError> {
84        let mut merged = self.facets.clone();
85        merged.overlay(facets);
86        self.install_facets(merged)
87    }
88
89    pub(crate) fn node_facet<T: DeserializeOwned>(
90        &self,
91        key: NodeKey,
92        facet: &'static str,
93    ) -> Option<T> {
94        let node = self.inner.node(key)?;
95        let value = self
96            .facets
97            .get(&node.id, &chartulary::FacetId::new(facet))?;
98        // Borrowing deserializer: `&Value` is itself a `Deserializer`, so the
99        // stored subtree is read in place. `from_value` would deep-clone the
100        // whole tree first, and these accessors sit on the per-frame paint path.
101        T::deserialize(value).ok()
102    }
103
104    pub(crate) fn node_facet_or_default<T: DeserializeOwned + Default>(
105        &self,
106        key: NodeKey,
107        facet: &'static str,
108    ) -> T {
109        self.node_facet(key, facet).unwrap_or_default()
110    }
111
112    pub(crate) fn set_node_facet<T: Serialize>(
113        &mut self,
114        key: NodeKey,
115        facet: &'static str,
116        value: &T,
117    ) -> bool {
118        let Some(node_id) = self.inner.node(key).map(|node| node.id) else {
119            return false;
120        };
121        let facet_id = chartulary::FacetId::new(facet);
122        let value = serde_json::to_value(value).expect("kernel facet must serialize");
123        if self.facets.get(&node_id, &facet_id) == Some(&value) {
124            return false;
125        }
126        self.facets
127            .set(node_id, facet_id, value, &chartulary::AcceptAll)
128            .expect("AcceptAll cannot reject a kernel facet");
129        if facet == VISIT_HISTORY {
130            self.bump_visit_revision();
131        }
132        true
133    }
134
135    pub(crate) fn remove_facets_for_node(&mut self, node_id: Uuid) {
136        self.facets.remove_node(&node_id);
137    }
138}
139
140// ---------------------------------------------------------------------------
141// Live batched content writers. Exact Resource captures carry the shared content;
142// legacy Replay variants continue using the raw Surface setters in node_props.
143// ---------------------------------------------------------------------------
144
145impl Graph {
146    /// Insert tags on the shown Resource, retaining each tagger's assertion.
147    pub fn insert_node_tags(&mut self, key: NodeKey, tags: Vec<String>) -> bool {
148        let mut changed = false;
149        for tag in tags {
150            changed |= self.insert_shown_tag(key, tag);
151        }
152        changed
153    }
154
155    /// Append literal assertions to the shown Resource in one facet replacement.
156    pub fn append_node_properties(&mut self, key: NodeKey, incoming: Vec<NodeProperty>) -> bool {
157        self.append_shown_properties(key, incoming)
158    }
159
160    /// Preserve complete classification variants and the caller's origin.
161    pub fn add_node_classifications(
162        &mut self,
163        key: NodeKey,
164        incoming: Vec<NodeClassification>,
165    ) -> bool {
166        self.add_shown_classifications(key, incoming)
167    }
168}