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
use crate::{Error, RefConfig};
use base64::prelude::*;
use bytes::Bytes;
use http::{header::ToStrError, HeaderMap, HeaderValue, StatusCode};
use lambda_runtime_api_client::body::Body;
use serde::{Deserialize, Serialize};
use std::{
    borrow::Cow,
    collections::HashMap,
    fmt::{Debug, Display},
    time::{Duration, SystemTime},
};
use tokio_stream::Stream;

/// Diagnostic information about an error.
///
/// `Diagnostic` is automatically derived for types that implement
/// [`Display`][std::fmt::Display]; e.g., [`Error`][std::error::Error].
///
/// [`error_type`][`Diagnostic::error_type`] is derived from the type name of
/// the original error with [`std::any::type_name`] as a fallback, which may
/// not be reliable for conditional error handling.
/// You can define your own error container that implements `Into<Diagnostic>`
/// if you need to handle errors based on error types.
///
/// Example:
/// ```
/// use lambda_runtime::{Diagnostic, Error, LambdaEvent};
/// use std::borrow::Cow;
///
/// #[derive(Debug)]
/// struct ErrorResponse(Error);
///
/// impl<'a> Into<Diagnostic<'a>> for ErrorResponse {
///     fn into(self) -> Diagnostic<'a> {
///         Diagnostic {
///             error_type: Cow::Borrowed("MyError"),
///             error_message: Cow::Owned(self.0.to_string()),
///         }
///     }
/// }
///
/// async fn function_handler(_event: LambdaEvent<()>) -> Result<(), ErrorResponse> {
///    // ... do something
///    Ok(())
/// }
/// ```
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Diagnostic<'a> {
    /// Error type.
    ///
    /// `error_type` is derived from the type name of the original error with
    /// [`std::any::type_name`] as a fallback.
    /// Please implement your own `Into<Diagnostic>` if you need more reliable
    /// error types.
    pub error_type: Cow<'a, str>,
    /// Error message.
    ///
    /// `error_message` is the output from the [`Display`][std::fmt::Display]
    /// implementation of the original error as a fallback.
    pub error_message: Cow<'a, str>,
}

impl<'a, T> From<T> for Diagnostic<'a>
where
    T: Display,
{
    fn from(value: T) -> Self {
        Diagnostic {
            error_type: Cow::Borrowed(std::any::type_name::<T>()),
            error_message: Cow::Owned(format!("{value}")),
        }
    }
}

/// Client context sent by the AWS Mobile SDK.
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
pub struct ClientContext {
    /// Information about the mobile application invoking the function.
    #[serde(default)]
    pub client: ClientApplication,
    /// Custom properties attached to the mobile event context.
    #[serde(default)]
    pub custom: HashMap<String, String>,
    /// Environment settings from the mobile client.
    #[serde(default)]
    pub environment: HashMap<String, String>,
}

/// AWS Mobile SDK client fields.
#[derive(Serialize, Deserialize, Default, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ClientApplication {
    /// The mobile app installation id
    #[serde(alias = "installation_id")]
    pub installation_id: String,
    /// The app title for the mobile app as registered with AWS' mobile services.
    #[serde(alias = "app_title")]
    pub app_title: String,
    /// The version name of the application as registered with AWS' mobile services.
    #[serde(alias = "app_version_name")]
    pub app_version_name: String,
    /// The app version code.
    #[serde(alias = "app_version_code")]
    pub app_version_code: String,
    /// The package name for the mobile application invoking the function
    #[serde(alias = "app_package_name")]
    pub app_package_name: String,
}

/// Cognito identity information sent with the event
#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct CognitoIdentity {
    /// The unique identity id for the Cognito credentials invoking the function.
    #[serde(alias = "cognitoIdentityId", alias = "identity_id")]
    pub identity_id: String,
    /// The identity pool id the caller is "registered" with.
    #[serde(alias = "cognitoIdentityPoolId", alias = "identity_pool_id")]
    pub identity_pool_id: String,
}

