krab_core 0.2.0

Shared runtime for the Krab framework: config, HTTP, database, telemetry, resilience, signals, and protocol governance
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
//! # Server Functions (`#[server]`)
//!
//! Server functions allow you to write async functions that run on the server
//! and can be called transparently from the client (WASM) via RPC.
//!
//! ## Usage
//!
//! ```rust
//! use krab_core::server_fn::ServerFnError;
//! use krab_macros::server;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize)]
//! pub struct User {
//!     pub id: String,
//!     pub name: String,
//! }
//!
//! #[server]
//! pub async fn get_user(id: String) -> Result<User, ServerFnError> {
//!     find_user(&id).await.map_err(|e| ServerFnError::new(e.to_string()))
//! }
//!
//! # async fn find_user(id: &str) -> Result<User, std::io::Error> {
//! #     Ok(User { id: id.to_string(), name: "Ada".to_string() })
//! # }
//! ```
//!
//! On the server, this keeps the function as-is and generates an Axum handler.
//! On the client (WASM), the body is replaced with a `fetch` call to `/api/rpc/get_user`.
//!
//! Once a generated handler is mounted, the server function is a public HTTP POST endpoint.
//! Validate all inputs and enforce auth inside the function or in the mounted router stack.

use serde::{Deserialize, Serialize};
use std::future::Future;
use std::pin::Pin;

// ── Error Type ──────────────────────────────────────────────────────────────

/// Stable error category carried over the server-function wire contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ServerFnErrorCode {
    BadRequest,
    Validation,
    Unauthorized,
    Forbidden,
    NotFound,
    Conflict,
    Internal,
}

fn default_error_code() -> ServerFnErrorCode {
    ServerFnErrorCode::Internal
}

/// Error type returned by server functions.
///
/// Implements `Serialize`/`Deserialize` for wire transport, and converts
/// into an Axum response when used on the server side.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerFnError {
    /// Human-readable error message.
    pub message: String,
    /// HTTP status code for the error response.
    #[serde(default = "default_status")]
    pub status_code: u16,
    /// Stable machine-readable error category.
    #[serde(default = "default_error_code")]
    pub code: ServerFnErrorCode,
}

/// Wire response envelope emitted by server-function HTTP handlers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerFnErrorEnvelope {
    /// Legacy-compatible error string.
    pub error: String,
    /// Canonical error message.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    /// HTTP status code for the error response.
    #[serde(default = "default_status")]
    pub status_code: u16,
    /// Stable machine-readable error category.
    #[serde(default = "default_error_code")]
    pub code: ServerFnErrorCode,
}

impl From<ServerFnError> for ServerFnErrorEnvelope {
    fn from(err: ServerFnError) -> Self {
        Self {
            error: err.message.clone(),
            message: Some(err.message),
            status_code: err.status_code,
            code: err.code,
        }
    }
}

impl From<ServerFnErrorEnvelope> for ServerFnError {
    fn from(envelope: ServerFnErrorEnvelope) -> Self {
        Self {
            message: envelope.message.unwrap_or(envelope.error),
            status_code: envelope.status_code,
            code: envelope.code,
        }
    }
}

fn default_status() -> u16 {
    500
}

impl std::fmt::Display for ServerFnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ServerFnError({}): {}", self.status_code, self.message)
    }
}

impl std::error::Error for ServerFnError {}

impl ServerFnError {
    fn with_code(message: impl Into<String>, status_code: u16, code: ServerFnErrorCode) -> Self {
        Self {
            message: message.into(),
            status_code,
            code,
        }
    }

    /// Create a new server error with HTTP 500.
    pub fn new(message: impl Into<String>) -> Self {
        Self::with_code(message, 500, ServerFnErrorCode::Internal)
    }

