Skip to content

how to initialize SDK client outside of function handler #616

Closed
@peterborkuti

Description

@peterborkuti

Dear Developers,

I created an example for s3:
peterborkuti@dbc5d3d

It works, but as I read aws best practices for lambda:
https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html
"Initialize SDK clients and database connections outside of the function handler"

I could not do it (I am absolute beginner in Rust but I have solid knowledge in Java and JavaScript)

What I tried

creating static/const but client creation is async

const client: Client = get_client().await;

static mut

static mut client : Option<Client> = None;
...
// in main:
client = Some(get_client().await); // but it is unsafe

using lambdas context in main

pub(crate) async fn function_handler<F1, Fut1, F2, Fut2>(fn_get_file: F1, fn_put_file: F2, event: LambdaEvent<S3Event>) -> Result<(), Error> 
    where
        F1: Fn(&str, &str) -> Fut1,
        Fut1: Future<Output = Option<Cursor<Vec<u8>>>>,
        F2: Fn(&str, &str, ByteStream) -> Fut2,
        Fut2: Future<Output = ()>
     {

(With the above handler testing would be very easy, I think, because the client is "embedded" in the fn_get_file and fn_put_file functions, so when testing we do not need sdk client at all)

in main I tried to binding the client parameters to fn_get_file and fn_put_file:

    let client = get_client().await;

    let clientRef = |x:Client| &x;

    let clientBroker = move || clientRef(client); 

    let fn_get_file = move |bucket: &str, key: &str| get_file(&clientBroker(), bucket, key);
    let fn_put_file = |bucket: &str, key: &str, bytes: ByteStream| put_file(&clientBroker(), bucket, key, bytes);
    let fn_function_handler = |event: LambdaEvent<S3Event>| function_handler(fn_get_file, fn_put_file, event);  

    run(service_fn(fn_function_handler)).await
    

First I had lifetime issues (tried to solve with "move" and now I got:"expected a closure that implements the Fn trait, but this closure only implements FnOnce":

Do you have any ideas how to do it?

Thank you in advance
Péter

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions