rok-core 0.6.0

Core primitives for the rok ecosystem — errors, crypto, i18n, config, DI, and more
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
use crate::rok_exception;
use thiserror::Error;

// ── RokError (legacy enum) ────────────────────────────────────────────────────

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum RokError {
    #[error("not found")]
    NotFound,

    #[error("forbidden")]
    Forbidden,

    #[cfg(feature = "orm")]
    #[error("database error: {0}")]
    Orm(sqlx::Error),

    #[error("internal server error: {0}")]
    Internal(String),
}

#[cfg(feature = "orm")]
impl From<sqlx::Error> for RokError {
    fn from(e: sqlx::Error) -> Self {
        match e {
            sqlx::Error::RowNotFound => Self::NotFound,
            other => Self::Orm(other),
        }
    }
}

impl From<String> for RokError {
    fn from(s: String) -> Self {
        Self::Internal(s)
    }
}

impl From<&str> for RokError {
    fn from(s: &str) -> Self {
        Self::Internal(s.to_string())
    }
}

#[cfg(feature = "axum")]
mod axum_impl {
    use super::RokError;
    use axum::{
        http::StatusCode,
        response::{IntoResponse, Response},
        Json,
    };

    impl IntoResponse for RokError {
        fn into_response(self) -> Response {
            match self {
                RokError::NotFound => {
                    (StatusCode::NOT_FOUND, Json(serde_json::json!({"message": "not found"}))).into_response()
                }
                RokError::Forbidden => {
                    (StatusCode::FORBIDDEN, Json(serde_json::json!({"message": "forbidden"}))).into_response()
                }
                #[cfg(feature = "orm")]
                RokError::Orm(e) => {
                    #[cfg(feature = "app")]
                    tracing::error!(error = %e, "Internal server error (ORM)");
                    (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"message": "internal server error"}))).into_response()
                }
                #[cfg(feature = "orm")]
                RokError::Internal(ref msg) => {
                    #[cfg(feature = "app")]
                    tracing::error!(error = %msg, "Internal server error");
                    (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"message": "internal server error"}))).into_response()
                }
                #[cfg(not(feature = "orm"))]
                RokError::Internal(ref msg) => {
                    #[cfg(feature = "app")]
                    tracing::error!(error = %msg, "Internal server error");
                    (StatusCode::INTERNAL_SERVER_ERROR, Json(serde_json::json!({"message": "internal server error"}))).into_response()
                }
            }
        }
    }
}

// ── RokException trait ────────────────────────────────────────────────────────

/// Base trait for all typed exceptions in the rok ecosystem.
///
/// Analogous to AdonisJS `Exception` — every crate exposes `E_*` structs
/// implementing this trait.  Self-handled exceptions can convert themselves
/// to an HTTP response; non-self-handled ones must be caught by a global
/// error handler.
pub trait RokException: std::error::Error + Send + Sync + 'static {
    /// Exception identifier (e.g. `"E_ROW_NOT_FOUND"`).
    fn name(&self) -> &'static str;
    /// HTTP status code.
    fn status_code(&self) -> u16;
    /// Whether this exception can produce its own HTTP response.
    fn self_handled(&self) -> bool {
        true
    }
    /// Optional i18n translation key.
    fn translation_id(&self) -> Option<&'static str> {
        None
    }
    /// Optional help text for debugging.
    fn help(&self) -> Option<&'static str> {
        None
    }
}

// ── Standard exceptions ──────────────────────────────────────────────────────

rok_exception! {
    /// Generic HTTP error. Can be instantiated with custom status and messages.
    pub struct E_HTTP_EXCEPTION {
        status = 500,
        self_handled = true,
        fields: {
            pub message: String,
        }
    }
}

rok_exception! {
    /// Raised when `Response::abort()` is called inside a handler.
    pub struct E_HTTP_REQUEST_ABORTED {
        status = 500,
        self_handled = true,
        fields: {
            pub message: String,
        }
    }
}

rok_exception! {
    /// Raised when the server receives a request for a non-existing route.
    pub struct E_ROUTE_NOT_FOUND {
        status = 404,
        self_handled = true,
        fields: {
            pub method: String,
            pub path: String,
        }
    }
}

rok_exception! {
    /// Raised when a route exists but the HTTP method does not match.
    pub struct E_METHOD_NOT_ALLOWED {
        status = 405,
        self_handled = true,
        fields: {
            pub method: String,
            pub path: String,
        }
    }
}

