1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// SPDX-License-Identifier: Apache-2.0
//! CRDT sync gate, pending-delta bookkeeping, remote-delta import/apply, and
//! background sync startup.
use std::sync::Arc;
use nodedb_types::error::{NodeDbError, NodeDbResult};
use crate::nodedb::core::types::{NodeDbLite, SyncGate};
use crate::nodedb::lock_ext::LockExt;
use crate::storage::engine::StorageEngine;
impl<S: StorageEngine> NodeDbLite<S> {
/// Install a per-document [`SyncGate`]. Documents the gate rejects are kept
/// local-only (excluded from CRDT delta, FTS, and vector sync channels).
pub fn set_sync_gate(&self, gate: Arc<dyn SyncGate>) {
let mut slot = self
.sync_gate
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
*slot = Some(gate);
}
/// Whether a document write may be synced. Defaults to `true` when no gate is
/// installed (sync-everything, the prior behavior).
pub(crate) fn should_sync_doc(
&self,
collection: &str,
fields: &std::collections::HashMap<String, nodedb_types::Value>,
) -> bool {
match self.sync_gate.read() {
Ok(slot) => slot
.as_ref()
.map(|g| g.should_sync(collection, fields))
.unwrap_or(true),
Err(_) => true,
}
}
/// Access pending CRDT deltas (for sync client).
pub fn pending_crdt_deltas(
&self,
) -> NodeDbResult<Vec<crate::engine::crdt::engine::PendingDelta>> {
let crdt = self.crdt.lock_or_recover();
Ok(crdt.pending_deltas().to_vec())
}
/// Acknowledge synced deltas (called after Origin ACK).
pub fn acknowledge_deltas(&self, acked_id: u64) -> NodeDbResult<()> {
let mut crdt = self.crdt.lock_or_recover();
crdt.acknowledge(acked_id);
Ok(())
}
/// Assign a stable stream seq to a pending CRDT delta (first-send only).
///
/// No-op if the delta already has a non-zero seq. Called by the sync
/// transport to ensure the same seq is reused on reconnect re-sends.
pub fn set_crdt_pending_delta_seq(&self, mutation_id: u64, seq: u64) -> NodeDbResult<()> {
let mut crdt = self.crdt.lock_or_recover();
crdt.set_pending_delta_seq(mutation_id, seq);
Ok(())
}
/// Import remote deltas from Origin into `collection`'s Loro document.
///
/// The collection must be supplied by the caller: each collection has its
/// own document, and the update bytes alone do not identify which one.
pub fn import_remote_deltas(&self, collection: &str, data: &[u8]) -> NodeDbResult<()> {
let guard = self
.fts_state
.try_admit_mutation("import_remote_deltas")
.map_err(NodeDbError::from)?;
let result = (|| {
let imported = self
.crdt
.lock_or_recover()
.import_remote(collection, data)
.map_err(NodeDbError::storage)?;
// Re-index the rows the delta changed. They came from a peer, so
// nothing is staged back.
self.reindex_documents_local(
collection,
imported.changed_rows.iter().map(String::as_str),
)?;
Ok(())
})();
guard.finish(result)
}
/// Apply a server-originated row post-image from Origin.
///
/// Unlike [`Self::import_remote_deltas`], the payload here is a
/// MessagePack row image rather than Loro update bytes. Origin sends it
/// for writes that have no client-authored CRDT operation to replicate
/// (SQL DML, DDL-managed system rows). An empty payload with `delete` set
/// removes the row.
///
/// A KV collection's row is the `{key, value…}` row every KV read
/// returns. It lands in the KV store as the body a local write of the
/// same row stores. Any other collection's row lands in its Loro
/// document.
///
/// Neither write reaches the outbound queue: the write came FROM Origin,
/// so pushing it back would echo it into a loop.
pub async fn apply_remote_row(
&self,
collection: &str,
document_id: &str,
payload: &[u8],
delete: bool,
) -> NodeDbResult<()> {
let guard = self.fts_state.admit_mutation().await;
let result = async {
if self.is_kv_collection(collection).await? {
return self
.kv_apply_remote_row(collection, document_id, payload, delete)
.await;
}
self.apply_remote_document_row(collection, document_id, payload, delete)
}
.await;
guard.finish(result)
}
/// Apply a remote row post-image to `collection`'s Loro document.
fn apply_remote_document_row(
&self,
collection: &str,
document_id: &str,
payload: &[u8],
delete: bool,
) -> NodeDbResult<()> {
use crate::nodedb::convert::value_to_loro;
use nodedb_types::value::Value;
let mut crdt = self.crdt.lock_or_recover();
let mutation_id = if delete {
crdt.delete(collection, document_id)
.map_err(NodeDbError::storage)?
} else {
// Origin writes a row post-image as standard msgpack, not the
// tagged zerompk `Value` encoding.
let value = nodedb_types::value_from_msgpack(payload).map_err(|e| {
NodeDbError::serialization(
"msgpack",
format!("row push for '{collection}'/'{document_id}' does not decode: {e}"),
)
})?;
let Value::Object(fields) = value else {
return Err(NodeDbError::serialization(
"msgpack",
format!(
"row push for '{collection}'/'{document_id}' is a {}, not a row map",
value.type_name()
),
));
};
let loro_fields: Vec<(&str, loro::LoroValue)> = fields
.iter()
.map(|(k, v)| (k.as_str(), value_to_loro(v)))
.collect();
crdt.upsert(collection, document_id, &loro_fields)
.map_err(NodeDbError::from)?
};
crdt.drop_pending(mutation_id);
drop(crdt);
// Keep the text index on the row as it now stands. The row came from
// Origin, so nothing is staged back to it.
self.reindex_documents_local(collection, [document_id])?;
Ok(())
}
/// Reject a specific delta (rollback optimistic local state).
pub fn reject_delta(&self, mutation_id: u64) -> NodeDbResult<()> {
let guard = self
.fts_state
.try_admit_mutation("reject_delta")
.map_err(NodeDbError::from)?;
let result = (|| {
let mut crdt = self.crdt.lock_or_recover();
let rejected = crdt.reject_delta(mutation_id);
drop(crdt);
if let Some(delta) = rejected {
self.reindex_documents_local(&delta.collection, [delta.document_id.as_str()])?;
}
Ok(())
})();
guard.finish(result)
}
/// Start background sync to Origin.
///
/// Spawns a task that connects to the Origin WebSocket endpoint, pushes
/// pending deltas, and receives shape updates, reconnecting on its own.
///
/// Returns immediately — the sync runs in the background. Returns `None`
/// when sync is already running on this database: a second loop would
/// push the same deltas twice, and the first would no longer be the one
/// [`stop_sync`](Self::stop_sync) stops.
///
/// The task is registered with the database, so `stop_sync` and
/// [`shutdown`](Self::shutdown) both stop it.
///
/// Requires the `sync` feature.
#[cfg(all(not(target_arch = "wasm32"), feature = "sync"))]
pub fn start_sync(
self: &Arc<Self>,
config: crate::sync::SyncConfig,
) -> Option<Arc<crate::sync::SyncClient>> {
if self.tasks.has(crate::tasks::TaskKind::Sync) {
return None;
}
let client = Arc::new(crate::sync::SyncClient::new(config));
let delegate: Arc<dyn crate::sync::SyncDelegate> = Arc::clone(self) as _;
let client_clone = Arc::clone(&client);
let (stop_tx, mut stop) = crate::tasks::TaskRegistry::signal();
let handle = crate::runtime::spawn(async move {
// `run_sync_loop` reconnects forever and has no exit of its own,
// so the stop signal is what ends it. Racing the two cancels the
// loop at its current await point, which is why the transport
// aborts its own children on drop rather than relying on the
// normal return path.
tokio::select! {
_ = crate::sync::run_sync_loop(client_clone, delegate) => {}
_ = stop.stopped() => {}
}
});
self.tasks
.track(crate::tasks::TaskKind::Sync, stop_tx, handle);
Some(client)
}
/// Stop background sync, leaving the database open and usable.
///
/// Returns `true` when sync was running. Sync can be restarted afterwards
/// with a fresh [`start_sync`](Self::start_sync) — the reconnect-with-a-
/// new-token path.
///
/// Requires the `sync` feature.
#[cfg(all(not(target_arch = "wasm32"), feature = "sync"))]
pub async fn stop_sync(&self) -> bool {
self.tasks.stop(crate::tasks::TaskKind::Sync).await
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use nodedb_types::value::Value;
use crate::storage::pagedb_storage::PagedbStorageMem;
use super::*;
async fn open_db() -> Arc<NodeDbLite<PagedbStorageMem>> {
let storage = PagedbStorageMem::open_in_memory()
.await
.expect("open in-memory storage");
NodeDbLite::open(storage).await.expect("open NodeDbLite")
}
#[tokio::test]
async fn a_pushed_document_row_lands_in_its_loro_document() {
let db = open_db().await;
let mut fields = HashMap::new();
fields.insert("name".to_string(), Value::String("ada".into()));
let row = nodedb_types::value_to_msgpack(&Value::Object(fields)).expect("encode");
db.apply_remote_row("people", "p1", &row, false)
.await
.expect("apply row");
let stored = db.crdt.lock_or_recover().read("people", "p1");
let Some(loro::LoroValue::Map(map)) = stored else {
panic!("row p1 is not a map: {stored:?}");
};
assert_eq!(
map.get("name"),
Some(&loro::LoroValue::String("ada".to_string().into()))
);
assert!(db.pending_crdt_deltas().expect("pending").is_empty());
}
#[tokio::test]
async fn a_pushed_document_payload_that_is_not_a_row_map_is_refused() {
let db = open_db().await;
let scalar = nodedb_types::value_to_msgpack(&Value::Integer(1)).expect("encode");
let err = db
.apply_remote_row("people", "p1", &scalar, false)
.await
.expect_err("a scalar is not a row");
assert!(err.message().contains("not a row map"), "{err}");
}
}