/// The Lambda function execution context. The values in this struct
/// are populated using the [Lambda environment variables](https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html)
/// and [the headers returned by the poll request to the Runtime APIs](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html#runtimes-api-next).
#[non_exhaustive]
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Context {
    /// The AWS request ID generated by the Lambda service.
    pub request_id: String,
    /// The execution deadline for the current invocation in milliseconds.
    pub deadline: u64,
    /// The ARN of the Lambda function being invoked.
    pub invoked_function_arn: String,
    /// The X-Ray trace ID for the current invocation.
    pub xray_trace_id: Option<String>,
    /// The client context object sent by the AWS mobile SDK. This field is
    /// empty unless the function is invoked using an AWS mobile SDK.
    pub client_context: Option<ClientContext>,
    /// The Cognito identity that invoked the function. This field is empty
    /// unless the invocation request to the Lambda APIs was made using AWS
    /// credentials issues by Amazon Cognito Identity Pools.
    pub identity: Option<CognitoIdentity>,
    /// Lambda function configuration from the local environment variables.
    /// Includes information such as the function name, memory allocation,
    /// version, and log streams.
    pub env_config: RefConfig,
}

impl Default for Context {
    fn default() -> Context {
        Context {
            request_id: "".to_owned(),
            deadline: 0,
            invoked_function_arn: "".to_owned(),
            xray_trace_id: None,
            client_context: None,
            identity: None,
            env_config: std::sync::Arc::new(crate::Config::default()),
        }
    }
}

impl Context {
    /// Create a new [Context] struct based on the function configuration
    /// and the incoming request data.
    pub fn new(request_id: &str, env_config: RefConfig, headers: &HeaderMap) -> Result<Self, Error> {
        let client_context: Option<ClientContext> = if let Some(value) = headers.get("lambda-runtime-client-context") {
            serde_json::from_str(value.to_str()?)?
        } else {
            None
        };

        let identity: Option<CognitoIdentity> = if let Some(value) = headers.get("lambda-runtime-cognito-identity") {
            serde_json::from_str(value.to_str()?)?
        } else {
            None
        };

        let ctx = Context {
            request_id: request_id.to_owned(),
            deadline: headers
                .get("lambda-runtime-deadline-ms")
                .expect("missing lambda-runtime-deadline-ms header")
                .to_str()?
                .parse::<u64>()?,
            invoked_function_arn: headers
                .get("lambda-runtime-invoked-function-arn")
                .unwrap_or(&HeaderValue::from_static(
                    "No header lambda-runtime-invoked-function-arn found.",
                ))
                .to_str()?
                .to_owned(),
            xray_trace_id: headers
                .get("lambda-runtime-trace-id")
                .map(|v| String::from_utf8_lossy(v.as_bytes()).to_string()),
            client_context,
            identity,
            env_config,
        };

        Ok(ctx)
    }

    /// The execution deadline for the current invocation.
    pub fn deadline(&self) -> SystemTime {
        SystemTime::UNIX_EPOCH + Duration::from_millis(self.deadline)
    }
}

/// Extract the invocation request id from the incoming request.
pub(crate) fn invoke_request_id(headers: &HeaderMap) -> Result<&str, ToStrError> {
    headers
        .get("lambda-runtime-aws-request-id")
        .expect("missing lambda-runtime-aws-request-id header")
        .to_str()
}

/// Incoming Lambda request containing the event payload and context.
#[derive(Clone, Debug)]
pub struct LambdaEvent<T> {
    /// Event payload.
    pub payload: T,
    /// Invocation context.
    pub context: Context,
}

impl<T> LambdaEvent<T> {
    /// Creates a new Lambda request
    pub fn new(payload: T, context: Context) -> Self {
        Self { payload, context }
    }

    /// Split the Lambda event into its payload and context.
    pub fn into_parts(self) -> (T, Context) {
        (self.payload, self.context)
    }
}

/// Metadata prelude for a stream response.
#[derive(Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MetadataPrelude {
    #[serde(with = "http_serde::status_code")]
    /// The HTTP status code.
    pub status_code: StatusCode,
    #[serde(with = "http_serde::header_map")]
    /// The HTTP headers.
    pub headers: HeaderMap,
    /// The HTTP cookies.
    pub cookies: Vec<String>,
}

pub trait ToStreamErrorTrailer {
    /// Convert the hyper error into a stream error trailer.
    fn to_tailer(&self) -> String;
}

impl ToStreamErrorTrailer for Error {
    fn to_tailer(&self) -> String {
        format!(
            "Lambda-Runtime-Function-Error-Type: Runtime.StreamError\r\nLambda-Runtime-Function-Error-Body: {}\r\n",
            BASE64_STANDARD.encode(self.to_string())
        )
    }
}

