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
// SPDX-License-Identifier: BUSL-1.1
//! Policy resolution dispatch for validation violations.
use crate::CrdtAuthContext;
use crate::constraint::{Constraint, ConstraintKind};
use crate::error::Result;
use crate::policy::{ConflictPolicy, PolicyResolution, ResolvedAction};
use crate::state::CrdtState;
use super::core::Validator;
use super::types::{ProposedChange, ValidationOutcome};
impl Validator {
/// Validate with declarative policy resolution.
///
/// This is the new core validation method. It attempts to resolve violations
/// via policy before falling back to the DLQ.
///
/// # Arguments
///
/// * `state` — current CRDT state
/// * `peer_id` — source peer ID
/// * `change` — proposed change
/// * `delta_bytes` — raw delta bytes
/// * `hlc_timestamp` — Hybrid Logical Clock timestamp of the incoming write
///
/// Returns:
/// - `Ok(PolicyResolution::AutoResolved(_))` if the policy auto-fixed the violation
/// - `Ok(PolicyResolution::Deferred { .. })` if deferred for retry (entry already enqueued)
/// - `Ok(PolicyResolution::WebhookRequired { .. })` if webhook call needed (caller's responsibility)
/// - `Ok(PolicyResolution::Escalate)` if escalating to DLQ (entry already enqueued)
/// - `Err(_)` if an internal error occurred
pub fn validate_with_policy(
&mut self,
state: &CrdtState,
peer_id: u64,
auth: CrdtAuthContext,
change: &ProposedChange,
delta_bytes: Vec<u8>,
hlc_timestamp: u64,
) -> Result<PolicyResolution> {
match self.validate(state, change) {
ValidationOutcome::Accepted => {
// No violation; return synthetic "auto-resolved" to maintain API consistency
Ok(PolicyResolution::AutoResolved(
ResolvedAction::OverwriteExisting,
))
}
ValidationOutcome::Rejected(violations) => {
// Exactly one violation per constraint (current design)
let v = &violations[0];
let constraint = self
.constraints
.all()
.iter()
.find(|c| c.name == v.constraint_name)
.cloned()
.unwrap_or_else(|| Constraint {
name: v.constraint_name.clone(),
collection: change.collection.clone(),
field: String::new(),
kind: ConstraintKind::NotNull,
});
let policy = self.policies.get_owned(&change.collection);
let policy_for_kind = policy.for_kind(&constraint.kind);
// Attempt policy resolution
match policy_for_kind {
ConflictPolicy::LastWriterWins => {
tracing::info!(
constraint = %v.constraint_name,
collection = %change.collection,
timestamp = hlc_timestamp,
reason = %v.reason,
"resolved via LAST_WRITER_WINS"
);
Ok(PolicyResolution::AutoResolved(
ResolvedAction::OverwriteExisting,
))
}
ConflictPolicy::RenameSuffix => {
let counter_key = (change.collection.clone(), constraint.field.clone());
let suffix = self.suffix_counter.entry(counter_key).or_insert(0);
*suffix += 1;
let new_value = format!(
"{}_{}",
change
.fields
.iter()
.find(|(f, _)| f == &constraint.field)
.map(|(_, v)| format!("{:?}", v))
.unwrap_or_else(|| "unknown".to_string()),
suffix
);
tracing::info!(
constraint = %v.constraint_name,
field = %constraint.field,
new_value = %new_value,
"resolved via RENAME_APPEND_SUFFIX"
);
Ok(PolicyResolution::AutoResolved(
ResolvedAction::RenamedField {
field: constraint.field.clone(),
new_value,
},
))
}
ConflictPolicy::CascadeDefer {
max_retries,
ttl_secs,
} => {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64;
let base_ms = 500u64;
let first_retry_after_ms = base_ms;
let id = self.deferred.enqueue(
peer_id,
auth.user_id,
auth.tenant_id,
delta_bytes,
change.collection.clone(),
constraint.name.clone(),
0,
*max_retries,
now_ms,
first_retry_after_ms,
*ttl_secs,
);
tracing::info!(
constraint = %v.constraint_name,
deferred_id = id,
reason = %v.reason,
"resolved via CASCADE_DEFER (queued for retry)"
);
Ok(PolicyResolution::Deferred {
retry_after_ms: first_retry_after_ms,
attempt: 0,
})
}
ConflictPolicy::Custom {
webhook_url,
timeout_secs,
} => {
tracing::info!(
constraint = %v.constraint_name,
webhook_url = %webhook_url,
"escalated to webhook"
);
Ok(PolicyResolution::WebhookRequired {
webhook_url: webhook_url.clone(),
timeout_secs: *timeout_secs,
})
}
ConflictPolicy::EscalateToDlq => {
self.dlq.enqueue(
peer_id,
auth.user_id,
auth.tenant_id,
delta_bytes,
&constraint,
v.reason.clone(),
v.hint.clone(),
)?;
tracing::info!(
constraint = %v.constraint_name,
collection = %change.collection,
"escalated to DLQ"
);
Ok(PolicyResolution::Escalate)
}
}
}
}
}
}