    /// Create a bad request error (HTTP 400).
    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::with_code(message, 400, ServerFnErrorCode::BadRequest)
    }

    /// Create a validation error (HTTP 400).
    pub fn validation(message: impl Into<String>) -> Self {
        Self::with_code(message, 400, ServerFnErrorCode::Validation)
    }

    /// Create an unauthorized error (HTTP 401).
    pub fn unauthorized(message: impl Into<String>) -> Self {
        Self::with_code(message, 401, ServerFnErrorCode::Unauthorized)
    }

    /// Create a forbidden error (HTTP 403).
    pub fn forbidden(message: impl Into<String>) -> Self {
        Self::with_code(message, 403, ServerFnErrorCode::Forbidden)
    }

    /// Create a not found error (HTTP 404).
    pub fn not_found(message: impl Into<String>) -> Self {
        Self::with_code(message, 404, ServerFnErrorCode::NotFound)
    }

    /// Create a conflict error (HTTP 409).
    pub fn conflict(message: impl Into<String>) -> Self {
        Self::with_code(message, 409, ServerFnErrorCode::Conflict)
    }

    /// Create an error from an HTTP status code, preserving the closest known category.
    pub fn from_status(status_code: u16, message: impl Into<String>) -> Self {
        let code = match status_code {
            400 => ServerFnErrorCode::BadRequest,
            401 => ServerFnErrorCode::Unauthorized,
            403 => ServerFnErrorCode::Forbidden,
            404 => ServerFnErrorCode::NotFound,
            409 => ServerFnErrorCode::Conflict,
            _ => ServerFnErrorCode::Internal,
        };
        Self::with_code(message, status_code, code)
    }
}

/// Return a validation error when a server-function precondition is false.
pub fn validate_server_fn(
    condition: bool,
    message: impl Into<String>,
) -> Result<(), ServerFnError> {
    if condition {
        Ok(())
    } else {
        Err(ServerFnError::validation(message))
    }
}

/// Require an authenticated caller before running a server-function mutation.
pub fn require_server_fn_auth(
    authenticated: bool,
    message: impl Into<String>,
) -> Result<(), ServerFnError> {
    if authenticated {
        Ok(())
    } else {
        Err(ServerFnError::unauthorized(message))
    }
}

/// Require a caller scope before running a protected server function.
pub fn require_server_fn_scope<I, S>(scopes: I, required: &str) -> Result<(), ServerFnError>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    if scopes.into_iter().any(|scope| scope.as_ref() == required) {
        Ok(())
    } else {
        Err(ServerFnError::forbidden(format!(
            "missing required scope '{required}'"
        )))
    }
}

/// Decode a server-function error response body into the canonical error type.
pub fn decode_server_fn_error_body(body: &str, fallback_status_code: u16) -> ServerFnError {
    if let Ok(envelope) = serde_json::from_str::<ServerFnErrorEnvelope>(body) {
        return envelope.into();
    }
    if let Ok(err) = serde_json::from_str::<ServerFnError>(body) {
        return err;
    }
    ServerFnError::from_status(fallback_status_code, body)
}

impl From<serde_json::Error> for ServerFnError {
    fn from(err: serde_json::Error) -> Self {
        Self::bad_request(format!("serialization error: {}", err))
    }
}

impl From<anyhow::Error> for ServerFnError {
    fn from(err: anyhow::Error) -> Self {
        Self::new(err.to_string())
    }
}

// ── Axum Integration (server side) ──────────────────────────────────────────

#[cfg(feature = "rest")]
impl axum::response::IntoResponse for ServerFnError {
    fn into_response(self) -> axum::response::Response {
        let status = axum::http::StatusCode::from_u16(self.status_code)
            .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
        let body = ServerFnErrorEnvelope::from(self);
        (status, axum::Json(body)).into_response()
    }
}

// ── Registration ────────────────────────────────────────────────────────────

/// Type alias for server function handler.
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;

/// A registered server function entry point.
///
/// Two variants, selected by feature. The `rest` form carries the dispatch
/// handler; the client form is metadata only, because a browser build has no
/// axum `Response` to hand back. Previously only the field was gated while the
/// struct itself was not, so with `rest` off both definitions landed in the same
/// namespace — invisible while the whole module was gated behind `rest`, and an
/// immediate `E0428` once it was not.
#[cfg(feature = "rest")]
pub struct ServerFnRegistration {
    /// Function name (snake_case).
    pub name: &'static str,
    /// URL path for this function (e.g., `/api/rpc/get_user`).
    pub url: &'static str,
    /// Handler that accepts JSON args and returns an Axum response (can be streaming).
    pub handler: fn(serde_json::Value) -> BoxFuture<axum::response::Response>,
}

/// Client-side registration metadata. See the `rest` variant above.
#[cfg(not(feature = "rest"))]
pub struct ServerFnRegistration {
    /// Function name (snake_case).
    pub name: &'static str,
    /// URL path for this function (e.g., `/api/rpc/get_user`).
    pub url: &'static str,
}

const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<ServerFnRegistration>();
};

