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
//! `HttpService` server that uses AWS Lambda Rust Runtime as backend.
//!
//! This crate builds on the standard http interface provided by the
//! [lambda_http](https://docs.rs/lambda_http) crate and provides a http server
//! that runs on the lambda runtime.
//!
//! Compatible services like [tide](https://github.com/rustasync/tide) apps can
//! run on lambda and processing events from API Gateway or ALB without much
//! change.
//!
//! # Examples
//!
//! **Hello World**
//!
//! ```rust,ignore
//! fn main() {
//!     let mut app = tide::App::new();
//!     app.at("/").get(async move |_| "Hello, world!");
//!     http_service_lambda::run(app.into_http_service());
//! }
//! ```

#![forbid(future_incompatible, rust_2018_idioms)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, missing_doc_code_examples)]
#![cfg_attr(test, deny(warnings))]

use futures::{FutureExt, TryFutureExt};
use http_service::{Body as HttpBody, HttpService, Request as HttpRequest};
use lambda_http::{Body as LambdaBody, Handler, Request as LambdaHttpRequest};
use lambda_runtime::{error::HandlerError, Context};
use std::future::Future;
use std::sync::Arc;
use tokio::runtime::Runtime as TokioRuntime;

type LambdaResponse = lambda_http::Response<lambda_http::Body>;

trait ResultExt<OK, ERR> {
    fn handler_error(self, description: &str) -> Result<OK, HandlerError>;
}

impl<OK, ERR> ResultExt<OK, ERR> for Result<OK, ERR> {
    fn handler_error(self, description: &str) -> Result<OK, HandlerError> {
        self.map_err(|_| HandlerError::from(description))
    }
}

trait CompatHttpBodyAsLambda {
    fn into_lambda(self) -> LambdaBody;
}

impl CompatHttpBodyAsLambda for Vec<u8> {
    fn into_lambda(self) -> LambdaBody {
        if self.is_empty() {
            return LambdaBody::Empty;
        }
        match String::from_utf8(self) {
            Ok(s) => LambdaBody::from(s),
            Err(e) => LambdaBody::from(e.into_bytes()),
        }
    }
}

struct Server<S> {
    service: Arc<S>,
    rt: TokioRuntime,
}

impl<S> Server<S>
where
    S: HttpService,
{
    fn new(s: S) -> Server<S> {
        Server {
            service: Arc::new(s),
            rt: tokio::runtime::Runtime::new().expect("failed to start new Runtime"),
        }
    }

    fn serve(
        &self,
        req: LambdaHttpRequest,
    ) -> impl Future<Output = Result<LambdaResponse, HandlerError>> {
        let service = self.service.clone();
        async move {
            let req: HttpRequest = req.map(|b| HttpBody::from(b.as_ref()));
            let mut connection = service
                .connect()
                .into_future()
                .await
                .handler_error("connect")?;
            let (parts, body) = service
                .respond(&mut connection, req)
                .into_future()
                .await
                .handler_error("respond")?
                .into_parts();
            let resp = LambdaResponse::from_parts(
                parts,
                body.into_vec().await.handler_error("body")?.into_lambda(),
            );
            Ok(resp)
        }
    }
}

impl<S> Handler<LambdaResponse> for Server<S>
where
    S: HttpService,
{
    fn run(
        &mut self,
        req: LambdaHttpRequest,
        _ctx: Context,
    ) -> Result<LambdaResponse, HandlerError> {
        // Lambda processes one event at a time in a Function. Each invocation
        // is not in async context so it's ok to block here.
        self.rt.block_on(self.serve(req).boxed().compat())
    }
}

/// Run the given `HttpService` on the default runtime, using `lambda_http` as
/// backend.
pub fn run<S: HttpService>(s: S) {
    let server = Server::new(s);
    // Let Lambda runtime start its own tokio runtime
    lambda_http::start(server, None);
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::future;

    struct DummyService;

    impl HttpService for DummyService {
        type Connection = ();
        type ConnectionFuture = future::Ready<Result<(), ()>>;
        type ResponseFuture = future::BoxFuture<'static, Result<http_service::Response, ()>>;
        fn connect(&self) -> Self::ConnectionFuture {
            future::ok(())
        }
        fn respond(&self, _conn: &mut (), _req: http_service::Request) -> Self::ResponseFuture {
            Box::pin(async move { Ok(http_service::Response::new(http_service::Body::empty())) })
        }
    }

    #[test]
    fn handle_apigw_request() {
        // from the docs
        // https://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-api-gateway-request
        let input = include_str!("../tests/data/apigw_proxy_request.json");
        let request = lambda_http::request::from_str(input).unwrap();
        let mut handler = Server::new(DummyService);
        let result = handler.run(request, Context::default());
        assert!(
            result.is_ok(),
            format!("event was not handled as expected {:?}", result)
        );
    }

    #[test]
    fn handle_alb_request() {
        // from the docs
        // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers
        let input = include_str!("../tests/data/alb_request.json");
        let request = lambda_http::request::from_str(input).unwrap();
        let mut handler = Server::new(DummyService);
        let result = handler.run(request, Context::default());
        assert!(
            result.is_ok(),
            format!("event was not handled as expected {:?}", result)
        );
    }
}