ohkami 0.24.9

A performant, declarative, and runtime-flexible web framework for Rust
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
#![cfg(feature = "rt_lambda")]
#![allow(non_snake_case, non_camel_case_types)]

pub(crate) use internal::*;
/// Internal interfances between Lambda Events.
///
/// Based on :
///
/// * <https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/aws-lambda/trigger/api-gateway-proxy.d.ts>
/// * <https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html>
/// * <https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integration-requests.html>
pub(crate) mod internal {
    use crate::{Method, request::RequestHeaders, response::ResponseHeaders};
    use ohkami_lib::map::TupleMap;
    use serde::{Deserialize, Serialize};
    type JsonMap = serde_json::Map<String, serde_json::Value>;

    fn serialize_headers<S: serde::Serializer>(
        h: &ResponseHeaders,
        s: S,
    ) -> Result<S::Ok, S::Error> {
        s.collect_map(h.iter())
    }

    fn deserialize_headers<'de, D: serde::Deserializer<'de>>(
        d: D,
    ) -> Result<RequestHeaders, D::Error> {
        return d.deserialize_map(HeadersVisitor);

        /////////////////////////////////////////////////////////////////////////

        struct HeadersVisitor;

        impl<'de> serde::de::Visitor<'de> for HeadersVisitor {
            type Value = RequestHeaders;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a map")
            }

            #[inline]
            fn visit_map<A: serde::de::MapAccess<'de>>(
                self,
                mut access: A,
            ) -> Result<Self::Value, A::Error> {
                let mut h = RequestHeaders::new();
                while let Some((k, v)) = access.next_entry::<&str, &str>()? {
                    // in this context, there's no assurance
                    // that `v` lives enough
                    let v: Vec<u8> = v.to_owned().into_bytes();

                    if let Some(s) = crate::request::RequestHeader::from_bytes(k.as_bytes()) {
                        h.insert(s, v.into());
                    } else {
                        // this will be allowed here becasue
                        // one Lambda function isn't process a lot of requests
                        let k: &'static str = k.to_owned().leak();

                        h.insert_custom(ohkami_lib::Slice::from_bytes(k.as_bytes()), v.into());
                    }
                }
                Ok(h)
            }
        }
    }

    #[derive(Serialize)]
    #[cfg_attr(test, derive(Debug, PartialEq))]
    pub struct LambdaResponse {
        pub statusCode: u16,
        #[serde(serialize_with = "serialize_headers")]
        pub headers: ResponseHeaders,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub cookies: Option<Vec<String>>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub body: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub isBase64Encoded: Option<bool>,
    }

    #[derive(Deserialize)]
    pub struct LambdaHTTPRequest {
        /* @skip version: "2.0", */
        /* @unused routeKey: "$default", */
        /* @skip rawPath: String, // using requestContext.http.path */
        pub rawQueryString: String,
        #[serde(default)]
        pub cookies: Vec<String>,
        #[serde(deserialize_with = "deserialize_headers")]
        pub headers: RequestHeaders,
        /* @skip pathParameters: TupleMap<String, String>, */
        /* @skip queryStringParameters, // parsing rawQueryString */
        pub requestContext: LambdaHTTPRequestContext,
        #[serde(default)]
        pub body: Option<String>,
        pub isBase64Encoded: bool,
        #[serde(default)]
        pub stageVariables: Option<Box<TupleMap<String, String>>>,
    }

    #[derive(Deserialize)]
    pub struct LambdaHTTPRequestContext {
        /* @skip accountId: String, */
        pub apiId: String,
        #[serde(default)]
        pub authentication: Option<LambdaRequestAuthentication>,
        #[serde(default)]
        pub authorizer: Option<LambdaRequestAuthorizer>,
        pub domainName: String,
        /* @skip domainPrefix: String, // domainName is enough */
        pub http: LambdaHTTPRequestDetails,
        pub requestId: String,
        /* @unused routeKey: "$default", */
        /* @unused stage: "$default", */
        /* @skip time: String, // timeEpoch is enough */
        pub timeEpoch: u64,
    }

    #[derive(Deserialize)]
    pub struct LambdaHTTPRequestDetails {
        pub method: Method,
        pub path: String,
        /* @skip protocol: String, */
        pub sourceIp: std::net::IpAddr,
        /* @skip userAgent: String, */
    }

    #[derive(Deserialize)]
    pub struct LambdaRequestAuthentication {
        pub clientCertPem: String,
        pub issuerDN: String,
        pub subjectDN: String,
        pub serialNumber: String,
        pub validity: LambdaRequestAuthenticationValidity,
    }
    #[derive(Deserialize)]
    pub struct LambdaRequestAuthenticationValidity {
        pub notAfter: String,
        pub notBefore: String,
    }

    #[derive(Deserialize)]
    pub enum LambdaRequestAuthorizer {
        iam {
            accessKey: String,
            accountId: String,
            callerId: String,
            /* @unused cognitoIdentity */
            principalOrgId: String,
            userArn: String,
            userId: String,
        },
        jwt {
            claims: JsonMap,
            scopes: Vec<String>,
        },
    }
}

