brain-edge 0.2.1

The HTTP/JSON edge for the Brain memory database — a self-hostable binary and an embeddable library that speaks the same API the Arc cloud hosts.
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
//! HTTP error type — one JSON error envelope, mapped from Brain's taxonomy.
//!
//! A `5xx` body deliberately carries no internal detail. `BrainError` renders
//! frame-codec faults, protocol violations and version mismatches into their
//! `Display` text, and forwarding that to an HTTP caller tells them about the
//! edge's conversation with its database rather than about their request. The
//! detail is logged with the request id instead, so an operator can still find
//! it — see [`ApiError::log_internal`].

use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use brain_db_sdk::BrainError;
use brain_db_sdk::wire::types::{ErrorCategoryWire, ErrorCodeWire};
use serde::Serialize;

/// A structured API error. Serializes to `{ "error": { code, message } }` with
/// the matching HTTP status.
#[derive(Debug)]
pub struct ApiError {
    status: StatusCode,
    code: &'static str,
    /// What the caller is told.
    message: String,
    /// What the caller is NOT told: the underlying failure, logged instead.
    ///
    /// `Some` only for statuses that describe a fault on this side. A `4xx`
    /// message is about the caller's own request and is safe to return.
    internal: Option<String>,
}

#[derive(Serialize)]
struct ErrorBody<'a> {
    error: ErrorInner<'a>,
}

#[derive(Serialize)]
struct ErrorInner<'a> {
    code: &'a str,
    message: &'a str,
}

impl ApiError {
    /// A `401` for a missing/blank credential.
    pub fn unauthorized(message: impl Into<String>) -> Self {
        Self {
            status: StatusCode::UNAUTHORIZED,
            code: "unauthorized",
            message: message.into(),
            internal: None,
        }
    }

    /// A `501` for a capability this edge was not configured with.
    ///
    /// Used when BYOK is requested but no key-encryption key is set: the edge
    /// declines rather than falling back to storing a provider key in the
    /// clear. `501` rather than `503` because it will not start working on
    /// retry — it needs configuration.
    pub fn not_implemented(message: impl Into<String>) -> Self {
        Self {
            status: StatusCode::NOT_IMPLEMENTED,
            code: "not_implemented",
            message: message.into(),
            internal: None,
        }
    }

    /// A `409` for a request that conflicts with the tenant's current state.
    pub fn conflict(message: impl Into<String>) -> Self {
        Self {
            status: StatusCode::CONFLICT,
            code: "conflict",
            message: message.into(),
            internal: None,
        }
    }

    /// A `502` when an upstream the edge depends on could not be reached.
    ///
    /// The detail is deliberately thin: an upstream error can embed the request
    /// URL and headers, and for the LLM broker those headers carry a tenant's
    /// provider key.
    pub fn bad_gateway(message: impl Into<String>) -> Self {
        Self {
            status: StatusCode::BAD_GATEWAY,
            code: "upstream.error",
            message: message.into(),
            internal: None,
        }
    }

    /// A `409 llm_credential.missing` — this namespace has no provider key.
    ///
    /// Shares the code the data plane returns for the same condition (see
    /// `from_brain`), so one code means one thing whichever surface produced
    /// it, and a client's handling works against both.
    pub fn llm_credential_missing(message: impl Into<String>) -> Self {
        Self {
            status: StatusCode::CONFLICT,
            code: "llm_credential.missing",
            message: message.into(),
            internal: None,
        }
    }

    /// A `404` for a resource this tenant has not created.
    pub fn not_found(message: impl Into<String>) -> Self {
        Self {
            status: StatusCode::NOT_FOUND,
            code: "not_found",
            message: message.into(),
            internal: None,
        }
    }

    /// A `400` for a malformed request the edge itself rejects.
    pub fn bad_request(message: impl Into<String>) -> Self {
        Self {
            status: StatusCode::BAD_REQUEST,
            code: "bad_request",
            message: message.into(),
            internal: None,
        }
    }

