saddle-core 0.3.29

Shared contracts for Saddle components
Documentation
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Allocation-free source facts for admitted execution. Not execution authority.
use crate::{CaptureSite, DiagnosticCategory, DiagnosticCode, DiagnosticStage};
use serde::{Serialize, Serializer};

/// Audited metadata only, never arbitrary error messages or business values.
#[derive(Clone, Copy)]
pub struct InlineDiagnosticText {
    bytes: [u8; 192],
    len: u8,
    truncated: bool,
    redacted: bool,
}
impl InlineDiagnosticText {
    pub fn metadata(value: &str) -> Self {
        let mut out = Self {
            bytes: [0; 192],
            len: 0,
            truncated: false,
            redacted: false,
        };
        let mut len = value.len().min(192);
        while !value.is_char_boundary(len) {
            len -= 1;
        }
        out.truncated = len < value.len();
        if !value[..len]
            .chars()
            .all(|c| c.is_alphanumeric() || "_:<>[],(); &*.-".contains(c))
        {
            out.redacted = true;
            return out;
        }
        out.bytes[..len].copy_from_slice(&value.as_bytes()[..len]);
        out.len = len as u8;
        out.truncated = len < value.len();
        out
    }
}
impl Serialize for InlineDiagnosticText {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut value = serializer.serialize_struct("InlineDiagnosticText", 3)?;
        value.serialize_field(
            "value",
            std::str::from_utf8(&self.bytes[..self.len as usize]).unwrap_or(""),
        )?;
        value.serialize_field("truncated", &self.truncated)?;
        value.serialize_field("redacted", &self.redacted)?;
        value.end()
    }
}

#[derive(Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DiagnosticFactUnavailable {
    OpaqueSource,
    MetadataUnavailable,
    NotApplicable,
}

/// Membership must come from the generated response registry, not an error text.
#[derive(Clone, Copy, Serialize)]
pub struct RegisteredDiagnosticCode(&'static str);
impl RegisteredDiagnosticCode {
    pub fn from_registered(code: &'static str, registry: &[&'static str]) -> Option<Self> {
        (!code.is_empty()
            && code.len() <= 128
            && code
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
            && registry.len() <= 256
            && registry.contains(&code))
        .then_some(Self(code))
    }
}

/// Fixed source facts. Static codes must come from the component's closed mapping.
#[derive(Clone, Copy, Serialize)]
pub struct BoundedDiagnosticCause {
    stage: DiagnosticStage,
    code: DiagnosticCode,
    io_kind: Option<DiagnosticCode>,
    os_code: Option<i32>,
    database_code: Option<u32>,
    sqlstate: Option<InlineDiagnosticText>,
    column_index: Option<u64>,
    column_count: Option<u64>,
    target_rust_type: Option<InlineDiagnosticText>,
    actual_db_type: Option<InlineDiagnosticText>,
    object: Option<InlineDiagnosticText>,
    unavailable: Option<DiagnosticFactUnavailable>,
    target_type_unavailable: Option<DiagnosticFactUnavailable>,
    actual_type_unavailable: Option<DiagnosticFactUnavailable>,
}
impl BoundedDiagnosticCause {
    pub fn new(stage: DiagnosticStage, code: DiagnosticCode) -> Self {
        Self {
            stage,
            code,
            io_kind: None,
            os_code: None,
            database_code: None,
            sqlstate: None,
            column_index: None,
            column_count: None,
            target_rust_type: None,
            actual_db_type: None,
            object: None,
            unavailable: None,
            target_type_unavailable: Some(DiagnosticFactUnavailable::MetadataUnavailable),
            actual_type_unavailable: Some(DiagnosticFactUnavailable::MetadataUnavailable),
        }
    }
    pub fn with_system(mut self, kind: DiagnosticCode, os: Option<i32>) -> Self {
        self.io_kind = Some(kind);
        self.os_code = os;
        self
    }
    pub fn with_database_code(mut self, code: u32) -> Self {
        self.database_code = Some(code);
        self
    }
    pub fn with_sqlstate(mut self, state: &str) -> Self {
        self.sqlstate = (state.len() == 5
            && state
                .bytes()
                .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()))
        .then(|| InlineDiagnosticText::metadata(state));
        self
    }
    pub fn with_column(mut self, index: Option<u64>, count: Option<u64>) -> Self {
        self.column_index = index;
        self.column_count = count;
        self
    }
    pub fn with_types(
        mut self,
        target: Option<InlineDiagnosticText>,
        actual: Option<InlineDiagnosticText>,
        unavailable: Option<DiagnosticFactUnavailable>,
    ) -> Self {
        self.target_rust_type = target;
        self.actual_db_type = actual;
        self.unavailable = unavailable;
        self.target_type_unavailable = if target.is_some() {
            None
        } else {
            Some(unavailable.unwrap_or(DiagnosticFactUnavailable::MetadataUnavailable))
        };
        self.actual_type_unavailable = if actual.is_some() {
            None
        } else {
            Some(unavailable.unwrap_or(DiagnosticFactUnavailable::MetadataUnavailable))
        };
        self
    }
    pub fn with_object(mut self, object: InlineDiagnosticText) -> Self {
        self.object = Some(object);
        self
    }
}

