noema-actix-webapi 0.1.0

Actix-web backend runtime on Noema (modules, sqlx, UoW, swagger, WebSocket dispatch)
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
use std::future::{Ready, ready};
use std::marker::PhantomData;
use std::rc::Rc;
use std::sync::Arc;
use std::task::{Context, Poll};

use actix_web::body::{EitherBody, MessageBody};
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::http::StatusCode;
use actix_web::{Error as ActixError, HttpRequest, HttpResponse};
use futures::future::LocalBoxFuture;
use noema::core::{Container, Resolver};
use tracing::Instrument;
use uuid::Uuid;

pub const IDEMPOTENCY_HEADER: &str = "Idempotency-Key";

/// Reject the HTTP request before the handler (invalid token, etc.).
#[derive(Debug, Clone)]
pub struct RequestError {
    status: StatusCode,
    message: String,
}

impl RequestError {
    pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
        Self {
            status,
            message: message.into(),
        }
    }

    pub fn unauthorized(message: impl Into<String>) -> Self {
        Self::new(StatusCode::UNAUTHORIZED, message)
    }

    pub fn forbidden(message: impl Into<String>) -> Self {
        Self::new(StatusCode::FORBIDDEN, message)
    }

    pub fn bad_request(message: impl Into<String>) -> Self {
        Self::new(StatusCode::BAD_REQUEST, message)
    }

    pub fn status(&self) -> StatusCode {
        self.status
    }

    pub fn message(&self) -> &str {
        &self.message
    }

    pub fn into_response(self) -> HttpResponse {
        HttpResponse::build(self.status).body(self.message)
    }
}

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

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

const REQUEST_NOT_BOUND: &str =
    "RequestContext not bound; wrap with request_context::<T>() or inject a test double";

/// App-defined extra hung on [`RequestContext`]. Use `()` when you only need id + idempotency.
///
/// `?Send`: the wrap runs on Actix’s worker thread (`HttpRequest` is `Rc`).
#[async_trait::async_trait(?Send)]
pub trait RequestExtra: Clone + Send + Sync + 'static {
    async fn from_request(req: &HttpRequest) -> Result<Self, RequestError>;
}

#[async_trait::async_trait(?Send)]
impl RequestExtra for () {
    async fn from_request(_req: &HttpRequest) -> Result<Self, RequestError> {
        Ok(())
    }
}

/// Injectable HTTP request port. Production: `resolve::<dyn RequestContext<T> + Send + Sync>()`
/// (reads the task-local bound by [`request_context`]). Tests: pass your own impl.
pub trait RequestContext<T: RequestExtra>: Send + Sync {
    fn id(&self) -> Uuid;
    fn idempotency_key(&self) -> Option<String>;
    fn extra(&self) -> T;
}

/// Snapshot bound for one HTTP request. Also a [`RequestContext`] you can inject in unit tests.
#[derive(Clone)]
pub struct RequestScope<T: RequestExtra> {
    id: Uuid,
    idempotency_key: Option<String>,
    extra: T,
}

impl<T: RequestExtra> RequestScope<T> {
    pub fn new(id: Uuid, idempotency_key: Option<String>, extra: T) -> Self {
        Self {
            id,
            idempotency_key,
            extra,
        }
    }

    /// Bound only inside a request wrapped with [`request_context`].
    /// `T` must be the same type as that wrap — one extra per request, no type tag.
    pub fn get() -> Option<Self> {
        CURRENT
            .try_with(|slot| {
                // SAFETY: `with_request::<T>` stored `RequestScope<T>`. This task binds one extra.
                let ctx = unsafe { &*(slot.ptr as *const RequestScope<T>) };
                ctx.clone()
            })
            .ok()
    }

    pub fn id(&self) -> Uuid {
        self.id
    }

    pub fn idempotency_key(&self) -> Option<&str> {
        self.idempotency_key.as_deref()
    }

    pub fn extra(&self) -> &T {
        &self.extra
    }
}

impl<T: RequestExtra> RequestContext<T> for RequestScope<T> {
    fn id(&self) -> Uuid {
        self.id
    }

    fn idempotency_key(&self) -> Option<String> {
        self.idempotency_key.clone()
    }

    fn extra(&self) -> T {
        self.extra.clone()
    }
}

struct AmbientRequestContext<T>(PhantomData<fn() -> T>);

impl<T: RequestExtra> RequestContext<T> for AmbientRequestContext<T> {
    fn id(&self) -> Uuid {
        RequestScope::<T>::get().expect(REQUEST_NOT_BOUND).id()
    }