rok_exception! {
    /// Raised when attempting to generate a URL for a route name that does not exist.
    pub struct E_CANNOT_LOOKUP_ROUTE {
        status = 500,
        self_handled = false,
        fields: {
            pub route_name: String,
        }
    }
}

rok_exception! {
    /// Raised when a required route parameter is not present in the URL.
    pub struct E_MISSING_ROUTE_PARAM {
        status = 500,
        self_handled = false,
        fields: {
            pub param_name: String,
        }
    }
}

rok_exception! {
    /// Raised when `APP_KEY` length is less than 16 characters.
    pub struct E_INSECURE_APP_KEY {
        status = 500,
        self_handled = false,
        fields: {
            pub actual_length: usize,
        }
    }
}

rok_exception! {
    /// Raised when `APP_KEY` is not defined in config.
    pub struct E_MISSING_APP_KEY {
        status = 500,
        self_handled = false,
        fields: {
        }
    }
}

rok_exception! {
    /// Raised when one or more environment variables fail validation.
    pub struct E_INVALID_ENV_VARIABLES {
        status = 500,
        self_handled = false,
        fields: {
            pub help: String,
        }
    }
}

rok_exception! {
    /// Raised when a required config key is missing.
    pub struct E_MISSING_CONFIG_KEY {
        status = 500,
        self_handled = false,
        fields: {
            pub key: String,
        }
    }
}

rok_exception! {
    /// Raised when a config value cannot be parsed into the expected type.
    pub struct E_CONFIG_PARSE_ERROR {
        status = 500,
        self_handled = false,
        fields: {
            pub key: String,
            pub expected: String,
        }
    }
}

rok_exception! {
    /// Raised when attempting to write to a session opened in read-only mode.
    pub struct E_SESSION_NOT_MUTABLE {
        status = 500,
        self_handled = false,
        fields: {
        }
    }
}

rok_exception! {
    /// Raised when the session store is accessed before the session middleware has run.
    pub struct E_SESSION_NOT_READY {
        status = 500,
        self_handled = false,
        fields: {
        }
    }
}

// ── Box<dyn RokException> → axum IntoResponse ────────────────────────────────

#[cfg(feature = "axum")]
impl axum::response::IntoResponse for Box<dyn RokException> {
    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 = serde_json::json!({
            "error": self.name(),
            "message": self.to_string(),
            "statusCode": self.status_code(),
        });
        (status, axum::Json(body)).into_response()
    }
}

// ── rok_exception! macro ─────────────────────────────────────────────────────

