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