Skip to main content

kernel/graph/
frozen_link.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//! Immutable, source-qualified link readings borne by Resources.
8
9use super::{CoverageNote, Graph, GraphStratum};
10use crate::persistence::{PersistedEdge, PersistedResourceFacet, PersistedResourceRecord};
11use petgraph::visit::{EdgeRef, IntoEdgeReferences};
12use serde::{Deserialize, Serialize};
13use uuid::Uuid;
14
15pub const FROZEN_LINK: &str = "graph.frozen-link/v1";
16
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18#[serde(deny_unknown_fields)]
19pub struct FrozenLinkEndpoint {
20    pub id: Uuid,
21    pub resource: Option<Uuid>,
22    pub address: Option<String>,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct FrozenSourceBinding {
28    pub authority: String,
29    pub domain: String,
30    pub resource: String,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
35pub enum FrozenSourceRevision {
36    Available { revision: String },
37    Unavailable { reason: String },
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
42pub enum FrozenLinkSource {
43    Available {
44        binding: FrozenSourceBinding,
45        revision: FrozenSourceRevision,
46    },
47    Unavailable {
48        reason: String,
49    },
50}
51
52impl FrozenLinkSource {
53    fn validate(&self) -> Result<(), String> {
54        let nonempty = |value: &str| !value.trim().is_empty() && value == value.trim();
55        match self {
56            Self::Available { binding, revision } => {
57                if !nonempty(&binding.authority)
58                    || !nonempty(&binding.domain)
59                    || !nonempty(&binding.resource)
60                {
61                    return Err("frozen source binding fields must be nonempty and trimmed".into());
62                }
63                match revision {
64                    FrozenSourceRevision::Available { revision } if nonempty(revision) => Ok(()),
65                    FrozenSourceRevision::Available { .. } => {
66                        Err("frozen source revision must be nonempty and trimmed".into())
67                    },
68                    FrozenSourceRevision::Unavailable { reason } if nonempty(reason) => Ok(()),
69                    FrozenSourceRevision::Unavailable { .. } => {
70                        Err("unavailable source revision requires a reason".into())
71                    },
72                }
73            },
74            Self::Unavailable { reason } if nonempty(reason) => Ok(()),
75            Self::Unavailable { .. } => Err("unavailable frozen source requires a reason".into()),
76        }
77    }
78}
79
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
81#[serde(deny_unknown_fields)]
82pub struct FrozenLink {
83    version: u32,
84    stratum: GraphStratum,
85    first: FrozenLinkEndpoint,
86    second: FrozenLinkEndpoint,
87    revision: u64,
88    source: FrozenLinkSource,
89    coverage: CoverageNote,
90    statements: Vec<PersistedEdge>,
91}
92
93impl FrozenLink {
94    pub fn stratum(&self) -> GraphStratum {
95        self.stratum
96    }
97    pub fn first(&self) -> &FrozenLinkEndpoint {
98        &self.first
99    }
100    pub fn second(&self) -> &FrozenLinkEndpoint {
101        &self.second
102    }
103    /// The local structural revision observed at freeze time; not a public source revision.
104    pub fn revision(&self) -> u64 {
105        self.revision
106    }
107    pub fn source(&self) -> &FrozenLinkSource {
108        &self.source
109    }
110    pub fn coverage(&self) -> &CoverageNote {
111        &self.coverage
112    }
113    pub fn statements(&self) -> &[PersistedEdge] {
114        &self.statements
115    }
116}
117
118pub struct OpenedFrozenLink<'a> {
119    pub link: &'a FrozenLink,
120    pub coverage: CoverageNote,
121}
122
123pub(super) fn validate_frozen_link_record(
124    record: &PersistedResourceRecord,
125) -> Result<Option<FrozenLink>, String> {
126    let facets = record
127        .facets
128        .iter()
129        .filter(|facet| facet.facet == FROZEN_LINK)
130        .collect::<Vec<_>>();
131    if facets.len() > 1 {
132        return Err("duplicate frozen link facets".into());
133    }
134    let Some(facet) = facets.first() else {
135        return Ok(None);
136    };
137    let raw: serde_json::Value = serde_json::from_str(&facet.value_json)
138        .map_err(|error| format!("invalid frozen link: {error}"))?;
139    let link: FrozenLink = serde_json::from_value(raw.clone())
140        .map_err(|error| format!("invalid frozen link: {error}"))?;
141    let mut known = serde_json::to_value(&link).map_err(|error| error.to_string())?;
142    for edge in known["statements"]
143        .as_array_mut()
144        .expect("serialized edge array")
145    {
146        if let Some(statements) = edge
147            .get_mut("assertions")
148            .and_then(serde_json::Value::as_array_mut)
149        {
150            super::frozen_selection::normalize_statement_defaults(statements);
151        }
152        if let Some(statements) = edge
153            .get_mut("semantic")
154            .and_then(|semantic| semantic.get_mut("statements"))
155            .and_then(serde_json::Value::as_array_mut)
156        {
157            super::frozen_selection::normalize_statement_defaults(statements);
158        }
159    }
160    super::frozen_selection::validate_retained_keys(&raw, &known)?;
161    if link.version != 1 {
162        return Err("unsupported frozen link version".into());
163    }
164    link.source.validate()?;
165    if link.first.id > link.second.id {
166        return Err("frozen link endpoints must be in canonical order".into());
167    }
168    for endpoint in [&link.first, &link.second] {
169        if endpoint.id.is_nil()
170            || endpoint.resource.is_some_and(|id| id.is_nil())
171            || endpoint
172                .address
173                .as_ref()
174                .is_some_and(|address| address.trim().is_empty() || address != address.trim())
175        {
176            return Err("invalid frozen link endpoint".into());
177        }
178    }
179    if link.stratum == GraphStratum::Resource
180        && (link.first.resource != Some(link.first.id)
181            || link.second.resource != Some(link.second.id))
182    {
183        return Err("resource link endpoints must retain resource identity".into());
184    }
185    if link.stratum == GraphStratum::Resource
186        && [&link.first, &link.second].into_iter().any(|endpoint| {
187            endpoint.address.as_ref().is_none_or(|address| {
188                chartulary::resource_id_from_canonical_iri(address) != endpoint.id
189            })
190        })
191    {
192        return Err("resource endpoint address does not match its identity".into());
193    }
194    if link.statements.is_empty() {
195        return Err("frozen link must retain at least one pair bucket".into());
196    }
197    super::assertion_handles::validate_assertion_handles(
198        link.statements.iter().map(|edge| (link.stratum, edge)),
199    )
200    .map_err(|error| error.to_string())?;
201    for edge in &link.statements {
202        let from = edge
203            .from_node_id
204            .parse::<Uuid>()
205            .map_err(|_| "invalid frozen link source id")?;
206        let to = edge
207            .to_node_id
208            .parse::<Uuid>()
209            .map_err(|_| "invalid frozen link target id")?;
210        let valid_pair = (from == link.first.id && to == link.second.id)
211            || (from == link.second.id && to == link.first.id);
212        if from.to_string() != edge.from_node_id || to.to_string() != edge.to_node_id || !valid_pair
213        {
214            return Err("frozen link bucket is outside its canonical endpoint pair".into());
215        }
216        for statement in edge.retained_assertions() {
217            if statement.statement_id.trim().is_empty() {
218                return Err("frozen link assertion id must be nonempty".into());
219            }
220        }
221        let payload = super::snapshot::payload_from_persisted(edge);
222        if super::snapshot::persisted_edge_for_ids(from, to, &payload) != *edge {
223            return Err("inconsistent frozen link bucket payload".into());
224        }
225    }
226    Ok(Some(link))
227}
228
229impl Graph {
230    fn link_coverage(&self, resources: &[Uuid], surfaces: &[Uuid]) -> CoverageNote {
231        let resources = resources
232            .iter()
233            .copied()
234            .collect::<std::collections::BTreeSet<_>>();
235        let surfaces = surfaces
236            .iter()
237            .copied()
238            .collect::<std::collections::BTreeSet<_>>();
239        let mut note = self.known_coverage.clone();
240        note.limits.retain(|limit| {
241            (limit.resources.is_empty() && limit.surfaces.is_empty())
242                || limit.resources.iter().any(|id| resources.contains(id))
243                || limit.surfaces.iter().any(|id| surfaces.contains(id))
244        });
245        let missing_resources = resources
246            .iter()
247            .copied()
248            .filter(|id| self.resource(*id).is_none())
249            .filter(|id| {
250                !note.limits.iter().any(|limit| {
251                    limit.layer == super::CoverageLayer::Residency
252                        && ((limit.resources.is_empty() && limit.surfaces.is_empty())
253                            || limit.resources.contains(id))
254                })
255            })
256            .collect::<Vec<_>>();
257        if !missing_resources.is_empty() {
258            let mut limit = super::CoverageLimit::new(
259                super::CoverageLayer::Possession,
260                "referenced resources are unavailable",
261            );
262            limit.count = Some(missing_resources.len());
263            limit.resources = missing_resources;
264            note.push(limit);
265        }
266        let missing_surfaces = surfaces
267            .iter()
268            .copied()
269            .filter(|id| self.get_node_key_by_id(*id).is_none())
270            .filter(|id| {
271                !note.limits.iter().any(|limit| {
272                    limit.layer == super::CoverageLayer::Residency
273                        && ((limit.resources.is_empty() && limit.surfaces.is_empty())
274                            || limit.surfaces.contains(id))
275                })
276            })
277            .collect::<Vec<_>>();
278        if !missing_surfaces.is_empty() {
279            let mut limit = super::CoverageLimit::new(
280                super::CoverageLayer::Possession,
281                "referenced surfaces are unavailable",
282            );
283            limit.count = Some(missing_surfaces.len());
284            limit.surfaces = missing_surfaces;
285            note.push(limit);
286        }
287        note
288    }
289
290    /// Read a current pair without minting a Resource. An empty pair is a valid
291    /// reading result for drift comparison, but cannot be frozen.
292    pub fn read_link_snapshot(
293        &self,
294        stratum: GraphStratum,
295        first: Uuid,
296        second: Uuid,
297        source: FrozenLinkSource,
298    ) -> Result<FrozenLink, String> {
299        source.validate()?;
300        let (first, second) = if first <= second {
301            (first, second)
302        } else {
303            (second, first)
304        };
305        let (first_endpoint, second_endpoint, statements) = match stratum {
306            GraphStratum::Surface => {
307                let (first_key, first_node) = self
308                    .get_node_by_id(first)
309                    .ok_or("missing first Surface link endpoint")?;
310                let (second_key, second_node) = self
311                    .get_node_by_id(second)
312                    .ok_or("missing second Surface link endpoint")?;
313                let endpoints = (
314                    FrozenLinkEndpoint {
315                        id: first,
316                        resource: self.shown_resource_id(first_key),
317                        address: Some(first_node.url().to_owned()),
318                    },
319                    FrozenLinkEndpoint {
320                        id: second,
321                        resource: self.shown_resource_id(second_key),
322                        address: Some(second_node.url().to_owned()),
323                    },
324                );
325                let rows = self
326                    .inner
327                    .inner()
328                    .edge_references()
329                    .filter_map(|edge| {
330                        let from = self.inner.node(edge.source())?.id;
331                        let to = self.inner.node(edge.target())?.id;
332                        ((from == first && to == second) || (from == second && to == first)).then(
333                            || super::snapshot::persisted_edge_for_ids(from, to, edge.weight()),
334                        )
335                    })
336                    .collect::<Vec<_>>();
337                (endpoints.0, endpoints.1, rows)
338            },
339            GraphStratum::Resource => {
340                let first_resource = self
341                    .resource(first)
342                    .ok_or("missing first Resource endpoint")?;
343                let second_resource = self
344                    .resource(second)
345                    .ok_or("missing second Resource endpoint")?;
346                let endpoints = (
347                    FrozenLinkEndpoint {
348                        id: first,
349                        resource: Some(first),
350                        address: Some(first_resource.canonical_iri().to_owned()),
351                    },
352                    FrozenLinkEndpoint {
353                        id: second,
354                        resource: Some(second),
355                        address: Some(second_resource.canonical_iri().to_owned()),
356                    },
357                );
358                let rows = self
359                    .resource_edges()
360                    .filter_map(|(from, to, payload)| {
361                        let (from, to) = (from.id(), to.id());
362                        ((from == first && to == second) || (from == second && to == first))
363                            .then(|| super::snapshot::persisted_edge_for_ids(from, to, payload))
364                    })
365                    .collect::<Vec<_>>();
366                (endpoints.0, endpoints.1, rows)
367            },
368        };
369        let resource_refs = [first_endpoint.resource, second_endpoint.resource]
370            .into_iter()
371            .flatten()
372            .collect::<Vec<_>>();
373        let surface_refs = if stratum == GraphStratum::Surface {
374            vec![first, second]
375        } else {
376            Vec::new()
377        };
378        Ok(FrozenLink {
379            version: 1,
380            stratum,
381            first: first_endpoint,
382            second: second_endpoint,
383            revision: self.revision(),
384            source,
385            coverage: self.link_coverage(&resource_refs, &surface_refs),
386            statements,
387        })
388    }
389
390    /// Freeze a link in one graph stratum as a distinct immutable Resource.
391    pub fn freeze_link_with_nonce(
392        &mut self,
393        stratum: GraphStratum,
394        first: Uuid,
395        second: Uuid,
396        source: FrozenLinkSource,
397        nonce: Uuid,
398    ) -> Result<Uuid, String> {
399        if nonce.is_nil() {
400            return Err("frozen Resource nonce must be non-nil".into());
401        }
402        let link = self.read_link_snapshot(stratum, first, second, source)?;
403        if link.statements.is_empty() {
404            return Err("cannot freeze a link with no pair buckets".into());
405        }
406        let iri = format!("urn:uuid:{nonce}");
407        let owner = super::ResourceNode::for_term(&iri);
408        if self.resource(owner.id()).is_some() {
409            return Err("frozen Resource nonce is already in use".into());
410        }
411        let record = PersistedResourceRecord {
412            canonical_iri: iri,
413            facets: vec![PersistedResourceFacet {
414                facet: FROZEN_LINK.into(),
415                value_json: serde_json::to_string(&link).map_err(|error| error.to_string())?,
416            }],
417        };
418        validate_frozen_link_record(&record)?;
419        if !self.set_resource_record(owner.id(), Some(record.clone())) {
420            return Err("frozen Resource admission refused".into());
421        }
422        self.record_delta(&super::CapturedDelta::ReplaySetResourceRecordById {
423            resource_id: owner.id().to_string(),
424            record: Some(record),
425        });
426        Ok(owner.id())
427    }
428
429    pub fn open_frozen_link(&self, owner: Uuid) -> Result<OpenedFrozenLink<'_>, String> {
430        let link = self
431            .resource(owner)
432            .and_then(|resource| resource.nested_link())
433            .ok_or("resource bears no frozen link")?;
434        let resource_refs = [link.first.resource, link.second.resource]
435            .into_iter()
436            .flatten()
437            .collect::<Vec<_>>();
438        let surface_refs = if link.stratum == GraphStratum::Surface {
439            vec![link.first.id, link.second.id]
440        } else {
441            Vec::new()
442        };
443        let coverage = self.link_coverage(&resource_refs, &surface_refs);
444        Ok(OpenedFrozenLink { link, coverage })
445    }
446}