/// Define a typed exception struct implementing [`RokException`].
///
/// Self-handled exceptions (default) also implement `axum::IntoResponse`
/// when the `axum` feature is enabled.
///
/// # Example
///
/// ```rust,ignore
/// use rok_core::rok_exception;
///
/// rok_exception! {
///     /// Raised when a query returns no rows.
///     pub struct E_ROW_NOT_FOUND {
///         status = 404,
///         self_handled = false,
///         fields: {
///             pub model: Option<&'static str>,
///             pub id: Option<String>,
///         },
///     }
/// }
/// ```
#[macro_export]
macro_rules! rok_exception {
    // ── Self-handled + translation ──────────────────────────────────────────
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            status = $status:expr,
            self_handled = true,
            translation = $translation:expr,
            fields: { $(pub $field:ident: $ty:ty),* $(,)? }
        }
    ) => {
        $(#[$meta])*
        #[allow(non_camel_case_types)]
        #[derive(Debug)]
        $vis struct $name {
            $(pub $field: $ty,)*
        }
        impl $name { $vis fn new($($field: $ty),*) -> Self { Self { $($field),* } } }
        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                use $crate::RokException;
                write!(f, concat!("{} (", stringify!($name), ")"), self.status_code())
            }
        }
        impl std::error::Error for $name {}
        impl $crate::error::RokException for $name {
            fn name(&self) -> &'static str { stringify!($name) }
            fn status_code(&self) -> u16 { $status }
            fn self_handled(&self) -> bool { true }
            fn translation_id(&self) -> Option<&'static str> { Some($translation) }
        }
        #[cfg(feature = "axum")]
        impl axum::response::IntoResponse for $name {
            fn into_response(self) -> axum::response::Response {
                let status = axum::http::StatusCode::from_u16($status)
                    .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
                let body = serde_json::json!({
                    "error": stringify!($name),
                    "message": self.to_string(),
                    "statusCode": $status,
                });
                (status, axum::Json(body)).into_response()
            }
        }
    };

    // ── Self-handled, no translation
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            status = $status:expr,
            self_handled = true,
            fields: { $(pub $field:ident: $ty:ty),* $(,)? }
        }
    ) => {
        $(#[$meta])*
        #[allow(non_camel_case_types)]
        #[derive(Debug)]
        $vis struct $name {
            $(pub $field: $ty,)*
        }
        impl $name { $vis fn new($($field: $ty),*) -> Self { Self { $($field),* } } }
        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                use $crate::RokException;
                write!(f, concat!("{} (", stringify!($name), ")"), self.status_code())
            }
        }
        impl std::error::Error for $name {}
        impl $crate::error::RokException for $name {
            fn name(&self) -> &'static str { stringify!($name) }
            fn status_code(&self) -> u16 { $status }
            fn self_handled(&self) -> bool { true }
            fn translation_id(&self) -> Option<&'static str> { None }
        }
        #[cfg(feature = "axum")]
        impl axum::response::IntoResponse for $name {
            fn into_response(self) -> axum::response::Response {
                let status = axum::http::StatusCode::from_u16($status)
                    .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
                let body = serde_json::json!({
                    "error": stringify!($name),
                    "message": self.to_string(),
                    "statusCode": $status,
                });
                (status, axum::Json(body)).into_response()
            }
        }
    };

    // ── Non-self-handled + translation ──────────────────────────────────────
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            status = $status:expr,
            self_handled = false,
            translation = $translation:expr,
            fields: { $(pub $field:ident: $ty:ty),* $(,)? }
        }
    ) => {
        $(#[$meta])*
        #[allow(non_camel_case_types)]
        #[derive(Debug)]
        $vis struct $name {
            $(pub $field: $ty,)*
        }
        impl $name { $vis fn new($($field: $ty),*) -> Self { Self { $($field),* } } }
        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                use $crate::RokException;
                write!(f, concat!("{} (", stringify!($name), ")"), self.status_code())
            }
        }
        impl std::error::Error for $name {}
        impl $crate::error::RokException for $name {
            fn name(&self) -> &'static str { stringify!($name) }
            fn status_code(&self) -> u16 { $status }
            fn self_handled(&self) -> bool { false }
            fn translation_id(&self) -> Option<&'static str> { Some($translation) }
        }
    };

    // ── Non-self-handled, no translation ────────────────────────────────────
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            status = $status:expr,
            self_handled = false,
            fields: { $(pub $field:ident: $ty:ty),* $(,)? }
        }
    ) => {
        $(#[$meta])*
        #[allow(non_camel_case_types)]
        #[derive(Debug)]
        $vis struct $name {
            $(pub $field: $ty,)*
        }
        impl $name { $vis fn new($($field: $ty),*) -> Self { Self { $($field),* } } }
        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                use $crate::RokException;
                write!(f, concat!("{} (", stringify!($name), ")"), self.status_code())
            }
        }
        impl std::error::Error for $name {}
        impl $crate::error::RokException for $name {
            fn name(&self) -> &'static str { stringify!($name) }
            fn status_code(&self) -> u16 { $status }
            fn self_handled(&self) -> bool { false }
            fn translation_id(&self) -> Option<&'static str> { None }
        }
    };

    // ── No self_handled (default = true, no translation) ────────────────────
    (
        $(#[$meta:meta])*
        $vis:vis struct $name:ident {
            status = $status:expr,
            fields: { $(pub $field:ident: $ty:ty),* $(,)? }
        }
    ) => {
        $(#[$meta])*
        #[allow(non_camel_case_types)]
        #[derive(Debug)]
        $vis struct $name {
            $(pub $field: $ty,)*
        }
        impl $name { $vis fn new($($field: $ty),*) -> Self { Self { $($field),* } } }
        impl std::fmt::Display for $name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                use $crate::RokException;
                write!(f, concat!("{} (", stringify!($name), ")"), self.status_code())
            }
        }
        impl std::error::Error for $name {}
        impl $crate::error::RokException for $name {
            fn name(&self) -> &'static str { stringify!($name) }
            fn status_code(&self) -> u16 { $status }
            fn self_handled(&self) -> bool { true }
            fn translation_id(&self) -> Option<&'static str> { None }
        }
        #[cfg(feature = "axum")]
        impl axum::response::IntoResponse for $name {
            fn into_response(self) -> axum::response::Response {
                let status = axum::http::StatusCode::from_u16($status)
                    .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR);
                let body = serde_json::json!({
                    "error": stringify!($name),
                    "message": self.to_string(),
                    "statusCode": $status,
                });
                (status, axum::Json(body)).into_response()
            }
        }
    };
}