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
// SPDX-License-Identifier: BUSL-1.1
//! CRDT document-row handlers: field-carrying upsert / delete for SQL DML on
//! `crdt='true'` document collections. The Data Plane builds the Loro mutation
//! server-side, then materializes the merged row into the sparse store with
//! `EventSource::User` + text indexing so scans, secondary/spatial/vector
//! indexes, AFTER triggers, and CDC all observe it.
use loro::LoroValue;
use tracing::debug;
use nodedb_types::Surrogate;
use crate::bridge::envelope::{ErrorCode, Response};
use crate::data::executor::core_loop::CoreLoop;
use crate::data::executor::doc_format;
use crate::data::executor::handlers::point::apply_delete::PointDeleteParams;
use crate::data::executor::handlers::returning_rows;
use crate::data::executor::task::ExecutionTask;
use crate::engine::document::store::surrogate_to_doc_id;
use nodedb_physical::physical_plan::ReturningSpec;
/// Borrowed arguments for [`CoreLoop::execute_crdt_doc_upsert`], grouped so the
/// handler stays within the argument-count limit.
pub(in crate::data::executor) struct CrdtDocUpsert<'a> {
pub collection: &'a str,
pub document_id: &'a str,
pub fields_json: &'a str,
pub surrogate: Surrogate,
pub partial: bool,
pub returning: Option<&'a ReturningSpec>,
}
impl CoreLoop {
/// Insert-or-replace (`partial = false`) or partial-merge (`partial = true`)
/// a document row's scalar fields, server-built from `fields_json`.
pub(in crate::data::executor) fn execute_crdt_doc_upsert(
&mut self,
task: &ExecutionTask,
args: CrdtDocUpsert<'_>,
) -> Response {
let CrdtDocUpsert {
collection,
document_id,
fields_json,
surrogate,
partial,
returning,
} = args;
debug!(core = self.core_id, %collection, %document_id, partial, "crdt doc upsert");
let tenant_id = task.request.tenant_id;
let Ok(json_map) =
sonic_rs::from_str::<serde_json::Map<String, serde_json::Value>>(fields_json)
else {
return self.response_error(
task,
ErrorCode::Internal {
detail: format!("crdt doc upsert: invalid fields_json for {document_id}"),
},
);
};
let fields: Vec<(&str, LoroValue)> = json_map
.iter()
.map(|(k, v)| (k.as_str(), super::convert::json_to_loro_value(v)))
.collect();
let materialized = {
let engine = match self.get_crdt_engine(task.request.database_id, tenant_id) {
Ok(e) => e,
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: e.to_string(),
},
);
}
};
let res = if partial {
engine.doc_set_fields(collection, document_id, &fields)
} else {
engine.doc_upsert(collection, document_id, &fields)
};
if let Err(e) = res {
return self.response_error(
task,
ErrorCode::Internal {
detail: e.to_string(),
},
);
}
if surrogate != Surrogate::ZERO {
Self::encode_crdt_row(engine, collection, document_id)
} else {
None
}
};
let response = if let Some(bytes) = materialized {
self.materialize_document_write(
task,
tenant_id.as_u64(),
collection,
surrogate,
&bytes,
true,
);
if let Some(spec) = returning {
let with_id =
nodedb_query::msgpack_scan::inject_str_field(&bytes, "id", document_id);
let doc = doc_format::decode_document(&with_id)
.unwrap_or_else(|| serde_json::json!({ "id": document_id }));
match returning_rows::build_rows_payload(spec, &[doc]) {
Ok(payload) => self.response_with_payload(task, payload),
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: format!("RETURNING encode: {e}"),
},
);
}
}
} else {
self.response_ok(task)
}
} else if let Some(spec) = returning {
match returning_rows::build_rows_payload(spec, &[]) {
Ok(payload) => self.response_with_payload(task, payload),
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: format!("RETURNING encode: {e}"),
},
);
}
}
} else {
self.response_ok(task)
};
self.checkpoint_coordinator.mark_dirty("crdt", 1);
response
}
/// Delete a document row: tombstone in the collection's Loro doc, then
/// remove it from the sparse store with the full index cascade + CDC delete
/// event (mirrors the point-delete apply path with `enforce = false`, since
/// the write was already admitted on its origin).
pub(in crate::data::executor) fn execute_crdt_doc_delete(
&mut self,
task: &ExecutionTask,
collection: &str,
document_id: &str,
surrogate: Surrogate,
returning: Option<&ReturningSpec>,
) -> Response {
debug!(core = self.core_id, %collection, %document_id, "crdt doc delete");
let tenant_id = task.request.tenant_id;
{
let engine = match self.get_crdt_engine(task.request.database_id, tenant_id) {
Ok(e) => e,
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: e.to_string(),
},
);
}
};
if let Err(e) = engine.doc_delete(collection, document_id) {
return self.response_error(
task,
ErrorCode::Internal {
detail: e.to_string(),
},
);
}
}
let tid = tenant_id.as_u64();
let storage_key = surrogate_to_doc_id(surrogate);
let outcome = match self.apply_point_delete(PointDeleteParams {
database_id: task.request.database_id.as_u64(),
tid,
collection,
document_id: storage_key.as_str(),
surrogate,
user_roles: &task.request.user_roles,
enforce: false,
}) {
Ok(outcome) => outcome,
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: e.to_string(),
},
);
}
};
self.checkpoint_coordinator.mark_dirty("sparse", 1);
// Emit the delete to the Event Plane only when a row was actually
// removed, threading the pre-delete bytes through as `old_value` so
// CDC/change-stream consumers observe the prior state.
if let Some(prior_bytes) = outcome.prior_value.as_deref() {
let old_converted = self.resolve_event_payload(
task.request.database_id.as_u64(),
tid,
collection,
prior_bytes,
);
self.emit_write_event(
task,
collection,
crate::event::WriteOp::Delete,
storage_key.as_str(),
None,
Some(old_converted.as_deref().unwrap_or(prior_bytes)),
);
}
// Project the pre-deletion row for RETURNING. `outcome.prior_value` is
// only borrowed by the CDC emit above (via `.as_deref()`), so it is
// still available here; the user-visible `document_id` is injected as
// `id` exactly like PointDelete.
let response = if let Some(spec) = returning {
if let Some(prior_bytes) = outcome.prior_value.as_deref() {
let with_id =
nodedb_query::msgpack_scan::inject_str_field(prior_bytes, "id", document_id);
let doc = doc_format::decode_document(&with_id)
.unwrap_or_else(|| serde_json::json!({ "id": document_id }));
match returning_rows::build_rows_payload(spec, &[doc]) {
Ok(payload) => self.response_with_payload(task, payload),
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: format!("RETURNING encode: {e}"),
},
);
}
}
} else {
match returning_rows::build_rows_payload(spec, &[]) {
Ok(payload) => self.response_with_payload(task, payload),
Err(e) => {
return self.response_error(
task,
ErrorCode::Internal {
detail: format!("RETURNING encode: {e}"),
},
);
}
}
}
} else {
self.response_ok(task)
};
self.checkpoint_coordinator.mark_dirty("crdt", 1);
response
}
}