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
#![warn(missing_docs)]
#![deny(warnings)]
//! Lambda runtime makes it easy to run Rust code inside AWS Lambda. To create
//! Lambda function with this library simply include it as a dependency, make
//! sure that you declare a function that respects the `Handler` type, and call
//! the `start()` function from your main method. The executable in your deployment
//! package must be called `bootstrap`.
//!
//! ```rust,no_run
//! use lambda_runtime::{error::HandlerError, lambda, Context};
//! use simple_error::bail;
//! use serde_derive::{Serialize, Deserialize};
//!
//! #[derive(Deserialize, Clone)]
//! struct CustomEvent {
//!     first_name: String,
//!     last_name: String,
//! }
//!
//! #[derive(Serialize, Clone)]
//! struct CustomOutput {
//!     message: String,
//! }
//!
//! fn main() {
//!     lambda!(my_handler);
//! }
//!
//! fn my_handler(e: CustomEvent, ctx: Context) -> Result<CustomOutput, HandlerError> {
//!     if e.first_name == "" {
//!         bail!("Empty first name");
//!     }
//!     Ok(CustomOutput{
//!         message: format!("Hello, {}!", e.first_name),
//!     })
//! }
//! ```
use failure::Fail;
use lambda_runtime_core::{start_with_config, EnvConfigProvider, HandlerError, LambdaErrorExt};
use serde;
use serde_json;
use std::fmt::Display;
use tokio::runtime::Runtime as TokioRuntime;

pub use lambda_runtime_core::Context;

/// The error module exposes the HandlerError type.
pub mod error {
    pub use lambda_runtime_core::{HandlerError, LambdaErrorExt, LambdaResultExt};
}

/// Functions acting as a handler must conform to this type.
pub trait Handler<Event, Output, EventError> {
    /// Method to execute the handler function
    fn run(&mut self, event: Event, ctx: Context) -> Result<Output, EventError>;
}

/// Implementation of the `Handler` trait for both function pointers
/// and closures.
impl<Function, Event, Output, EventError> Handler<Event, Output, EventError> for Function
where
    Function: FnMut(Event, Context) -> Result<Output, EventError>,
    EventError: Fail + LambdaErrorExt + Display + Send + Sync,
{
    fn run(&mut self, event: Event, ctx: Context) -> Result<Output, EventError> {
        (*self)(event, ctx)
    }
}

/// Wraps a typed handler into a closure that complies with the `Handler` trait
/// defined in the `lambda_runtime_core` crate. The closure simply uses `serde_json`
/// to serialize and deserialize the incoming event from a `Vec<u8>` and the output
/// to a `Vec<u8>`.
fn wrap<Event, Output, EventError>(
    mut h: impl Handler<Event, Output, EventError>,
) -> impl FnMut(Vec<u8>, Context) -> Result<Vec<u8>, HandlerError>
where
    Event: serde::de::DeserializeOwned,
    Output: serde::Serialize,
    EventError: Fail + LambdaErrorExt + Display + Send + Sync,
{
    move |ev, ctx| {
        let event: Event = serde_json::from_slice(&ev)?;
        match h.run(event, ctx) {
            Ok(out) => {
                let out_bytes = serde_json::to_vec(&out)?;
                Ok(out_bytes)
            }
            Err(e) => Err(HandlerError::new(e)),
        }
    }
}

/// Creates a new runtime and begins polling for events using Lambda's Runtime APIs.
///
/// # Arguments
///
/// * `f` A function pointer that conforms to the `Handler` type.
///
/// # Panics
/// The function panics if the Lambda environment variables are not set.
pub fn start<Event, Output, EventError>(f: impl Handler<Event, Output, EventError>, runtime: Option<TokioRuntime>)
where
    Event: serde::de::DeserializeOwned,
    Output: serde::Serialize,
    EventError: Fail + LambdaErrorExt + Display + Send + Sync,
{
    let wrapped = wrap(f);
    start_with_config(wrapped, &EnvConfigProvider::default(), runtime)
}

/// Initializes the Lambda runtime with the given handler. Optionally this macro can
/// also receive a customized instance of Tokio runtime to drive internal lambda operations
/// to completion
#[macro_export]
macro_rules! lambda {
    ($handler:ident) => {
        $crate::start($handler, None)
    };
    ($handler:ident, $runtime:expr) => {
        $crate::start($handler, Some($runtime))
    };
    ($handler:expr) => {
        $crate::start($handler, None)
    };
    ($handler:expr, $runtime:expr) => {
        $crate::start($handler, Some($runtime))
    };
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use lambda_runtime_core::Context;
    use serde_derive::{Deserialize, Serialize};
    use serde_json;

    fn test_context() -> Context {
        Context {
            memory_limit_in_mb: 128,
            function_name: "test_func".to_string(),
            function_version: "$LATEST".to_string(),
            invoked_function_arn: "arn:aws:lambda".to_string(),
            aws_request_id: "123".to_string(),
            xray_trace_id: Some("123".to_string()),
            log_stream_name: "logStream".to_string(),
            log_group_name: "logGroup".to_string(),
            client_context: Option::default(),
            identity: Option::default(),
            deadline: 0,
        }
    }

    #[derive(Serialize, Deserialize)]
    struct Input {
        name: String,
    }

    #[derive(Serialize, Deserialize)]
    struct Output {
        msg: String,
    }

    #[test]
    fn runtime_invokes_handler() {
        let handler_ok = |_e: Input, _c: Context| -> Result<Output, HandlerError> {
            Ok(Output {
                msg: "hello".to_owned(),
            })
        };
        let mut wrapped_ok = wrap(handler_ok);
        let input = Input {
            name: "test".to_owned(),
        };
        let output = wrapped_ok.run(
            serde_json::to_vec(&input).expect("Could not convert input to Vec"),
            test_context(),
        );
        assert_eq!(
            output.is_err(),
            false,
            "Handler threw an unexpected error: {}",
            output.err().unwrap()
        );
        let output_obj: Output = serde_json::from_slice(&output.ok().unwrap()).expect("Could not serialize output");
        assert_eq!(
            output_obj.msg,
            "hello".to_owned(),
            "Unexpected output message: {}",
            output_obj.msg
        );
    }

    #[test]
    fn runtime_captures_error() {
        let handler_ok = |e: Input, _c: Context| -> Result<Output, HandlerError> {
            let _age = e.name.parse::<u8>()?;
            Ok(Output {
                msg: "hello".to_owned(),
            })
        };
        let mut wrapped_ok = wrap(handler_ok);
        let input = Input {
            name: "test".to_owned(),
        };
        let output = wrapped_ok.run(
            serde_json::to_vec(&input).expect("Could not convert input to Vec"),
            test_context(),
        );
        assert_eq!(output.is_err(), true, "Handler did not throw an error");
        let err = output.err().unwrap();
        assert_eq!(
            err.error_type(),
            "std::num::ParseIntError",
            "Unexpected error_type: {}",
            err.error_type()
        );
    }
}