Skip to main content

kernel/graph/
resource_content.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, recorded content on shared resources. Unknown facets remain untouched.
8
9use super::{CapturedDelta, Graph, NodeKey, ResourceNode};
10use crate::persistence::{PersistedResourceFacet, PersistedResourceRecord};
11use crate::types::{ClassificationScheme, ClassificationStatus, NodeClassification, NodeProperty};
12use petgraph::visit::{EdgeRef, IntoEdgeReferences};
13use serde::{Deserialize, Serialize, de::DeserializeOwned};
14use uuid::Uuid;
15
16pub const RESOURCE_PROPERTIES: &str = "semantic.properties";
17pub const RESOURCE_CLASSIFICATIONS: &str = "semantic.classification-variants/v1";
18pub const TAG_CONCEPT: &str = "semantic.tag-concept/v1";
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum ContentError {
22    MissingResource,
23    HandleCollision(String),
24    AmbiguousClassification(Vec<String>),
25    MissingClassification(String),
26    InvalidFacet(String),
27}
28impl std::fmt::Display for ContentError {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        write!(f, "{self:?}")
31    }
32}
33impl std::error::Error for ContentError {}
34
35pub(crate) fn validate_content_record(
36    record: &PersistedResourceRecord,
37) -> Result<(), ContentError> {
38    for facet in &record.facets {
39        match facet.facet.as_str() {
40            super::frozen_selection::FROZEN_SELECTION => {
41                super::frozen_selection::selection_from_record(record)
42                    .map_err(ContentError::InvalidFacet)?;
43            },
44            super::frozen_link::FROZEN_LINK => {
45                super::frozen_link::validate_frozen_link_record(record)
46                    .map_err(ContentError::InvalidFacet)?;
47            },
48            RESOURCE_PROPERTIES => {
49                let properties: Vec<crate::types::NodeProperty> =
50                    serde_json::from_str(&facet.value_json)
51                        .map_err(|e| ContentError::InvalidFacet(e.to_string()))?;
52                let mut handles = std::collections::BTreeMap::new();
53                for property in &properties {
54                    if let Some(previous) = handles.insert(&property.statement_id, property)
55                        && previous != property
56                    {
57                        return Err(ContentError::HandleCollision(property.statement_id.clone()));
58                    }
59                }
60            },
61            RESOURCE_CLASSIFICATIONS => {
62                let variants: Vec<super::resource_classifications::ClassificationVariant> =
63                    serde_json::from_str(&facet.value_json)
64                        .map_err(|e| ContentError::InvalidFacet(e.to_string()))?;
65                super::resource_classifications::validate_variants(&variants)?;
66            },
67            TAG_CONCEPT => {
68                let concept: super::resource_tags::TagConcept =
69                    serde_json::from_str(&facet.value_json)
70                        .map_err(|e| ContentError::InvalidFacet(e.to_string()))?;
71                super::resource_tags::validate_tag_concept(&record.canonical_iri, &concept)?;
72            },
73            _ => {},
74        }
75    }
76    Ok(())
77}
78
79#[derive(Clone, PartialEq, Eq)]
80enum ResourceHandlePayload {
81    Semantic(super::SemanticStatement),
82    Literal(crate::types::NodeProperty),
83    /// A row of the write under check, whose statements are not yet stored.
84    Pending,
85}
86#[derive(Clone, PartialEq, Eq)]
87enum ResourceHandleOwner {
88    Relation(Uuid, Uuid),
89    Literal(Uuid),
90}
91
92/// Literals about to replace what one owner holds, checked before they are stored.
93#[derive(Clone, Copy)]
94pub(crate) enum LiteralWrite<'a> {
95    Resource(Uuid, &'a [NodeProperty]),
96    /// Retained Surface literals, by Surface node id.
97    Surface(Uuid, &'a [NodeProperty]),
98}
99
100/// A write checked against the handle rule before it is stored.
101#[derive(Clone, Copy)]
102pub(crate) enum PendingWrite<'a> {
103    Literals(LiteralWrite<'a>),
104    /// The handles of the rows that replace every Resource edge from one
105    /// Resource to another. Each handle may sit on one row only.
106    ResourceEdges(Uuid, Uuid, &'a [String]),
107    /// The handles of the rows that replace every Surface edge from one node to
108    /// another, by node id.
109    SurfaceEdges(Uuid, Uuid, &'a [String]),
110}
111
112impl Graph {
113    pub(crate) fn insert_node_tag(&mut self, key: NodeKey, tag: String) -> bool {
114        self.insert_shown_tag(key, tag)
115    }
116    pub(crate) fn remove_node_tag(&mut self, key: NodeKey, tag: &str) -> bool {
117        self.remove_shown_tag(key, tag)
118    }
119    pub(crate) fn append_node_property(&mut self, key: NodeKey, property: NodeProperty) -> bool {
120        self.append_shown_properties(key, vec![property])
121    }
122    pub(crate) fn add_node_classification(
123        &mut self,
124        key: NodeKey,
125        classification: NodeClassification,
126    ) -> bool {
127        self.add_shown_classifications(key, vec![classification])
128    }
129    pub(crate) fn remove_node_classification(
130        &mut self,
131        key: NodeKey,
132        scheme: &ClassificationScheme,
133        value: &str,
134    ) -> bool {
135        self.unique_shown_classification(key, scheme, value)
136            .ok()
137            .flatten()
138            .is_some_and(|(id, variant)| {
139                self.remove_resource_classification(id, &variant)
140                    .unwrap_or(false)
141            })
142    }
143    pub(crate) fn set_node_classification_status(
144        &mut self,
145        key: NodeKey,
146        scheme: &ClassificationScheme,
147        value: &str,
148        status: ClassificationStatus,
149    ) -> bool {
150        self.unique_shown_classification(key, scheme, value)
151            .ok()
152            .flatten()
153            .is_some_and(|(id, variant)| {
154                self.edit_resource_classification(id, &variant, Some(status), None)
155                    .unwrap_or(false)
156            })
157    }
158    pub(crate) fn set_node_primary_classification(
159        &mut self,
160        key: NodeKey,
161        scheme: &ClassificationScheme,
162        value: &str,
163    ) -> bool {
164        self.unique_shown_classification(key, scheme, value)
165            .ok()
166            .flatten()
167            .is_some_and(|(id, variant)| {
168                self.edit_resource_classification(id, &variant, None, Some(true))
169                    .unwrap_or(false)
170            })
171    }
172
173    /// Check Resource handle ownership after a host overlays retained Surface facets.
174    /// Held Surface-only duplicates keep their historical grammar. Checked open and
175    /// replayed writes share this one rule; a replayed edge set also keeps each
176    /// handle to one row.
177    pub fn validate_active_resource_assertion_handles(&self) -> Result<(), ContentError> {
178        self.validate_handles_after(None)
179    }
180
181    /// Whether storing `write` leaves the graph passing checked open. A write that
182    /// claims no literal its owner does not already hold cannot collide, so it skips
183    /// the scan.
184    pub(crate) fn admit_literals(&self, write: LiteralWrite<'_>) -> Result<(), ContentError> {
185        let (held, incoming) = match write {
186            LiteralWrite::Resource(id, incoming) => (self.resource_properties(id), incoming),
187            LiteralWrite::Surface(id, incoming) => (
188                self.get_node_key_by_id(id)
189                    .and_then(|key| self.legacy_node_properties(key))
190                    .unwrap_or_default(),
191                incoming,
192            ),
193        };
194        if incoming.iter().all(|property| held.contains(property)) {
195            return Ok(());
196        }
197        self.validate_handles_after(Some(PendingWrite::Literals(write)))
198    }
199
200    pub(crate) fn admit_record_literals(
201        &self,
202        id: Uuid,
203        record: Option<&PersistedResourceRecord>,
204    ) -> Result<(), ContentError> {
205        let properties: Vec<NodeProperty> = record
206            .and_then(|record| {
207                record
208                    .facets
209                    .iter()
210                    .find(|facet| facet.facet == RESOURCE_PROPERTIES)
211            })
212            .and_then(|facet| serde_json::from_str(&facet.value_json).ok())
213            .unwrap_or_default();
214        self.admit_literals(LiteralWrite::Resource(id, &properties))
215    }
216
217    pub(crate) fn admit_surface_facet(
218        &self,
219        node_id: Uuid,
220        facet: &str,
221        value: &serde_json::Value,
222    ) -> Result<(), ContentError> {
223        if facet != super::node_facets::SEMANTIC_PROPERTIES {
224            return Ok(());
225        }
226        let properties = Vec::<NodeProperty>::deserialize(value).unwrap_or_default();
227        self.admit_literals(LiteralWrite::Surface(node_id, &properties))
228    }
229
230    pub(super) fn validate_handles_after(
231        &self,
232        write: Option<PendingWrite<'_>>,
233    ) -> Result<(), ContentError> {
234        let literals = match write {
235            Some(PendingWrite::Literals(literals)) => Some(literals),
236            _ => None,
237        };
238        let mut handles = std::collections::BTreeMap::<
239            String,
240            (ResourceHandleOwner, ResourceHandlePayload),
241        >::new();
242        // A strict claim is refused whenever any other row holds the handle.
243        let mut insert = |id: String,
244                          owner: ResourceHandleOwner,
245                          payload: ResourceHandlePayload,
246                          strict: bool|
247         -> Result<(), ContentError> {
248            if let Some((held_owner, held_payload)) = handles.get(&id) {
249                if strict || *held_owner != owner || *held_payload != payload {
250                    return Err(ContentError::HandleCollision(id));
251                }
252            } else {
253                handles.insert(id, (owner, payload));
254            }
255            Ok(())
256        };
257        for (from, to, payload) in self.resource_edges() {
258            if matches!(write, Some(PendingWrite::ResourceEdges(a, b, _)) if (a, b) == (from.id(), to.id()))
259            {
260                continue;
261            }
262            for statement in payload.assertions() {
263                insert(
264                    statement.statement_id.clone(),
265                    ResourceHandleOwner::Relation(from.id(), to.id()),
266                    ResourceHandlePayload::Semantic(statement.clone()),
267                    false,
268                )?;
269            }
270        }
271        if let Some(PendingWrite::ResourceEdges(from, to, rows)) = write {
272            for id in rows {
273                let owner = ResourceHandleOwner::Relation(from, to);
274                insert(id.clone(), owner, ResourceHandlePayload::Pending, true)?;
275            }
276        }
277        let unheld = match literals {
278            Some(LiteralWrite::Resource(id, _)) if self.resource(id).is_none() => Some(id),
279            _ => None,
280        };
281        for id in self.resource_nodes().map(ResourceNode::id).chain(unheld) {
282            let held;
283            let properties = match literals {
284                Some(LiteralWrite::Resource(owner, properties)) if owner == id => properties,
285                _ => {
286                    held = self.resource_properties(id);
287                    &held
288                },
289            };
290            for property in properties {
291                insert(
292                    property.statement_id.clone(),
293                    ResourceHandleOwner::Literal(id),
294                    ResourceHandlePayload::Literal(property.clone()),
295                    false,
296                )?;
297            }
298        }
299        let replaced = match write {
300            Some(PendingWrite::SurfaceEdges(from, to, _)) => self
301                .get_node_key_by_id(from)
302                .zip(self.get_node_key_by_id(to)),
303            _ => None,
304        };
305        let mut surface_rows = std::collections::BTreeSet::new();
306        for edge in self.inner.inner().edge_references() {
307            if replaced == Some((edge.source(), edge.target())) {
308                continue;
309            }
310            for statement in edge.weight().assertions() {
311                if handles.contains_key(&statement.statement_id) {
312                    return Err(ContentError::HandleCollision(
313                        statement.statement_id.clone(),
314                    ));
315                }
316                if replaced.is_some() {
317                    surface_rows.insert(statement.statement_id.as_str());
318                }
319            }
320        }
321        if let Some(PendingWrite::SurfaceEdges(_, _, rows)) = write {
322            // Held Surface-only duplicates keep their historical grammar; a
323            // replayed set may not put a handle on a second row.
324            let mut claimed = std::collections::BTreeSet::new();
325            for id in rows {
326                if handles.contains_key(id)
327                    || surface_rows.contains(id.as_str())
328                    || !claimed.insert(id)
329                {
330                    return Err(ContentError::HandleCollision(id.clone()));
331                }
332            }
333        }
334        for (key, node) in self.nodes() {
335            let held;
336            let properties = match literals {
337                Some(LiteralWrite::Surface(owner, properties)) if owner == node.id => properties,
338                _ => {
339                    held = self.legacy_node_properties(key).unwrap_or_default();
340                    &held
341                },
342            };
343            for property in properties {
344                if handles.contains_key(&property.statement_id) {
345                    return Err(ContentError::HandleCollision(property.statement_id.clone()));
346                }
347            }
348        }
349        Ok(())
350    }
351
352    pub(crate) fn resource_content<T: DeserializeOwned>(&self, id: Uuid, facet: &str) -> Option<T> {
353        let value = self
354            .resource_facets()
355            .get(&id, &chartulary::FacetId::new(facet))?;
356        T::deserialize(value).ok()
357    }
358
359    pub(crate) fn write_resource_content<T: Serialize>(
360        &mut self,
361        id: Uuid,
362        facet: &str,
363        value: &T,
364    ) -> Result<bool, ContentError> {
365        let mut record = self
366            .resource_record(id)
367            .ok_or(ContentError::MissingResource)?;
368        let encoded =
369            serde_json::to_string(value).map_err(|e| ContentError::InvalidFacet(e.to_string()))?;
370        if let Some(stored) = record.facets.iter_mut().find(|entry| entry.facet == facet) {
371            if serde_json::from_str::<serde_json::Value>(&stored.value_json).ok()
372                == serde_json::from_str(&encoded).ok()
373            {
374                return Ok(false);
375            }
376            stored.value_json = encoded;
377        } else {
378            record.facets.push(PersistedResourceFacet {
379                facet: facet.into(),
380                value_json: encoded,
381            });
382        }
383        validate_content_record(&record)?;
384        if !self.set_resource_record(id, Some(record.clone())) {
385            return Err(ContentError::InvalidFacet("resource record refused".into()));
386        }
387        self.record_delta(&CapturedDelta::ReplaySetResourceRecordById {
388            resource_id: id.to_string(),
389            record: Some(record),
390        });
391        Ok(true)
392    }
393}