    fn idempotency_key(&self) -> Option<String> {
        RequestScope::<T>::get()
            .expect(REQUEST_NOT_BOUND)
            .idempotency_key
    }

    fn extra(&self) -> T {
        RequestScope::<T>::get().expect(REQUEST_NOT_BOUND).extra
    }
}

impl<T: RequestExtra> Resolver<dyn RequestContext<T> + Send + Sync> for Container {
    fn resolve() -> Arc<dyn RequestContext<T> + Send + Sync> {
        Arc::new(AmbientRequestContext(PhantomData))
    }
}

#[derive(Clone, Copy)]
struct Slot {
    ptr: usize,
}

tokio::task_local! {
    static CURRENT: Slot;
}

async fn with_request<T, F, R>(ctx: &RequestScope<T>, fut: F) -> R
where
    T: RequestExtra,
    F: std::future::Future<Output = R>,
{
    let slot = Slot {
        ptr: ctx as *const RequestScope<T> as usize,
    };
    CURRENT.scope(slot, fut).await
}

/// Opt-in Actix wrap: `.wrap(request_context::<T>())`.
pub fn request_context<T: RequestExtra>() -> RequestContextTransform<T> {
    RequestContextTransform(PhantomData)
}

pub struct RequestContextTransform<T>(PhantomData<T>);

impl<S, B, T> Transform<S, ServiceRequest> for RequestContextTransform<T>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    S::Future: 'static,
    B: MessageBody + 'static,
    T: RequestExtra,
{
    type Response = ServiceResponse<EitherBody<B>>;
    type Error = ActixError;
    type InitError = ();
    type Transform = RequestContextMiddleware<S, T>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(RequestContextMiddleware {
            service: Rc::new(service),
            _t: PhantomData,
        }))
    }
}

pub struct RequestContextMiddleware<S, T> {
    service: Rc<S>,
    _t: PhantomData<T>,
}