/// Four fixed causes plus explicit overflow. Capture never invokes Backtrace or
/// an arbitrary source formatter. Retain alongside the original Result, not in it.
#[derive(Serialize)]
pub struct BoundedDiagnostic {
    diagnostic_id: u64,
    primary_diagnostic_id: Option<u64>,
    category: DiagnosticCategory,
    capture_site: CaptureSite,
    origin_file: &'static str,
    origin_line: u32,
    origin_column: u32,
    causes: [Option<BoundedDiagnosticCause>; 4],
    cause_count: usize,
    omitted_causes: u64,
    stack_status: &'static str,
}
impl BoundedDiagnostic {
    #[track_caller]
    pub fn capture(
        category: DiagnosticCategory,
        site: CaptureSite,
        cause: BoundedDiagnosticCause,
    ) -> Self {
        let origin = std::panic::Location::caller();
        let file = origin
            .file()
            .rsplit("/crates/")
            .next()
            .unwrap_or(origin.file());
        let file = if file.starts_with('/') || file.contains('\\') {
            file.rsplit(['/', '\\']).next().unwrap_or("unknown")
        } else {
            file
        };
        Self {
            diagnostic_id: crate::diagnostic::NEXT_ID
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed),
            primary_diagnostic_id: None,
            category,
            capture_site: site,
            origin_file: file,
            origin_line: origin.line(),
            origin_column: origin.column(),
            causes: [Some(cause), None, None, None],
            cause_count: 1,
            omitted_causes: 0,
            stack_status: "unavailable_bounded_capture",
        }
    }
    pub fn wrap(mut self, cause: BoundedDiagnosticCause) -> Self {
        if self.cause_count == self.causes.len() {
            self.omitted_causes = self.omitted_causes.saturating_add(1);
        } else {
            self.causes.copy_within(0..self.cause_count, 1);
            self.causes[0] = Some(cause);
            self.cause_count += 1;
        }
        self
    }
    pub fn during_cleanup_of(mut self, primary: &Self) -> Self {
        self.primary_diagnostic_id = Some(primary.diagnostic_id);
        self
    }
    pub fn id(&self) -> u64 {
        self.diagnostic_id
    }
    pub fn category(&self) -> DiagnosticCategory {
        self.category
    }
    /// Links cleanup to an existing light source reference without retaining its body.
    pub fn during_cleanup_occurrence(mut self, primary: DiagnosticOccurrence) -> Self {
        self.primary_diagnostic_id = Some(primary.source_id());
        self
    }
    pub fn occurrence(&self) -> DiagnosticOccurrence {
        DiagnosticOccurrence {
            diagnostic_id: self.diagnostic_id,
            primary_diagnostic_id: self.primary_diagnostic_id,
        }
    }
    pub(crate) fn primary_id_for_projection(&self) -> Option<u64> {
        self.primary_diagnostic_id
    }
    pub(crate) fn simple_projection(&self) -> Option<(DiagnosticCategory, CaptureSite,
        &'static str, u32, u32, DiagnosticStage, DiagnosticCode)> {
        let cause = self.causes[0]?;
        (self.cause_count == 1 && self.omitted_causes == 0
            && cause.io_kind.is_none() && cause.os_code.is_none()
            && cause.database_code.is_none() && cause.sqlstate.is_none()
            && cause.column_index.is_none() && cause.column_count.is_none()
            && cause.target_rust_type.is_none() && cause.actual_db_type.is_none()
            && cause.object.is_none() && cause.unavailable.is_none()
            && matches!(cause.target_type_unavailable,
                Some(DiagnosticFactUnavailable::MetadataUnavailable))
            && matches!(cause.actual_type_unavailable,
                Some(DiagnosticFactUnavailable::MetadataUnavailable)))
            .then_some((self.category, self.capture_site, self.origin_file,
                self.origin_line, self.origin_column, cause.stage, cause.code))
    }
}