/// Compile-time metadata for a server function.
///
/// `#[server]` generates a hidden marker type named after the annotated
/// function and implements this trait for it. The marker lives only in the type
/// namespace (it is declared as `struct name {}`), so it coexists with the
/// function of the same name in the value namespace.
///
/// This is what lets [`collect_server_fns!`](crate::collect_server_fns) build a
/// registration table from bare function names without concatenating
/// identifiers — something `macro_rules!` cannot do on its own.
#[cfg(feature = "rest")]
pub trait ServerFn {
    /// The function name, as written in the source.
    const NAME: &'static str;
    /// The URL the generated handler is mounted at.
    const URL: &'static str;
    /// Decode JSON arguments, invoke the function, and encode the response.
    fn dispatch(args: serde_json::Value) -> BoxFuture<axum::response::Response>;
}

/// Build an Axum router from a list of server function registrations.
///
/// Each registration is mounted at its declared URL as a POST endpoint.
///
/// # Example
///
/// ```rust
/// use krab_core::collect_server_fns;
/// use krab_core::server_fn::{server_fn_router, ServerFn, ServerFnError, ServerFnRegistration};
/// use krab_macros::server;
///
/// #[server]
/// pub async fn get_user(id: String) -> Result<String, ServerFnError> {
///     Ok(format!("user:{id}"))
/// }
///
/// static SERVER_FNS: &[ServerFnRegistration] = &collect_server_fns![get_user];
///
/// let rpc_routes = server_fn_router(SERVER_FNS);
///
/// let app: axum::Router = axum::Router::new()
///     .merge(rpc_routes)
///     .route("/health", axum::routing::get(|| async { "ok" }));
/// ```
#[cfg(feature = "rest")]
pub fn server_fn_router(registrations: &'static [ServerFnRegistration]) -> axum::Router {
    use axum::routing::post;

    let mut router = axum::Router::new();
    for reg in registrations {
        let handler = reg.handler;
        router = router.route(
            reg.url,
            post(
                move |axum::Json(args): axum::Json<serde_json::Value>| async move {
                    handler(args).await
                },
            ),
        );
    }
    router
}

/// Build a catch-all RPC dispatcher that routes `/api/rpc/:fn_name` to
/// matching registrations.
///
/// This is an alternative to `server_fn_router` for simpler wiring.
#[cfg(feature = "rest")]
pub fn server_fn_dispatch_router(registrations: &'static [ServerFnRegistration]) -> axum::Router {
    router_with_dispatch(registrations)
}

#[cfg(feature = "rest")]
fn router_with_dispatch(registrations: &'static [ServerFnRegistration]) -> axum::Router {
    use axum::extract::Path;
    use axum::response::IntoResponse;

    axum::Router::new().route(
        "/api/rpc/{fn_name}",
        axum::routing::post(
            move |Path(fn_name): Path<String>,
                  axum::Json(args): axum::Json<serde_json::Value>| async move {
                for reg in registrations {
                    if reg.name == fn_name {
                        return (reg.handler)(args).await;
                    }
                }
                ServerFnError::not_found(format!("server function '{}' not found", fn_name))
                    .into_response()
            },
        ),
    )
}

// ── Client-Side Call (WASM) ─────────────────────────────────────────────────

