lambda_otel_lite/
lib.rs

1//! OpenTelemetry instrumentation optimized for AWS Lambda functions.
2//!
3//! This crate provides a lightweight, efficient implementation of OpenTelemetry tracing
4//! specifically designed for AWS Lambda functions. It offers flexible processing modes,
5//! automatic resource detection, and integration with the Lambda Extensions API.
6//!
7//! # Features
8//!
9//! - **Flexible Processing Modes**: Support for synchronous, asynchronous, and custom export strategies
10//! - **Automatic Resource Detection**: Automatic extraction of Lambda environment attributes
11//! - **Lambda Extension Integration**: Built-in extension for efficient telemetry export
12//! - **Efficient Memory Usage**: Fixed-size ring buffer to prevent memory growth
13//! - **AWS Event Support**: Automatic extraction of attributes from common AWS event types
14//! - **Flexible Context Propagation**: Support for W3C Trace Context and custom propagators
15//!
16//! # Architecture
17//!
18//! The crate is organized into several modules, each handling a specific aspect of telemetry:
19//!
20//! - [`telemetry`]: Core initialization and configuration
21//!   - Main entry point via `init_telemetry`
22//!   - Configures global tracer and span processors
23//!   - Returns a `TelemetryCompletionHandler` for span lifecycle management
24//!
25//! - [`processor`]: Lambda-optimized span processor
26//!   - Fixed-size ring buffer implementation
27//!   - Multiple processing modes
28//!   - Coordinates with extension for async export
29//!
30//! - [`extension`]: Lambda Extension implementation
31//!   - Manages extension lifecycle and registration
32//!   - Handles span export coordination
33//!   - Implements graceful shutdown
34//!
35//! - [`resource`]: Resource attribute management
36//!   - Automatic Lambda attribute detection
37//!   - Environment-based configuration
38//!   - Custom attribute support
39//!
40//! - [`extractors`]: Event processing
41//!   - Built-in support for API Gateway and ALB events
42//!   - Extensible trait system for custom events
43//!   - W3C Trace Context propagation
44//!
45//! The crate provides two integration patterns:
46//!
47//! - [`layer`]: Tower middleware integration
48//!   - Best for complex services with middleware chains
49//!   - Integrates with Tower's service ecosystem
50//!   - Standardized instrumentation across services
51//!
52//! - [`handler`]: Direct function wrapper
53//!   - Best for simple Lambda functions
54//!   - Lower overhead for basic use cases
55//!   - Quick integration with existing handlers
56//!
57//! # Processing Modes
58//!
59//! The crate supports three processing modes for telemetry data:
60//!
61//! - **Sync Mode**: Direct export in handler thread
62//!   - Simple execution path with no IPC overhead
63//!   - Efficient for small payloads and low resource environments
64//!   - Guarantees span delivery before response
65//!
66//! - **Async Mode**: Export via Lambda extension
67//!   - Requires coordination with extension process
68//!   - Additional overhead from IPC
69//!   - Best when advanced export features are needed
70//!   - Provides retry capabilities through extension
71//!
72//! - **Finalize Mode**: Custom export strategy
73//!   - Full control over export timing and behavior
74//!   - Compatible with BatchSpanProcessor
75//!   - Best for specialized export requirements
76//!
77//! See [`processor`] module for detailed documentation on processing modes.
78//!
79//! # Configuration
80//!
81//! Configuration is handled through environment variables:
82//!
83//! - `LAMBDA_EXTENSION_SPAN_PROCESSOR_MODE`: Controls processing mode
84//!   - "sync" for Sync mode (default)
85//!   - "async" for Async mode
86//!   - "finalize" for Finalize mode
87//!
88//! - `LAMBDA_SPAN_PROCESSOR_QUEUE_SIZE`: Controls buffer size
89//!   - Defaults to 2048 spans
90//!   - Should be tuned based on span volume
91//!
92//! - `OTEL_SERVICE_NAME`: Service name for spans
93//!   - Falls back to AWS_LAMBDA_FUNCTION_NAME
94//!   - Required for proper service identification
95//!
96//! See [`constants`] module for centralized constants and [`telemetry`] module for detailed configuration options.
97//!
98//! # Examples
99//!
100//! ## Using the Tower Layer
101//!
102//! ```no_run
103//! use lambda_otel_lite::{init_telemetry, OtelTracingLayer, TelemetryConfig};
104//! use lambda_runtime::{service_fn, Error, LambdaEvent, Runtime};
105//! use aws_lambda_events::event::apigw::ApiGatewayV2httpRequest;
106//! use tower::ServiceBuilder;
107//! use serde_json::Value;
108//!
109//! async fn function_handler(event: LambdaEvent<ApiGatewayV2httpRequest>) -> Result<Value, Error> {
110//!     Ok(serde_json::json!({ "statusCode": 200 }))
111//! }
112//!
113//! #[tokio::main]
114//! async fn main() -> Result<(), Error> {
115//!     let (tracer, completion_handler) = init_telemetry(TelemetryConfig::default()).await?;
116//!     
117//!     let service = ServiceBuilder::new()
118//!         .layer(OtelTracingLayer::new(completion_handler).with_name("tower-handler"))
119//!         .service_fn(function_handler);
120//!
121//!     Runtime::new(service).run().await
122//! }
123//! ```
124//!
125//! See [`layer`] module for more examples of automatic instrumentation.
126//!
127//! ## Using the Handler Wrapper
128//!
129//! ```no_run
130//! use lambda_otel_lite::{init_telemetry, create_traced_handler, TelemetryConfig};
131//! use lambda_runtime::{service_fn, Error, LambdaEvent, Runtime};
132//! use serde_json::Value;
133//!
134//! async fn handler(event: LambdaEvent<Value>) -> Result<Value, Error> {
135//!     Ok(serde_json::json!({ "statusCode": 200 }))
136//! }
137//!
138//! #[tokio::main]
139//! async fn main() -> Result<(), Error> {
140//!     let (_, completion_handler) = init_telemetry(TelemetryConfig::default()).await?;
141//!     
142//!     // Create the traced handler
143//!     let handler = create_traced_handler(
144//!         "my-handler",
145//!         completion_handler,
146//!         handler
147//!     );
148//!
149//!     // Use it directly with the runtime
150//!     Runtime::new(service_fn(handler)).run().await
151//! }
152//! ```
153
154pub use otlp_stdout_span_exporter::OtlpStdoutSpanExporter;
155
156pub mod constants;
157pub mod extension;
158pub mod extractors;
159pub mod handler;
160pub mod layer;
161pub mod logger;
162pub mod mode;
163pub mod processor;
164pub mod propagation;
165pub mod resource;
166pub mod telemetry;
167
168pub use extension::OtelInternalExtension;
169pub use extractors::{SpanAttributes, SpanAttributesExtractor, TriggerType};
170pub use handler::create_traced_handler;
171pub use layer::OtelTracingLayer;
172pub use mode::ProcessorMode;
173pub use processor::LambdaSpanProcessor;
174pub use propagation::LambdaXrayPropagator;
175pub use resource::get_lambda_resource;
176pub use telemetry::{
177    init_telemetry, TelemetryCompletionHandler, TelemetryConfig, TelemetryConfigBuilder,
178};
179
180#[cfg(doctest)]
181#[macro_use]
182extern crate doc_comment;
183
184#[cfg(doctest)]
185use doc_comment::doctest;
186
187#[cfg(doctest)]
188doctest!("../README.md", readme);