hyperdb-api-core 1.0.0-rc.4

Internal implementation details for hyperdb-api. Not a stable API; use hyperdb-api instead.
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// Copyright (c) 2026, Salesforce, Inc. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Error types for the Hyper client.
//!
//! [`Error`] is a flat enum: one variant per failure mode, matched
//! directly, with no `kind()` discriminator and no `Box<dyn StdError>`
//! cause channel. That is the shape the [Microsoft Pragmatic Rust
//! Guidelines][msrg] call for (M-ERRORS-CANONICAL-STRUCTS,
//! M-ERRORS-AVOID-WRAPPING-AND-AS-DYN), and it mirrors the public
//! `hyperdb_api::Error` this type feeds.
//!
//! This type is **internal**. It is not re-exported from `hyperdb-api`;
//! callers of the public API match on `hyperdb_api::Error` instead, which
//! `From<client::Error>` produces.
//!
//! [msrg]: https://microsoft.github.io/rust-guidelines/

use std::io;

use thiserror::Error as ThisError;

/// The error type for Hyper client operations.
///
/// Variants that can carry a server-supplied SQLSTATE expose it as a
/// field, so callers match on it structurally rather than scraping the
/// message. The remaining variants are single-string: whatever context
/// exists is already rendered into that string by the constructor.
///
/// Deliberately **not** `#[non_exhaustive]`. That attribute buys
/// forward-compatibility for downstream matches, which this type has no
/// use for: it is internal, not re-exported, and `hyperdb-api` is its only
/// consumer and ships from this same workspace in lockstep. What it would
/// cost is the compile-time exhaustiveness check on
/// `From<client::Error> for hyperdb_api::Error` — the one place a new
/// variant must be given a public mapping. Better that adding a variant
/// breaks that build than silently degrades to `Error::Internal`.
#[derive(Debug, ThisError)]
pub enum Error {
    /// Connection failed.
    #[error("{message}")]
    Connection {
        /// Human-readable description of the failure.
        message: String,
        /// SQLSTATE, when the failure arrived from the server (gRPC
        /// reports connection-class SQLSTATEs in the `08xxx` family).
        sqlstate: Option<String>,
    },

    /// Authentication failed.
    #[error("{0}")]
    Authentication(String),

    /// Query execution failed.
    ///
    /// The one variant that carries the server's full diagnostic
    /// payload — `DETAIL` and `HINT` are surfaced verbatim by the public
    /// `hyperdb_api::Error::Server` variant this maps to.
    #[error("{message}{}", render_detail(message, detail.as_deref()))]
    Query {
        /// The primary error message.
        message: String,
        /// SQLSTATE code, when the server supplied one.
        sqlstate: Option<String>,
        /// The server's `DETAIL` field.
        detail: Option<String>,
        /// The server's `HINT` field.
        hint: Option<String>,
    },

    /// Invalid response from server.
    #[error("{0}")]
    Protocol(String),

    /// I/O error.
    #[error("{0}")]
    Io(String),

    /// Configuration error.
    #[error("{0}")]
    Config(String),

    /// Operation timed out.
    #[error("{0}")]
    Timeout(String),

    /// Operation was cancelled.
    #[error("{message}")]
    Cancelled {
        /// Human-readable description of the cancellation.
        message: String,
        /// SQLSTATE, typically `57014` (`query_canceled`).
        sqlstate: Option<String>,
    },

    /// The connection was closed.
    #[error("{message}")]
    Closed {
        /// Human-readable description.
        message: String,
        /// SQLSTATE, when the server supplied one.
        sqlstate: Option<String>,
    },

    /// Type conversion error.
    #[error("{0}")]
    Conversion(String),

    /// Feature not supported by this connection type.
    #[error("{0}")]
    FeatureNotSupported(String),

    /// Other error.
    #[error("{0}")]
    Other(String),
}

/// Renders the `": {detail}"` suffix for [`Error::Query`]'s `Display`,
/// suppressing it when `message` already contains the detail text.
///
/// gRPC's `decode_error_info` builds `"{primary}: {customer_detail}"` as
/// the message and *also* reports `customer_detail` separately, so without
/// this guard the detail would print twice.
fn render_detail(message: &str, detail: Option<&str>) -> String {
    match detail {
        Some(detail) if !message.contains(detail) => format!(": {detail}"),
        _ => String::new(),
    }
}

impl Error {
    // Constructors. Every variant has one taking `impl Into<String>`;
    // the variants with a SQLSTATE field default it to `None` here and
    // are built with struct literals where a code is available.

    /// Creates a connection error with no SQLSTATE.
    pub fn connection(message: impl Into<String>) -> Self {
        Error::Connection {
            message: message.into(),
            sqlstate: None,
        }
    }

    /// Creates an authentication error.
    pub fn authentication(message: impl Into<String>) -> Self {
        Error::Authentication(message.into())
    }

