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
// SPDX-License-Identifier: BUSL-1.1
//! Pre-dispatch hook interception for the `dispatch_task_loop` write path:
//! BEFORE/INSTEAD OF trigger firing (with OLD-row fetch and probe-driven
//! event reclassification), truncate `restart_identity` extraction, and
//! clone CoW write-path interception. Split out of `execute.rs` to keep
//! that file under the file-size limit; behavior is unchanged — this is
//! the same code that used to run inline in the per-task dispatch loop.
use std::collections::HashMap;
use pgwire::api::results::{Response, Tag};
use pgwire::error::{ErrorInfo, PgWireError, PgWireResult};
use crate::control::security::identity::AuthenticatedIdentity;
use crate::control::trigger::dml_hook::DmlWriteInfo;
use crate::types::TenantId;
use nodedb_physical::physical_task::PhysicalTask;
use super::super::super::types::error_to_sqlstate;
use super::super::core::NodeDbPgHandler;
use super::super::plan::PlanKind;
/// Outcome of routing a single task through the in-transaction staging gate.
pub(super) enum TxnRouteOutcome {
/// Not staged/buffered: caller proceeds to normal dispatch with the
/// (possibly `txn_id`-stamped) task.
Proceed(Box<PhysicalTask>),
/// Fully handled (buffered "OK", or a staged write's real command tag).
/// Caller pushes this response and continues the loop.
Handled(Response),
}
impl NodeDbPgHandler {
/// Route a single task through the protocol-neutral in-transaction
/// staging gate (`shared::session::staging_gate`), translating its
/// outcome into this file's `PgWireResult`. A constraint violation on a
/// staged write surfaces here as the pgwire error, matching the
/// pre-refactor `stage_in_tx_point_write` behavior exactly.
pub(super) async fn route_task_in_txn(
&self,
addr: &std::net::SocketAddr,
identity: &AuthenticatedIdentity,
task: PhysicalTask,
) -> PgWireResult<TxnRouteOutcome> {
use crate::control::server::shared::session::expander_stage::{
ExpanderOutcome, route_in_tx_expander,
};
use crate::control::server::shared::session::staging_gate::{
InTxnRoute, StagingGateError, route_in_tx_write,
};
let user_id: Option<std::sync::Arc<str>> =
Some(std::sync::Arc::from(identity.username.as_str()));
// In-transaction `MERGE` and `UPDATE ... FROM` are resolved + staged at
// STATEMENT time by the expander (read-your-own-writes for later
// statements in the same txn); every other task falls through to the
// neutral staging gate. The expander dispatches each derived point op via
// the SAME closure, so it must be `Fn` — hence `user_id.clone()` per call.
let routed =
match route_in_tx_expander(&self.state, &self.sessions, addr, task, |stage_task| {
self.dispatch_task(stage_task, user_id.clone(), Some(identity))
})
.await
{
Ok(ExpanderOutcome::Handled(route)) => Ok(route),
Ok(ExpanderOutcome::Passthrough(task)) => {
route_in_tx_write(&self.state, &self.sessions, addr, *task, |stage_task| {
self.dispatch_task(stage_task, user_id.clone(), Some(identity))
})
.await
}
Err(e) => Err(e),
};
match routed {
Ok(InTxnRoute::Read(routed_task)) => Ok(TxnRouteOutcome::Proceed(routed_task)),
Ok(InTxnRoute::Buffered) => Ok(TxnRouteOutcome::Handled(Response::Execution(
Tag::new("OK"),
))),
Ok(InTxnRoute::Staged(outcome)) => {
let tag = super::super::plan::tag_from_staged(outcome.kind, outcome.affected);
Ok(TxnRouteOutcome::Handled(Response::Execution(tag)))
}
Err(StagingGateError::Dispatch(e)) => {
let (severity, code, message) = error_to_sqlstate(&e);
Err(PgWireError::UserError(Box::new(ErrorInfo::new(
severity.to_owned(),
code.to_owned(),
message,
))))
}
Err(StagingGateError::Rejected { code }) => {
let (severity, sqlstate, message) = match code {
Some(code) => {
crate::control::server::shared::ddl::sqlstate::error_code_to_sqlstate(&code)
}
None => ("ERROR", "XX000", "unknown data plane error".to_owned()),
};
Err(PgWireError::UserError(Box::new(ErrorInfo::new(
severity.to_owned(),
sqlstate.to_owned(),
message,
))))
}
}
}
}
/// Outcome of running the pre-dispatch hooks for a single task.
pub(super) enum PreDispatchOutcome {
/// The task was fully handled (trigger short-circuit, or clone write
/// interception). Caller pushes this response and continues the loop.
Handled(Response),
/// No interception occurred (or a mutation was applied in place);
/// caller proceeds to normal dispatch with the (possibly mutated) task
/// and the trigger bookkeeping needed for the AFTER-trigger phase.
/// Boxed: `PhysicalTask` makes this variant far larger than `Handled`,
/// which would otherwise bloat every `PreDispatchOutcome` on the stack.
Proceed(Box<PreDispatchProceed>),
}
/// Payload for [`PreDispatchOutcome::Proceed`], boxed to keep the enum small.
pub(super) struct PreDispatchProceed {
pub(super) task: PhysicalTask,
pub(super) dml_info: Option<DmlWriteInfo>,
pub(super) old_row: Option<HashMap<String, nodedb_types::Value>>,
pub(super) truncate_restart_collection: Option<String>,
}
impl NodeDbPgHandler {
/// Run trigger interception and clone write-path interception for a
/// single write task, before it reaches normal dispatch.
pub(super) async fn run_pre_dispatch_hooks(
&self,
identity: &AuthenticatedIdentity,
tenant_id: TenantId,
addr: &std::net::SocketAddr,
plan_kind: PlanKind,
mut task: PhysicalTask,
) -> PgWireResult<PreDispatchOutcome> {
// --- Trigger interception for DML writes ---
let mut dml_info = crate::control::trigger::dml_hook::classify_dml_write(&task.plan);
let database_id = self
.sessions
.get_current_database(addr)
.unwrap_or(crate::types::DatabaseId::DEFAULT);
// Fetch OLD row and fire BEFORE/INSTEAD OF triggers if applicable.
let old_row = if let Some(ref info) = dml_info
&& info.document_id.is_some()
&& (matches!(
info.event,
crate::control::trigger::DmlEvent::Update
| crate::control::trigger::DmlEvent::Delete
) || info.needs_existence_probe)
{
let doc_id = info.document_id.as_deref().unwrap_or("");
let row = crate::control::trigger::dml_hook::fetch_old_row(
&self.state,
database_id,
tenant_id,
&info.collection,
doc_id,
)
.await;
if !row.is_empty() { Some(row) } else { None }
} else {
None
};
// Probe-driven reclassification.
if let Some(ref mut info) = dml_info
&& info.needs_existence_probe
{
info.event = if old_row.is_some() {
crate::control::trigger::DmlEvent::Update
} else {
crate::control::trigger::DmlEvent::Insert
};
}
if let Some(ref info) = dml_info {
use crate::control::trigger::dml_hook_fire::PreDispatchResult;
match crate::control::trigger::dml_hook_fire::fire_pre_dispatch_triggers(
crate::control::trigger::dml_hook_fire::DispatchTriggerParams {
state: &self.state,
identity,
tenant_id,
info,
old_row: &old_row,
cascade_depth: 0,
},
)
.await
.map_err(|e| {
let (severity, code, message) = error_to_sqlstate(&e);
PgWireError::UserError(Box::new(ErrorInfo::new(
severity.to_owned(),
code.to_owned(),
message,
)))
})? {
PreDispatchResult::Handled => {
return Ok(PreDispatchOutcome::Handled(Response::Execution(Tag::new(
"OK",
))));
}
PreDispatchResult::Proceed {
mutated_fields: Some(fields),
} => {
crate::control::trigger::dml_hook::patch_task_with_mutated_fields(
&mut task, &fields,
);
}
PreDispatchResult::Proceed {
mutated_fields: None,
} => {}
}
}
// Extract truncate restart_identity info before task is moved.
let truncate_restart_collection =
if let nodedb_physical::physical_plan::PhysicalPlan::Document(
nodedb_physical::physical_plan::DocumentOp::Truncate {
collection,
restart_identity: true,
},
) = &task.plan
{
Some(collection.clone())
} else {
None
};
// --- Clone write-path interception ---
// For PointUpdate / PointDelete on Shadowed/Materializing clones,
// apply copy-up or tombstone before (or instead of) normal dispatch.
// Non-cloned collections and Materialized clones short-circuit here.
{
use super::clone_write_dispatch::CloneWriteOutcome;
match self
.maybe_intercept_clone_write(&task, identity, tenant_id)
.await?
{
CloneWriteOutcome::Handled(resp) => {
use crate::control::server::response_shape::compose::{
ShapeOutcome, shape_payload_no_plan,
};
match shape_payload_no_plan(resp.payload.as_ref(), plan_kind, None) {
ShapeOutcome::Rows(shaped) => {
// Clone write-path DML result (PointUpdate/PointDelete):
// no client-requested result formats, so text.
let (response, notice) =
crate::control::server::pgwire::handler::shape_encode::shaped_query_response(
shaped,
&[],
);
if let Some(n) = notice {
self.sessions.push_notice(addr, n);
}
return Ok(PreDispatchOutcome::Handled(response));
}
ShapeOutcome::Passthrough => {
let shaped =
crate::control::server::pgwire::handler::plan::payload_to_response(
resp.payload.as_ref(),
plan_kind,
)?;
if let Some(notice) = shaped.notice {
self.sessions.push_notice(addr, notice);
}
return Ok(PreDispatchOutcome::Handled(shaped.response));
}
}
}
CloneWriteOutcome::Passthrough => {}
}
}
Ok(PreDispatchOutcome::Proceed(Box::new(PreDispatchProceed {
task,
dml_info,
old_row,
truncate_restart_collection,
})))
}
}