/// A streaming response that contains the metadata prelude and the stream of bytes that will be
/// sent to the client.
#[derive(Debug)]
pub struct StreamResponse<S> {
    ///  The metadata prelude.
    pub metadata_prelude: MetadataPrelude,
    /// The stream of bytes that will be sent to the client.
    pub stream: S,
}

/// An enum representing the response of a function that can return either a buffered
/// response of type `B` or a streaming response of type `S`.
pub enum FunctionResponse<B, S> {
    /// A buffered response containing the entire payload of the response. This is useful
    /// for responses that can be processed quickly and have a relatively small payload size(<= 6MB).
    BufferedResponse(B),
    /// A streaming response that delivers the payload incrementally. This is useful for
    /// large payloads(> 6MB) or responses that take a long time to generate. The client can start
    /// processing the response as soon as the first chunk is available, without waiting
    /// for the entire payload to be generated.
    StreamingResponse(StreamResponse<S>),
}

/// a trait that can be implemented for any type that can be converted into a FunctionResponse.
/// This allows us to use the `into` method to convert a type into a FunctionResponse.
pub trait IntoFunctionResponse<B, S> {
    /// Convert the type into a FunctionResponse.
    fn into_response(self) -> FunctionResponse<B, S>;
}

impl<B, S> IntoFunctionResponse<B, S> for FunctionResponse<B, S> {
    fn into_response(self) -> FunctionResponse<B, S> {
        self
    }
}

impl<B> IntoFunctionResponse<B, Body> for B
where
    B: Serialize,
{
    fn into_response(self) -> FunctionResponse<B, Body> {
        FunctionResponse::BufferedResponse(self)
    }
}

impl<S, D, E> IntoFunctionResponse<(), S> for StreamResponse<S>
where
    S: Stream<Item = Result<D, E>> + Unpin + Send + 'static,
    D: Into<Bytes> + Send,
    E: Into<Error> + Send + Debug,
{
    fn into_response(self) -> FunctionResponse<(), S> {
        FunctionResponse::StreamingResponse(self)
    }
}