    /// Map a Brain client error to the matching HTTP status. Transport faults and
    /// unavailable/exhausted verdicts are `503`; auth verdicts `401`/`403`;
    /// validation/not-found/conflict map directly; anything else is `502`.
    pub fn from_brain(err: &BrainError) -> Self {
        match err {
            BrainError::Io(_) | BrainError::Closed | BrainError::Timeout(_) => Self {
                status: StatusCode::SERVICE_UNAVAILABLE,
                code: "engine.unavailable",
                // The OS error text describes the edge's own connectivity, not
                // the caller's request.
                message: "the memory engine is unavailable; retry shortly".to_string(),
                internal: Some(format!("brain unavailable: {err}")),
            },
            // BYOK credential verdicts are matched on the CODE before the
            // category fan-out below, because the category alone cannot carry
            // them: `Conflict` is also an ordinary idempotency conflict, and
            // telling an operator to register a provider key they already hold
            // is worse than a generic error.
            BrainError::Server {
                code: ErrorCodeWire::LlmCredentialMissing,
                message,
                ..
            } => Self {
                // 409, deliberately NOT 503. The SDK retry lists are
                // `(0, 503)` — a 503 here would make every client retry
                // forever against a tenant that simply has not registered a
                // key. This condition cannot self-heal, so it must be a 4xx.
                status: StatusCode::CONFLICT,
                code: "llm_credential.missing",
                message: message.clone(),
                internal: None,
            },
            BrainError::Server {
                code: ErrorCodeWire::LlmCredentialUnavailable,
                message,
                ..
            } => Self {
                // 503 so clients DO retry: the key exists, the broker was
                // briefly unreachable. Collapsing this into the 409 above
                // would permanently fail writes for a healthy tenant.
                status: StatusCode::SERVICE_UNAVAILABLE,
                code: "llm_credential.unavailable",
                message: message.clone(),
                internal: None,
            },
            BrainError::Server {
                category, message, ..
            } => {
                let (status, code) = match category {
                    ErrorCategoryWire::Authentication => (StatusCode::UNAUTHORIZED, "unauthorized"),
                    ErrorCategoryWire::Authorization => (StatusCode::FORBIDDEN, "forbidden"),
                    ErrorCategoryWire::Unavailable | ErrorCategoryWire::ResourceExhausted => {
                        (StatusCode::SERVICE_UNAVAILABLE, "engine.unavailable")
                    }
                    ErrorCategoryWire::Validation => (StatusCode::BAD_REQUEST, "bad_request"),
                    ErrorCategoryWire::NotFound => (StatusCode::NOT_FOUND, "not_found"),
                    ErrorCategoryWire::Conflict => (StatusCode::CONFLICT, "conflict"),
                    ErrorCategoryWire::Protocol | ErrorCategoryWire::Internal => {
                        (StatusCode::BAD_GATEWAY, "engine.error")
                    }
                };
                // Brain's own message is about THIS caller's request, so it is
                // returned as-is for the statuses that describe the request.
                // The 5xx arms are the edge reporting its own trouble.
                let internal = if status.is_server_error() {
                    Some(format!("brain {category:?}: {message}"))
                } else {
                    None
                };
                Self {
                    status,
                    code,
                    message: if internal.is_some() {
                        "the memory engine returned an error".to_string()
                    } else {
                        message.clone()
                    },
                    internal,
                }
            }
            // Frame-codec faults, protocol violations, version mismatches: all
            // describe the edge's conversation with Brain, none describe the
            // caller's request.
            other => Self {
                status: StatusCode::BAD_GATEWAY,
                code: "engine.error",
                message: "the memory engine returned an error".to_string(),
                internal: Some(format!("brain error: {other}")),
            },
        }
    }
}

impl ApiError {
    /// A `500` for a fault the edge itself could not classify.
    #[must_use]
    pub fn internal(detail: impl Into<String>) -> Self {
        Self {
            status: StatusCode::INTERNAL_SERVER_ERROR,
            code: "internal",
            message: "internal error".to_string(),
            internal: Some(detail.into()),
        }
    }

    /// Emit the withheld detail to the log, where the request id ties it back
    /// to the response the caller saw. Called once, on the way out.
    fn log_internal(&self) {
        if let Some(detail) = &self.internal {
            tracing::warn!(
                status = self.status.as_u16(),
                code = self.code,
                detail = %detail,
                "request failed"
            );
        }
    }

    /// The HTTP status this error renders as (test/introspection).
    #[cfg(test)]
    #[must_use]
    pub const fn status(&self) -> StatusCode {
        self.status
    }

    /// The message the caller is told (test/introspection).
    #[cfg(test)]
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        self.log_internal();
        let body = ErrorBody {
            error: ErrorInner {
                code: self.code,
                message: &self.message,
            },
        };
        (self.status, Json(body)).into_response()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use brain_db_sdk::wire::types::{ErrorCodeWire, ErrorResponse};

    fn server(category: ErrorCategoryWire, message: &str) -> BrainError {
        BrainError::from_server(ErrorResponse {
            code: ErrorCodeWire::PermissionDenied,
            category,
            message: message.to_string(),
            details: None,
            retry_after_ms: None,
        })
    }

    fn server_with_code(
        code: ErrorCodeWire,
        category: ErrorCategoryWire,
        message: &str,
    ) -> BrainError {
        BrainError::from_server(ErrorResponse {
            code,
            category,
            message: message.to_string(),
            details: None,
            retry_after_ms: None,
        })
    }

