ctb_storage/models/
node.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Data transfer objects and types representing graph nodes and metadata.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::Result;
30
31#[ipc_dto]
32#[derive(
33    serde::Serialize,
34    serde::Deserialize,
35    Debug,
36    Clone,
37    Copy,
38    PartialEq,
39    Eq,
40    Hash,
41)]
42#[serde(rename_all = "lowercase")]
43#[repr(u32)]
44pub enum NodeType {
45    Data = 1,
46    Statements = 2,
47    System = 3,
48}
49
50impl TryFrom<u32> for NodeType {
51    type Error = anyhow::Error;
52    fn try_from(v: u32) -> Result<Self, Self::Error> {
53        match v {
54            1 => Ok(NodeType::Data),
55            2 => Ok(NodeType::Statements),
56            3 => Ok(NodeType::System),
57            other => anyhow::bail!("Invalid NodeType value: {other}"),
58        }
59    }
60}
61
62impl From<NodeType> for u32 {
63    fn from(v: NodeType) -> Self {
64        match v {
65            NodeType::Data => 1,
66            NodeType::Statements => 2,
67            NodeType::System => 3,
68        }
69    }
70}
71
72impl TryFrom<i64> for NodeType {
73    type Error = anyhow::Error;
74    fn try_from(v: i64) -> Result<Self, Self::Error> {
75        match v {
76            1 => Ok(NodeType::Data),
77            2 => Ok(NodeType::Statements),
78            3 => Ok(NodeType::System),
79            other => anyhow::bail!("Invalid NodeType value: {other}"),
80        }
81    }
82}
83
84impl std::str::FromStr for NodeType {
85    type Err = anyhow::Error;
86    fn from_str(s: &str) -> Result<Self, Self::Err> {
87        match s {
88            "data" => Ok(NodeType::Data),
89            "statements" => Ok(NodeType::Statements),
90            "system" => Ok(NodeType::System),
91            other => anyhow::bail!("Invalid NodeType name: {other}"),
92        }
93    }
94}
95
96impl NodeType {
97    pub fn as_str(&self) -> &'static str {
98        match self {
99            NodeType::Data => "data",
100            NodeType::Statements => "statements",
101            NodeType::System => "system",
102        }
103    }
104
105    pub fn from_dto(
106        dto: ctb_utilities::ipc::service_traits::storage::NodeType,
107    ) -> Self {
108        match dto {
109            ctb_utilities::ipc::service_traits::storage::NodeType::Data => NodeType::Data,
110            ctb_utilities::ipc::service_traits::storage::NodeType::Statements => NodeType::Statements,
111            ctb_utilities::ipc::service_traits::storage::NodeType::System => NodeType::System,
112        }
113    }
114
115    pub fn to_dto(
116        &self,
117    ) -> ctb_utilities::ipc::service_traits::storage::NodeType {
118        match self {
119            NodeType::Data => ctb_utilities::ipc::service_traits::storage::NodeType::Data,
120            NodeType::Statements => ctb_utilities::ipc::service_traits::storage::NodeType::Statements,
121            NodeType::System => ctb_utilities::ipc::service_traits::storage::NodeType::System,
122        }
123    }
124}
125
126#[ipc_dto]
127#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
128pub struct Node {
129    pub id: u128,
130    pub graph_id: u128,
131    pub node_type: NodeType,
132    pub data: Vec<u8>,
133    pub checksum: Option<Vec<u8>>,
134    pub timestamp: u128,
135}
136
137impl Node {
138    pub fn new(
139        session_token: &str,
140        graph_id: u128,
141        node_type: NodeType,
142        data: &[u8],
143    ) -> Result<u128> {
144        ipcb!(storage).insert_node_b(
145            session_token,
146            graph_id,
147            node_type.to_dto(),
148            data,
149        )
150    }
151
152    pub fn list_nodes(session_token: &str) -> Result<Vec<Node>> {
153        let dtos = ipcb!(storage).list_nodes_b(session_token)?;
154        Ok(dtos.into_iter().map(Node::from).collect())
155    }
156
157    pub fn get(
158        session_token: &str,
159        graph_id: u128,
160        id: u128,
161    ) -> Result<Option<Self>> {
162        let dto = ipcb!(storage).get_node_dto_b(session_token, graph_id, id)?;
163        Ok(dto.map(Node::from))
164    }
165
166    pub fn to_dto(&self) -> ctb_utilities::ipc::service_traits::storage::Node {
167        ctb_utilities::ipc::service_traits::storage::Node {
168            id: self.id,
169            graph_id: self.graph_id,
170            node_type: self.node_type.to_dto(),
171            data: self.data.clone(),
172            checksum: self.checksum.clone(),
173            timestamp: self.timestamp,
174        }
175    }
176
177    pub fn set_node_type(
178        &mut self,
179        session_token: &str,
180        node_type: NodeType,
181    ) -> Result<()> {
182        ipcb!(storage).update_node_type_b(
183            session_token,
184            self.graph_id,
185            self.id,
186            node_type.to_dto(),
187        )?;
188        self.node_type = node_type;
189        Ok(())
190    }
191
192    pub fn set_data(&mut self, session_token: &str, data: &[u8]) -> Result<()> {
193        ipcb!(storage).update_node_data_b(
194            session_token,
195            self.graph_id,
196            self.id,
197            data.to_vec(),
198        )?;
199        self.data = data.to_vec();
200        Ok(())
201    }
202
203    /// Publish this local node to the global graph repository.
204    ///
205    /// Validates the target ID against restricted graph ranges, serializes the node
206    /// into binary package format, transmits the package to the remote global graph
207    /// server (or direct in-process global graph import during tests), asserts that
208    /// local and global checksums match, and mutates the local node to a system
209    /// redirect node.
210    pub fn to_packaged_node(&self) -> Result<Vec<u8>> {
211        let timestamp = if self.timestamp > 0 {
212            self.timestamp
213        } else {
214            std::time::SystemTime::now()
215                .duration_since(std::time::UNIX_EPOCH)
216                // Reason for fallback: system clock time prior to UNIX epoch defaults duration to 0 duration
217                .unwrap_or_default()
218                .as_micros()
219        };
220
221        crate::packaged_node::serialize_packaged_node(
222            self.node_type,
223            timestamp,
224            // Reason for fallback: unchecksummed node missing checksum field defaults to empty byte slice
225            self.checksum.as_deref().unwrap_or(&[]),
226            self.id,
227            self.graph_id,
228            &self.data,
229        )
230    }
231
232    pub async fn publish(
233        &mut self,
234        session_token: &str,
235        global_session_token: Option<&str>,
236        target_id: Option<u128>,
237    ) -> Result<u128> {
238        if let Some(tid) = target_id {
239            crate::global_graph_layout::validate_publish_target(tid)?;
240        }
241
242        // Reason for fallback: unchecksummed node missing checksum field defaults to empty byte slice
243        let local_checksum = bin2hex(self.checksum.as_deref().unwrap_or(&[]));
244        let package_bytes = self.to_packaged_node()?;
245
246        let (allocated_id, global_checksum) = if cfg!(test) || is_in_test() {
247            let allocated_id = crate::models::graph::get_global_graph()
248                .import_node(session_token, &package_bytes, target_id)?;
249            let global_node = Node::get(session_token, 0, allocated_id)?
250                .ok_or_else(|| {
251                    anyhow::anyhow!("Global node not found after publish")
252                })?;
253            // Reason for fallback: unchecksummed node missing checksum field defaults to empty byte slice
254            let checksum =
255                bin2hex(global_node.checksum.as_deref().unwrap_or(&[]));
256            (allocated_id, checksum)
257        } else {
258            let global_token = global_session_token
259                .ok_or_else(|| anyhow::anyhow!("Global graph user session is not initialized. Please ensure the deploy setup ran."))?;
260            let allocated_id =
261                ctb_api_client::ApiClient::publish_packaged_node(
262                    global_token,
263                    &package_bytes,
264                    target_id,
265                )
266                .await?;
267            let checksum =
268                ctb_api_client::ApiClient::fetch_node_checksum(allocated_id)
269                    .await?;
270            (allocated_id, checksum)
271        };
272
273        if global_checksum != local_checksum {
274            anyhow::bail!(
275                "Checksum mismatch! Local checksum is {local_checksum}, but global checksum is {global_checksum}."
276            );
277        }
278
279        let redirect_text = format!("@1114409@@{allocated_id}@");
280        let converted_data = ctb_formats_dcstring::dctext::dctext_to_dctf(
281            redirect_text.into_bytes(),
282        )?;
283
284        self.set_node_type(session_token, NodeType::System)?;
285        self.set_data(session_token, &converted_data)?;
286
287        Ok(allocated_id)
288    }
289}
290
291impl From<ctb_utilities::ipc::service_traits::storage::Node> for Node {
292    fn from(dto: ctb_utilities::ipc::service_traits::storage::Node) -> Self {
293        Node {
294            id: dto.id,
295            graph_id: dto.graph_id,
296            node_type: NodeType::from_dto(dto.node_type),
297            data: dto.data,
298            checksum: dto.checksum,
299            timestamp: dto.timestamp,
300        }
301    }
302}
303
304#[cfg(test)]
305#[allow(
306    clippy::panic,
307    clippy::expect_used,
308    clippy::unwrap_used,
309    clippy::unwrap_in_result,
310    clippy::panic_in_result_fn,
311    clippy::indexing_slicing,
312    clippy::arithmetic_side_effects,
313    reason = "Standard repository test boilerplate"
314)]
315mod tests {}