### Install Cargo Lambda with uv Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Install Cargo Lambda as an executable using uv. ```bash uv tool install cargo-lambda ``` -------------------------------- ### Install AWS CDK Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/http-axum/cdk/README.md Install the AWS CDK globally using NPM. ```bash npm install -g cdk ``` -------------------------------- ### Install Cargo Lambda with Scoop Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Use Scoop to install Cargo Lambda on Windows. ```bash scoop bucket add cargo-lambda https://github.com/cargo-lambda/scoop-cargo-lambda scoop install cargo-lambda/cargo-lambda ``` -------------------------------- ### Install npm dependencies Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/advanced-appconfig-feature-flags/README.md Navigate to the cdk directory and install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Deploy Lambda Function with AWS SAM CLI Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Deploy your serverless application defined in `template.yaml` using the AWS SAM CLI. Use the guided deployment option for initial setup. ```bash sam deploy --guided ``` -------------------------------- ### Install Cargo Lambda with Homebrew Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Use Homebrew to install Cargo Lambda on macOS. ```bash brew tap cargo-lambda/cargo-lambda brew install cargo-lambda ``` -------------------------------- ### Lambda Function URL Example Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/http-axum/cdk/README.md This is an example of the Lambda Function URL that will be printed after a successful stack deployment when the `ENABLE_LAMBDA_RUST_AXUM_FUNCTION_URL` environment variable is set. ```text CdkStack.AxumFunctionUrl = https://7st53uq3rpk4jweki2ek765gty0icvuf.lambda-url.us-east-1.on.aws/ ``` -------------------------------- ### Install Cargo Lambda with Pip Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Install Cargo Lambda using pip on any system with Python 3. ```bash pip3 install cargo-lambda ``` -------------------------------- ### Build Lambda Extension Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/extension-basic/README.md Build the Lambda extension for the default architecture. Ensure cargo-lambda is installed. ```bash cargo lambda build --release --extension ``` -------------------------------- ### Start Local Dev Server with Cargo Lambda Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Use `cargo lambda watch` to compile your function and start a local server that emulates the AWS Lambda control plane. This command works on Windows, Linux, and MacOS. ```bash cargo lambda watch ``` -------------------------------- ### API Gateway Endpoint URL Example Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/http-axum/cdk/README.md This is an example of the API Gateway endpoint URL that will be printed after a successful stack deployment. ```text CdkStack.axumEndpointC1B330D3 = https://sr0e4dqg1b.execute-api.us-east-1.amazonaws.com/prod/ ``` -------------------------------- ### Build CDK stack Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/advanced-appconfig-feature-flags/README.md Build the AWS CDK stack after installing dependencies. ```bash npm run build ``` -------------------------------- ### Initialize SDK Clients Outside Handler Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-http/README.md This example demonstrates initializing AWS SDK clients (like DynamoDB) outside the main handler function to leverage execution environment reuse for better performance. The DynamoDB client is passed into the handler. ```rust use aws_sdk_dynamodb::model::AttributeValue; use chrono::Utc; use lambda_http::{run, http::{StatusCode, Response}, service_fn, Error, RequestExt, IntoResponse, Request}; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .without_time() .with_max_level(tracing::Level::INFO) .init(); let config = aws_config::from_env() .load() .await; let dynamodb_client = aws_sdk_dynamodb::Client::new(&config); run(service_fn(|event: Request| function_handler(&dynamodb_client, event))).await } pub async fn function_handler(dynamodb_client: &aws_sdk_dynamodb::Client, event: Request) -> Result { let table = std::env::var("TABLE_NAME").expect("TABLE_NAME must be set"); let name = event.query_string_parameters_ref() .and_then(|params| params.first("name")) .unwrap_or_else(|| "stranger") .to_string(); dynamodb_client .put_item() .table_name(table) .item("ID", AttributeValue::S(Utc::now().timestamp().to_string())) .item("name", AttributeValue::S(name.to_owned())) .send() .await?; // Represents an HTTP response let response = Response::builder() .status(StatusCode::OK) .header("Content-Type", "application/json") .body(json!({ "message": format!("Hello, {}!", name), }).to_string()) .map_err(Box::new)?; Ok(response) } ``` -------------------------------- ### Example using builders with API Gateway custom authorizers Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-events/README.md Demonstrates type-safe, immutable construction of API Gateway V2 custom authorizer responses using the builder pattern. Ensure the 'builders' feature is enabled. ```rust use aws_lambda_events::event::apigw::{ ApiGatewayV2CustomAuthorizerSimpleResponse, ApiGatewayV2CustomAuthorizerV2Request, }; use lambda_runtime::{Error, LambdaEvent}; // Context type without Default implementation struct MyContext { user_id: String, permissions: Vec, } async fn handler( event: LambdaEvent, ) -> Result, Error> { let context = MyContext { user_id: "user-123".to_string(), permissions: vec!["read".to_string()], }; let response = ApiGatewayV2CustomAuthorizerSimpleResponse::builder() .is_authorized(true) .context(context) .build(); Ok(response) } ``` -------------------------------- ### Graceful Shutdown Handler Example Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Demonstrates using `spawn_graceful_shutdown_handler` with a custom shutdown hook to clean up resources, such as dropping a tracing log guard, upon receiving SIGTERM or SIGKILL. ```rust use lambda_runtime::{service_fn, LambdaEvent, Error}; use serde_json::{json, Value}; #[tokio::main] async fn main() -> Result<(), Error> { let func = service_fn(func); let (writer, log_guard) = tracing_appender::non_blocking(std::io::stdout()); lambda_runtime::tracing::init_default_subscriber_with_writer(writer); let shutdown_hook = || async move { std::mem::drop(log_guard); }; lambda_runtime::spawn_graceful_shutdown_handler(shutdown_hook).await; lambda_runtime::run(func).await?; Ok(()) } async fn func(event: LambdaEvent) -> Result { let (event, _context) = event.into_parts(); let first_name = event["firstName"].as_str().unwrap_or("world"); Ok(json!({ "message": format!("Hello, {}!", first_name) })) } ``` -------------------------------- ### Basic Rust Lambda Function Example Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md A simple Rust Lambda function that processes a JSON event with a 'firstName' field and returns a greeting. This example requires the 'lambda_runtime' and 'serde_json' crates. ```rust use lambda_runtime::{service_fn, LambdaEvent, Error}; use serde_json::{json, Value}; #[tokio::main] async fn main() -> Result<(), Error> { let func = service_fn(func); lambda_runtime::run(func).await?; Ok(()) } async fn func(event: LambdaEvent) -> Result { let (event, _context) = event.into_parts(); let first_name = event["firstName"].as_str().unwrap_or("world"); Ok(json!({ "message": format!("Hello, {}!", first_name) })) } ``` -------------------------------- ### Example Dockerized Test Suite Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md This JSON defines a test case for the `containerized-test-runner-for-aws-lambda`. It specifies the handler, request payload, and assertions, including response transformation using jq syntax. ```json { "tests": [ { "name": "test_echo", "handler": "basic-lambda", "request": { "command": "test" }, "assertions": [ { "response": { "msg": "Command test executed." }, "transform": "{msg: .msg}" } ] } ] } ``` -------------------------------- ### Lambda Request Authorizer Example Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-http/README.md This snippet demonstrates how to create a custom authorizer for API Gateway using Rust. It handles authorization logic based on request headers and generates an IAM policy response. ```rust use aws_lambda_events::apigw::{ ApiGatewayCustomAuthorizerRequestTypeRequest, ApiGatewayCustomAuthorizerResponse, ApiGatewayCustomAuthorizerPolicy, IamPolicyStatement, }; use lambda_runtime::{run, service_fn, Error, LambdaEvent}; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .without_time() .with_max_level(tracing::Level::INFO) .init(); run(service_fn(function_handler)).await } pub async fn function_handler(event: LambdaEvent) -> Result { // do something with the event payload let method_arn = event.payload.method_arn.unwrap(); // for example we could use the authorization header if let Some(token) = event.payload.headers.get("authorization") { // do something return Ok(custom_authorizer_response( "ALLOW", "some_principal", &method_arn, )); } Ok(custom_authorizer_response( &"DENY".to_string(), "", &method_arn)) } pub fn custom_authorizer_response(effect: &str, principal: &str, method_arn: &str) -> ApiGatewayCustomAuthorizerResponse { let stmt = IamPolicyStatement { action: vec!["execute-api:Invoke".to_string()], resource: vec![method_arn.to_owned()], effect: Some(effect.to_owned()), }; let policy = ApiGatewayCustomAuthorizerPolicy { version: Some("2012-10-17".to_string()), statement: vec![stmt], }; ApiGatewayCustomAuthorizerResponse { principal_id: Some(principal.to_owned()), policy_document: policy, context: json!({ "email": principal }), // https://github.com/aws/aws-lambda-rust-runtime/discussions/548 usage_identifier_key: None, } } ``` -------------------------------- ### Lambda Telemetry Processor Extension in Rust Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-extension/README.md Develop a Lambda Extension to process telemetry data. This example demonstrates handling function and platform initialization telemetry events. ```rust use lambda_extension::{service_fn, Error, Extension, LambdaTelemetry, LambdaTelemetryRecord, SharedService}; use tracing::info; async fn handler(events: Vec) -> Result<(), Error> { for event in events { match event.record { LambdaTelemetryRecord::Function(record) => { // do something with the function log record }, LambdaTelemetryRecord::PlatformInitStart { initialization_type: _, phase: _, runtime_version: _, runtime_version_arn: _, } => { // do something with the PlatformInitStart event }, // more types of telemetry events are available _ => () } } Ok(()) } #[tokio::main] async fn main() -> Result<(), Error> { let telemetry_processor = SharedService::new(service_fn(handler)); Extension::new().with_telemetry_processor(telemetry_processor).run().await?; Ok(()) } ``` -------------------------------- ### Build and Deploy Rust Lambda Function Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/basic-lambda-external-runtime/README.md Use cargo-lambda to build and deploy your Rust function. Ensure you have installed cargo-lambda and have an IAM role configured for deployment. ```bash cargo lambda build --release ``` ```bash cargo lambda deploy --iam-role YOUR_ROLE ``` -------------------------------- ### AWS Lambda Error Structure Example Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md An example JSON structure representing an error for AWS Lambda. This format includes the type and message of the error. ```json { "error_type": "the type of error raised", "error_message": "a string description of the error" } ``` -------------------------------- ### Lambda Log Processor Extension in Rust Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-extension/README.md Implement a Lambda Extension to process logs using the Lambda Logs API. This example shows how to iterate through log records and handle function or extension logs. ```rust use lambda_extension::{service_fn, Error, Extension, LambdaLog, LambdaLogRecord, SharedService}; use tracing::info; async fn handler(logs: Vec) -> Result<(), Error> { for log in logs { match log.record { LambdaLogRecord::Function(_record) => { // do something with the function log record }, LambdaLogRecord::Extension(_record) => { // do something with the extension log record }, _ => () } } Ok(()) } #[tokio::main] async fn main() -> Result<(), Error> { let logs_processor = SharedService::new(service_fn(handler)); Extension::new().with_logs_processor(logs_processor).run().await?; Ok(()) } ``` -------------------------------- ### Custom Event Serialization and Deserialization with Serde Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Defines custom event and response structures for Lambda functions using Serde for JSON serialization and deserialization. This example demonstrates handling custom ice cream events. ```rust use serde::{Serialize, Deserialize}; use serde_json::json; use std::error::Error; #[derive(Serialize, Deserialize)] pub struct NewIceCreamEvent { pub flavors: Vec, } #[derive(Serialize, Deserialize)] pub struct NewIceCreamResponse { pub flavors_added_count: usize, } fn main() -> Result<(), Box> { let flavors = json!({ "flavors": [ "Nocciola", "抹茶", "आम" ] }); let event: NewIceCreamEvent = serde_json::from_value(flavors)?; let response = NewIceCreamResponse { flavors_added_count: event.flavors.len(), }; serde_json::to_string(&response)?; Ok(()) } ``` -------------------------------- ### Enable Specific Lambda HTTP Feature Flag Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-http/README.md Example of how to disable default features and enable a specific feature flag (e.g., 'apigw_rest') for the lambda_http dependency in Cargo.toml. ```toml [dependencies.lambda_http] version = "0.5.3" default-features = false features = ["apigw_rest"] ``` -------------------------------- ### Deploy the Stack Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/http-axum/cdk/README.md Deploy the CDK stack to your AWS account. ```bash npm run cdk deploy ``` -------------------------------- ### Simple Lambda Extension in Rust Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-extension/README.md Create a basic Lambda Extension that responds to INVOKE and SHUTDOWN events. Ensure tokio and tracing are set up for async execution and logging. ```rust use lambda_extension::{service_fn, Error, LambdaEvent, NextEvent}; async fn my_extension(event: LambdaEvent) -> Result<(), Error> { match event.next { NextEvent::Shutdown(_e) => { // do something with the shutdown event } NextEvent::Invoke(_e) => { // do something with the invoke event } } Ok(()) } #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) // disable printing the name of the module in every log line. .with_target(false) // disabling time is handy because CloudWatch will add the ingestion time. .without_time() .init(); let func = service_fn(my_extension); lambda_extension::run(func).await } ``` -------------------------------- ### Run Local Development with AWS SDK for Rust Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/basic-sdk/README.md Use `cargo lambda watch` for local development. Manually supply a credentials file profile if environment variables are not set. ```bash AWS_PROFILE=my-profile cargo lambda watch ``` -------------------------------- ### Build Lambda Extension with cargo-lambda Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-extension/README.md Compile a Lambda Extension for release using cargo-lambda. Use the `--extension` flag for extensions and `--arm64` for ARM architecture builds. ```bash cargo lambda build --release --extension ``` ```bash cargo lambda build --release --extension --arm64 ``` -------------------------------- ### Build and Deploy Lambda Extension Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/extension-custom-events/README.md Use cargo-lambda to build and deploy the extension as a layer. The deploy command provides the ARN for the extension layer. ```bash cargo lambda build --release --extension ``` ```bash cargo lambda deploy --extension ``` -------------------------------- ### Build and Deploy Lambda Function Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/basic-streaming-response/README.md Commands to build and deploy a Rust Lambda function. Ensure you replace YOUR_ROLE with your actual IAM role. ```bash cargo lambda build --release ``` ```bash cargo lambda deploy --enable-function-url --iam-role YOUR_ROLE ``` -------------------------------- ### Build Lambda Binary with ZIP Output using Cargo Lambda Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Build your Rust Lambda function and package it as a zip file for deployment. Ensure to use the appropriate architecture flag. ```bash cargo lambda build --release --arm64 --output-format zip ``` -------------------------------- ### Create Lambda Function with AWS CLI Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Deploy a previously built Lambda function zip archive using the AWS CLI. Ensure the runtime and role ARN are correctly specified. ```bash $ aws lambda create-function --function-name rustTest \ --handler bootstrap \ --zip-file fileb://./target/lambda/basic/bootstrap.zip \ --runtime provided.al2023 \ --role arn:aws:iam::XXXXXXXXXXXXX:role/your_lambda_execution_role \ --environment Variables={RUST_BACKTRACE=1} \ --tracing-config Mode=Active ``` -------------------------------- ### Build and Deploy Rust Lambda Functions Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/advanced-sqs-multiple-functions-shared-data/README.md Commands to build and deploy Rust Lambda functions using cargo-lambda. Ensure QUEUE_URL is set for the producer. ```bash cargo lambda build --release ``` ```bash cargo lambda deploy consumer --iam-role YOUR_ROLE ``` ```bash cargo lambda deploy producer --iam-role YOUR_ROLE ``` -------------------------------- ### Deploy Lambda Extension Layer Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/extension-basic/README.md Deploy the built extension as a Lambda layer. The ARN provided can be used in your Lambda function configuration. ```bash cargo lambda deploy --extension ``` -------------------------------- ### Register Lambda Extension Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-runtime-api-client/README.md Demonstrates how to register a Lambda extension with the Runtime API. This involves constructing a POST request with the extension name and desired event types. ```rust use http::{Method, Request}; use hyper::Body; use lambda_runtime_api_client::{build_request, Client, Error}; fn register_request(extension_name: &str, events: &[&str]) -> Result, Error> { let events = serde_json::json!({ "events": events }); let req = build_request() .method(Method::POST) .uri("/2020-01-01/extension/register") .header("Lambda-Extension-Name", extension_name) .body(Body::from(serde_json::to_string(&events)?))?; Ok(req) } #[tokio::main] async fn main() -> Result<(), Error> { let client = Client::builder().build()?; let request = register_request("my_extension", &["INVOKE"])?; client.call(request).await } ``` -------------------------------- ### Deploy CDK stack Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/advanced-appconfig-feature-flags/README.md Deploy the AWS CDK stack to provision the infrastructure. ```bash cdk deploy ``` -------------------------------- ### Test Function Locally Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/extension-internal-flush/README.md Use `cargo lambda watch` to continuously build and run your function locally. Invoke it with sample data using `cargo lambda invoke`. ```bash cargo lambda watch ``` ```bash cargo lambda invoke --data-ascii '{"Records":[{"messageId":"MessageID_1","receiptHandle":"MessageReceiptHandle","body":"{\"a\":\"Test\",\"b\":123}"}]}' ``` -------------------------------- ### Build Lambda Extension for ARM 64 Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/extension-custom-events/README.md Build the extension specifically for ARM 64 architecture using cargo-lambda. ```bash cargo lambda build --release --extension --arm64 ``` -------------------------------- ### Test with Runtime Interface Emulator (RIE) Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Run `make test-rie` to build and test your Lambda function using the official AWS Lambda Runtime Interface Emulator. You can specify a custom handler or concurrency settings. ```bash make test-rie ``` ```bash HANDLER="basic-tenant-id" make test-rie ``` ```bash RIE_MAX_CONCURRENCY=4 make test-rie ``` -------------------------------- ### Configure AWS Credentials Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-extension/README.md Set up AWS CLI credentials in your terminal for deploying resources. This command prompts for Access Key ID, Secret Access Key, default region, and output format. ```bash aws configure ``` -------------------------------- ### Enable builder pattern support Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-events/README.md Add this command to enable the 'builders' feature, which provides builder pattern support for event types. ```bash cargo add aws_lambda_events --features builders ``` -------------------------------- ### Deploy Lambda Function with Cargo Lambda Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Use this command to deploy your Rust Lambda function. The function name will match your Rust package name. ```bash cargo lambda deploy ``` -------------------------------- ### Create a new Lambda function with Cargo Lambda Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Use the 'new' subcommand of Cargo Lambda to generate a new Rust Lambda function project. ```bash cargo lambda new YOUR_FUNCTION_NAME ``` -------------------------------- ### Add aws_lambda_events with specific features Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-events/README.md Use this command to add the crate to your project, disabling default features and enabling only the 'apigw' and 'alb' event features. ```bash cargo add aws_lambda_events --no-default-features --features apigw,alb ``` -------------------------------- ### Build Lambda Function with Cargo Lambda Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Builds a Rust Lambda function in release mode using Cargo Lambda. This is the standard command for creating a deployable artifact. ```bash cargo lambda build --release ``` -------------------------------- ### Add SQS Trigger to Lambda Consumer Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/advanced-sqs-multiple-functions-shared-data/README.md AWS CLI command to create an event source mapping, linking an SQS queue to a Lambda consumer function. Set the batch size as needed. ```bash aws lambda create-event-source-mapping \ --function-name consumer \ --region \ --event-source-arn \ --batch-size 1 ``` -------------------------------- ### Cross-Compile Lambda for ARM64 on Amazon Linux 2023 Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Builds a Rust Lambda function for the ARM64 architecture targeting Amazon Linux 2023. This is useful for Graviton-based Lambda instances. ```bash cargo lambda build --release --arm64 ``` -------------------------------- ### Build Rust Lambda Function for ARM 64 Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/basic-lambda-external-runtime/README.md Build your Rust Lambda function specifically for the ARM 64 architecture using the --arm64 flag with cargo lambda build. ```bash cargo lambda build --release --arm64 ``` -------------------------------- ### Enable Lambda Streaming Response Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/basic-streaming-response/README.md Instructions to enable the streaming response feature for your Lambda function URL via the AWS Lambda console. ```text Enable Lambda streaming response on Lambda console: change the function url's invoke mode to RESPONSE_STREAM ``` -------------------------------- ### AWS SAM Template for Rust Lambda Function Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Define your Lambda function infrastructure using a `template.yaml` file for deployment with AWS SAM CLI. Specify handler, runtime, and code location. ```yaml AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: MemorySize: 128 Architectures: ["arm64"] Handler: bootstrap Runtime: provided.al2023 Timeout: 5 CodeUri: target/lambda/basic/ Outputs: FunctionName: Value: !Ref HelloWorldFunction Description: Name of the Lambda function ``` -------------------------------- ### Invoke Lambda Function with AWS CLI Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Test your Lambda function using the AWS CLI after deployment. The `--cli-binary-format` argument is required for AWS CLI v2. ```bash $ aws lambda invoke \ --cli-binary-format raw-in-base64-out \ --function-name rustTest \ --payload '{"command": "Say Hi!"}' \ output.json ``` -------------------------------- ### Verify Streaming Response Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/basic-streaming-response/README.md Command to test the deployed Lambda function URL and verify that the response is streamed back with pauses. ```bash curl -v -N ``` -------------------------------- ### Initialize Default Tracing Subscriber Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Enables the default tracing subscriber for logging information to AWS CloudWatch. The log level is determined by the RUST_LOG environment variable. ```rust use lambda_runtime::{run, service_fn, tracing, Error}; #[tokio::main] async fn main() -> Result<(), Error> { tracing::init_default_subscriber(); run(service_fn(|event| tracing::info!(?event))).await } ``` -------------------------------- ### Automated Testing with Dockerized Test Harness Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Execute `make test-dockerized` to run automated tests using AWS's containerized test runner. This command utilizes test suites defined in JSON files. ```bash make test-dockerized ``` -------------------------------- ### Invoke Lambda Function Locally with Cargo Lambda Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Send requests to your locally running Lambda function using `cargo lambda invoke`. Replace `` with your function's name and provide data using `--data-ascii`. ```bash cargo lambda invoke --data-ascii '{ "command": "hi" }' ``` -------------------------------- ### Unit Test for HTTP Lambda Handler Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md This snippet demonstrates how to unit test a Lambda handler designed for HTTP events using `lambda_http`. It creates a `Request` from a string fixture. ```rust #[test] fn test_my_lambda_handler() { let input = include_str!("apigw_proxy_request.json"); let request = lambda_http::request::from_str(input) .expect("failed to create request"); let response = my_lambda_handler(request).await.expect("failed to handle request"); } ``` -------------------------------- ### Invoke HTTP Function Locally with cURL Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md For HTTP functions (Function URL, API Gateway), use `curl` to send POST requests to the local development server. Ensure the `content-type` header is set to `application/json`. ```bash curl -v -X POST \ 'http://127.0.0.1:9000/lambda-url//' \ -H 'content-type: application/json' \ -d '{ "command": "hi" }' ``` -------------------------------- ### Deploy Lambda Function with Custom Name using Cargo Lambda Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Specify a custom name for your Lambda function during deployment by appending it to the deploy command. ```bash cargo lambda deploy my-first-lambda-function ``` -------------------------------- ### SQS Batch Response with Item Failures Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Handles SQS batch messages and returns a response indicating which messages failed processing using the builder pattern. ```rust use aws_lambda_events::event::sqs::{ BatchItemFailureBuilder, SqsBatchResponseBuilder, SqsEvent, }; use lambda_runtime::{Error, LambdaEvent}; async fn handler(event: LambdaEvent) -> Result { let mut failures = Vec::new(); for record in event.payload.records { if let Err(_) = process_record(&record).await { let failure = BatchItemFailureBuilder::default() .item_identifier(record.message_id.unwrap()) .build()?; failures.push(failure); } } let response = SqsBatchResponseBuilder::default() .batch_item_failures(failures) .build()?; Ok(response) } ``` -------------------------------- ### Implement Custom Diagnostic from Error Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Implement the `From` for `Diagnostic` trait to control the `error_type` field. This provides full control over error reporting. ```rust use lambda_runtime::{Diagnostic, Error, LambdaEvent}; #[derive(Debug)] struct ErrorResponse(&'static str); impl From for Diagnostic { fn from(error: ErrorResponse) -> Diagnostic { Diagnostic { error_type: "MyErrorType".into(), error_message: error.0.to_string(), } } } async fn handler(_event: LambdaEvent<()>) -> Result<(), ErrorResponse> { Err(ErrorResponse("this is an error response")) } ``` -------------------------------- ### Invoke Lambda Function Remotely with Cargo Lambda Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Test your deployed Lambda function remotely using the invoke subcommand with sample data. ```bash cargo lambda invoke --remote \ --data-ascii '{"command": "hi"}' \ --output-format json \ my-first-lambda-function ``` -------------------------------- ### Invoke Lambda Function Deployed via SAM Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Invoke a Lambda function deployed using AWS SAM. Replace the placeholder function name with the actual name outputted by `sam deploy`. ```bash $ aws lambda invoke \ --cli-binary-format raw-in-base64-out \ --function-name HelloWorldFunction-XXXXXXXX \ --payload '{"command": "Say Hi!"}' \ output.json ``` -------------------------------- ### Invoke Lambda Function with AWS SDK for Rust Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/basic-sdk/README.md Invoke the Lambda function using `cargo lambda invoke` and provide the expected payload. ```bash cargo lambda invoke --data-ascii '{"bucket":"my-bucket"}' ``` -------------------------------- ### Transform Anyhow Error to Diagnostic Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md When the `anyhow` feature is enabled, `anyhow::Error` can be transformed into a `Diagnostic`. This simplifies error handling with the `anyhow` crate. ```rust use lambda_runtime::{Diagnostic, LambdaEvent}; async fn handler(_event: LambdaEvent) -> Result<(), Diagnostic> { Err(anyhow::anyhow!("this is an error").into()) } ``` -------------------------------- ### API Gateway Custom Authorizer Response with Builder Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Constructs a custom API Gateway V2 custom authorizer response using the builder pattern. This is useful for custom context types. ```rust use aws_lambda_events::event::apigw::{ ApiGatewayV2CustomAuthorizerSimpleResponseBuilder, ApiGatewayV2CustomAuthorizerV2Request, }; use lambda_runtime::{Error, LambdaEvent}; struct MyContext { user_id: String, permissions: Vec, } async fn handler( event: LambdaEvent, ) -> Result, Error> { let context = MyContext { user_id: "user-123".to_string(), permissions: vec!["read".to_string()], }; let response = ApiGatewayV2CustomAuthorizerSimpleResponseBuilder::default() .is_authorized(true) .context(context) .build()?; Ok(response) } ``` -------------------------------- ### Invoke Lambda Function Locally Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/basic-tenant-id/README.md Invokes the Lambda function locally using cargo-lambda. The tenant ID will be None during local testing unless a mock runtime environment with appropriate headers is set up. ```bash cargo lambda invoke --data-ascii '{"test": "data"}' ``` -------------------------------- ### Read Query String Parameters in Lambda Handler Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-http/README.md Extracts a 'name' query string parameter from an incoming HTTP request. Provides a default value if the parameter is missing. Requires the `RequestExt` trait. ```rust use lambda_http::{run, http::{StatusCode, Response}, service_fn, Error, RequestExt, IntoResponse, Request}; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .without_time() .with_max_level(tracing::Level::INFO) .init(); run(service_fn(function_handler)).await } pub async fn function_handler(event: Request) -> Result { let name = event.query_string_parameters_ref() .and_then(|params| params.first("name")) .unwrap_or_else(|| "stranger") .to_string(); // Represents an HTTP response let response = Response::builder() .status(StatusCode::OK) .header("Content-Type", "application/json") .body(json!({ "message": format!("Hello, {}!", name), }).to_string()) .map_err(Box::new)?; Ok(response) } ``` -------------------------------- ### Unit Test for Standard Lambda Handler Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/README.md Use this snippet to unit test a standard Lambda handler by directly calling it with deserialized event data and a default context. ```rust #[test] fn test_my_lambda_handler() { let input = serde_json::from_str("{\"command\": \"Say Hi!\"}").expect("failed to parse event"); let context = lambda_runtime::Context::default(); let event = lambda_runtime::LambdaEvent::new(input, context); my_lambda_handler(event).await.expect("failed to handle event"); } ``` -------------------------------- ### Access Tenant ID in Lambda Function Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/basic-tenant-id/README.md Accesses the tenant ID from the Lambda context and prints it. The tenant ID is automatically extracted from the 'lambda-runtime-aws-tenant-id' header. ```rust async fn function_handler(event: LambdaEvent) -> Result { let (event, context) = event.into_parts(); // Access tenant ID from context match &context.tenant_id { Some(tenant_id) => println!("Processing for tenant: {}", tenant_id), None => println!("No tenant ID provided"), } // ... rest of function logic } ``` -------------------------------- ### Destroy the Stack Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/http-axum/cdk/README.md Delete all resources created by the CDK stack from your AWS account. ```bash npm run cdk destroy ``` -------------------------------- ### Deserialize JSON Body in Lambda Handler Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/lambda-http/README.md Handles API Gateway proxy requests by deserializing a JSON payload into a Rust struct. Requires the `RequestPayloadExt` trait and `serde` for deserialization. ```rust use lambda_http::{run, http::{StatusCode, Response}, service_fn, Error, IntoResponse, Request, RequestPayloadExt}; use serde::{Deserialize, Serialize}; use serde_json::json; #[tokio::main] async fn main() -> Result<(), Error> { tracing_subscriber::fmt() .without_time() .with_max_level(tracing::Level::INFO) .init(); run(service_fn(function_handler)).await } pub async fn function_handler(event: Request) -> Result { let body = event.payload::()?; let response = Response::builder() .status(StatusCode::OK) .header("Content-Type", "application/json") .body(json!({ "message": "Hello World", "payload": body, }).to_string()) .map_err(Box::new)?; Ok(response) } #[derive(Deserialize, Serialize, Debug, Clone)] pub struct MyPayload { pub prop1: String, pub prop2: String, } ``` -------------------------------- ### Invoke Deployed Function Remotely Source: https://github.com/aws/aws-lambda-rust-runtime/blob/main/examples/extension-internal-flush/README.md Invoke your deployed Lambda function remotely using `cargo lambda invoke --remote` with the function name and sample data. ```bash cargo lambda invoke extension-internal-flush --remote --data-ascii '{"Records":[{"messageId":"MessageID_1","receiptHandle":"MessageReceiptHandle","body":"{\"a\":\"Test\",\"b\":123}"}]}' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.