    /// Creates a query error with no SQLSTATE, detail, or hint.
    pub fn query(message: impl Into<String>) -> Self {
        Error::Query {
            message: message.into(),
            sqlstate: None,
            detail: None,
            hint: None,
        }
    }

    /// Creates a protocol error.
    pub fn protocol(message: impl Into<String>) -> Self {
        Error::Protocol(message.into())
    }

    /// Creates an I/O error from a message.
    ///
    /// Prefer [`Error::from_io`] when an [`io::Error`] is in hand.
    pub fn io(message: impl Into<String>) -> Self {
        Error::Io(message.into())
    }

    /// Creates a configuration error.
    pub fn config(message: impl Into<String>) -> Self {
        Error::Config(message.into())
    }

    /// Creates a timeout error.
    pub fn timeout(message: impl Into<String>) -> Self {
        Error::Timeout(message.into())
    }

    /// Creates a cancellation error with no SQLSTATE.
    pub fn cancelled(message: impl Into<String>) -> Self {
        Error::Cancelled {
            message: message.into(),
            sqlstate: None,
        }
    }

    /// Creates a closed-connection error with no SQLSTATE.
    pub fn closed(message: impl Into<String>) -> Self {
        Error::Closed {
            message: message.into(),
            sqlstate: None,
        }
    }

    /// Creates a type-conversion error.
    pub fn conversion(message: impl Into<String>) -> Self {
        Error::Conversion(message.into())
    }

    /// Creates a "feature not supported" error.
    ///
    /// Used when an operation is not available on a particular connection
    /// type (e.g. write operations on gRPC connections).
    pub fn feature_not_supported(message: impl Into<String>) -> Self {
        Error::FeatureNotSupported(message.into())
    }

    /// Creates a generic "other" error.
    pub fn other(message: impl Into<String>) -> Self {
        Error::Other(message.into())
    }

    // Convenience constructors for the common shapes.

    /// Creates an I/O error from an [`io::Error`].
    ///
    /// Takes the error by value so it can be used point-free as
    /// `.map_err(Error::from_io)`.
    #[expect(
        clippy::needless_pass_by_value,
        reason = "call-site ergonomics: consumed as a `map_err` function reference"
    )]
    #[must_use]
    pub fn from_io(err: io::Error) -> Self {
        Error::Io(err.to_string())
    }

    /// Creates an error from a database error response.
    #[must_use]
    pub fn db(severity: &str, code: &str, message: &str) -> Self {
        Error::Query {
            message: format!("{severity}: {message} ({code})"),
            sqlstate: Some(code.to_string()),
            detail: None,
            hint: None,
        }
    }

    /// Returns the error message, without any `DETAIL` suffix that
    /// `Display` would append.
    #[must_use]
    pub fn message(&self) -> &str {
        match self {
            Error::Connection { message, .. }
            | Error::Query { message, .. }
            | Error::Cancelled { message, .. }
            | Error::Closed { message, .. } => message,
            Error::Authentication(message)
            | Error::Protocol(message)
            | Error::Io(message)
            | Error::Config(message)
            | Error::Timeout(message)
            | Error::Conversion(message)
            | Error::FeatureNotSupported(message)
            | Error::Other(message) => message,
        }
    }

    /// Returns the error detail, if available.
    #[must_use]
    pub fn detail(&self) -> Option<&str> {
        match self {
            Error::Query { detail, .. } => detail.as_deref(),
            _ => None,
        }
    }

    /// Returns the error hint, if available.
    #[must_use]
    pub fn hint(&self) -> Option<&str> {
        match self {
            Error::Query { hint, .. } => hint.as_deref(),
            _ => None,
        }
    }

    /// Extracts the `PostgreSQL` SQLSTATE code from the error, if present.
    ///
    /// SQLSTATE codes are 5-character codes that identify error conditions.
    /// See: <https://www.postgresql.org/docs/current/errcodes-appendix.html>
    ///
    /// For [`Error::Query`] with no stored code, falls back to scraping the
    /// trailing `(CODE)` that Hyper appends to wire error messages.
    ///
    /// # Example
    ///
    /// ```
    /// use hyperdb_api_core::client::Error;
    ///
    /// let err = Error::db("ERROR", "42P04", "database already exists");
    /// assert_eq!(err.sqlstate(), Some("42P04"));
    /// ```
    #[must_use]
    pub fn sqlstate(&self) -> Option<&str> {
        match self {
            Error::Connection { sqlstate, .. }
            | Error::Cancelled { sqlstate, .. }
            | Error::Closed { sqlstate, .. } => sqlstate.as_deref(),
            Error::Query {
                sqlstate, message, ..
            } => match sqlstate {
                Some(code) => Some(code),
                // Backwards compatibility: older paths encode the code in
                // the message rather than storing it.
                None => extract_sqlstate(message),
            },
            _ => None,
        }
    }
}