/// Call a server function from the client (WASM) via fetch.
///
/// This is used by the `#[server]` macro in the WASM client stub.
#[cfg(target_arch = "wasm32")]
pub async fn call_server_fn<A: Serialize, T: serde::de::DeserializeOwned>(
    url: &str,
    args: &A,
) -> Result<T, ServerFnError> {
    use wasm_bindgen::JsCast;
    use wasm_bindgen_futures::JsFuture;

    let window = web_sys::window().ok_or_else(|| ServerFnError::new("no window object"))?;
    let body = serde_json::to_string(args).map_err(|e| ServerFnError::new(e.to_string()))?;

    let opts = web_sys::RequestInit::new();
    opts.set_method("POST");
    opts.set_body(&wasm_bindgen::JsValue::from_str(&body));

    let request = web_sys::Request::new_with_str_and_init(url, &opts)
        .map_err(|_| ServerFnError::new("failed to create request"))?;
    request
        .headers()
        .set("Content-Type", "application/json")
        .map_err(|_| ServerFnError::new("failed to set content-type"))?;

    // Propagate a CSRF token if the server issues them. The CSRF cookie is
    // `HttpOnly` by design, so it can never be read from `document.cookie` —
    // the token endpoint returns the token in its JSON body and sets the
    // matching cookie on that same response, which the browser attaches to
    // this request automatically. Header and cookie names are the shared
    // constants in [`crate::csrf`], so client and middleware cannot drift.
    if let Some(token) = fetch_csrf_token(&window).await {
        let _ = request.headers().set(crate::csrf::CSRF_HEADER_NAME, &token);
    }

    let resp_value = JsFuture::from(window.fetch_with_request(&request))
        .await
        .map_err(|_| ServerFnError::new("fetch failed"))?;

    let resp: web_sys::Response = resp_value
        .dyn_into()
        .map_err(|_| ServerFnError::new("response cast failed"))?;

    let text = JsFuture::from(
        resp.text()
            .map_err(|_| ServerFnError::new("failed to read response body"))?,
    )
    .await
    .map_err(|_| ServerFnError::new("failed to await response text"))?;

    let text_str = text
        .as_string()
        .ok_or_else(|| ServerFnError::new("response is not a string"))?;

    if resp.ok() {
        serde_json::from_str(&text_str).map_err(|e| ServerFnError::new(e.to_string()))
    } else {
        // Try to parse server error
        Err(decode_server_fn_error_body(&text_str, resp.status()))
    }
}

/// Fetch a CSRF token from [`crate::csrf::CSRF_TOKEN_ENDPOINT_PATH`].
///
/// Returns `None` when the endpoint is not mounted (404), unreachable, or the
/// body does not carry [`crate::csrf::CSRF_TOKEN_JSON_FIELD`] — in which case
/// the call proceeds without a CSRF header, exactly as before for deployments
/// that do not enable CSRF protection.
#[cfg(target_arch = "wasm32")]
async fn fetch_csrf_token(window: &web_sys::Window) -> Option<String> {
    use wasm_bindgen::JsCast;
    use wasm_bindgen_futures::JsFuture;

    let opts = web_sys::RequestInit::new();
    opts.set_method("GET");

    let request =
        web_sys::Request::new_with_str_and_init(crate::csrf::CSRF_TOKEN_ENDPOINT_PATH, &opts)
            .ok()?;

    let resp_value = JsFuture::from(window.fetch_with_request(&request))
        .await
        .ok()?;
    let resp: web_sys::Response = resp_value.dyn_into().ok()?;
    if !resp.ok() {
        return None;
    }

    let text = JsFuture::from(resp.text().ok()?).await.ok()?;
    let text = text.as_string()?;
    let parsed: serde_json::Value = serde_json::from_str(&text).ok()?;
    parsed
        .get(crate::csrf::CSRF_TOKEN_JSON_FIELD)?
        .as_str()
        .map(ToString::to_string)
}

/// Native client-side call path for non-WASM targets.
#[cfg(not(target_arch = "wasm32"))]
pub async fn call_server_fn<A: Serialize, T: serde::de::DeserializeOwned>(
    url: &str,
    args: &A,
) -> Result<T, ServerFnError> {
    let client = reqwest::Client::new();
    let response = client
        .post(url)
        .json(args)
        .send()
        .await
        .map_err(|err| ServerFnError::new(format!("request failed: {err}")))?;

    let status = response.status();
    let body = response
        .text()
        .await
        .map_err(|err| ServerFnError::new(format!("failed to read response body: {err}")))?;

    if status.is_success() {
        serde_json::from_str(&body)
            .map_err(|err| ServerFnError::new(format!("invalid success payload: {err}")))
    } else {
        Err(decode_server_fn_error_body(&body, status.as_u16()))
    }
}

// ── Convenience Macro ───────────────────────────────────────────────────────