    #[test]
    fn a_missing_llm_credential_is_a_409_not_a_503() {
        // The status choice is the contract. Every SDK's retry list is
        // `(0, 503)`, so mapping this to 503 would make clients retry forever
        // against a tenant that has simply not registered a provider key.
        let err = ApiError::from_brain(&server_with_code(
            ErrorCodeWire::LlmCredentialMissing,
            ErrorCategoryWire::Conflict,
            "no provider key registered for acme",
        ));
        assert_eq!(err.status(), StatusCode::CONFLICT);
        assert_eq!(err.code, "llm_credential.missing");
        assert_eq!(err.message(), "no provider key registered for acme");
        assert!(
            err.internal.is_none(),
            "this is about the caller's workspace, not the edge's own trouble"
        );
    }

    #[test]
    fn a_transient_credential_failure_is_a_503_so_clients_retry() {
        let err = ApiError::from_brain(&server_with_code(
            ErrorCodeWire::LlmCredentialUnavailable,
            ErrorCategoryWire::Unavailable,
            "credential broker unreachable",
        ));
        assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert_eq!(err.code, "llm_credential.unavailable");
    }

    #[test]
    fn an_ordinary_conflict_is_not_reported_as_a_missing_credential() {
        // `Conflict` also covers idempotency conflicts. Matching on category
        // alone would tell operators to configure a key they already have.
        let err = ApiError::from_brain(&server_with_code(
            ErrorCodeWire::IdempotencyConflict,
            ErrorCategoryWire::Conflict,
            "same request id, different body",
        ));
        assert_eq!(err.status(), StatusCode::CONFLICT);
        assert_eq!(err.code, "conflict");
    }

    #[test]
    fn a_4xx_returns_the_engine_message_because_it_is_about_this_request() {
        // Validation / not-found / conflict describe what the caller asked for,
        // so withholding the detail would only make the API harder to use.
        let err = ApiError::from_brain(&server(ErrorCategoryWire::Validation, "k must be 1..=100"));
        assert_eq!(err.status(), StatusCode::BAD_REQUEST);
        assert_eq!(err.message(), "k must be 1..=100");
        assert!(err.internal.is_none(), "nothing to withhold on a 4xx");
    }

    #[test]
    fn a_5xx_withholds_the_engine_message() {
        // `Internal` is the engine reporting its own trouble. Forwarding that
        // text tells the caller about the edge's conversation with its
        // database rather than about their request.
        let err = ApiError::from_brain(&server(
            ErrorCategoryWire::Internal,
            "shard 7 wal replay failed at lsn 918273",
        ));
        assert_eq!(err.status(), StatusCode::BAD_GATEWAY);
        assert!(
            !err.message().contains("shard 7") && !err.message().contains("lsn"),
            "internal state must not reach the caller, got: {}",
            err.message()
        );
        // Withheld, not discarded: it is logged with the request id.
        assert!(
            err.internal
                .as_deref()
                .unwrap_or_default()
                .contains("wal replay failed"),
            "the detail must still be available to the log"
        );
    }

    #[test]
    fn a_transport_fault_withholds_the_os_error() {
        // The OS text describes the edge's own connectivity to its backend.
        let err = ApiError::from_brain(&BrainError::Io(std::io::Error::from(
            std::io::ErrorKind::ConnectionRefused,
        )));
        assert_eq!(err.status(), StatusCode::SERVICE_UNAVAILABLE);
        assert!(
            !err.message().to_lowercase().contains("refused"),
            "the OS error must not reach the caller, got: {}",
            err.message()
        );
        assert!(err.internal.is_some(), "and must still reach the log");
    }

    #[test]
    fn a_protocol_fault_withholds_the_protocol_detail() {
        // Frame-codec faults and version mismatches are entirely about the
        // edge↔Brain link; a caller can do nothing with them.
        let err = ApiError::from_brain(&BrainError::Protocol(
            "expected WELCOME on stream 0, got 0x00FF".to_string(),
        ));
        assert_eq!(err.status(), StatusCode::BAD_GATEWAY);
        assert!(
            !err.message().contains("WELCOME") && !err.message().contains("0x00FF"),
            "protocol internals must not reach the caller, got: {}",
            err.message()
        );
        assert!(err.internal.is_some());
    }

    #[test]
    fn every_5xx_arm_withholds_something_and_every_4xx_arm_does_not() {
        // Exhaustive over the category table, so a new arm cannot be added
        // without a decision being made about what the caller is told.
        let categories = [
            ErrorCategoryWire::Protocol,
            ErrorCategoryWire::Authentication,
            ErrorCategoryWire::Authorization,
            ErrorCategoryWire::Validation,
            ErrorCategoryWire::NotFound,
            ErrorCategoryWire::Conflict,
            ErrorCategoryWire::ResourceExhausted,
            ErrorCategoryWire::Internal,
            ErrorCategoryWire::Unavailable,
        ];
        for category in categories {
            let err = ApiError::from_brain(&server(category, "engine detail"));
            assert_eq!(
                err.status().is_server_error(),
                err.internal.is_some(),
                "{category:?}: a 5xx must withhold, a 4xx must not"
            );
        }
    }
}