netlify_lambda/
types.rs

1use crate::{Config, Error};
2use http::HeaderMap;
3use serde::{Deserialize, Serialize};
4use std::{collections::HashMap, convert::TryFrom};
5
6#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
7#[serde(rename_all = "camelCase")]
8pub(crate) struct Diagnostic {
9    pub(crate) error_type: String,
10    pub(crate) error_message: String,
11}
12
13#[test]
14fn round_trip_lambda_error() -> Result<(), Error> {
15    use serde_json::{json, Value};
16    let expected = json!({
17        "errorType": "InvalidEventDataError",
18        "errorMessage": "Error parsing event data.",
19    });
20
21    let actual: Diagnostic = serde_json::from_value(expected.clone())?;
22    let actual: Value = serde_json::to_value(actual)?;
23    assert_eq!(expected, actual);
24
25    Ok(())
26}
27
28/// The request ID, which identifies the request that triggered the function invocation. This header
29/// tracks the invocation within the Lambda control plane. The request ID is used to specify completion
30/// of a given invocation.
31#[derive(Debug, Clone, PartialEq)]
32pub struct RequestId(pub String);
33
34/// The date that the function times out in Unix time milliseconds. For example, `1542409706888`.
35#[derive(Debug, Clone, PartialEq)]
36pub struct InvocationDeadline(pub u64);
37
38/// The ARN of the Lambda function, version, or alias that is specified in the invocation.
39/// For instance, `arn:aws:lambda:us-east-2:123456789012:function:custom-runtime`.
40#[derive(Debug, Clone, PartialEq)]
41pub struct FunctionArn(pub String);
42
43/// The AWS X-Ray Tracing header. For more information,
44/// please see [AWS' documentation](https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-tracingheader).
45#[derive(Debug, Clone, PartialEq)]
46pub struct XRayTraceId(pub String);
47
48/// For invocations from the AWS Mobile SDK contains data about client application and device.
49#[derive(Debug, Clone, PartialEq)]
50struct MobileClientContext(String);
51
52/// For invocations from the AWS Mobile SDK, data about the Amazon Cognito identity provider.
53#[derive(Debug, Clone, PartialEq)]
54struct MobileClientIdentity(String);
55
56/// Client context sent by the AWS Mobile SDK.
57#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
58pub struct ClientContext {
59    /// Information about the mobile application invoking the function.
60    pub client: ClientApplication,
61    /// Custom properties attached to the mobile event context.
62    pub custom: HashMap<String, String>,
63    /// Environment settings from the mobile client.
64    pub environment: HashMap<String, String>,
65}
66
67/// AWS Mobile SDK client fields.
68#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
69#[serde(rename_all = "camelCase")]
70pub struct ClientApplication {
71    /// The mobile app installation id
72    pub installation_id: String,
73    /// The app title for the mobile app as registered with AWS' mobile services.
74    pub app_title: String,
75    /// The version name of the application as registered with AWS' mobile services.
76    pub app_version_name: String,
77    /// The app version code.
78    pub app_version_code: String,
79    /// The package name for the mobile application invoking the function
80    pub app_package_name: String,
81}
82
83/// Cognito identity information sent with the event
84#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
85pub struct CognitoIdentity {
86    /// The unique identity id for the Cognito credentials invoking the function.
87    pub identity_id: String,
88    /// The identity pool id the caller is "registered" with.
89    pub identity_pool_id: String,
90}
91
92/// The Lambda function execution context. The values in this struct
93/// are populated using the [Lambda environment variables](https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html)
94/// and the headers returned by the poll request to the Runtime APIs.
95#[non_exhaustive]
96#[derive(Clone, Debug, PartialEq, Default)]
97pub struct Context {
98    /// The AWS request ID generated by the Lambda service.
99    pub request_id: String,
100    /// The execution deadline for the current invocation in milliseconds.
101    pub deadline: u64,
102    /// The ARN of the Lambda function being invoked.
103    pub invoked_function_arn: String,
104    /// The X-Ray trace ID for the current invocation.
105    pub xray_trace_id: String,
106    /// The client context object sent by the AWS mobile SDK. This field is
107    /// empty unless the function is invoked using an AWS mobile SDK.
108    pub client_context: Option<ClientContext>,
109    /// The Cognito identity that invoked the function. This field is empty
110    /// unless the invocation request to the Lambda APIs was made using AWS
111    /// credentials issues by Amazon Cognito Identity Pools.
112    pub identity: Option<CognitoIdentity>,
113    /// Lambda function configuration from the local environment variables.
114    /// Includes information such as the function name, memory allocation,
115    /// version, and log streams.
116    pub env_config: Config,
117}
118
119impl TryFrom<HeaderMap> for Context {
120    type Error = Error;
121    fn try_from(headers: HeaderMap) -> Result<Self, Self::Error> {
122        let ctx = Context {
123            request_id: headers["lambda-runtime-aws-request-id"]
124                .to_str()
125                .expect("Missing Request ID")
126                .to_owned(),
127            deadline: headers["lambda-runtime-deadline-ms"]
128                .to_str()?
129                .parse()
130                .expect("Missing deadline"),
131            invoked_function_arn: headers
132                .get("lambda-runtime-invoked-function-arn")
133                .and_then(|h| h.to_str().ok())
134                .map(str::to_owned)
135                .unwrap_or_default(),
136            xray_trace_id: headers
137                .get("lambda-runtime-trace-id")
138                .and_then(|h| h.to_str().ok())
139                .map(str::to_owned)
140                .unwrap_or_default(),
141            ..Default::default()
142        };
143        Ok(ctx)
144    }
145}