/* TODO
#[cfg(feature="ws")]
pub use ws::*;
#[cfg(feature="ws")]
mod ws {
    use super::internal;
    use crate::util::ErrorMessage;
    use std::{future::Future, marker::PhantomData};

    #[derive(Deserialize)]
    pub struct LambdaWebSocketRequest {
        pub requestContext: LambdaWebSocketRequestContext,
        pub body: Option<String>,
        pub isBase64Encoded: bool,
        pub stageVariables: TupleMap<String, String>,
    }

    #[derive(Deserialize)]
    pub struct LambdaWebSocketRequestContext {
        pub apiId: String,
        /* @skip connectedAt: u64, */
        pub connectionId: String,
        pub domainName: String,
        pub eventType: LambdaWebSocketEventType,
        /* @skip extendedRequestId: String, */
        pub routeKey: String,
        /* @skip messageDirection: "IN", */
        pub messageId: String,
        pub requestId: String,
        /* @skip requestTime: String, // requestTimeEpoch is enough */
        pub requestTimeEpoch: u64,
        pub stage: String,
    }

    #[derive(Deserialize)]
    pub enum LambdaWebSocketEventType {
        CONNECT,
        DISCONNECT,
        MESSAGE,
    }

    struct Client {
        host: String,
        path: String,
        conn: tokio::net::TcpStream,
    }
    struct ClientInit {
        domain_name: &str,
        stage: &str,
        connection_id: &str,
    }
    impl Client {
        /// Create backend client based on
        /// <https://docs.aws.amazon.com/en_us/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html>
        async fn new(init: ClientInit) -> Result<Self, impl std::error::Error> {
            use ::ohkami_lib::percent_encode;

            let conn = tokio::net::TcpStream::connect(init.domain_name).await?;
            let host = init.domain_name.to_owned();
            let path = format!(
                "/{stage}/%40connections/{connection_id}",
                stage = percent_encode(init.stage),
                connection_id = percent_encode(init.connection_id)
            );
            Ok(Self { host, conn })
        }

        async fn fetch(
            &mut self,
            method: &'static str,
            body: Option<LambdaWebSocketMESSAGE>,
        ) -> Result<(), impl std::error::Error> {
            use ohkami_lib::num::itoa;
            use tokio::io::AsyncWriteExt;

            let mut request = Vec::with_capacity(
                method.len() + " ".len() + self.path.len() + " HTTP/1.1\r\n".len() +
                "host: ".len() + self.host.len() + "\r\n".len() +
                "\r\n".len() +
                body.as_ref().map(|b|
                    "content-length: 32000\r\n".len() +
                    "content-type: application/octet-stream\r\n".len() +
                    b.len()
                ).unwrap_or(0)
            );
            {
                request.push(method.as_bytes());
                request.push(b" ");
                request.push(self.path.as_bytes());
                request.push(b" HTTP/1.1\r\n");
                {
                    request.push(b"host: ");
                    request.push(self.host.as_bytes());
                    request.push(b"\r\n");
                }
                if let Some(ref body) = body {
                    request.push(b"content-length: ");
                    request.push(itoa(body.len()).as_bytes());
                    request.push(b"\r\n");
                    request.push(b"content-type: ");
                    request.push(if body.is_text() {b"text/plain"} else {b"application/octet-stream"});
                    request.push(b"\r\n");
                }
                request.push(b"\r\n");
                if let Some(body) = body {
                    request.push(body);
                }
            }

            self.conn.write_all(request).await?;

            Ok(())
        }
    }

    /// ```no_run
    /// use ohkami::{LambdaWebSocket, LambdaWebSocketMESSAGE};
    /// use lambda_runtime::Error;
    ///
    /// #[ohkami::lambda]
    /// async fn main() -> Result<(), Error> {
    ///     lambda_runtime::run(LambdaWebSocket::handle(echo)).await
    /// }
    ///
    /// async fn echo(
    ///     ws: LambdaWebSocket<LamdaWebSocketMESSAGE>
    /// ) -> Result<(), Error> {
    ///     ws.send(ws.event).await?;
    ///     Ok(())
    /// }
    /// ```
    pub struct LambdaWebSocket<E: TryFrom<LambdaWebSocketEvent, std::error::Error> = LambdaWebSocketEvent> {
        pub context: internal::LambdaWebSocketRequestContext,
        pub event: E,
        client: Client,
    }

    impl<E: TryFrom<LambdaWebSocketEvent, std::error::Error>> LambdaWebSocket<E> {
        async fn new(
            context: internal::LambdaWebSocketRequestContext,
            event: E,
        ) -> Result<Self, impl std::error::Error> {
            let client = Client::new(ClientInit {
                domain_name: &context.domainName,
                stage: &context.stage,
                connection_id: &context.connectionId,
            }).await?;

            Ok(Self {
                context,
                event,
                client
            })
        }

        pub async fn send(&mut self, data: impl Into<LambdaWebSocketMESSAGE>) -> Result<(), impl std::error::Error> {
            self.client().await?.fetch("POST", Some(match data.into() {
                LambdaWebSocketMESSAGE::Text(t) => t.as_bytes(),
                LambdaWebSocketMESSAGE::Binary(b) => b.as_bytes()
            })).await
        }
        pub async fn close(mut self) -> Result<(), impl std::error::Error> {
            self.client().await?.fetch("DELETE", None).await
        }

        pub async fn handle<F, Fut>(handler: F) ->
            impl lambda_runtime::Service<
                lambda_runtime::LambdaEvent<internal::LambdaWebSocketRequest>,
                Response = lambda_runtime::FunctionResponse<
                    internal::LambdaResponse,
                    std::pin::Pin<Box<dyn ohkami_lib::Stream<Item = Result<String, std::convert::Infallible>> + Send>>
                >
            >
        where
            F:   Fn(Self) -> Fut,
            Fut: Future<Output = Result<(), lambda_runtime::Error>>,
        {
            return LambdaWebSocketService {
                handler,
                __fut__: PhantomData
            };

            ///////////////////////////////////////////////////////

            use lambda_runtime::{Service, LambdaEvent};
            use internal::{LambdaWebSocketRequest, LambdaResponse};

            struct LambdaWebSocketService<F, Fut> {
                handler: F,
                __fut__: PhantomData<Fut>,
            }

            impl Service<LambdaEvent<LambdaWebSocketRequest>, E, F, Fut> for LambdaWebSocketService<F, Fut>
            where
                F:   Fn(LambdaWebSocket<E>) -> Fut,
                E:   TryFrom<LambdaWebSocketEvent, std::error::Error>,
                Fut: Future<Output = Result<(), lambda_runtime::Error>>,
            {
                type Response = lambda_runtime::FunctionResponse<
                    internal::LambdaResponse,
                    std::pin::Pin<Box<dyn ohkami_lib::Stream<Item = Result<String, std::convert::Infallible>> + Send>>
                >;
                type Error = lambda_runtime::Error;
                type Future = impl Future<Output = Result<(), lambda_runtime::Error>>;

                fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll<Result<(), Self::Error>> {
                    std::task::Poll::Ready(Ok(()))
                }

                fn call(&mut self, req: LambdaEvent<LambdaWebSocketRequest>) -> Self::Future {
                    let payload: internal::LambdaWebSocketRequest = req.payload;

                    let event = match &payload.requestContext.eventType {
                        internal::LambdaWebSocketEventType::CONNECT => {
                            LambdaWebSocketEvent::CONNECT(LambdaWebSocketCONNECT)
                        }
                        internal::LambdaWebSocketEventType::DISCONNECT => {
                            LambdaWebSocketEvent::DISCONNECT(LambdaWebSocketDISCONNECT)
                        }
                        internal::LambdaWebSocketEventType::MESSAGE => {
                            let body = payload.body
                                .ok_or_else(|| Box::new(ErrorMessage("Got MESSAGE event, but not `body` found".into())))?;
                            let body = if payload.isBase64Encoded {
                                use ::base64::engine::{Engine as _, general_purpose::STANDARD as BASE64};
                                LambdaWebSocketMESSAGE::Binary(BASE64.decode(body)?)
                            } else {
                                LambdaWebSocketMESSAGE::Text(body)
                            };
                            LambdaWebSocketEvent::MESSAGE(body)
                        }
                    };

                    async move {
                        let ws = LambdaWebSocket::new(
                            payload.requestContext,
                            E::try_from(event)?
                        ).await?;

                        (self.handler)(ws).await?;

                        Ok(lambda_runtime::FunctionResponse::BufferedResponse(internal::LambdaResponse {
                            statusCode: 200,
                            headers: ResponseHeaders::new(),
                            cookies: None,
                            body: None,
                            isBase64Encoded: None,
                        }))
                    }
                }
            }
        }
    }

    pub enum LambdaWebSocketEvent {
        CONNECT(LambdaWebSocketCONNECT),
        DISCONNECT(LambdaWebSocketDISCONNECT),
        MESSAGE(LambdaWebSocketMESSAGE),
    }
    impl TryFrom<LambdaWebSocketEvent> for LambdaWebSocketEvent {
        type Error = std::convert::Infallible;
        fn try_from(e: LambdaWebSocketEvent) -> Result<Self, Self::Error> {
            Ok(e)
        }
    }

    pub struct LambdaWebSocketCONNECT;
    impl TryFrom<LambdaWebSocketEvent> for LambdaWebSocketCONNECT {
        type Error = ErrorMessage;
        fn try_from(e: LambdaWebSocketEvent) -> Result<Self, Self::Error> {
            match e {
                LambdaWebSocketEvent::CONNECT(it) => Ok(it),
                LambdaWebSocketEvent::DISCONNECT(_) => Err(ErrorMessage(
                    "Expected CONNECT event, but got DISCONNECT".into()
                )),
                LambdaWebSocketEvent::MESSAGE(_) => Err(ErrorMessage(
                    "Expected CONNECT event, but got MESSAGE".into()
                )),
            }
        }
    }

    pub struct LambdaWebSocketDISCONNECT;
    impl TryFrom<LambdaWebSocketEvent> for LambdaWebSocketDISCONNECT {
        type Error = ErrorMessage;
        fn try_from(e: LambdaWebSocketEvent) -> Result<Self, Self::Error> {
            match e {
                LambdaWebSocketEvent::DISCONNECT(it) => Ok(it),
                LambdaWebSocketEvent::MESSAGE(_) => Err(ErrorMessage(
                    "Expected DISCONNECT event, but got MESSAGE".into()
                )),
                LambdaWebSocketEvent::CONNECT(_) => Err(ErrorMessage(
                    "Expected DISCONNECT event, but got CONNECT".into()
                )),
            }
        }
    }

    pub enum LambdaWebSocketMESSAGE {
        Text(String),
        Binary(Vec<u8>),
    }
    impl LambdaWebSocketMESSAGE {
        pub fn len(&self) -> usize {
            match self {
                Self::Text(t) => t.len(),
                Self::Binary(b) => b.len(),
            }
        }

        pub fn is_text(&self) -> bool {
            matches!(self, Self::Text(_))
        }
        pub fn is_binary(&self) -> bool {
            matches!(self, Self::Binary(_))
        }
    }
    impl TryFrom<LambdaWebSocketEvent> for LambdaWebSocketMESSAGE {
        type Error = ErrorMessage;
        fn try_from(e: LambdaWebSocketEvent) -> Result<Self, Self::Error> {
            match e {
                LambdaWebSocketEvent::MESSAGE(it) => Ok(it),
                LambdaWebSocketEvent::CONNECT(_) => Err(ErrorMessage(
                    "Expected MESSAGE event, but got CONNECT".into()
                )),
                LambdaWebSocketEvent::DISCONNECT(_) => Err(ErrorMessage(
                    "Expected MESSAGE event, but got DISCONNECT".into()
                )),
            }
        }
    }
    const _: () = {
        impl From<String> for LambdaWebSocketMESSAGE {
            fn from(text: String) -> Self {Self::Text(text)}
        }
        impl From<&str> for LambdaWebSocketMESSAGE {
            fn from(text: &str) -> Self {Self::Text(text.to_owned())}
        }
        impl From<std::borrow::Cow<str>> for LambdaWebSocketMESSAGE {
            fn from(text: String) -> Self {Self::Text(text.into())}
        }

        impl From<Vec<u8>> for LambdaWebSocketMESSAGE {
            fn from(binary: Vec<u8>) -> Self {Self::binary(binary)}
        }
        impl From<&[u8]> for LambdaWebSocketMESSAGE {
            fn from(binary: &[u8]) -> Self {Self::binary(binary.to_owned())}
        }
        impl From<std::borrow::Cow<[u8]>> for LambdaWebSocketMESSAGE {
            fn from(binary: std::borrow::<[u8]>) -> Self {Self::binary(binary.into())}
        }
    };
}
*/