/// Extracts the SQLSTATE code from a Hyper error message.
///
/// Hyper error messages have the format: "SEVERITY: message (CODE)"
/// where CODE is the 5-character SQLSTATE code.
fn extract_sqlstate(message: &str) -> Option<&str> {
    // Find the last occurrence of '(' which should contain the SQLSTATE code
    let start = message.rfind('(')?;
    let end = message[start..].find(')')?;

    let code = message[start + 1..start + end].trim();

    // Validate that it looks like a SQLSTATE code (5 alphanumeric characters)
    if code.len() == 5 && code.chars().all(|c| c.is_ascii_alphanumeric()) {
        Some(code)
    } else {
        None
    }
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Self {
        Error::from_io(err)
    }
}

/// Result type for Hyper client operations.
pub type Result<T> = std::result::Result<T, Error>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sqlstate_extraction() {
        // Standard format: "SEVERITY: message (CODE)"
        let err = Error::db("ERROR", "42P04", "database \"test\" already exists");
        assert_eq!(err.sqlstate(), Some("42P04"));

        // Duplicate object
        let err = Error::db("ERROR", "42710", "duplicate object");
        assert_eq!(err.sqlstate(), Some("42710"));

        // Duplicate schema
        let err = Error::db("ERROR", "42P06", "schema \"public\" already exists");
        assert_eq!(err.sqlstate(), Some("42P06"));

        // Duplicate table
        let err = Error::db("ERROR", "42P07", "table \"users\" already exists");
        assert_eq!(err.sqlstate(), Some("42P07"));
    }

    #[test]
    fn test_sqlstate_non_query_error() {
        // Non-query errors carry no SQLSTATE unless one was supplied.
        let err = Error::connection("connection failed");
        assert_eq!(err.sqlstate(), None);

        let err = Error::timeout("operation timed out");
        assert_eq!(err.sqlstate(), None);
    }

    /// The gRPC path builds `Connection` / `Cancelled` / `Closed` with a
    /// server-supplied SQLSTATE; `sqlstate()` must surface it, because the
    /// public `hyperdb_api::Error` mapping forwards it to callers.
    #[test]
    fn test_sqlstate_on_non_query_variants() {
        let err = Error::Cancelled {
            message: "query canceled".to_string(),
            sqlstate: Some("57014".to_string()),
        };
        assert_eq!(err.sqlstate(), Some("57014"));

        let err = Error::Connection {
            message: "connection failure".to_string(),
            sqlstate: Some("08006".to_string()),
        };
        assert_eq!(err.sqlstate(), Some("08006"));

        let err = Error::Closed {
            message: "closed".to_string(),
            sqlstate: Some("08003".to_string()),
        };
        assert_eq!(err.sqlstate(), Some("08003"));
    }

    /// `Display` appends `DETAIL` only when the message doesn't already
    /// carry it — gRPC folds the detail into the message *and* reports it
    /// separately, and printing it twice was the bug this guard prevents.
    #[test]
    fn test_display_detail_suffix() {
        let err = Error::Query {
            message: "column not found".to_string(),
            sqlstate: None,
            detail: Some("column \"foo\" does not exist".to_string()),
            hint: None,
        };
        assert_eq!(
            err.to_string(),
            "column not found: column \"foo\" does not exist"
        );

        let err = Error::Query {
            message: "column not found: column \"foo\" does not exist".to_string(),
            sqlstate: None,
            detail: Some("column \"foo\" does not exist".to_string()),
            hint: None,
        };
        assert_eq!(
            err.to_string(),
            "column not found: column \"foo\" does not exist",
            "detail already present in the message must not be repeated"
        );
    }

    /// An `io::Error` renders exactly once. The previous struct-shaped
    /// error stored the same text as both `message` and `cause`, so
    /// `Display` emitted it twice.
    #[test]
    fn test_io_error_renders_once() {
        let io_err = io::Error::new(io::ErrorKind::ConnectionRefused, "refused");
        let err = Error::from(io_err);
        assert_eq!(err.to_string(), "refused");
    }

    #[test]
    fn test_extract_sqlstate_edge_cases() {
        // Valid SQLSTATE
        assert_eq!(extract_sqlstate("ERROR: message (42P04)"), Some("42P04"));

        // With spaces
        assert_eq!(extract_sqlstate("ERROR: message ( 42P04 )"), Some("42P04"));

        // Multiple parentheses (should extract last one)
        assert_eq!(
            extract_sqlstate("ERROR: (extra info) message (42P04)"),
            Some("42P04")
        );

        // Invalid: too short
        assert_eq!(extract_sqlstate("ERROR: message (42P)"), None);

        // Invalid: too long
        assert_eq!(extract_sqlstate("ERROR: message (42P044)"), None);

        // Invalid: non-alphanumeric
        assert_eq!(extract_sqlstate("ERROR: message (42-04)"), None);

        // No parentheses
        assert_eq!(extract_sqlstate("ERROR: message"), None);

        // Empty parentheses
        assert_eq!(extract_sqlstate("ERROR: message ()"), None);
    }
}