type-bridge 2.0.2

Public client SDK for TypeBridge
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
//! Error handling for the public TypeBridge client.

use std::error::Error as StdError;
use std::fmt;

use type_bridge_contract::diagnostic::{Diagnostic, DiagnosticCategory, DiagnosticPathSegment};
use type_bridge_orm::match_request::{MatchError, MatchErrorCategory};

/// Stable public classification for TypeBridge client failures.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorCategory {
    /// Connection establishment or connectivity failed.
    Connection,
    /// Generated or installed schema authority failed verification.
    Schema,
    /// Generated input or provider evidence failed model validation.
    ModelValidation,
    /// A typed query was invalid before provider execution.
    QueryAuthoring,
    /// The provider failed while executing an accepted query.
    QueryExecution,
    /// A transaction lifecycle operation failed.
    Transaction,
    /// A remote envelope, reply, transport, or integrity contract failed.
    Remote,
    /// The selected provider or remote executor lacks a required capability.
    Capability,
    /// A canonical client, provider, or remote resource ceiling was exceeded.
    ResourceLimit,
    /// A requested entity or schema element was not found.
    NotFound,
    /// An underlying database operation failed outside a narrower category.
    Database,
    /// A client invariant failed outside the stable categories above.
    Other,
}

impl ErrorCategory {
    /// Return the stable language-neutral category spelling.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Connection => "connection",
            Self::Schema => "schema",
            Self::ModelValidation => "model_validation",
            Self::QueryAuthoring => "query_authoring",
            Self::QueryExecution => "query_execution",
            Self::Transaction => "transaction",
            Self::Remote => "remote",
            Self::Capability => "capability",
            Self::ResourceLimit => "resource_limit",
            Self::NotFound => "not_found",
            Self::Database => "database",
            Self::Other => "other",
        }
    }
}