#[cfg(feature="nightly"/* `noop_waker` is stabilized in 1.85.0 and then remove this cfg */)]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Method, Ohkami, Route};
    use std::task::{Context, Waker};

    fn new_req(
        method: Method,
        path: &'static str,
        body: Option<String>,
    ) -> lambda_runtime::LambdaEvent<LambdaHTTPRequest> {
        lambda_runtime::LambdaEvent {
            context: Default::default(),
            payload: LambdaHTTPRequest {
                rawQueryString: String::new(),
                cookies: Vec::new(),
                headers: crate::request::RequestHeaders::new(),
                body,
                isBase64Encoded: false,
                stageVariables: None,
                requestContext: LambdaHTTPRequestContext {
                    apiId: String::new(),
                    authentication: None,
                    authorizer: None,
                    domainName: String::new(),
                    requestId: String::new(),
                    timeEpoch: 0,
                    http: LambdaHTTPRequestDetails {
                        method,
                        path: String::from(path),
                        sourceIp: crate::util::IP_0000,
                    },
                },
            },
        }
    }

    #[test]
    fn lambda_runtime_run_ohkami_compiles() {
        #[allow(clippy::let_underscore_future/* just checking compilablity */)]
        let _/* : impl Future */ = lambda_runtime::run(Ohkami::new(()));
    }

    #[test]
    fn ohkami_service_call() {
        tokio::runtime::Runtime::new().unwrap().block_on(async {
            let mut o = Ohkami::new(("/hello".GET(|| async { "Hello, Service!" }),));

            /* poll_ready first */
            let _ = <Ohkami as lambda_runtime::Service<
                lambda_runtime::LambdaEvent<crate::x_lambda::LambdaHTTPRequest>,
            >>::poll_ready(&mut o, &mut Context::from_waker(Waker::noop()));

            {
                /* 404 */
                let res = <Ohkami as lambda_runtime::Service<
                    lambda_runtime::LambdaEvent<crate::x_lambda::LambdaHTTPRequest>,
                >>::call(&mut o, new_req(Method::GET, "/", None))
                .await
                .unwrap();

                let lambda_runtime::FunctionResponse::BufferedResponse(res) = res else {
                    panic!("Unexpected `StreamingResponse`")
                };

                assert_eq!(
                    res,
                    LambdaResponse {
                        statusCode: 404,
                        headers: crate::response::ResponseHeaders::from_iter([
                            (
                                "Date",
                                ohkami_lib::imf_fixdate(crate::util::unix_timestamp())
                            ),
                            ("Content-Length", "0".into()),
                            // ("Content-Type", "text/plain; charset=UTF-8".into()),
                        ]),
                        cookies: None,
                        body: None,            //Some("Hello, Service!".into()),
                        isBase64Encoded: None, //Some(false),
                    }
                );
            }
            {
                /* OK */
                let res = <Ohkami as lambda_runtime::Service<
                    lambda_runtime::LambdaEvent<crate::x_lambda::LambdaHTTPRequest>,
                >>::call(&mut o, new_req(Method::GET, "/hello", None))
                .await
                .unwrap();

                let lambda_runtime::FunctionResponse::BufferedResponse(res) = res else {
                    panic!("Unexpected `StreamingResponse`")
                };

                assert_eq!(
                    res,
                    LambdaResponse {
                        statusCode: 200,
                        headers: crate::response::ResponseHeaders::from_iter([
                            (
                                "Date",
                                ohkami_lib::imf_fixdate(crate::util::unix_timestamp())
                            ),
                            ("Content-Length", "15".into()),
                            ("Content-Type", "text/plain; charset=UTF-8".into()),
                        ]),
                        cookies: None,
                        body: Some("Hello, Service!".into()),
                        isBase64Encoded: Some(false),
                    }
                );
            }
            {
                /* OK twice */
                let res = <Ohkami as lambda_runtime::Service<
                    lambda_runtime::LambdaEvent<crate::x_lambda::LambdaHTTPRequest>,
                >>::call(&mut o, new_req(Method::GET, "/hello", None))
                .await
                .unwrap();

                let lambda_runtime::FunctionResponse::BufferedResponse(res) = res else {
                    panic!("Unexpected `StreamingResponse`")
                };

                assert_eq!(
                    res,
                    LambdaResponse {
                        statusCode: 200,
                        headers: crate::response::ResponseHeaders::from_iter([
                            (
                                "Date",
                                ohkami_lib::imf_fixdate(crate::util::unix_timestamp())
                            ),
                            ("Content-Length", "15".into()),
                            ("Content-Type", "text/plain; charset=UTF-8".into()),
                        ]),
                        cookies: None,
                        body: Some("Hello, Service!".into()),
                        isBase64Encoded: Some(false),
                    }
                );
            }
        });
    }
}