opentelemetry-lambda-extension 0.1.7

AWS Lambda extension for collecting and exporting OpenTelemetry signals
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Configuration loading and management.
//!
//! This module provides layered configuration for the extension using figment.
//! Configuration is loaded from (in order of priority):
//! 1. Default values (compiled in)
//! 2. Config file: `/var/task/otel-extension.toml` (optional)
//! 3. Standard OpenTelemetry environment variables (`OTEL_*`)
//! 4. Extension-specific environment variables (`LAMBDA_OTEL_*`)
//!
//! # Supported Standard Environment Variables
//!
//! The following standard OpenTelemetry environment variables are supported:
//!
//! | Variable | Config Path | Description |
//! |----------|-------------|-------------|
//! | `OTEL_EXPORTER_OTLP_ENDPOINT` | `exporter.endpoint` | OTLP endpoint URL |
//! | `OTEL_EXPORTER_OTLP_PROTOCOL` | `exporter.protocol` | Protocol (http or grpc) |
//! | `OTEL_EXPORTER_OTLP_HEADERS` | `exporter.headers` | Comma-separated key=value pairs |
//! | `OTEL_EXPORTER_OTLP_COMPRESSION` | `exporter.compression` | Compression (gzip or none) |
//!
//! Extension-specific variables with `LAMBDA_OTEL_` prefix take precedence.

use figment::{
    Figment,
    providers::{Env, Format, Serialized, Toml},
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;

const DEFAULT_CONFIG_PATH: &str = "/var/task/otel-extension.toml";
const ENV_PREFIX: &str = "LAMBDA_OTEL_";

/// OTLP protocol for export.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Protocol {
    /// gRPC protocol (port 4317).
    Grpc,
    /// HTTP/protobuf protocol (port 4318).
    #[default]
    Http,
}

/// Compression algorithm for OTLP export.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Compression {
    /// No compression.
    None,
    /// Gzip compression.
    #[default]
    Gzip,
}

/// Flush strategy for buffered signals.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum FlushStrategy {
    /// Adaptive strategy based on invocation patterns.
    #[default]
    Default,
    /// Flush at the end of each invocation.
    End,
    /// Periodic flush at fixed intervals.
    Periodic,
    /// Continuous flush every 20 seconds.
    Continuous,
}

/// Main configuration struct for the extension.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// OTLP exporter configuration.
    pub exporter: ExporterConfig,
    /// OTLP receiver configuration.
    pub receiver: ReceiverConfig,
    /// Flush behaviour configuration.
    pub flush: FlushConfig,
    /// Span correlation configuration.
    pub correlation: CorrelationConfig,
    /// Telemetry API configuration.
    pub telemetry_api: TelemetryApiConfig,
}

impl Config {
    /// Loads configuration from all sources.
    ///
    /// Configuration is loaded in the following order (later sources override earlier):
    /// 1. Default values
    /// 2. Config file at `/var/task/otel-extension.toml` (if it exists)
    /// 3. Environment variables with `LAMBDA_OTEL_` prefix
    ///
    /// # Errors
    ///
    /// Returns an error if configuration parsing fails.
    #[allow(clippy::result_large_err)]
    pub fn load() -> Result<Self, figment::Error> {
        Self::load_from_path(DEFAULT_CONFIG_PATH)
    }

    /// Loads configuration from a custom config file path.
    ///
    /// # Errors
    ///
    /// Returns an error if configuration parsing fails.
    #[allow(clippy::result_large_err)]
    pub fn load_from_path<P: AsRef<Path>>(config_path: P) -> Result<Self, figment::Error> {
        let mut figment = Figment::from(Serialized::defaults(Config::default()));

        if config_path.as_ref().exists() {
            figment = figment.merge(Toml::file(config_path));
        }

        figment = figment.merge(standard_otel_env());
        figment = figment.merge(Env::prefixed(ENV_PREFIX).split("_"));

        figment.extract()
    }

    /// Creates a new config builder for testing.
    pub fn builder() -> ConfigBuilder {
        ConfigBuilder::new()
    }
}

/// OTLP exporter configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ExporterConfig {
    /// OTLP endpoint URL.
    pub endpoint: Option<String>,
    /// Protocol to use for export.
    pub protocol: Protocol,
    /// Request timeout in milliseconds.
    #[serde(with = "duration_ms")]
    pub timeout: Duration,
    /// Compression algorithm.
    pub compression: Compression,
    /// Additional headers to send with requests.
    #[serde(default)]
    pub headers: HashMap<String, String>,
}

