Skip to main content

kernel/graph/
identity.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//! Graph identity types and rkyv archive helpers.
8//!
9//! Extracted from `graph/mod.rs` per the 2026-04-30 renderer plan §6.4
10//! decomposition target (5,459 LOC → split). Contains:
11//!
12//! - Stable handle types (`NodeKey`, `EdgeKey`) — petgraph index aliases.
13//! - Backend type aliases (`GraphDirection`, `GraphIndex`).
14//! - `GraphViewId` — per-graph-view-pane identity (UUID-backed).
15//! - rkyv `with = ...` archive helpers for `Uuid`, `Point2D<f32>`,
16//!   and `Vector2D<f32>` — bridge types between rkyv's primitive
17//!   archive shape and the actual field types used in `Node`/`Edge`/etc.
18//!
19//! WASM-clean: no host-side dependencies beyond what `graph/mod.rs`
20//! already imports.
21
22use petgraph::Directed;
23use petgraph::stable_graph::{EdgeIndex, NodeIndex};
24use rkyv::{
25    Archive, Archived, Deserialize, Place, Resolver, Serialize,
26    rancor::Fallible,
27    with::{ArchiveWith, DeserializeWith, SerializeWith},
28};
29use uuid::Uuid;
30
31/// Stable surface handle (petgraph NodeIndex — survives other deletions).
32pub type SurfaceNodeKey = NodeIndex;
33
34/// Compatibility name for a stable surface handle.
35pub type NodeKey = SurfaceNodeKey;
36
37/// Stable surface edge handle (petgraph EdgeIndex).
38pub type EdgeKey = EdgeIndex;
39
40/// A resource edge handle. Its raw index never crosses into surface APIs.
41///
42/// ```compile_fail
43/// use kernel::graph::{Graph, ResourceEdgeKey};
44/// fn surface_read(graph: &Graph, resource: ResourceEdgeKey) {
45///     graph.get_edge(resource);
46/// }
47/// ```
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
49pub struct ResourceEdgeKey(EdgeIndex);
50
51impl ResourceEdgeKey {
52    pub(crate) fn from_raw(key: EdgeIndex) -> Self {
53        Self(key)
54    }
55
56    pub(crate) fn raw(self) -> EdgeIndex {
57        self.0
58    }
59}
60
61/// An edge handle together with its owning graph stratum.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub enum RelationKey {
64    Surface(EdgeKey),
65    Resource(ResourceEdgeKey),
66}
67
68/// Graph backend direction type exposed for adapter integration.
69pub type GraphDirection = Directed;
70
71/// Graph backend index type exposed for adapter integration.
72pub type GraphIndex = petgraph::graph::DefaultIx;
73
74/// Unique identifier for a graph-view pane (one projection of a graph;
75/// many graph-view panes can exist concurrently, each with its own
76/// camera / selection / filter state).
77///
78/// Pre-M4 slice 10 (2026-04-22) this lived in `app/graph_views.rs`;
79/// moved here alongside the other graph-level identity types so
80/// portable runtime code (`ToolSurfaceReturnTarget`, `FrameViewModel`,
81/// etc.) can reference it without reaching across the app boundary.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
83pub struct GraphViewId(Uuid);
84
85impl GraphViewId {
86    /// Fresh random identity. Gated to non-WASM because
87    /// `Uuid::new_v4()` requires an OS randomness source that is
88    /// unavailable on `wasm32-unknown-unknown`; WASM hosts construct
89    /// via [`GraphViewId::from_uuid`] with a host-supplied UUID.
90    #[cfg(not(target_arch = "wasm32"))]
91    pub fn new() -> Self {
92        Self(Uuid::new_v4())
93    }
94
95    pub fn from_uuid(id: Uuid) -> Self {
96        Self(id)
97    }
98
99    pub fn as_uuid(self) -> Uuid {
100        self.0
101    }
102}
103
104#[cfg(not(target_arch = "wasm32"))]
105impl Default for GraphViewId {
106    fn default() -> Self {
107        Self::new()
108    }
109}
110
111pub(crate) struct UuidAsBytes;
112
113impl ArchiveWith<Uuid> for UuidAsBytes {
114    type Archived = Archived<[u8; 16]>;
115    type Resolver = Resolver<[u8; 16]>;
116
117    fn resolve_with(field: &Uuid, resolver: Self::Resolver, out: Place<Self::Archived>) {
118        let bytes = *field.as_bytes();
119        bytes.resolve(resolver, out);
120    }
121}
122
123impl<S> SerializeWith<Uuid, S> for UuidAsBytes
124where
125    S: Fallible + ?Sized,
126    [u8; 16]: Serialize<S>,
127{
128    fn serialize_with(field: &Uuid, serializer: &mut S) -> Result<Self::Resolver, S::Error> {
129        let bytes = *field.as_bytes();
130        bytes.serialize(serializer)
131    }
132}
133
134impl<D> DeserializeWith<Archived<[u8; 16]>, Uuid, D> for UuidAsBytes
135where
136    D: Fallible + ?Sized,
137    Archived<[u8; 16]>: Deserialize<[u8; 16], D>,
138{
139    fn deserialize_with(
140        field: &Archived<[u8; 16]>,
141        deserializer: &mut D,
142    ) -> Result<Uuid, D::Error> {
143        let bytes = field.deserialize(deserializer)?;
144        Ok(Uuid::from_bytes(bytes))
145    }
146}
147
148// `Point2DAsTuple` (the rkyv with-adapter for `Node.position`) left with the
149// position field (S2): position is no longer graph truth, so the node carries no
150// coordinate to archive. `UuidAsBytes` remains for the node identity.
151//
152// `Vector2DAsTuple` (the rkyv with-adapter for `Node.velocity`) left with the
153// velocity field: seiche owns live velocity, so the graph node no longer carries
154// it. `Point2DAsTuple` remains for the transient projected position.
155
156/// rkyv with-adapter archiving a journal [`LogId`](muniment::LogId) as its
157/// string form — for `Node.nested` (the borne graph's identity; the one-node
158/// ruling's containment tier). Wrap `Option<LogId>` fields as
159/// `#[rkyv(with = rkyv::with::Map<LogIdAsString>)]`.
160pub(crate) struct LogIdAsString;
161
162impl ArchiveWith<muniment::LogId> for LogIdAsString {
163    type Archived = Archived<String>;
164    type Resolver = Resolver<String>;
165
166    fn resolve_with(field: &muniment::LogId, resolver: Self::Resolver, out: Place<Self::Archived>) {
167        field.as_str().to_string().resolve(resolver, out);
168    }
169}
170
171impl<S> SerializeWith<muniment::LogId, S> for LogIdAsString
172where
173    S: Fallible + ?Sized,
174    String: Serialize<S>,
175{
176    fn serialize_with(
177        field: &muniment::LogId,
178        serializer: &mut S,
179    ) -> Result<Self::Resolver, S::Error> {
180        field.as_str().to_string().serialize(serializer)
181    }
182}
183
184impl<D> DeserializeWith<Archived<String>, muniment::LogId, D> for LogIdAsString
185where
186    D: Fallible + ?Sized,
187    Archived<String>: Deserialize<String, D>,
188{
189    fn deserialize_with(
190        field: &Archived<String>,
191        deserializer: &mut D,
192    ) -> Result<muniment::LogId, D::Error> {
193        let raw: String = field.deserialize(deserializer)?;
194        Ok(muniment::LogId::new(raw))
195    }
196}