Istvan
Istvan

Reputation: 8572

How to pass in stateful client to lambda function?

I am working on a simple Lambda function and I was wondering if I could pass in client (dynamodb this time) to the handler, so we do not re-connect for every request.

The macro is defined here:

https://docs.rs/lambda_http/0.1.1/lambda_http/macro.lambda.html 3

My function so far:

fn main() -> Result<(), Box<dyn Error>> {
    simple_logger::init_with_level(log::Level::Debug)?;
    info!("Starting up...");
    let dynamodb_client = DynamoDbClient::new(Region::EuCentral1);
    lambda!(router);
    return Ok(());
}

fn router(req: Request, ctx: Context) -> Result<impl IntoResponse, HandlerError> {
let h_req = HReq {
    http_path: req.uri().path(),
    http_method: req.method(),
};

match h_req {
    HReq {
        http_path: "/login",
        http_method: &Method::POST,
    } => user_login(req, ctx),

    _ => {
        error!(
            "Not supported http method or path {}, {}",
            h_req.http_path, h_req.http_method
        );
        let mut resp = Response::default();
        *resp.status_mut() = StatusCode::METHOD_NOT_ALLOWED;
        Ok(resp)
    }
}

}

Is it possible to extend this macro to have a second option so I can add the client all the way down to the functions which are actually talking to the database?

Upvotes: 1

Views: 350

Answers (2)

Istvan
Istvan

Reputation: 8572

After considering all the options I decided to implement this with lazy_static.

#[macro_use]
extern crate lazy_static;

lazy_static! {
    static ref DYNAMODB_CLIENT: DynamoDbClient = DynamoDbClient::new(Region::EuCentral1);
}

This is getting instantiated at run time and can be used internally in the module without any problems.

Upvotes: 0

K Mo
K Mo

Reputation: 2155

DynamoDB is a web service, each request to it is treated as a distinct API call.

There is no functionality to keep a client connection alive in the same way you would with a regular database connection (e.g. MySQL).

My rust knowledge is a little lacking, so I don't know if http keepalive is set by default with the DynamoDBClient, but making sure http keepalive is set will help performance.

Upvotes: 2

Related Questions