impl<S, B, T> Service<ServiceRequest> for RequestContextMiddleware<S, T>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
    S::Future: 'static,
    B: MessageBody + 'static,
    T: RequestExtra,
{
    type Response = ServiceResponse<EitherBody<B>>;
    type Error = ActixError;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&self, req: ServiceRequest) -> Self::Future {
        let service = Rc::clone(&self.service);
        Box::pin(async move {
            let extra = match T::from_request(req.request()).await {
                Ok(extra) => extra,
                Err(err) => {
                    let res = crate::cors::apply_cors(req.request(), err.into_response());
                    return Ok(req.into_response(res).map_into_right_body());
                }
            };
            let idempotency_key = req
                .headers()
                .get(IDEMPOTENCY_HEADER)
                .and_then(|v| v.to_str().ok())
                .filter(|s| !s.is_empty())
                .map(str::to_string);
            let ctx = RequestScope {
                id: Uuid::now_v7(),
                idempotency_key,
                extra,
            };
            let request_id = ctx.id();
            with_request(
                &ctx,
                async move { service.call(req).await }.instrument(tracing::info_span!(
                    "http.request",
                    request_id = %request_id
                )),
            )
            .await
            .map(|res| res.map_into_left_body())
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::{App, HttpResponse, http::StatusCode, test, web};
    use std::sync::Arc;

    async fn echo_id() -> HttpResponse {
        let ctx = RequestScope::<()>::get().expect("bound");
        HttpResponse::Ok().body(ctx.id().to_string())
    }

    async fn echo_key() -> HttpResponse {
        let ctx = RequestScope::<()>::get().expect("bound");
        HttpResponse::Ok().body(ctx.idempotency_key().unwrap_or("").to_string())
    }

    #[actix_web::test]
    async fn get_is_none_without_wrap() {
        async fn inner() -> HttpResponse {
            assert!(RequestScope::<()>::get().is_none());
            HttpResponse::Ok().finish()
        }
        let srv = test::init_service(App::new().route("/", web::get().to(inner))).await;
        let resp = test::call_service(&srv, test::TestRequest::get().uri("/").to_request()).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[actix_web::test]
    async fn wrap_binds_id_and_idempotency_key() {
        let srv = test::init_service(
            App::new()
                .wrap(request_context::<()>())
                .route("/id", web::get().to(echo_id))
                .route("/key", web::get().to(echo_key)),
        )
        .await;

        let id_resp =
            test::call_service(&srv, test::TestRequest::get().uri("/id").to_request()).await;
        assert_eq!(id_resp.status(), StatusCode::OK);

        let key_req = test::TestRequest::get()
            .uri("/key")
            .insert_header((IDEMPOTENCY_HEADER, "abc-1"))
            .to_request();
        let key_resp = test::call_service(&srv, key_req).await;
        assert_eq!(key_resp.status(), StatusCode::OK);
        let body = test::read_body(key_resp).await;
        assert_eq!(body, "abc-1");
    }

    #[derive(Clone)]
    struct Flag(u8);

    #[async_trait::async_trait(?Send)]
    impl RequestExtra for Flag {
        async fn from_request(_req: &HttpRequest) -> Result<Self, RequestError> {
            Ok(Flag(7))
        }
    }

    #[actix_web::test]
    async fn extra_is_typed() {
        async fn inner() -> HttpResponse {
            let ctx = RequestScope::<Flag>::get().expect("flag");
            assert_eq!(ctx.extra().0, 7);
            HttpResponse::Ok().finish()
        }
        let srv = test::init_service(
            App::new()
                .wrap(request_context::<Flag>())
                .route("/", web::get().to(inner)),
        )
        .await;
        let resp = test::call_service(&srv, test::TestRequest::get().uri("/").to_request()).await;
        assert_eq!(resp.status(), StatusCode::OK);
    }

    #[derive(Clone)]
    struct Denied;

    #[async_trait::async_trait(?Send)]
    impl RequestExtra for Denied {
        async fn from_request(_req: &HttpRequest) -> Result<Self, RequestError> {
            Err(RequestError::unauthorized("nope"))
        }
    }

    #[actix_web::test]
    async fn from_request_err_skips_handler() {
        async fn inner() -> HttpResponse {
            panic!("handler must not run");
        }
        let srv = test::init_service(
            App::new()
                .wrap(request_context::<Denied>())
                .route("/", web::get().to(inner)),
        )
        .await;
        let resp = test::call_service(&srv, test::TestRequest::get().uri("/").to_request()).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[actix_web::test]
    async fn from_request_err_gets_acao_when_cors_is_outer() {
        async fn inner() -> HttpResponse {
            panic!("handler must not run");
        }
        let cfg = crate::config::CorsConfig {
            origins: vec!["*".into()],
            ..crate::config::CorsConfig::default()
        };
        let srv = test::init_service(
            App::new()
                .wrap(request_context::<Denied>())
                .wrap(crate::cors::cors_from(&cfg))
                .route("/", web::get().to(inner)),
        )
        .await;
        let req = test::TestRequest::get()
            .uri("/")
            .insert_header((actix_web::http::header::ORIGIN, "http://localhost:8080"))
            .to_request();
        let resp = test::call_service(&srv, req).await;
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(
            resp.headers()
                .get(actix_web::http::header::ACCESS_CONTROL_ALLOW_ORIGIN)
                .unwrap(),
            "http://localhost:8080"
        );
        assert_eq!(test::read_body(resp).await, "nope");
    }

    struct UsesCtx {
        ctx: Arc<dyn RequestContext<Flag> + Send + Sync>,
    }

    impl UsesCtx {
        fn flag(&self) -> u8 {
            self.ctx.extra().0
        }
    }

    #[actix_web::test]
    async fn handler_accepts_injected_request_context() {
        let h = UsesCtx {
            ctx: Arc::new(RequestScope::new(
                Uuid::now_v7(),
                Some("abc-1".into()),
                Flag(7),
            )),
        };
        assert_eq!(h.flag(), 7);
        assert_eq!(h.ctx.idempotency_key().as_deref(), Some("abc-1"));
    }

    #[actix_web::test]
    async fn resolve_delegates_to_bound_scope() {
        async fn inner() -> HttpResponse {
            let ctx = noema::resolve::<dyn RequestContext<()> + Send + Sync>();
            HttpResponse::Ok().body(ctx.idempotency_key().unwrap_or_default())
        }
        let srv = test::init_service(
            App::new()
                .wrap(request_context::<()>())
                .route("/", web::get().to(inner)),
        )
        .await;
        let req = test::TestRequest::get()
            .uri("/")
            .insert_header((IDEMPOTENCY_HEADER, "abc-1"))
            .to_request();
        let resp = test::call_service(&srv, req).await;
        assert_eq!(resp.status(), StatusCode::OK);
        assert_eq!(test::read_body(resp).await, "abc-1");
    }
}