/// Collect server function registrations into an array.
///
/// Takes the bare names of `#[server]`-annotated functions and resolves each
/// one's name, URL, and dispatch handler through the
/// [`ServerFn`](crate::server_fn::ServerFn) marker type that `#[server]`
/// generates. Requires the `rest` feature.
///
/// # Example
///
/// ```rust
/// use krab_core::collect_server_fns;
/// use krab_core::server_fn::{ServerFn, ServerFnError};
/// use krab_macros::server;
///
/// #[server]
/// pub async fn get_user(id: String) -> Result<String, ServerFnError> {
///     Ok(format!("user:{id}"))
/// }
///
/// #[server]
/// pub async fn list_items() -> Result<Vec<String>, ServerFnError> {
///     Ok(vec!["a".to_string()])
/// }
///
/// static SERVER_FNS: &[krab_core::server_fn::ServerFnRegistration] =
///     &collect_server_fns![get_user, list_items];
///
/// assert_eq!(SERVER_FNS.len(), 2);
/// assert_eq!(SERVER_FNS[0].name, "get_user");
/// assert_eq!(SERVER_FNS[0].url, "/api/rpc/get_user");
/// ```
#[macro_export]
macro_rules! collect_server_fns {
    ($($fn_name:ident),* $(,)?) => {
        [
            $($crate::server_fn::ServerFnRegistration {
                name: <$fn_name as $crate::server_fn::ServerFn>::NAME,
                url: <$fn_name as $crate::server_fn::ServerFn>::URL,
                handler: <$fn_name as $crate::server_fn::ServerFn>::dispatch,
            }),*
        ]
    };
}

// ── Tests ───────────────────────────────────────────────────────────────────

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

    #[test]
    fn server_fn_error_display() {
        let err = ServerFnError::new("something went wrong");
        assert_eq!(err.to_string(), "ServerFnError(500): something went wrong");
        assert_eq!(err.status_code, 500);
    }

    #[test]
    fn server_fn_error_constructors() {
        assert_eq!(ServerFnError::bad_request("bad").status_code, 400);
        assert_eq!(
            ServerFnError::validation("bad input").code,
            ServerFnErrorCode::Validation
        );
        assert_eq!(ServerFnError::unauthorized("no").status_code, 401);
        assert_eq!(ServerFnError::forbidden("denied").status_code, 403);
        assert_eq!(ServerFnError::not_found("gone").status_code, 404);
        assert_eq!(ServerFnError::conflict("dup").status_code, 409);
    }

    #[test]
    fn server_fn_error_serialization() {
        let err = ServerFnError::bad_request("invalid input");
        let json = serde_json::to_string(&err).unwrap();
        let parsed: ServerFnError = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.message, "invalid input");
        assert_eq!(parsed.status_code, 400);
        assert_eq!(parsed.code, ServerFnErrorCode::BadRequest);
    }

    #[test]
    fn server_fn_error_deserializes_legacy_error_envelope() {
        let parsed =
            decode_server_fn_error_body(r#"{"error":"invalid payload","status_code":400}"#, 500);
        assert_eq!(parsed.message, "invalid payload");
        assert_eq!(parsed.status_code, 400);
        assert_eq!(parsed.code, ServerFnErrorCode::Internal);
    }

    #[test]
    fn server_fn_error_envelope_is_client_deserializable() {
        let envelope = ServerFnErrorEnvelope::from(ServerFnError::validation("missing field"));
        let json = serde_json::to_string(&envelope).unwrap();
        let parsed = decode_server_fn_error_body(&json, 500);

        assert_eq!(parsed.message, "missing field");
        assert_eq!(parsed.status_code, 400);
        assert_eq!(parsed.code, ServerFnErrorCode::Validation);
    }

    #[test]
    fn validation_and_auth_helpers_return_typed_errors() {
        assert!(validate_server_fn(true, "ok").is_ok());
        let validation = validate_server_fn(false, "name is required").unwrap_err();
        assert_eq!(validation.status_code, 400);
        assert_eq!(validation.code, ServerFnErrorCode::Validation);

        let unauthorized = require_server_fn_auth(false, "login required").unwrap_err();
        assert_eq!(unauthorized.status_code, 401);
        assert_eq!(unauthorized.code, ServerFnErrorCode::Unauthorized);

        let forbidden = require_server_fn_scope(["users:read"], "users:write").unwrap_err();
        assert_eq!(forbidden.status_code, 403);
        assert_eq!(forbidden.code, ServerFnErrorCode::Forbidden);
    }

    #[test]
    fn server_fn_error_from_anyhow() {
        let anyhow_err = anyhow::anyhow!("something failed");
        let err: ServerFnError = anyhow_err.into();
        assert_eq!(err.status_code, 500);
        assert!(err.message.contains("something failed"));
    }

    #[test]
    fn server_fn_error_from_serde() {
        let serde_err = serde_json::from_str::<String>("not valid json").unwrap_err();
        let err: ServerFnError = serde_err.into();
        assert_eq!(err.status_code, 400);
        assert!(err.message.contains("serialization error"));
    }
}