1use crate::db::{get_connection, validate_and_get_user};
23use crate::models::node::NodeType;
24#[allow(
25 unused_imports,
26 clippy::wildcard_imports,
27 reason = "Standard workspace module prelude"
28)]
29use crate::utilities::*;
30use anyhow::{Result, anyhow};
31use sea_query::{
32 ConditionalStatement, Expr, ExprTrait, Iden, OrderedStatement, Query,
33 QueryStatementWriter, SchemaStatementBuilder, SqliteQueryBuilder,
34 ValueType,
35};
36use turso::Value;
37
38#[derive(sea_query::Iden)]
39#[iden(rename = "nodes")]
40enum Nodes {
41 Table,
42 #[iden(rename = "id")]
43 Id,
44 #[iden(rename = "graph_id")]
45 GraphId,
46 #[iden(rename = "type")]
47 Type,
48 #[iden(rename = "data")]
49 Data,
50 #[iden(rename = "checksum")]
51 Checksum,
52 #[iden(rename = "timestamp")]
53 Timestamp,
54}
55
56pub(crate) async fn ensure_statement_does_not_revise_data_nodes(
60 conn: &turso::Connection,
61 graph_id: u128,
62 node_type: NodeType,
63 data: &[u8],
64) -> Result<()> {
65 if !matches!(node_type, NodeType::Statements | NodeType::System) {
66 return Ok(());
67 }
68 let Ok(dc_str) = ctb_formats_dcstring::DcStr::from_bytes(data) else {
69 return Ok(());
70 };
71 let resolver = ctb_formats_dcstring::syntax::default_syntax_resolver();
72 use ctb_formats_dcstring::{DcCharExt, DcRole};
73
74 let mut chars = dc_str.chars().peekable();
75 let mut target_ids: Vec<(u128, &'static str)> = Vec::new();
76
77 let next_atom = |it: &mut std::iter::Peekable<ctb_formats_dcstring::DcChars<'_>>|
78 -> Option<ctb_formats_dcstring::DcChar> {
79 let ch = it.next()?;
80 if ch.fills_role_with(DcRole::Escape, resolver.as_ref())
81 || ch.fills_role_with(
82 DcRole::QuoteFollowingDcAsAtom,
83 resolver.as_ref(),
84 )
85 {
86 it.next()
87 } else {
88 Some(ch)
89 }
90 };
91
92 while let Some(verb) = chars.next() {
93 let is_sup =
94 verb.fills_role_with(DcRole::Supersedes, resolver.as_ref());
95 let is_ret = verb.fills_role_with(DcRole::Retracts, resolver.as_ref());
96 if is_sup {
97 if let (Some(subj), Some(obj)) =
98 (next_atom(&mut chars), next_atom(&mut chars))
99 {
100 if !subj.fills_role_with(
101 DcRole::EnclosingDocument,
102 resolver.as_ref(),
103 ) {
104 target_ids.push((subj.to_u128(), "supersede with"));
105 }
106 if !obj.fills_role_with(
107 DcRole::EnclosingDocument,
108 resolver.as_ref(),
109 ) {
110 target_ids.push((obj.to_u128(), "supersede"));
111 }
112 }
113 } else if is_ret
114 && let (Some(_subj), Some(obj)) =
115 (next_atom(&mut chars), next_atom(&mut chars))
116 && !obj
117 .fills_role_with(DcRole::EnclosingDocument, resolver.as_ref())
118 {
119 target_ids.push((obj.to_u128(), "retract"));
120 }
121 }
122
123 if target_ids.is_empty() {
124 return Ok(());
125 }
126
127 let graph_id_blob = graph_id.to_be_bytes().to_vec();
128 for (target_id, action) in target_ids {
129 let (sql, values) = Query::select()
130 .column(Nodes::Type)
131 .from(Nodes::Table)
132 .and_where(Expr::col(Nodes::GraphId).eq(graph_id_blob.clone()))
133 .and_where(Expr::col(Nodes::Id).eq(target_id.to_be_bytes().to_vec()))
134 .limit(1)
135 .build(SqliteQueryBuilder);
136 let params = crate::db::sea_values_to_turso(values)?;
137 let mut stmt = conn.prepare(&sql).await?;
138 let mut rows = stmt.query(params).await?;
139 if let Some(row) = rows.next().await? {
140 let existing_type = match row.get_value(0) {
141 Ok(Value::Integer(i)) => NodeType::try_from(i).ok(),
142 Ok(Value::Text(s)) => s.parse::<NodeType>().ok(),
143 _ => None,
144 };
145 ensure!(
146 existing_type != Some(NodeType::Data),
147 "Cannot {action} pure value node (NodeType::Data) l{target_id}; pure value nodes are immutable"
148 );
149 }
150 }
151 Ok(())
152}
153
154#[ipc_method]
156pub async fn insert_node(
157 session_token: String,
158 graph_id: u128,
159 node_type: NodeType,
160 data: &[u8],
161) -> Result<u128> {
162 let user = validate_and_get_user(&session_token).await?;
163 let user_id = user.local_id();
164 let db_name = format!("graphs/{user_id}/user_data");
165 let conn = get_connection(&db_name).await?;
166 ensure_statement_does_not_revise_data_nodes(
167 &conn, graph_id, node_type, data,
168 )
169 .await?;
170
171 let checksum = {
172 use sha2::{Digest, Sha256};
173 Sha256::digest(data).to_vec()
174 };
175
176 let use_explicit_id =
177 crate::models::sync_impl::get_local_id_range(user_id, graph_id)
178 .await
179 .unwrap_or(None)
181 .is_some();
182 let node_id = if use_explicit_id {
183 let server_url = crate::pc_settings::get_str_setting(
184 crate::pc_settings::PcSettingStrKey::ServerUrl,
185 )
186 .unwrap_or_else(|| crate::pc_settings::DEFAULT_SERVER_URL.to_string());
188 let session_id = crate::sync::start_sync_session(&server_url, user_id)
189 .await
190 .ok();
191 let id = crate::sync::allocate_local_id(
192 user_id,
193 graph_id,
194 &server_url,
195 session_id.as_deref(),
196 )
197 .await?;
198 Some(id)
199 } else {
200 let (sql, values) = Query::select()
202 .column(Nodes::Id)
203 .from(Nodes::Table)
204 .order_by(Nodes::Id, sea_query::Order::Desc)
205 .limit(1)
206 .build(SqliteQueryBuilder);
207
208 let params = crate::db::sea_values_to_turso(values)?;
209 let mut stmt = conn.prepare(&sql).await?;
210 let mut rows = stmt.query(params).await?;
211 let max_id = if let Some(row) = rows.next().await? {
212 if let Ok(Value::Blob(b)) = row.get_value(0) {
213 u128::from_be_bytes(
214 b.as_slice()
215 .try_into()
216 .context("max_id blob did not fit into 16 bytes")?,
217 )
218 } else {
219 0
220 }
221 } else {
222 0
223 };
224 Some(max_id.saturating_add(1))
225 };
226
227 let id = node_id.ok_or_else(|| anyhow!("Failed to generate node ID"))?;
228 let id_blob = id.to_be_bytes().to_vec();
229 let graph_id_blob = graph_id.to_be_bytes().to_vec();
230
231 let timestamp = std::time::SystemTime::now()
232 .duration_since(std::time::UNIX_EPOCH)
233 .unwrap_or_default()
235 .as_micros();
236 let timestamp_blob = timestamp.to_be_bytes().to_vec();
237
238 let (sql, values) = Query::insert()
239 .into_table(Nodes::Table)
240 .columns([
241 Nodes::Id,
242 Nodes::GraphId,
243 Nodes::Type,
244 Nodes::Data,
245 Nodes::Checksum,
246 Nodes::Timestamp,
247 ])
248 .values_panic([
249 id_blob.into(),
250 graph_id_blob.into(),
251 u32::from(node_type).into(),
252 data.into(),
253 checksum.into(),
254 timestamp_blob.into(),
255 ])
256 .build(SqliteQueryBuilder);
257
258 let params = crate::db::sea_values_to_turso(values)?;
259 conn.execute(&sql, params).await?;
260 Ok(id)
261}
262
263#[ipc_method]
265pub async fn update_node_type(
266 session_token: String,
267 graph_id: u128,
268 node_id: u128,
269 node_type: NodeType,
270) -> Result<()> {
271 let user = validate_and_get_user(&session_token).await?;
272 if graph_id == 0 {
273 anyhow::bail!("Global graph is read-only.");
274 }
275 let db_name = format!("graphs/{}/user_data", user.local_id());
276 let conn = get_connection(&db_name).await?;
277
278 let id_blob = node_id.to_be_bytes().to_vec();
279 let graph_id_blob = graph_id.to_be_bytes().to_vec();
280
281 let (sql, values) = Query::update()
282 .table(Nodes::Table)
283 .values([(Nodes::Type, u32::from(node_type).into())])
284 .and_where(Expr::col(Nodes::Id).eq(id_blob))
285 .and_where(Expr::col(Nodes::GraphId).eq(graph_id_blob))
286 .build(SqliteQueryBuilder);
287
288 let params = crate::db::sea_values_to_turso(values)?;
289 conn.execute(&sql, params).await?;
290 Ok(())
291}
292
293#[ipc_method]
295pub async fn update_node_data(
296 session_token: String,
297 graph_id: u128,
298 node_id: u128,
299 data: Vec<u8>,
300) -> Result<()> {
301 let user = validate_and_get_user(&session_token).await?;
302 if graph_id == 0 {
303 anyhow::bail!("Global graph is read-only.");
304 }
305 let db_name = format!("graphs/{}/user_data", user.local_id());
306 let conn = get_connection(&db_name).await?;
307
308 let id_blob = node_id.to_be_bytes().to_vec();
309 let graph_id_blob = graph_id.to_be_bytes().to_vec();
310
311 let (sql, values) = Query::update()
312 .table(Nodes::Table)
313 .values([(Nodes::Data, data.into())])
314 .and_where(Expr::col(Nodes::Id).eq(id_blob))
315 .and_where(Expr::col(Nodes::GraphId).eq(graph_id_blob))
316 .build(SqliteQueryBuilder);
317
318 let params = crate::db::sea_values_to_turso(values)?;
319 conn.execute(&sql, params).await?;
320 Ok(())
321}
322
323#[ipc_method]
325pub async fn get_node(
326 session_token: String,
327 graph_id: u128,
328 id: u128,
329) -> Result<Option<Vec<u8>>> {
330 let user = validate_and_get_user(&session_token).await?;
331 let db_name = if graph_id == 0 {
332 let global_user_id =
333 crate::models::user_impl::get_user_by_name("global".to_string())
334 .await?
335 .ok_or_else(|| anyhow!("Global user not found"))?
336 .id;
337 format!("graphs/{global_user_id}/user_data")
338 } else {
339 format!("graphs/{}/user_data", user.local_id())
340 };
341 let conn = get_connection(&db_name).await?;
342
343 let id_blob = id.to_be_bytes().to_vec();
344 let graph_id_blob = graph_id.to_be_bytes().to_vec();
345
346 let (sql, values) = Query::select()
347 .column(Nodes::Data)
348 .from(Nodes::Table)
349 .and_where(Expr::col(Nodes::Id).eq(id_blob))
350 .and_where(Expr::col(Nodes::GraphId).eq(graph_id_blob))
351 .build(SqliteQueryBuilder);
352
353 let params = crate::db::sea_values_to_turso(values)?;
354 let mut stmt = conn.prepare(&sql).await?;
355 let mut rows = stmt.query(params).await?;
356 if let Some(row) = rows.next().await? {
357 if let Ok(Value::Blob(b)) = row.get_value(0) {
358 return Ok(Some(b));
359 }
360 }
361 Ok(None)
362}
363
364#[ipc_method]
366pub async fn get_node_dto(
367 session_token: String,
368 graph_id: u128,
369 id: u128,
370) -> Result<Option<::ctb_utilities::ipc::service_traits::storage::Node>> {
371 let user = validate_and_get_user(&session_token).await?;
372 let db_name = if graph_id == 0 {
373 let global_user_id =
374 crate::models::user_impl::get_user_by_name("global".to_string())
375 .await?
376 .ok_or_else(|| anyhow!("Global user not found"))?
377 .id;
378 format!("graphs/{global_user_id}/user_data")
379 } else {
380 format!("graphs/{}/user_data", user.local_id())
381 };
382 let conn = get_connection(&db_name).await?;
383
384 let id_blob = id.to_be_bytes().to_vec();
385 let graph_id_blob = graph_id.to_be_bytes().to_vec();
386
387 let (sql, values) = Query::select()
388 .columns([
389 Nodes::Id,
390 Nodes::GraphId,
391 Nodes::Type,
392 Nodes::Data,
393 Nodes::Checksum,
394 Nodes::Timestamp,
395 ])
396 .from(Nodes::Table)
397 .and_where(Expr::col(Nodes::Id).eq(id_blob))
398 .and_where(Expr::col(Nodes::GraphId).eq(graph_id_blob))
399 .build(SqliteQueryBuilder);
400
401 let params = crate::db::sea_values_to_turso(values)?;
402 let mut stmt = conn.prepare(&sql).await?;
403 let mut rows = stmt.query(params).await?;
404 if let Some(row) = rows.next().await? {
405 let mut id_val = 0;
406 let mut graph_id_val = 0;
407 let mut type_val = NodeType::Data;
408 let mut data_val = Vec::new();
409 let mut checksum_val = None;
410 let mut timestamp_val = 0u128;
411
412 if let Ok(Value::Blob(b)) = row.get_value(0) {
413 id_val = u128::from_be_bytes(
414 b.as_slice()
415 .try_into()
416 .context("Node ID blob did not fit into 16 bytes")?,
417 );
418 }
419 if let Ok(Value::Blob(b)) = row.get_value(1) {
420 graph_id_val = u128::from_be_bytes(
421 b.as_slice()
422 .try_into()
423 .context("Graph ID blob did not fit into 16 bytes")?,
424 );
425 }
426 match row.get_value(2) {
427 Ok(Value::Integer(i)) => {
428 if let Ok(t) = NodeType::try_from(i) {
429 type_val = t;
430 }
431 }
432 Ok(Value::Text(s)) => {
433 if let Ok(t) = s.parse::<NodeType>() {
434 type_val = t;
435 }
436 }
437 _ => {}
438 }
439 if let Ok(Value::Blob(b)) = row.get_value(3) {
440 data_val = b;
441 }
442 if let Ok(Value::Blob(b)) = row.get_value(4) {
443 checksum_val = Some(b);
444 }
445 match row.get_value(5) {
446 Ok(Value::Blob(b)) => {
447 if b.len() == 16 {
448 timestamp_val =
449 u128::from_be_bytes(b.as_slice().try_into().context(
450 "Timestamp 16-byte blob conversion failed",
451 )?);
452 } else if b.len() == 8 {
453 timestamp_val = u128::from(u64::from_be_bytes(
454 b.as_slice().try_into().context(
455 "Timestamp 8-byte blob conversion failed",
456 )?,
457 ));
458 }
459 }
460 Ok(Value::Integer(i)) => {
461 timestamp_val = u128::try_from(i)
462 .context("integer timestamp did not fit into u128")?;
463 }
464 _ => {}
465 }
466
467 return Ok(Some(::ctb_utilities::ipc::service_traits::storage::Node {
468 id: id_val,
469 graph_id: graph_id_val,
470 node_type: type_val.to_dto(),
471 data: data_val,
472 checksum: checksum_val,
473 timestamp: timestamp_val,
474 }));
475 }
476 Ok(None)
477}
478
479#[ipc_method]
481pub async fn list_nodes(
482 session_token: String,
483) -> Result<Vec<::ctb_utilities::ipc::service_traits::storage::Node>> {
484 let user = validate_and_get_user(&session_token).await?;
485 let db_name = format!("graphs/{}/user_data", user.local_id());
486 let conn = get_connection(&db_name).await?;
487
488 let (sql, values) = Query::select()
489 .columns([
490 Nodes::Id,
491 Nodes::GraphId,
492 Nodes::Type,
493 Nodes::Data,
494 Nodes::Checksum,
495 Nodes::Timestamp,
496 ])
497 .from(Nodes::Table)
498 .order_by(Nodes::Id, sea_query::Order::Desc)
499 .build(SqliteQueryBuilder);
500
501 let params = crate::db::sea_values_to_turso(values)?;
502 let mut stmt = conn.prepare(&sql).await?;
503 let mut rows = stmt.query(params).await?;
504 let mut list = Vec::new();
505 while let Some(row) = rows.next().await? {
506 let mut id_val = 0;
507 let mut graph_id_val = 0;
508 let mut type_val = NodeType::Data;
509 let mut data_val = Vec::new();
510 let mut checksum_val = None;
511 let mut timestamp_val = 0u128;
512
513 if let Ok(Value::Blob(b)) = row.get_value(0) {
514 id_val = u128::from_be_bytes(
515 b.as_slice()
516 .try_into()
517 .context("Node ID blob did not fit into 16 bytes")?,
518 );
519 }
520 if let Ok(Value::Blob(b)) = row.get_value(1) {
521 graph_id_val = u128::from_be_bytes(
522 b.as_slice()
523 .try_into()
524 .context("Graph ID blob did not fit into 16 bytes")?,
525 );
526 }
527 match row.get_value(2) {
528 Ok(Value::Integer(i)) => {
529 if let Ok(t) = NodeType::try_from(i) {
530 type_val = t;
531 }
532 }
533 Ok(Value::Text(s)) => {
534 if let Ok(t) = s.parse::<NodeType>() {
535 type_val = t;
536 }
537 }
538 _ => {}
539 }
540 if let Ok(Value::Blob(b)) = row.get_value(3) {
541 data_val = b;
542 }
543 if let Ok(Value::Blob(b)) = row.get_value(4) {
544 checksum_val = Some(b);
545 }
546 match row.get_value(5) {
547 Ok(Value::Blob(b)) => {
548 if b.len() == 16 {
549 timestamp_val =
550 u128::from_be_bytes(b.as_slice().try_into().context(
551 "Timestamp 16-byte blob conversion failed",
552 )?);
553 } else if b.len() == 8 {
554 timestamp_val = u128::from(u64::from_be_bytes(
555 b.as_slice().try_into().context(
556 "Timestamp 8-byte blob conversion failed",
557 )?,
558 ));
559 }
560 }
561 Ok(Value::Integer(i)) => {
562 timestamp_val = u128::try_from(i)
563 .context("integer timestamp did not fit into u128")?;
564 }
565 _ => {}
566 }
567
568 list.push(::ctb_utilities::ipc::service_traits::storage::Node {
569 id: id_val,
570 graph_id: graph_id_val,
571 node_type: type_val.to_dto(),
572 data: data_val,
573 checksum: checksum_val,
574 timestamp: timestamp_val,
575 });
576 }
577 Ok(list)
578}