impl Default for ExporterConfig {
    fn default() -> Self {
        Self {
            endpoint: None,
            protocol: Protocol::Http,
            timeout: Duration::from_millis(500),
            compression: Compression::Gzip,
            headers: HashMap::new(),
        }
    }
}

/// OTLP receiver configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ReceiverConfig {
    /// gRPC port (default 4317).
    pub grpc_port: u16,
    /// HTTP port (default 4318).
    pub http_port: u16,
    /// Whether to enable the gRPC receiver.
    pub grpc_enabled: bool,
    /// Whether to enable the HTTP receiver.
    pub http_enabled: bool,
}

impl Default for ReceiverConfig {
    fn default() -> Self {
        Self {
            grpc_port: 4317,
            http_port: 4318,
            grpc_enabled: true,
            http_enabled: true,
        }
    }
}

/// Flush behaviour configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct FlushConfig {
    /// Flush strategy to use.
    pub strategy: FlushStrategy,
    /// Periodic flush interval in milliseconds.
    #[serde(with = "duration_ms")]
    pub interval: Duration,
    /// Maximum batch size in bytes.
    pub max_batch_bytes: usize,
    /// Maximum entries per batch.
    pub max_batch_entries: usize,
}

impl Default for FlushConfig {
    fn default() -> Self {
        Self {
            strategy: FlushStrategy::Default,
            interval: Duration::from_secs(20),
            max_batch_bytes: 4 * 1024 * 1024,
            max_batch_entries: 1000,
        }
    }
}

/// Span correlation configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CorrelationConfig {
    /// Maximum time to wait for parent span context in milliseconds.
    #[serde(with = "duration_ms")]
    pub max_correlation_delay: Duration,
    /// Maximum buffered events per invocation.
    pub max_buffered_events_per_invocation: usize,
    /// Maximum total buffered events.
    pub max_total_buffered_events: usize,
    /// Maximum lifetime for invocation context in milliseconds.
    #[serde(with = "duration_ms")]
    pub max_invocation_lifetime: Duration,
    /// Whether to emit orphaned spans without parent context.
    pub emit_orphaned_spans: bool,
}

impl Default for CorrelationConfig {
    fn default() -> Self {
        Self {
            max_correlation_delay: Duration::from_millis(500),
            max_buffered_events_per_invocation: 50,
            max_total_buffered_events: 500,
            max_invocation_lifetime: Duration::from_secs(15 * 60),
            emit_orphaned_spans: true,
        }
    }
}

/// Telemetry API configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TelemetryApiConfig {
    /// Whether to enable Telemetry API subscription.
    pub enabled: bool,
    /// Port for receiving Telemetry API events.
    pub listener_port: u16,
    /// Buffer size for Telemetry API events.
    pub buffer_size: usize,
}

impl Default for TelemetryApiConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            listener_port: 9999,
            buffer_size: 256,
        }
    }
}

/// Builder for constructing configuration programmatically.
#[must_use = "builders do nothing unless .build() is called"]
pub struct ConfigBuilder {
    config: Config,
}

impl ConfigBuilder {
    /// Creates a new config builder with default values.
    pub fn new() -> Self {
        Self {
            config: Config::default(),
        }
    }

    /// Sets the exporter endpoint.
    pub fn exporter_endpoint(mut self, endpoint: impl Into<String>) -> Self {
        self.config.exporter.endpoint = Some(endpoint.into());
        self
    }

    /// Sets the exporter protocol.
    pub fn exporter_protocol(mut self, protocol: Protocol) -> Self {
        self.config.exporter.protocol = protocol;
        self
    }

    /// Sets the exporter timeout.
    pub fn exporter_timeout(mut self, timeout: Duration) -> Self {
        self.config.exporter.timeout = timeout;
        self
    }

    /// Sets the flush strategy.
    pub fn flush_strategy(mut self, strategy: FlushStrategy) -> Self {
        self.config.flush.strategy = strategy;
        self
    }

    /// Sets the flush interval.
    pub fn flush_interval(mut self, interval: Duration) -> Self {
        self.config.flush.interval = interval;
        self
    }

    /// Sets the correlation delay.
    pub fn correlation_delay(mut self, delay: Duration) -> Self {
        self.config.correlation.max_correlation_delay = delay;
        self
    }

