|
| 1 | +# Runtime Extensions for AWS Lambda in Rust |
| 2 | + |
| 3 | +[](https://docs.rs/lambda_extension) |
| 4 | + |
| 5 | +**`lambda-extension`** is a library that makes it easy to write AWS Lambda Runtime Extensions in Rust. |
| 6 | + |
| 7 | +## Example extension |
| 8 | + |
| 9 | +The code below creates a simple extension that's registered to every `INVOKE` and `SHUTDOWN` events, and logs them in CloudWatch. |
| 10 | + |
| 11 | +```rust,no_run |
| 12 | +use lambda_extension::{extension_fn, Error, NextEvent}; |
| 13 | +use log::LevelFilter; |
| 14 | +use simple_logger::SimpleLogger; |
| 15 | +use tracing::info; |
| 16 | +
|
| 17 | +async fn log_extension(event: NextEvent) -> Result<(), Error> { |
| 18 | + match event { |
| 19 | + NextEvent::Shutdown(event) => { |
| 20 | + info!("{}", event); |
| 21 | + } |
| 22 | + NextEvent::Invoke(event) => { |
| 23 | + info!("{}", event); |
| 24 | + } |
| 25 | + } |
| 26 | + Ok(()) |
| 27 | +} |
| 28 | +
|
| 29 | +#[tokio::main] |
| 30 | +async fn main() -> Result<(), Error> { |
| 31 | + SimpleLogger::new().with_level(LevelFilter::Info).init().unwrap(); |
| 32 | +
|
| 33 | + let func = extension_fn(log_extension); |
| 34 | + lambda_extension::run(func).await |
| 35 | +} |
| 36 | +``` |
| 37 | + |
| 38 | +## Deployment |
| 39 | + |
| 40 | +Lambda extensions can be added to your functions either using [Lambda layers](https://docs.aws.amazon.com/lambda/latest/dg/using-extensions.html#using-extensions-config), or adding them to [containers images](https://docs.aws.amazon.com/lambda/latest/dg/using-extensions.html#invocation-extensions-images). Regardless of how you deploy them, the extensions MUST be compiled against the same architecture that your lambda functions runs on. The only two architectures that AWS Lambda supports are `aarch64-unknown-linux-gnu` for ARM functions, and `x86_64-unknown-linux-gnu` for x86 functions. |
| 41 | + |
| 42 | +### Building extensions |
| 43 | + |
| 44 | +Once you've decided which target you'll use, you can install it by running the next `rustup` command: |
| 45 | + |
| 46 | +```bash |
| 47 | +$ rustup target add x86_64-unknown-linux-gnu |
| 48 | +``` |
| 49 | + |
| 50 | +Then, you can compile the extension against that target: |
| 51 | + |
| 52 | +```bash |
| 53 | +$ cargo build -p lambda_extension --example basic --release --target x86_64-unknown-linux-gnu |
| 54 | +``` |
| 55 | + |
| 56 | +This previous command will generate a binary file in `target/x86_64-unknown-linux-gnu/release/examples` called `basic`. When the extension is registered with the [Runtime Extensions API](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-extensions-api.html#runtimes-extensions-api-reg), that's the name that the extension will be registered with. If you want to register the extension with a different name, you only have to rename this binary file and deploy it with the new name. |
0 commit comments