impl<S, D, E> From<S> for StreamResponse<S>
where
    S: Stream<Item = Result<D, E>> + Unpin + Send + 'static,
    D: Into<Bytes> + Send,
    E: Into<Error> + Send + Debug,
{
    fn from(value: S) -> Self {
        StreamResponse {
            metadata_prelude: Default::default(),
            stream: value,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::Config;
    use std::sync::Arc;

    #[test]
    fn round_trip_lambda_error() {
        use serde_json::{json, Value};
        let expected = json!({
            "errorType": "InvalidEventDataError",
            "errorMessage": "Error parsing event data.",
        });

        let actual = Diagnostic {
            error_type: Cow::Borrowed("InvalidEventDataError"),
            error_message: Cow::Borrowed("Error parsing event data."),
        };
        let actual: Value = serde_json::to_value(actual).expect("failed to serialize diagnostic");
        assert_eq!(expected, actual);
    }

    #[test]
    fn context_with_expected_values_and_types_resolves() {
        let config = Arc::new(Config::default());

        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        headers.insert(
            "lambda-runtime-invoked-function-arn",
            HeaderValue::from_static("arn::myarn"),
        );
        headers.insert("lambda-runtime-trace-id", HeaderValue::from_static("arn::myarn"));
        let tried = Context::new("id", config, &headers);
        assert!(tried.is_ok());
    }

    #[test]
    fn context_with_certain_missing_headers_still_resolves() {
        let config = Arc::new(Config::default());

        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        let tried = Context::new("id", config, &headers);
        assert!(tried.is_ok());
    }

    #[test]
    fn context_with_client_context_resolves() {
        let mut custom = HashMap::new();
        custom.insert("key".to_string(), "value".to_string());
        let mut environment = HashMap::new();
        environment.insert("key".to_string(), "value".to_string());
        let client_context = ClientContext {
            client: ClientApplication {
                installation_id: String::new(),
                app_title: String::new(),
                app_version_name: String::new(),
                app_version_code: String::new(),
                app_package_name: String::new(),
            },
            custom,
            environment,
        };
        let client_context_str = serde_json::to_string(&client_context).unwrap();
        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        headers.insert(
            "lambda-runtime-client-context",
            HeaderValue::from_str(&client_context_str).unwrap(),
        );

        let config = Arc::new(Config::default());
        let tried = Context::new("id", config, &headers);
        assert!(tried.is_ok());
        let tried = tried.unwrap();
        assert!(tried.client_context.is_some());
        assert_eq!(tried.client_context.unwrap(), client_context);
    }

    #[test]
    fn context_with_empty_client_context_resolves() {
        let config = Arc::new(Config::default());
        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        headers.insert("lambda-runtime-client-context", HeaderValue::from_static("{}"));
        let tried = Context::new("id", config, &headers);
        assert!(tried.is_ok());
        assert!(tried.unwrap().client_context.is_some());
    }

    #[test]
    fn context_with_identity_resolves() {
        let config = Arc::new(Config::default());

        let cognito_identity = CognitoIdentity {
            identity_id: String::new(),
            identity_pool_id: String::new(),
        };
        let cognito_identity_str = serde_json::to_string(&cognito_identity).unwrap();
        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        headers.insert(
            "lambda-runtime-cognito-identity",
            HeaderValue::from_str(&cognito_identity_str).unwrap(),
        );
        let tried = Context::new("id", config, &headers);
        assert!(tried.is_ok());
        let tried = tried.unwrap();
        assert!(tried.identity.is_some());
        assert_eq!(tried.identity.unwrap(), cognito_identity);
    }

    #[test]
    fn context_with_bad_deadline_type_is_err() {
        let config = Arc::new(Config::default());

        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert(
            "lambda-runtime-deadline-ms",
            HeaderValue::from_static("BAD-Type,not <u64>"),
        );
        headers.insert(
            "lambda-runtime-invoked-function-arn",
            HeaderValue::from_static("arn::myarn"),
        );
        headers.insert("lambda-runtime-trace-id", HeaderValue::from_static("arn::myarn"));
        let tried = Context::new("id", config, &headers);
        assert!(tried.is_err());
    }

    #[test]
    fn context_with_bad_client_context_is_err() {
        let config = Arc::new(Config::default());

        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        headers.insert(
            "lambda-runtime-client-context",
            HeaderValue::from_static("BAD-Type,not JSON"),
        );
        let tried = Context::new("id", config, &headers);
        assert!(tried.is_err());
    }

    #[test]
    fn context_with_empty_identity_is_err() {
        let config = Arc::new(Config::default());

        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        headers.insert("lambda-runtime-cognito-identity", HeaderValue::from_static("{}"));
        let tried = Context::new("id", config, &headers);
        assert!(tried.is_err());
    }

    #[test]
    fn context_with_bad_identity_is_err() {
        let config = Arc::new(Config::default());

        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        headers.insert(
            "lambda-runtime-cognito-identity",
            HeaderValue::from_static("BAD-Type,not JSON"),
        );
        let tried = Context::new("id", config, &headers);
        assert!(tried.is_err());
    }

    #[test]
    #[should_panic]
    fn context_with_missing_deadline_should_panic() {
        let config = Arc::new(Config::default());

        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert(
            "lambda-runtime-invoked-function-arn",
            HeaderValue::from_static("arn::myarn"),
        );
        headers.insert("lambda-runtime-trace-id", HeaderValue::from_static("arn::myarn"));
        let _ = Context::new("id", config, &headers);
    }

    #[test]
    fn invoke_request_id_should_not_panic() {
        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-aws-request-id", HeaderValue::from_static("my-id"));
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        headers.insert(
            "lambda-runtime-invoked-function-arn",
            HeaderValue::from_static("arn::myarn"),
        );
        headers.insert("lambda-runtime-trace-id", HeaderValue::from_static("arn::myarn"));

        let _ = invoke_request_id(&headers);
    }

    #[test]
    #[should_panic]
    fn invoke_request_id_should_panic() {
        let mut headers = HeaderMap::new();
        headers.insert("lambda-runtime-deadline-ms", HeaderValue::from_static("123"));
        headers.insert(
            "lambda-runtime-invoked-function-arn",
            HeaderValue::from_static("arn::myarn"),
        );
        headers.insert("lambda-runtime-trace-id", HeaderValue::from_static("arn::myarn"));

        let _ = invoke_request_id(&headers);
    }
}