    /// Sets whether to emit orphaned spans.
    pub fn emit_orphaned_spans(mut self, emit: bool) -> Self {
        self.config.correlation.emit_orphaned_spans = emit;
        self
    }

    /// Enables or disables the gRPC receiver.
    pub fn grpc_receiver(mut self, enabled: bool) -> Self {
        self.config.receiver.grpc_enabled = enabled;
        self
    }

    /// Enables or disables the HTTP receiver.
    pub fn http_receiver(mut self, enabled: bool) -> Self {
        self.config.receiver.http_enabled = enabled;
        self
    }

    /// Sets the gRPC receiver port.
    pub fn grpc_port(mut self, port: u16) -> Self {
        self.config.receiver.grpc_port = port;
        self
    }

    /// Sets the HTTP receiver port.
    pub fn http_port(mut self, port: u16) -> Self {
        self.config.receiver.http_port = port;
        self
    }

    /// Enables or disables the Telemetry API.
    pub fn telemetry_api(mut self, enabled: bool) -> Self {
        self.config.telemetry_api.enabled = enabled;
        self
    }

    /// Builds the configuration.
    pub fn build(self) -> Config {
        self.config
    }
}

impl Default for ConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Partial exporter config for standard OTEL env var overrides.
#[derive(Debug, Default, Serialize)]
struct PartialExporterConfig {
    #[serde(skip_serializing_if = "Option::is_none")]
    endpoint: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    protocol: Option<Protocol>,
    #[serde(skip_serializing_if = "Option::is_none")]
    compression: Option<Compression>,
    #[serde(skip_serializing_if = "HashMap::is_empty")]
    headers: HashMap<String, String>,
}

/// Partial config for standard OTEL env var overrides.
#[derive(Debug, Default, Serialize)]
struct PartialConfig {
    #[serde(skip_serializing_if = "is_partial_exporter_empty")]
    exporter: PartialExporterConfig,
}

fn is_partial_exporter_empty(config: &PartialExporterConfig) -> bool {
    config.endpoint.is_none()
        && config.protocol.is_none()
        && config.compression.is_none()
        && config.headers.is_empty()
}

fn standard_otel_env() -> Serialized<PartialConfig> {
    let mut config = PartialConfig::default();

    if let Ok(endpoint) = std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT") {
        config.exporter.endpoint = Some(endpoint);
    }

    if let Ok(protocol) = std::env::var("OTEL_EXPORTER_OTLP_PROTOCOL") {
        config.exporter.protocol = match protocol.to_lowercase().as_str() {
            "grpc" => Some(Protocol::Grpc),
            "http/protobuf" | "http" => Some(Protocol::Http),
            _ => None,
        };
    }

    if let Ok(compression) = std::env::var("OTEL_EXPORTER_OTLP_COMPRESSION") {
        config.exporter.compression = match compression.to_lowercase().as_str() {
            "gzip" => Some(Compression::Gzip),
            "none" => Some(Compression::None),
            _ => None,
        };
    }

    if let Ok(headers_str) = std::env::var("OTEL_EXPORTER_OTLP_HEADERS") {
        for pair in headers_str.split(',') {
            if let Some((key, value)) = pair.split_once('=') {
                config
                    .exporter
                    .headers
                    .insert(key.trim().to_string(), value.trim().to_string());
            }
        }
    }

    Serialized::defaults(config)
}

mod duration_ms {
    use serde::{Deserialize, Deserializer, Serializer};
    use std::time::Duration;

    pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u64(duration.as_millis() as u64)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
    where
        D: Deserializer<'de>,
    {
        let ms = u64::deserialize(deserializer)?;
        Ok(Duration::from_millis(ms))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_default_config() {
        let config = Config::default();

        assert!(config.exporter.endpoint.is_none());
        assert_eq!(config.exporter.protocol, Protocol::Http);
        assert_eq!(config.exporter.timeout, Duration::from_millis(500));
        assert_eq!(config.exporter.compression, Compression::Gzip);

        assert_eq!(config.receiver.grpc_port, 4317);
        assert_eq!(config.receiver.http_port, 4318);
        assert!(config.receiver.grpc_enabled);
        assert!(config.receiver.http_enabled);

        assert_eq!(config.flush.strategy, FlushStrategy::Default);
        assert_eq!(config.flush.interval, Duration::from_secs(20));

        assert_eq!(
            config.correlation.max_correlation_delay,
            Duration::from_millis(500)
        );
        assert!(config.correlation.emit_orphaned_spans);

        assert!(config.telemetry_api.enabled);
    }

    #[test]
    fn test_config_builder() {
        let config = Config::builder()
            .exporter_endpoint("https://collector:4318")
            .exporter_protocol(Protocol::Grpc)
            .exporter_timeout(Duration::from_millis(1000))
            .flush_strategy(FlushStrategy::Continuous)
            .flush_interval(Duration::from_secs(10))
            .correlation_delay(Duration::from_millis(200))
            .emit_orphaned_spans(false)
            .grpc_receiver(false)
            .http_receiver(true)
            .grpc_port(5317)
            .http_port(5318)
            .telemetry_api(false)
            .build();

        assert_eq!(
            config.exporter.endpoint,
            Some("https://collector:4318".to_string())
        );
        assert_eq!(config.exporter.protocol, Protocol::Grpc);
        assert_eq!(config.exporter.timeout, Duration::from_millis(1000));
        assert_eq!(config.flush.strategy, FlushStrategy::Continuous);
        assert_eq!(config.flush.interval, Duration::from_secs(10));
        assert_eq!(
            config.correlation.max_correlation_delay,
            Duration::from_millis(200)
        );
        assert!(!config.correlation.emit_orphaned_spans);
        assert!(!config.receiver.grpc_enabled);
        assert!(config.receiver.http_enabled);
        assert_eq!(config.receiver.grpc_port, 5317);
        assert_eq!(config.receiver.http_port, 5318);
        assert!(!config.telemetry_api.enabled);
    }

    #[test]
    fn test_load_from_toml() {
        let toml_content = r#"
[exporter]
endpoint = "https://test-collector:4318"
protocol = "grpc"
timeout = 1000

[receiver]
grpc_port = 5317
http_port = 5318
grpc_enabled = false

[flush]
strategy = "periodic"
interval = 15000

[correlation]
max_correlation_delay = 300
emit_orphaned_spans = false
"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(toml_content.as_bytes()).unwrap();

        let config = Config::load_from_path(temp_file.path()).unwrap();

        assert_eq!(
            config.exporter.endpoint,
            Some("https://test-collector:4318".to_string())
        );
        assert_eq!(config.exporter.protocol, Protocol::Grpc);
        assert_eq!(config.exporter.timeout, Duration::from_millis(1000));
        assert_eq!(config.receiver.grpc_port, 5317);
        assert_eq!(config.receiver.http_port, 5318);
        assert!(!config.receiver.grpc_enabled);
        assert_eq!(config.flush.strategy, FlushStrategy::Periodic);
        assert_eq!(config.flush.interval, Duration::from_secs(15));
        assert_eq!(
            config.correlation.max_correlation_delay,
            Duration::from_millis(300)
        );
        assert!(!config.correlation.emit_orphaned_spans);
    }

    #[test]
    fn test_load_nonexistent_file_uses_defaults() {
        let config = Config::load_from_path("/nonexistent/path/config.toml").unwrap();

        assert!(config.exporter.endpoint.is_none());
        assert_eq!(config.receiver.grpc_port, 4317);
    }

    #[test]
    fn test_protocol_serialization() {
        assert_eq!(serde_json::to_string(&Protocol::Grpc).unwrap(), "\"grpc\"");
        assert_eq!(serde_json::to_string(&Protocol::Http).unwrap(), "\"http\"");
    }

    #[test]
    fn test_compression_serialization() {
        assert_eq!(
            serde_json::to_string(&Compression::None).unwrap(),
            "\"none\""
        );
        assert_eq!(
            serde_json::to_string(&Compression::Gzip).unwrap(),
            "\"gzip\""
        );
    }

    #[test]
    fn test_flush_strategy_serialization() {
        assert_eq!(
            serde_json::to_string(&FlushStrategy::Default).unwrap(),
            "\"default\""
        );
        assert_eq!(
            serde_json::to_string(&FlushStrategy::End).unwrap(),
            "\"end\""
        );
        assert_eq!(
            serde_json::to_string(&FlushStrategy::Periodic).unwrap(),
            "\"periodic\""
        );
        assert_eq!(
            serde_json::to_string(&FlushStrategy::Continuous).unwrap(),
            "\"continuous\""
        );
    }
}