/// Read-only correlation, not delivery confirmation or execution authority.
///
/// ```compile_fail
/// use saddle_core::DiagnosticOccurrence;
/// let forged = DiagnosticOccurrence { diagnostic_id: 1, primary_diagnostic_id: None };
/// ```
#[derive(Clone, Copy, Serialize)]
pub struct DiagnosticOccurrence {
    diagnostic_id: u64,
    primary_diagnostic_id: Option<u64>,
}
impl DiagnosticOccurrence {
    /// Compare a fixed-size capture with its original source submission.
    pub fn matches_bounded_diagnostic(&self, diagnostic: &BoundedDiagnostic) -> bool {
        self.diagnostic_id == diagnostic.id()
    }
    /// Compare source identity while allowing a later cleanup association.
    pub fn matches_diagnostic(&self, diagnostic: &crate::Diagnostic) -> bool {
        self.diagnostic_id == diagnostic.id()
    }
    pub(crate) const fn source_id(&self) -> u64 {
        self.diagnostic_id
    }
    pub(crate) fn from_diagnostic(diagnostic: &crate::Diagnostic) -> Self {
        Self {
            diagnostic_id: diagnostic.id(),
            primary_diagnostic_id: diagnostic.primary_id_for_projection(),
        }
    }
}

#[derive(Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OperationOutcome {
    Succeeded,
    Rejected,
    Failed,
    Cancelled,
    TimedOut,
    Panicked,
    Unknown,
}
#[derive(Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PhysicalDispositionFact {
    NotUsed,
    Returned,
    Discarded,
    Unknown,
}
#[derive(Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BusinessOutcome {
    Success,
    Failure,
    Unknown,
}
#[derive(Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ResponseDelivery {
    NotStarted,
    Partial,
    LocalWriteComplete,
    Failed,
    Cancelled,
    TimedOut,
    Unknown,
}
#[derive(Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CleanupOutcome {
    NotRun,
    Succeeded,
    Failed,
    Unknown,
}

/// Each domain reports only facts it owns; defaults are deliberately unknown.
/// These are observations, not proof of delivery, finalization or execution.
#[derive(Clone, Copy, Serialize)]
pub struct DiagnosticOutcomeAxes {
    pub operation: OperationOutcome,
    pub physical: PhysicalDispositionFact,
    pub business: BusinessOutcome,
    pub business_code: Option<RegisteredDiagnosticCode>,
    pub delivery: ResponseDelivery,
    pub bytes_written: Option<u64>,
    pub cleanup: CleanupOutcome,
}
impl Default for DiagnosticOutcomeAxes {
    fn default() -> Self {
        Self {
            operation: OperationOutcome::Unknown,
            physical: PhysicalDispositionFact::Unknown,
            business: BusinessOutcome::Unknown,
            business_code: None,
            delivery: ResponseDelivery::Unknown,
            bytes_written: None,
            cleanup: CleanupOutcome::Unknown,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn bounded_causes_primary_cleanup_metadata_and_business_code() {
        let cause = BoundedDiagnosticCause::new(
            DiagnosticStage::RequestDb,
            DiagnosticCode::new("db.decode").unwrap(),
        )
        .with_database_code(1064)
        .with_sqlstate("42000")
        .with_types(
            None,
            Some(InlineDiagnosticText::metadata("VARCHAR")),
            Some(DiagnosticFactUnavailable::OpaqueSource),
        );
        let mut primary = BoundedDiagnostic::capture(
            DiagnosticCategory::UnexpectedError,
            CaptureSite::FirstObserved,
            cause,
        );
        let id = primary.id();
        for _ in 0..6 {
            primary = primary.wrap(cause);
        }
        let p = serde_json::to_value(&primary).unwrap();
        assert_eq!(p["diagnostic_id"], id);
        assert_eq!(p["omitted_causes"], 3);
        assert_eq!(p["causes"][0]["sqlstate"]["value"], "42000");
        assert_eq!(p["causes"][0]["target_type_unavailable"], "opaque_source");
        assert!(p["causes"][0]["actual_type_unavailable"].is_null());
        let cleanup = BoundedDiagnostic::capture(
            DiagnosticCategory::UnexpectedError,
            CaptureSite::FirstObserved,
            cause,
        )
        .during_cleanup_of(&primary);
        assert_ne!(cleanup.id(), id);
        assert_eq!(
            serde_json::to_value(cleanup).unwrap()["primary_diagnostic_id"],
            id
        );
        let secret =
            serde_json::to_value(InlineDiagnosticText::metadata("mysql://SECRET@host")).unwrap();
        assert_eq!(secret["redacted"], true);
        assert!(!secret.to_string().contains("SECRET"));
        let long = serde_json::to_value(InlineDiagnosticText::metadata(&"界".repeat(100))).unwrap();
        assert_eq!(long["truncated"], true);
        assert!(
            RegisteredDiagnosticCode::from_registered("INVALID_VALUE", &["INVALID_VALUE"])
                .is_some()
        );
        assert!(RegisteredDiagnosticCode::from_registered("FOREIGN", &["INVALID_VALUE"]).is_none());
        assert!(
            RegisteredDiagnosticCode::from_registered("SECRET@host", &["SECRET@host"]).is_none()
        );
    }
}