impl fmt::Display for ErrorCategory {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Stage at which generated-model evidence failed validation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ModelValidationPhase {
    /// Generated constructor input failed before provider execution.
    Input,
    /// Provider row evidence failed while hydrating a generated model.
    Hydration,
}

/// Primary error type for the TypeBridge client SDK.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Generated-model evidence did not match the installed schema projection.
    #[error("Model validation failed during {phase:?}: {message}")]
    ModelValidation {
        phase: ModelValidationPhase,
        code: String,
        path: Vec<String>,
        message: String,
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// A structured engine or remote-contract failure mapped into stable
    /// client-owned categories, codes, and paths.
    #[error("{category} error [{code}]: {message}")]
    Classified {
        category: ErrorCategory,
        phase: Option<ModelValidationPhase>,
        code: String,
        path: Vec<String>,
        message: String,
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Schema verification or installation failed.
    #[error("Schema verification failed: {message}")]
    SchemaVerification {
        message: String,
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Connection to the database failed.
    #[error("Connection error: {message}")]
    Connection {
        message: String,
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Database query or operation failed.
    #[error("Query execution error: {message}")]
    QueryExecution {
        message: String,
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Database transaction failed.
    #[error("Transaction error: {message}")]
    Transaction {
        message: String,
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Requested schema element or database entity was not found.
    #[error("Entity not found: {message}")]
    NotFound {
        message: String,
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Underlying database error.
    #[error("Database error: {message}")]
    Database {
        message: String,
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Client request or execution error.
    #[error("Client error: {message}")]
    Other {
        message: String,
        #[source]
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },
}

impl Error {
    #[allow(dead_code)]
    pub(crate) fn model_validation(
        phase: ModelValidationPhase,
        code: impl Into<String>,
        path: Vec<String>,
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    ) -> Self {
        Self::ModelValidation {
            phase,
            code: code.into(),
            path,
            message: message.into(),
            source,
        }
    }

    pub(crate) fn classified(
        category: ErrorCategory,
        phase: Option<ModelValidationPhase>,
        code: impl Into<String>,
        path: Vec<String>,
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    ) -> Self {
        Self::Classified {
            category,
            phase,
            code: code.into(),
            path,
            message: message.into(),
            source,
        }
    }

    /// Construct one application-owned remote transport failure.
    ///
    /// Transport implementations should use a stable lowercase snake-case
    /// code so callers can handle the failure without parsing its message.
    #[must_use]
    pub fn remote(
        code: impl Into<String>,
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    ) -> Self {
        Self::classified(
            ErrorCategory::Remote,
            None,
            code,
            Vec::new(),
            message,
            source,
        )
    }

    pub(crate) fn from_match(error: MatchError, phase: ModelValidationPhase) -> Self {
        let category = match error.category() {
            MatchErrorCategory::InvalidPlan => ErrorCategory::QueryAuthoring,
            MatchErrorCategory::Cardinality | MatchErrorCategory::ResultDecode => {
                ErrorCategory::ModelValidation
            }
            MatchErrorCategory::UnsupportedCapability => ErrorCategory::Capability,
            MatchErrorCategory::StaleSchema => ErrorCategory::Schema,
            MatchErrorCategory::ResourceLimit => ErrorCategory::ResourceLimit,
            MatchErrorCategory::Provider => ErrorCategory::QueryExecution,
        };
        let model_phase = (category == ErrorCategory::ModelValidation).then_some(phase);
        let code = error.code().as_str().to_owned();
        let path = error
            .path()
            .segments()
            .iter()
            .map(ToString::to_string)
            .collect();
        let message = error.message().to_owned();
        Self::classified(
            category,
            model_phase,
            code,
            path,
            message,
            Some(Box::new(error)),
        )
    }

    pub(crate) fn from_remote_diagnostic(error: Diagnostic) -> Self {
        let category = match error.category() {
            DiagnosticCategory::UnsupportedCapability => ErrorCategory::Capability,
            DiagnosticCategory::ResourceLimit => ErrorCategory::ResourceLimit,
            DiagnosticCategory::InvalidContract | DiagnosticCategory::Integrity => {
                ErrorCategory::Remote
            }
        };
        let code = error.code().as_str().to_owned();
        let path = error
            .path()
            .segments()
            .iter()
            .map(|segment| match segment {
                DiagnosticPathSegment::Field(value) => value.clone(),
                DiagnosticPathSegment::Index(value) => format!("[{value}]"),
                DiagnosticPathSegment::Identifier(value) => value.clone(),
            })
            .collect();
        let message = error.message().to_owned();
        Self::classified(category, None, code, path, message, Some(Box::new(error)))
    }

    #[allow(dead_code)]
    pub(crate) fn from_orm(err: type_bridge_orm::OrmError) -> Self {
        match err {
            type_bridge_orm::OrmError::Match(error) => {
                Self::from_match(error, ModelValidationPhase::Input)
            }
            error @ type_bridge_orm::OrmError::Connection(_) => Self::Connection {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error @ type_bridge_orm::OrmError::QueryExecution(_) => Self::QueryExecution {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error @ type_bridge_orm::OrmError::Transaction(_) => Self::Transaction {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error @ type_bridge_orm::OrmError::NotFound(_) => Self::NotFound {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error @ type_bridge_orm::OrmError::Hydration { .. } => Self::ModelValidation {
                phase: ModelValidationPhase::Hydration,
                code: "invalid_provider_evidence".into(),
                path: vec![],
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
            error => Self::Database {
                message: error.to_string(),
                source: Some(Box::new(error)),
            },
        }
    }

    pub(crate) fn from_orm_hydration(err: type_bridge_orm::OrmError) -> Self {
        match err {
            type_bridge_orm::OrmError::Match(error) => {
                Self::from_match(error, ModelValidationPhase::Hydration)
            }
            error => Self::from_orm(error),
        }
    }

    /// Return the stable public failure category.
    #[must_use]
    pub const fn category(&self) -> ErrorCategory {
        match self {
            Self::ModelValidation { .. } => ErrorCategory::ModelValidation,
            Self::Classified { category, .. } => *category,
            Self::SchemaVerification { .. } => ErrorCategory::Schema,
            Self::Connection { .. } => ErrorCategory::Connection,
            Self::QueryExecution { .. } => ErrorCategory::QueryExecution,
            Self::Transaction { .. } => ErrorCategory::Transaction,
            Self::NotFound { .. } => ErrorCategory::NotFound,
            Self::Database { .. } => ErrorCategory::Database,
            Self::Other { .. } => ErrorCategory::Other,
        }
    }

    /// Return the error message string.
    #[must_use]
    pub fn message(&self) -> &str {
        match self {
            Self::ModelValidation { message, .. }
            | Self::Classified { message, .. }
            | Self::SchemaVerification { message, .. }
            | Self::Connection { message, .. }
            | Self::QueryExecution { message, .. }
            | Self::Transaction { message, .. }
            | Self::NotFound { message, .. }
            | Self::Database { message, .. }
            | Self::Other { message, .. } => message,
        }
    }

    /// Return the stable machine-readable failure code, when available.
    #[must_use]
    pub fn code(&self) -> Option<&str> {
        match self {
            Self::ModelValidation { code, .. } | Self::Classified { code, .. } => Some(code),
            _ => None,
        }
    }

    /// Return the owned structured diagnostic path, when available.
    #[must_use]
    pub fn path(&self) -> Option<&[String]> {
        match self {
            Self::ModelValidation { path, .. } | Self::Classified { path, .. } => Some(path),
            _ => None,
        }
    }

    /// Return the model-validation phase, when applicable.
    #[must_use]
    pub const fn model_validation_phase(&self) -> Option<ModelValidationPhase> {
        match self {
            Self::ModelValidation { phase, .. } => Some(*phase),
            Self::Classified { phase, .. } => *phase,
            _ => None,
        }
    }
}

/// Convenience Result type for the TypeBridge client.
pub type Result<T, E = Error> = std::result::Result<T, E>;

#[cfg(test)]
mod tests {
    use super::{Error, ErrorCategory};

    #[test]
    fn public_error_categories_and_remote_constructor_are_stable() {
        let categories = [
            (ErrorCategory::Connection, "connection"),
            (ErrorCategory::Schema, "schema"),
            (ErrorCategory::ModelValidation, "model_validation"),
            (ErrorCategory::QueryAuthoring, "query_authoring"),
            (ErrorCategory::QueryExecution, "query_execution"),
            (ErrorCategory::Transaction, "transaction"),
            (ErrorCategory::Remote, "remote"),
            (ErrorCategory::Capability, "capability"),
            (ErrorCategory::ResourceLimit, "resource_limit"),
            (ErrorCategory::NotFound, "not_found"),
            (ErrorCategory::Database, "database"),
            (ErrorCategory::Other, "other"),
        ];
        for (category, spelling) in categories {
            assert_eq!(category.as_str(), spelling);
            assert_eq!(category.to_string(), spelling);
        }

        let error = Error::remote("remote_transport", "connection reset", None);
        assert_eq!(error.category(), ErrorCategory::Remote);
        assert_eq!(error.code(), Some("remote_transport"));
        assert_eq!(error.path(), Some(&[][..]));
        assert_eq!(error.message(), "connection reset");
    }
}