ctb_storage/models/
sync_impl.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//! Database query implementation for sync logs and remote replication state.
21
22use crate::db::get_connection;
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29use anyhow::Result;
30use sea_query::{
31    Alias, ConditionalStatement, Expr, ExprTrait, Iden, Query,
32    QueryStatementWriter, SchemaStatementBuilder, SqliteQueryBuilder,
33};
34use turso::Value;
35
36#[derive(sea_query::Iden)]
37#[iden(rename = "sync_tokens")]
38enum SyncTokens {
39    Table,
40    #[iden(rename = "key")]
41    Key,
42    #[iden(rename = "token")]
43    Token,
44}
45
46#[derive(sea_query::Iden)]
47#[iden(rename = "sync_id_ranges")]
48enum SyncIdRanges {
49    Table,
50    #[iden(rename = "graph_id")]
51    GraphId,
52    #[iden(rename = "range_data")]
53    RangeData,
54}
55
56/// [CLIENT-SIDE] Stores a newly finalized blind token locally in the user's database.
57#[ipc_method]
58pub async fn save_local_token(
59    user_id: u64,
60    key: u64,
61    token: String,
62) -> Result<()> {
63    let db_name = format!("graphs/{user_id}/user_data");
64    let conn = get_connection(&db_name).await?;
65
66    let (sql, values) = Query::insert()
67        .into_table(SyncTokens::Table)
68        .columns([SyncTokens::Key, SyncTokens::Token])
69        .values_panic([
70            <i64 as TryFrom<_>>::try_from(key)?.into(),
71            token.into(),
72        ])
73        .on_conflict(
74            sea_query::OnConflict::column(SyncTokens::Key)
75                .update_column(SyncTokens::Token)
76                .to_owned(),
77        )
78        .build(SqliteQueryBuilder);
79    let params = crate::db::sea_values_to_turso(values)?;
80    conn.execute(&sql, params).await?;
81    Ok(())
82}
83
84/// [CLIENT-SIDE] Fetches all unspent local blind tokens from the user's database.
85#[ipc_method]
86pub async fn get_local_tokens(user_id: u64) -> Result<Vec<(u64, String)>> {
87    let db_name = format!("graphs/{user_id}/user_data");
88    let conn = get_connection(&db_name).await?;
89
90    let (sql, values) = Query::select()
91        .columns([SyncTokens::Key, SyncTokens::Token])
92        .from(SyncTokens::Table)
93        .build(SqliteQueryBuilder);
94    let params = crate::db::sea_values_to_turso(values)?;
95    let mut stmt = conn.prepare(&sql).await?;
96    let mut rows = stmt.query(params).await?;
97    let mut tokens = Vec::new();
98    while let Some(row) = rows.next().await? {
99        let key = match row.get_value(0)? {
100            Value::Integer(v) => <u64 as TryFrom<_>>::try_from(v)?,
101            _ => continue,
102        };
103        let token = match row.get_value(1)? {
104            Value::Text(s) => s,
105            _ => continue,
106        };
107        tokens.push((key, token));
108    }
109    Ok(tokens)
110}
111
112/// [CLIENT-SIDE] Deletes a spent local token from the user's database.
113#[ipc_method]
114pub async fn delete_local_token(user_id: u64, key: u64) -> Result<()> {
115    let db_name = format!("graphs/{user_id}/user_data");
116    let conn = get_connection(&db_name).await?;
117
118    let (sql, values) = Query::delete()
119        .from_table(SyncTokens::Table)
120        .and_where(
121            Expr::col(SyncTokens::Key).eq(<i64 as TryFrom<_>>::try_from(key)?),
122        )
123        .build(SqliteQueryBuilder);
124    let params = crate::db::sea_values_to_turso(values)?;
125    conn.execute(&sql, params).await?;
126    Ok(())
127}
128
129/// [CLIENT-SIDE] Saves the reserved local ID range for a graph in the user's database.
130#[ipc_method]
131pub async fn save_local_id_range(
132    user_id: u64,
133    graph_id: u128,
134    range_bytes: Vec<u8>,
135) -> Result<()> {
136    let db_name = format!("graphs/{user_id}/user_data");
137    let conn = get_connection(&db_name).await?;
138
139    let (sql, values) = Query::insert()
140        .into_table(SyncIdRanges::Table)
141        .columns([SyncIdRanges::GraphId, SyncIdRanges::RangeData])
142        .values_panic([graph_id.to_string().into(), range_bytes.into()])
143        .on_conflict(
144            sea_query::OnConflict::column(SyncIdRanges::GraphId)
145                .update_column(SyncIdRanges::RangeData)
146                .to_owned(),
147        )
148        .build(SqliteQueryBuilder);
149    let params = crate::db::sea_values_to_turso(values)?;
150    conn.execute(&sql, params).await?;
151    Ok(())
152}
153
154/// [CLIENT-SIDE] Retrieves the reserved local ID range for a graph from the user's database.
155#[ipc_method]
156pub async fn get_local_id_range(
157    user_id: u64,
158    graph_id: u128,
159) -> Result<Option<Vec<u8>>> {
160    let db_name = format!("graphs/{user_id}/user_data");
161    let conn = get_connection(&db_name).await?;
162
163    let (sql, values) = Query::select()
164        .column(SyncIdRanges::RangeData)
165        .from(SyncIdRanges::Table)
166        .and_where(Expr::col(SyncIdRanges::GraphId).eq(graph_id.to_string()))
167        .build(SqliteQueryBuilder);
168    let params = crate::db::sea_values_to_turso(values)?;
169    let mut stmt = conn.prepare(&sql).await?;
170    let mut rows = stmt.query(params).await?;
171    if let Some(row) = rows.next().await? {
172        if let Ok(Value::Blob(b)) = row.get_value(0) {
173            return Ok(Some(b));
174        }
175    }
176    Ok(None)
177}
178
179/// [SERVER-SIDE] Checks if a blind token's serial hex is marked as spent.
180#[ipc_method]
181pub async fn is_token_spent(serial_hex: String) -> Result<bool> {
182    let conn = get_connection("sync").await?;
183
184    let (sql, values) = Query::select()
185        .column(Alias::new("key"))
186        .from(Alias::new("spent_tokens"))
187        .and_where(Expr::col(Alias::new("key")).eq(serial_hex))
188        .build(SqliteQueryBuilder);
189    let params = crate::db::sea_values_to_turso(values)?;
190    let mut stmt = conn.prepare(&sql).await?;
191    let mut rows = stmt.query(params).await?;
192    Ok(rows.next().await?.is_some())
193}
194
195/// [SERVER-SIDE] Marks a blind token as spent to prevent double-spending.
196#[ipc_method]
197pub async fn spend_token(serial_hex: String) -> Result<()> {
198    let conn = get_connection("sync").await?;
199
200    let now = std::time::SystemTime::now()
201        .duration_since(std::time::UNIX_EPOCH)
202        .context("System time is before UNIX epoch")?
203        .as_secs();
204
205    let (sql, values) = Query::insert()
206        .into_table(Alias::new("spent_tokens"))
207        .columns([Alias::new("key"), Alias::new("spent_at")])
208        .values_panic([
209            serial_hex.into(),
210            <i64 as TryFrom<_>>::try_from(now)?.into(),
211        ])
212        .on_conflict(
213            sea_query::OnConflict::column(Alias::new("key"))
214                .do_nothing()
215                .to_owned(),
216        )
217        .build(SqliteQueryBuilder);
218    let params = crate::db::sea_values_to_turso(values)?;
219    conn.execute(&sql, params).await?;
220    Ok(())
221}
222
223/// [SERVER-SIDE] Allocates a block of 10,000 unique IDs for the given graph.
224#[ipc_method]
225pub async fn allocate_next_remote_range(graph_id: u128) -> Result<u64> {
226    let conn = get_connection("sync").await?;
227
228    let key = graph_id.to_string();
229    conn.execute("BEGIN IMMEDIATE TRANSACTION", ()).await?;
230
231    let res = async {
232        let (sql_query, values) = Query::select()
233            .column(Alias::new("start_id"))
234            .from(Alias::new("graph_id_allocators"))
235            .and_where(Expr::col(Alias::new("graph_id")).eq(&key))
236            .build(SqliteQueryBuilder);
237        let params = crate::db::sea_values_to_turso(values)?;
238        let mut stmt = conn.prepare(&sql_query).await?;
239        let mut rows = stmt.query(params).await?;
240        let next_start = if let Some(row) = rows.next().await? {
241            if let Ok(Value::Integer(v)) = row.get_value(0) {
242                <u64 as TryFrom<_>>::try_from(v)?
243            } else {
244                1
245            }
246        } else {
247            1
248        };
249
250        let next_range_start = next_start.saturating_add(10000);
251
252        let (sql_insert, insert_values) = Query::insert()
253            .into_table(Alias::new("graph_id_allocators"))
254            .columns([Alias::new("graph_id"), Alias::new("start_id")])
255            .values_panic([
256                key.into(),
257                <i64 as TryFrom<_>>::try_from(next_range_start)?.into(),
258            ])
259            .on_conflict(
260                sea_query::OnConflict::column(Alias::new("graph_id"))
261                    .update_column(Alias::new("start_id"))
262                    .to_owned(),
263            )
264            .build(SqliteQueryBuilder);
265        let params_insert = crate::db::sea_values_to_turso(insert_values)?;
266        conn.execute(&sql_insert, params_insert).await?;
267
268        Ok(next_start)
269    }
270    .await;
271
272    match res {
273        Ok(start) => {
274            conn.execute("COMMIT", ()).await?;
275            Ok(start)
276        }
277        Err(e) => {
278            conn.execute("ROLLBACK", ()).await?;
279            Err(e)
280        }
281    }
282}
283
284/// [SERVER-SIDE] Stores an encrypted graph/node chunk payload on the server.
285#[ipc_method]
286pub async fn save_sync_chunk(
287    hash: String,
288    data: Vec<u8>,
289    expiry: u64,
290) -> Result<()> {
291    let conn = get_connection("sync").await?;
292
293    let (sql, values) = Query::insert()
294        .into_table(Alias::new("sync_chunks"))
295        .columns([
296            Alias::new("chunk_hash"),
297            Alias::new("chunk_data"),
298            Alias::new("expiry"),
299        ])
300        .values_panic([
301            hash.into(),
302            data.into(),
303            <i64 as TryFrom<_>>::try_from(expiry)?.into(),
304        ])
305        .on_conflict(
306            sea_query::OnConflict::column(Alias::new("chunk_hash"))
307                .update_columns([
308                    Alias::new("chunk_data"),
309                    Alias::new("expiry"),
310                ])
311                .to_owned(),
312        )
313        .build(SqliteQueryBuilder);
314    let params = crate::db::sea_values_to_turso(values)?;
315    conn.execute(&sql, params).await?;
316    Ok(())
317}
318
319/// [SERVER-SIDE] Retrieves an encrypted graph/node chunk payload from the server.
320#[ipc_method]
321pub async fn get_sync_chunk(hash: String) -> Result<Option<Vec<u8>>> {
322    let conn = get_connection("sync").await?;
323
324    let (sql, values) = Query::select()
325        .column(Alias::new("chunk_data"))
326        .from(Alias::new("sync_chunks"))
327        .and_where(Expr::col(Alias::new("chunk_hash")).eq(hash))
328        .build(SqliteQueryBuilder);
329    let params = crate::db::sea_values_to_turso(values)?;
330    let mut stmt = conn.prepare(&sql).await?;
331    let mut rows = stmt.query(params).await?;
332    if let Some(row) = rows.next().await? {
333        if let Ok(Value::Blob(b)) = row.get_value(0) {
334            return Ok(Some(b));
335        }
336    }
337    Ok(None)
338}