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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//! Value-only provider failure vocabulary; classification belongs to the runtime.
use serde::{Deserialize, Serialize};
/// Validated TypeDB server code (`[A-Z]{3}[0-9]+`, at most 32 bytes).
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(transparent)]
pub struct Code(String);
impl Code {
/// Validate a code without retaining invalid input.
pub fn new(value: impl Into<String>) -> Option<Self> {
let value = value.into();
let bytes = value.as_bytes();
(bytes.len() >= 4
&& bytes.len() <= 32
&& bytes[..3].iter().all(u8::is_ascii_uppercase)
&& bytes[3..].iter().all(u8::is_ascii_digit))
.then_some(Self(value))
}
/// Validated code text, without brackets.
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl<'de> Deserialize<'de> for Code {
fn deserialize<D: serde::Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
Self::new(String::deserialize(decoder)?)
.ok_or_else(|| serde::de::Error::custom("invalid provider code"))
}
}
/// Value-free transport diagnosis shared by HTTP discovery and driver adapters.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TransportKind {
/// The operation or HTTP/2 keep-alive timed out.
Timeout,
/// The endpoint refused the connection or is unavailable.
Unavailable,
/// TLS negotiation or certificate validation failed.
Tls,
/// Credentials were rejected.
Authentication,
/// The connection or transaction is closed.
Closed,
/// No more specific structural transport diagnosis is available.
Other,
}
impl TransportKind {
/// Fixed description; never includes provider or connection values.
#[must_use]
pub const fn description(self) -> &'static str {
match self {
Self::Timeout => "timeout",
Self::Unavailable => "connection refused or unavailable",
Self::Tls => "TLS/certificate failure",
Self::Authentication => "authentication failure",
Self::Closed => "closed connection",
Self::Other => "other transport",
}
}
/// Recognize only this runtime-owned fixed vocabulary on legacy strings.
#[must_use]
pub fn from_description(value: &str) -> Option<Self> {
match value {
"timeout" => Some(Self::Timeout),
"connection refused or unavailable" => Some(Self::Unavailable),
"TLS/certificate failure" => Some(Self::Tls),
"authentication failure" => Some(Self::Authentication),
"closed connection" => Some(Self::Closed),
"other transport" => Some(Self::Other),
_ => None,
}
}
}
/// Where the provider rejected an operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Phase {
/// Query execution, before commit.
Query,
/// Commit validation.
Commit,
}
/// Conflict kind reported by fixed provider wording, without winner inference.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LockKind {
/// Concurrent exclusive writes.
Exclusive,
/// A concurrent commit deletes data this transaction requires.
RequireDeletedKey,
/// This transaction deletes data a concurrent commit requires.
DeletingRequiredKey,
/// The provider wording is unrecognized.
Unknown,
}
/// Annotation identified by a pinned provider code, never by parsing values.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AnnotationKind {
/// Abstract instance constraint.
Abstract,
/// Regular-expression constraint.
Regex,
/// Range constraint.
Range,
/// Enumerated values constraint.
Values,
/// Distinctness constraint.
Distinct,
/// Other annotation constraint.
Unknown,
}
/// Value-free reason for a proven rejection.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Reason {
/// Commit-time isolation conflict.
Conflict {
/// Reported lock kind.
lock: LockKind,
},
/// Cardinality constraint.
Cardinality,
/// Unique/key constraint.
Unique,
/// Another annotation constraint.
Constraint {
/// Annotation kind.
annotation: AnnotationKind,
},
/// Other provider rejection.
Other {
/// Validated provider code.
code: Code,
},
}
/// Provider outcome without values, transaction identities, or raw prose.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "outcome", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Failure {
/// The transaction did not store any changes.
Rejected {
/// Failure phase.
phase: Phase,
/// Value-free rejection reason.
reason: Reason,
/// Staged operation index, when structurally available.
op_index: Option<u32>,
},
/// A commit may have applied; repeating it can duplicate changes.
Indeterminate {
/// Provider code, if structurally available and valid.
code: Option<Code>,
},
}
impl Failure {
/// Whether repeating the whole transaction cannot duplicate this commit.
#[must_use]
pub const fn retry_safe(&self) -> bool {
matches!(self, Self::Rejected { .. })
}
/// Provider code implied by the typed reason, if known.
#[must_use]
pub fn code(&self) -> Option<&str> {
match self {
Self::Indeterminate { code } => code.as_ref().map(Code::as_str),
Self::Rejected { reason, .. } => Some(match reason {
Reason::Conflict { .. } => "STC2",
Reason::Cardinality => "CNT5",
Reason::Unique => "CNT9",
Reason::Constraint { annotation } => match annotation {
AnnotationKind::Abstract => "CNT4",
AnnotationKind::Regex => "CNT6",
AnnotationKind::Range => "CNT7",
AnnotationKind::Values => "CNT8",
AnnotationKind::Distinct => "CNT10",
AnnotationKind::Unknown => return None,
},
Reason::Other { code } => code.as_str(),
}),
}
}
/// Attach the executing staged item without parsing provider text.
#[must_use]
pub fn with_op_index(mut self, index: u32) -> Self {
if let Self::Rejected { op_index, .. } = &mut self {
*op_index = Some(index);
}
self
}
}
impl Failure {
/// Flat value-free projection shared by HTTP and language exception attributes.
#[must_use]
pub fn host_json(&self) -> serde_json::Value {
let (phase, reason, lock, annotation, index) = match self {
Self::Rejected {
phase,
reason,
op_index,
} => {
let (name, lock, annotation) = match reason {
Reason::Conflict { lock } => (
"conflict",
Some(match lock {
LockKind::Exclusive => "exclusive",
LockKind::RequireDeletedKey => "require_deleted_key",
LockKind::DeletingRequiredKey => "deleting_required_key",
LockKind::Unknown => "unknown",
}),
None,
),
Reason::Cardinality => ("cardinality", None, None),
Reason::Unique => ("unique", None, None),
Reason::Constraint { annotation } => (
"constraint",
None,
Some(match annotation {
AnnotationKind::Abstract => "abstract",
AnnotationKind::Regex => "regex",
AnnotationKind::Range => "range",
AnnotationKind::Values => "values",
AnnotationKind::Distinct => "distinct",
AnnotationKind::Unknown => "unknown",
}),
),
Reason::Other { .. } => ("other", None, None),
};
(
match phase {
Phase::Query => "query",
Phase::Commit => "commit",
},
Some(name),
lock,
annotation,
*op_index,
)
}
Self::Indeterminate { .. } => ("commit", None, None, None, None),
};
serde_json::json!({"phase":phase,"reason":reason,"lock_kind":lock,"annotation":annotation,
"op_index":index,"retry_safe":self.retry_safe(),"code":self.code()})
}
/// The inverse of [`Self::host_json`]: the failure a host form names.
///
/// `None` unless `retry_safe` and `phase` are present and every value is
/// in the closed vocabulary and consistent with the others (a reason's
/// fixed provider code, a lock only on a conflict), so a remote reply
/// cannot name a failure this side would not classify the same way.
#[must_use]
pub fn from_host_json(value: &serde_json::Value) -> Option<Self> {
let text = |key: &str| value.get(key).and_then(serde_json::Value::as_str);
let retry_safe = value.get("retry_safe")?.as_bool()?;
let phase = match text("phase")? {
"query" => Phase::Query,
"commit" => Phase::Commit,
_ => return None,
};
let failure = if retry_safe {
let reason = match text("reason")? {
"conflict" => Reason::Conflict {
lock: match text("lock_kind")? {
"exclusive" => LockKind::Exclusive,
"require_deleted_key" => LockKind::RequireDeletedKey,
"deleting_required_key" => LockKind::DeletingRequiredKey,
"unknown" => LockKind::Unknown,
_ => return None,
},
},
"cardinality" => Reason::Cardinality,
"unique" => Reason::Unique,
"constraint" => Reason::Constraint {
annotation: match text("annotation")? {
"abstract" => AnnotationKind::Abstract,
"regex" => AnnotationKind::Regex,
"range" => AnnotationKind::Range,
"values" => AnnotationKind::Values,
"distinct" => AnnotationKind::Distinct,
"unknown" => AnnotationKind::Unknown,
_ => return None,
},
},
"other" => Reason::Other {
code: Code::new(text("code")?)?,
},
_ => return None,
};
let op_index = match value.get("op_index") {
None | Some(serde_json::Value::Null) => None,
Some(index) => Some(u32::try_from(index.as_u64()?).ok()?),
};
Self::Rejected {
phase,
reason,
op_index,
}
} else {
Self::Indeterminate {
code: match text("code") {
None => None,
Some(code) => Some(Code::new(code)?),
},
}
};
// Every field the host form names must be the one this failure renders.
let rendered = failure.host_json();
[
"phase",
"reason",
"lock_kind",
"annotation",
"op_index",
"code",
]
.iter()
.all(|key| value.get(*key).unwrap_or(&serde_json::Value::Null) == &rendered[*key])
.then_some(failure)
}
}