Skip to main content

antfly_embedded/
error.rs

1// Copyright 2026 Antfly, Inc.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Stable Antfly C ABI error codes.
17//!
18//! This mirrors `go/pkg/embedded/errors.go`: names and descriptions are
19//! hand-maintained Rust values, not sourced from `antfly_error_code_name`/
20//! `antfly_error_code_description` at runtime, so `Error` is usable (and its
21//! `Display` output is meaningful) even when this crate is built without the
22//! `libantfly` feature and no dylib is linked. `tests/errors.rs` (linked)
23//! cross-checks these against the live C ABI.
24
25use std::fmt;
26
27/// A stable Antfly C ABI error code, mapped onto a typed Rust enum.
28///
29/// `ANTFLY_OK` (0) is success and is never represented by `Error`; every
30/// fallible call in this crate returns `Result<T, Error> = Result<T>`.
31#[derive(Debug, Clone)]
32pub enum Error {
33    /// Owned diagnostic from a native call. Use `code()`/`kind()` to classify.
34    Native { code: i32, detail: String },
35    /// An [`Error::OutcomeUnknown`] from a batch or autocommit SQL write that
36    /// issued an outcome receipt. Resolve the receipt later with
37    /// `Database::outcome_receipt_status`. Compares equal to
38    /// `Error::OutcomeUnknown`; read the receipt with
39    /// [`Error::outcome_receipt`].
40    OutcomeUnknownWithReceipt {
41        detail: Option<String>,
42        receipt: String,
43    },
44    /// An argument, request, path, or open mode is invalid.
45    InvalidArgument,
46    /// The requested database object was not found.
47    NotFound,
48    /// A version predicate did not match the current document version.
49    VersionConflict,
50    /// A transaction intent conflicts with the requested operation.
51    IntentConflict,
52    /// The requested transaction was not found.
53    TxnNotFound,
54    /// The requested resource is temporarily busy or changed during
55    /// streaming; stabilize it and retry.
56    Busy,
57    /// The operation may have taken effect: it was published but crash
58    /// durability could not be confirmed, or a failure left it unknown
59    /// whether it applied. Inspect the affected data; do not retry
60    /// automatically.
61    OutcomeUnknown,
62    /// The operation requires a capability that is not supported by this
63    /// platform or filesystem. Retrying unchanged will not succeed.
64    Unsupported,
65    /// Derived work stalled or a derived worker failed. Inspect pending-work
66    /// diagnostics and repair or reopen the database. A batch may already
67    /// have committed: inspect its error detail and do not replay a batch
68    /// reported as committed.
69    Stalled,
70    /// The operation was cancelled, including a pending replacement or a
71    /// progress/stream callback returning `false`, or an IO interruption.
72    Cancelled,
73    /// A replacement exhausted its consecutive or lifetime retry budget,
74    /// or encountered a permanent error. Inspect its pending-work diagnostics.
75    ReplacementFailed,
76    /// The requested operation conflicts with a pending replacement.
77    ReplacementPending,
78    /// The requested configuration differs from the pending replacement.
79    ReplacementConfigurationMismatch,
80    /// An internal error occurred.
81    Internal,
82    /// A C ABI error code this binding does not recognize, carrying the raw
83    /// numeric value.
84    Unknown(i32),
85}
86
87impl Error {
88    /// Stable category, independent of the owned diagnostic.
89    pub fn kind(&self) -> Error {
90        Error::from_code(self.code())
91    }
92    pub fn detail(&self) -> Option<&str> {
93        match self {
94            Error::Native { detail, .. } => Some(detail),
95            Error::OutcomeUnknownWithReceipt { detail, .. } => detail.as_deref(),
96            _ => None,
97        }
98    }
99    /// The outcome receipt of an `OutcomeUnknown` batch or autocommit SQL
100    /// write, when the database issued one.
101    pub fn outcome_receipt(&self) -> Option<&str> {
102        match self {
103            Error::OutcomeUnknownWithReceipt { receipt, .. } => Some(receipt),
104            _ => None,
105        }
106    }
107    /// Attaches `receipt` to an `OutcomeUnknown` error; other errors are
108    /// returned unchanged.
109    pub(crate) fn with_outcome_receipt(self, receipt: Option<String>) -> Error {
110        match receipt {
111            Some(receipt) if self.code() == 7 => Error::OutcomeUnknownWithReceipt {
112                detail: self.detail().map(str::to_owned),
113                receipt,
114            },
115            _ => self,
116        }
117    }
118    /// [`Error::from_native`] for calls that issue outcome receipts: reads
119    /// the receipt first, on this thread, before any other native call.
120    pub(crate) fn from_native_with_receipt(code: i32) -> Error {
121        let receipt = if code == 7 {
122            last_outcome_receipt()
123        } else {
124            None
125        };
126        Error::from_native(code).with_outcome_receipt(receipt)
127    }
128    pub(crate) fn from_native(code: i32) -> Error {
129        #[cfg(feature = "libantfly")]
130        if unsafe { antfly_embedded_sys::antfly_last_error_code() } == code {
131            let detail = last_error_detail();
132            if !detail.is_empty() {
133                return Error::Native { code, detail };
134            }
135        }
136        Error::from_code(code)
137    }
138
139    /// Maps a raw `antfly_error_code` to a typed `Error`. Callers should
140    /// treat `ANTFLY_OK` (0) as success, not as an `Error`; this function
141    /// will happily map it to `Error::Unknown(0)` if asked.
142    pub fn from_code(code: i32) -> Error {
143        match code {
144            1 => Error::InvalidArgument,
145            2 => Error::NotFound,
146            3 => Error::VersionConflict,
147            4 => Error::IntentConflict,
148            5 => Error::TxnNotFound,
149            6 => Error::Busy,
150            7 => Error::OutcomeUnknown,
151            8 => Error::Unsupported,
152            9 => Error::Stalled,
153            11 => Error::ReplacementFailed,
154            12 => Error::ReplacementPending,
155            13 => Error::ReplacementConfigurationMismatch,
156            10 => Error::Cancelled,
157            255 => Error::Internal,
158            other => Error::Unknown(other),
159        }
160    }
161
162    /// The raw numeric `antfly_error_code` this value represents.
163    pub fn code(&self) -> i32 {
164        match self {
165            Error::Native { code, .. } => *code,
166            Error::OutcomeUnknownWithReceipt { .. } => 7,
167            Error::InvalidArgument => 1,
168            Error::NotFound => 2,
169            Error::VersionConflict => 3,
170            Error::IntentConflict => 4,
171            Error::TxnNotFound => 5,
172            Error::Busy => 6,
173            Error::OutcomeUnknown => 7,
174            Error::Unsupported => 8,
175            Error::Stalled => 9,
176            Error::ReplacementFailed => 11,
177            Error::ReplacementPending => 12,
178            Error::ReplacementConfigurationMismatch => 13,
179            Error::Cancelled => 10,
180            Error::Internal => 255,
181            Error::Unknown(code) => *code,
182        }
183    }
184
185    /// The stable symbolic C ABI name for this error, e.g. `"ANTFLY_BUSY"`.
186    pub fn name(&self) -> &'static str {
187        match self {
188            Error::InvalidArgument => "ANTFLY_INVALID_ARGUMENT",
189            Error::NotFound => "ANTFLY_NOT_FOUND",
190            Error::VersionConflict => "ANTFLY_VERSION_CONFLICT",
191            Error::IntentConflict => "ANTFLY_INTENT_CONFLICT",
192            Error::TxnNotFound => "ANTFLY_TXN_NOT_FOUND",
193            Error::Busy => "ANTFLY_BUSY",
194            Error::OutcomeUnknown => "ANTFLY_OUTCOME_UNKNOWN",
195            Error::Unsupported => "ANTFLY_UNSUPPORTED",
196            Error::Stalled => "ANTFLY_STALLED",
197            Error::ReplacementFailed => "ANTFLY_REPLACEMENT_FAILED",
198            Error::ReplacementPending => "ANTFLY_REPLACEMENT_PENDING",
199            Error::ReplacementConfigurationMismatch => "ANTFLY_REPLACEMENT_CONFIGURATION_MISMATCH",
200            Error::Cancelled => "ANTFLY_CANCELLED",
201            Error::Internal => "ANTFLY_INTERNAL",
202            Error::Unknown(_) => "ANTFLY_UNKNOWN_ERROR",
203            Error::Native { code, .. } => Error::from_code(*code).name(),
204            Error::OutcomeUnknownWithReceipt { .. } => Error::OutcomeUnknown.name(),
205        }
206    }
207
208    /// A short, stable description for this error.
209    pub fn description(&self) -> &'static str {
210        match self {
211            Error::InvalidArgument => "an argument, request, path, or open mode is invalid",
212            Error::NotFound => "the requested database object was not found",
213            Error::VersionConflict => {
214                "a version predicate did not match the current document version"
215            }
216            Error::IntentConflict => "a transaction intent conflicts with the requested operation",
217            Error::TxnNotFound => "the requested transaction was not found",
218            Error::Busy => {
219                "the requested resource is temporarily busy or changed during streaming; \
220                 stabilize it and retry"
221            }
222            Error::OutcomeUnknown => {
223                "the operation may have taken effect, but whether it applied or became durable \
224                 could not be confirmed; inspect the affected data and do not retry automatically"
225            }
226            Error::Unsupported => {
227                "the operation requires a capability that is not supported by this platform \
228                 or filesystem"
229            }
230            Error::Stalled => {
231                "derived work stalled or failed; inspect pending-work diagnostics and \
232                 repair or reopen the database"
233            }
234            Error::ReplacementFailed => {
235                "replacement failed after its retry budget; inspect diagnostics and cancel before retrying"
236            }
237            Error::ReplacementPending => "index name is reserved by a pending replacement",
238            Error::ReplacementConfigurationMismatch => {
239                "replacement configuration differs from the reserved request"
240            }
241            Error::Cancelled => "the caller cancelled the operation",
242            Error::Internal => "an internal error occurred",
243            Error::Unknown(_) => "unknown Antfly error code",
244            Error::Native { code, .. } => Error::from_code(*code).description(),
245            Error::OutcomeUnknownWithReceipt { .. } => Error::OutcomeUnknown.description(),
246        }
247    }
248}
249
250impl fmt::Display for Error {
251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252        write!(f, "{}: {}", self.name(), self.description())?;
253        if let Some(detail) = self.detail() {
254            write!(f, ": {detail}")?;
255        }
256        if let Some(receipt) = self.outcome_receipt() {
257            write!(f, " (outcome receipt {receipt})")?;
258        }
259        Ok(())
260    }
261}
262
263// Preserve stable-code comparisons when native diagnostics are present.
264impl PartialEq for Error {
265    fn eq(&self, other: &Self) -> bool {
266        self.code() == other.code()
267    }
268}
269impl Eq for Error {}
270impl std::hash::Hash for Error {
271    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
272        std::hash::Hash::hash(&self.code(), state);
273    }
274}
275
276impl std::error::Error for Error {}
277
278/// A `Result` whose error type is [`Error`].
279pub type Result<T> = std::result::Result<T, Error>;
280
281/// Copy the most recent native failure detail on the current thread.
282/// Call immediately after a failed operation; later failures replace it.
283#[cfg(feature = "libantfly")]
284pub fn last_error_detail() -> String {
285    unsafe {
286        std::ffi::CStr::from_ptr(antfly_embedded_sys::antfly_last_error_detail())
287            .to_string_lossy()
288            .into_owned()
289    }
290}
291
292/// This thread's most recent outcome receipt, or `None` when the failed call
293/// issued none (or the library is not linked).
294fn last_outcome_receipt() -> Option<String> {
295    #[cfg(feature = "libantfly")]
296    {
297        let mut out = antfly_embedded_sys::antfly_buffer::default();
298        let code = unsafe { antfly_embedded_sys::antfly_last_error_outcome_receipt(&mut out) };
299        if code != antfly_embedded_sys::ANTFLY_OK {
300            return None;
301        }
302        let bytes = unsafe { crate::ffi::take_buffer(out) };
303        if bytes.is_empty() {
304            return None;
305        }
306        Some(String::from_utf8_lossy(&bytes).into_owned())
307    }
308    #[cfg(not(feature = "libantfly"))]
309    None
310}