Module layer

Source
Expand description

Tower middleware for OpenTelemetry tracing in AWS Lambda functions.

This module provides a Tower middleware layer that automatically creates OpenTelemetry spans for Lambda invocations. It supports automatic extraction of span attributes from common AWS event types and allows for custom attribute extraction through a flexible trait system.

§When to Use the Tower Layer

The Tower layer approach is recommended when:

  • You need middleware composition (e.g., combining with other Tower layers)
  • You want a more idiomatic Rust approach using traits
  • Your application has complex middleware requirements
  • You’re already using Tower in your application

For simpler use cases, consider using the handler wrapper approach instead.

§Architecture

The layer operates by wrapping a Lambda service with OpenTelemetry instrumentation:

  1. Creates a span for each Lambda invocation
  2. Extracts attributes from the event using either:
    • Built-in implementations of SpanAttributesExtractor for supported event types
    • Custom implementations of SpanAttributesExtractor for user-defined types
    • A closure-based extractor for one-off customizations
  3. Propagates context from incoming requests via headers
  4. Tracks response status codes
  5. Signals completion for span export through the TelemetryCompletionHandler

§Features

  • Automatic span creation for Lambda invocations
  • Built-in support for common AWS event types:
    • API Gateway v1/v2 (HTTP method, path, route, protocol)
    • Application Load Balancer (HTTP method, path, target group ARN)
  • Extensible attribute extraction through the SpanAttributesExtractor trait
  • Custom attribute extraction through closure-based extractors
  • Automatic context propagation from HTTP headers
  • Response status code tracking

§Basic Usage

use lambda_otel_lite::{init_telemetry, OtelTracingLayer, TelemetryConfig};
use lambda_runtime::{service_fn, Error, LambdaEvent, Runtime};
use aws_lambda_events::event::apigw::ApiGatewayV2httpRequest;
use tower::ServiceBuilder;

async fn function_handler(event: LambdaEvent<ApiGatewayV2httpRequest>) -> Result<serde_json::Value, Error> {
    Ok(serde_json::json!({"statusCode": 200}))
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    let (_, completion_handler) = init_telemetry(TelemetryConfig::default()).await?;
     
    let service = ServiceBuilder::new()
        .layer(OtelTracingLayer::new(completion_handler)
            .with_name("my-handler"))
        .service_fn(function_handler);

    Runtime::new(service).run().await
}

§Custom Attribute Extraction

You can implement the SpanAttributesExtractor trait for your own event types:

use lambda_otel_lite::{SpanAttributes, SpanAttributesExtractor};
use std::collections::HashMap;
use opentelemetry::Value;
struct MyEvent {
    user_id: String,
}

impl SpanAttributesExtractor for MyEvent {
    fn extract_span_attributes(&self) -> SpanAttributes {
        let mut attributes = HashMap::new();
        attributes.insert("user.id".to_string(), Value::String(self.user_id.clone().into()));
        SpanAttributes {
            attributes,
            ..SpanAttributes::default()
        }
    }
}

§Context Propagation

The layer automatically extracts and propagates tracing context from HTTP headers in supported event types. This enables distributed tracing across service boundaries. The W3C Trace Context format is used for propagation.

§Response Tracking

For HTTP responses, the layer automatically:

  • Sets http.status_code from the response statusCode
  • Sets span status to ERROR for 5xx responses
  • Sets span status to OK for all other responses

Structs§

CompletionFuture
Future that calls complete() on the completion handler when the inner future completes.
OtelTracingLayer
Tower middleware to create an OpenTelemetry tracing span for Lambda invocations.
OtelTracingService
Tower service returned by OtelTracingLayer.