ctb_storage/models/
graph.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//! Represents a graph: user's main local knowledge graph, other graphs of the
21//! user, graphs shared with the user, or general resource library graph.
22//!
23//! Most of the graph data is not part of this struct, instead kept on disk and
24//! read as needed.
25
26#[expect(unused_imports, reason = "imported module dependencies")]
27use crate::utilities::*;
28
29use std::io::Read;
30
31use anyhow::Result;
32
33use crate::node::{Node, NodeType};
34use crate::user::User;
35
36#[derive(Debug, Default)]
37pub struct Graph {
38    /// Graph ID, from which can be derived the path to the graph's data in
39    /// storage. Indexed from 1 for local user graphs and referenced team
40    /// graphs. 0 is the library graph.
41    pub graph_id: u128,
42    /// ID of the most recently inserted node
43    pub last_id: u128,
44    /// Human-readable label for the graph
45    pub label: String,
46    /// ID of the user who owns the graph, or None for local user and graph
47    pub owner: Option<u64>,
48}
49
50pub fn get_global_graph() -> Graph {
51    Graph {
52        graph_id: 0,
53        last_id: 0,
54        label: "Global".to_string(),
55        owner: None,
56    }
57}
58
59impl Graph {
60    pub fn new(id: u128, label: &str, creator: &User) -> Graph {
61        Graph {
62            graph_id: id,
63            last_id: 0,
64            label: label.to_string(),
65            owner: creator.remote_id(),
66        }
67    }
68
69    pub fn get_next_id(&self) -> u128 {
70        self.last_id.saturating_add(1)
71    }
72
73    pub fn create_node<R: Read>(
74        &self,
75        creator: &User,
76        node_type: NodeType,
77        mut data: R,
78    ) -> Result<Node> {
79        // Read entire reader into a Vec<u8>
80        let mut buf = Vec::new();
81        data.read_to_end(&mut buf)?; // returns io::Result<usize>
82
83        let converted_data = if node_type == NodeType::Statements {
84            ctb_formats_dcstring::dctext::dctext_to_dctf(buf)?
85        } else {
86            buf
87        };
88
89        let token = creator
90            .session_token()
91            .ok_or_else(|| anyhow::anyhow!("No active session token for user"))?
92            .to_string();
93        let node_id = ipcb!(storage).insert_node_b(
94            &token,
95            self.graph_id,
96            node_type.to_dto(),
97            &converted_data,
98        )?;
99
100        let checksum = {
101            use sha2::{Digest, Sha256};
102            Some(Sha256::digest(&converted_data).to_vec())
103        };
104
105        let timestamp = std::time::SystemTime::now()
106            .duration_since(std::time::UNIX_EPOCH)
107            // Reason for fallback: system clock time prior to UNIX epoch defaults duration to 0 duration
108            .unwrap_or_default()
109            .as_micros();
110
111        Ok(Node {
112            id: node_id,
113            graph_id: self.graph_id,
114            node_type,
115            data: converted_data,
116            checksum,
117            timestamp,
118        })
119    }
120
121    pub fn read_node(
122        &self,
123        owner: &User,
124        id: u128,
125        _remote: bool,
126    ) -> Result<Node> {
127        let token = owner
128            .session_token()
129            .ok_or_else(|| anyhow::anyhow!("No active session token for user"))?
130            .to_string();
131        let node = Node::get(&token, self.graph_id, id)?
132            .ok_or_else(|| anyhow::anyhow!("Node not found"))?;
133        Ok(node)
134    }
135
136    pub fn is_writable_by(&self, user: &User) -> bool {
137        // TODO
138        // Local user graphs are writable by the user
139        if self.graph_id > 0 {
140            if let Ok(graph_idx) = usize::try_from(self.graph_id) {
141                if graph_idx <= user.get_graph_count() {
142                    return true;
143                }
144            }
145        }
146        false
147    }
148
149    pub fn allocate_next_system_id(&self, session_token: &str) -> Result<u128> {
150        ipcb!(storage).allocate_next_system_id_b(session_token)
151    }
152
153    pub fn import_node(
154        &self,
155        session_token: &str,
156        package: &[u8],
157        target_id: Option<u128>,
158    ) -> Result<u128> {
159        ipcb!(storage).publish_packaged_node_to_global_b(
160            session_token,
161            package.to_vec(),
162            target_id,
163        )
164    }
165
166    pub fn import_node_for_global_graph(
167        &self,
168        session_token: &str,
169        package: &[u8],
170    ) -> Result<u128> {
171        self.import_node(session_token, package, None)
172    }
173}
174
175#[cfg(test)]
176pub fn get_test_graph(username: &str) -> Graph {
177    use crate::user::get_test_user;
178
179    Graph::new(12345, "test", &get_test_user(username))
180}
181
182#[cfg(test)]
183#[allow(
184    clippy::panic,
185    clippy::expect_used,
186    clippy::unwrap_used,
187    clippy::unwrap_in_result,
188    clippy::panic_in_result_fn,
189    clippy::indexing_slicing,
190    clippy::arithmetic_side_effects,
191    reason = "Standard repository test boilerplate"
192)]
193mod tests {
194    use anyhow::Context;
195
196    use super::*;
197
198    use crate::user::get_test_user;
199
200    #[crate::ctb_test]
201    fn can_create_node() -> Result<()> {
202        let name = function_name!();
203        let user = get_test_user(name);
204        let data = b"test data";
205        let graph = Graph::new(1, "test", &user);
206
207        let node = graph
208            .create_node(&user, NodeType::Data, &data[..])
209            .context("Failed to create node")?;
210
211        assert_eq!(node.id, 1);
212        assert_eq!(node.data, b"test data");
213
214        let node = graph
215            .create_node(&user, NodeType::Data, &b"test data 2"[..])
216            .context("Failed to create node")?;
217
218        assert_eq!(node.id, 2);
219        assert_eq!(node.data, b"test data 2");
220
221        Ok(())
222    }
223
224    #[crate::ctb_test]
225    fn rejects_supersede_or_retract_of_data_node() -> Result<()> {
226        let name = function_name!();
227        let user = get_test_user(name);
228        let graph = Graph::new(1, "test_immutability", &user);
229        let token = user
230            .session_token()
231            .context("Missing session token")?
232            .to_string();
233
234        let data_node =
235            graph.create_node(&user, NodeType::Data, &b"immutable payload"[..])?;
236
237        // Build DcTF statement `592 615 <data_node.id>`: must be rejected at writer layer.
238        let mut ret_dc = ctb_formats_dcstring::DcString::new();
239        ret_dc.push(ctb_formats_dcstring::dc::DC_RETRACTS);
240        ret_dc.push(ctb_formats_dcstring::dc::DC_ENCLOSING_DOCUMENT);
241        ret_dc.push(ctb_formats_dcstring::DcChar::from_u128(data_node.id));
242        let ret_err = ipcb!(storage)
243            .insert_node_b(
244                &token,
245                graph.graph_id,
246                NodeType::Statements.to_dto(),
247                ret_dc.as_bytes(),
248            )
249            .unwrap_err();
250        assert!(
251            ret_err.to_string().contains("pure value node"),
252            "Unexpected error: {ret_err}"
253        );
254
255        // Create a legitimate statement node and verify retracting IT succeeds.
256        let mut stmt_dc = ctb_formats_dcstring::DcString::new();
257        stmt_dc.push(ctb_formats_dcstring::dc::DC_HAS_A);
258        stmt_dc.push(ctb_formats_dcstring::DcChar::from_u128(data_node.id));
259        stmt_dc.push(ctb_formats_dcstring::dc::DC_CANONICAL_NAME);
260        let stmt_id = ipcb!(storage).insert_node_b(
261            &token,
262            graph.graph_id,
263            NodeType::Statements.to_dto(),
264            stmt_dc.as_bytes(),
265        )?;
266
267        let mut ret_stmt_dc = ctb_formats_dcstring::DcString::new();
268        ret_stmt_dc.push(ctb_formats_dcstring::dc::DC_RETRACTS);
269        ret_stmt_dc.push(ctb_formats_dcstring::dc::DC_ENCLOSING_DOCUMENT);
270        ret_stmt_dc.push(ctb_formats_dcstring::DcChar::from_u128(stmt_id));
271        let ret_stmt_id = ipcb!(storage).insert_node_b(
272            &token,
273            graph.graph_id,
274            NodeType::Statements.to_dto(),
275            ret_stmt_dc.as_bytes(),
276        )?;
277        assert!(ret_stmt_id > stmt_id);
278
279        Ok(())
280    }
281}