armature-framework 0.2.2

A modern, type-safe HTTP framework for Rust inspired by Angular and NestJS. Features dependency injection, decorators, middleware, authentication (JWT/OAuth2/SAML), validation, OpenAPI/Swagger, caching, job queues, and observability.
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# OpenTelemetry Integration Guide

Comprehensive observability for Armature applications with distributed tracing, metrics, and logging.

## Table of Contents

- [Overview]#overview
- [Features]#features
- [Quick Start]#quick-start
- [Configuration]#configuration
- [Tracing]#tracing
- [Metrics]#metrics
- [Exporters]#exporters
- [Middleware]#middleware
- [Best Practices]#best-practices
- [Examples]#examples

## Overview

The `armature-opentelemetry` module provides comprehensive observability for your Armature applications using the OpenTelemetry standard. It automatically instruments HTTP requests, collects metrics, and enables distributed tracing across your services.

### Why OpenTelemetry?

- **Vendor-neutral**: Works with Jaeger, Zipkin, Prometheus, Grafana, and more
- **Industry standard**: CNCF graduated project with wide adoption
- **Comprehensive**: Traces, metrics, and logs in one framework
- **Distributed tracing**: Follow requests across microservices
- **Performance insights**: Identify bottlenecks and optimize

## Features

✅ **Automatic HTTP Instrumentation**
- Traces every HTTP request automatically
- Captures method, path, status, duration
- Propagates trace context across services

✅ **Distributed Tracing**
- W3C Trace Context propagation
- Parent-child span relationships
- Service mesh compatible

✅ **Metrics Collection**
- Request counts
- Request durations (histograms)
- Active requests (gauges)
- Custom business metrics

✅ **Multiple Exporters**
- OTLP (OpenTelemetry Protocol)
- Jaeger
- Zipkin
- Prometheus

✅ **Flexible Configuration**
- Environment-based config
- Code-based builder pattern
- Sampling strategies
- Resource attributes

## Quick Start

### Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
armature-framework = { version = "0.1", features = ["opentelemetry"] }

# Choose exporters
armature-opentelemetry = { version = "0.1", features = ["otlp", "prometheus"] }
```

### Basic Setup

```rust
use armature_framework::prelude::*;
use armature_opentelemetry::*;

#[module()]
#[derive(Default)]
struct AppModule;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize telemetry
    let telemetry = TelemetryBuilder::new("my-service")
        .with_version("1.0.0")
        .with_environment("production")
        .with_otlp_endpoint("http://localhost:4317")
        .with_tracing()
        .with_metrics()
        .build()
        .await?;

    // Create application
    let app = Application::create::<AppModule>().await;

    // Run server
    app.listen(3000).await?;

    // Shutdown gracefully
    telemetry.shutdown().await?;
    Ok(())
}
```

### Running with Docker

Start Jaeger all-in-one (includes OTLP collector):

```bash
docker run -d --name jaeger \
  -p 16686:16686 \
  -p 4317:4317 \
  -p 4318:4318 \
  jaegertracing/all-in-one:latest
```

View traces at: http://localhost:16686

## Configuration

### Builder Pattern

```rust
let telemetry = TelemetryBuilder::new("my-service")
    // Service info
    .with_version("1.0.0")
    .with_namespace("production")
    .with_environment("us-west-2")

    // Enable features
    .with_tracing()
    .with_metrics()

    // Exporter config
    .with_otlp_endpoint("http://collector:4317")

    // Sampling
    .with_sampling_ratio(0.1)  // Sample 10% of traces

    // Custom attributes
    .with_attribute("team", "platform")
    .with_attribute("cluster", "k8s-prod")

    .build()
    .await?;
```

### Configuration Struct

```rust
use armature_opentelemetry::*;

let config = TelemetryConfig {
    service_name: "my-service".to_string(),
    service_version: Some("1.0.0".to_string()),
    environment: Some("production".to_string()),
    enable_tracing: true,
    enable_metrics: true,
    tracing: TracingConfig {
        exporter: TracingExporter::Otlp,
        otlp_endpoint: Some("http://localhost:4317".to_string()),
        sampling_ratio: 1.0,
        max_attributes_per_span: 128,
        max_events_per_span: 128,
    },
    metrics: MetricsConfig {
        exporter: MetricsExporter::Otlp,
        otlp_endpoint: Some("http://localhost:4317".to_string()),
        collection_interval_secs: 60,
    },
    resource_attributes: vec![
        ("team".to_string(), "platform".to_string()),
    ],
};

let telemetry = TelemetryBuilder::new("my-service")
    .with_config(config)
    .build()
    .await?;
```

### Environment Variables

```bash
export OTEL_SERVICE_NAME="my-service"
export OTEL_SERVICE_VERSION="1.0.0"
export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4317"
export OTEL_TRACES_SAMPLER="parentbased_traceidratio"
export OTEL_TRACES_SAMPLER_ARG="0.1"
```

## Tracing

### Automatic Tracing

HTTP requests are automatically traced when using the middleware:

```rust
let app = Application::new(container, router)
    .with_middleware(telemetry.middleware());
```

Each request creates a span with:
- HTTP method
- Request path
- Status code
- Duration
- Request/response headers
- User agent

### Manual Spans

Create custom spans for specific operations:

```rust
use armature_opentelemetry::*;

async fn process_order(order_id: u64) -> Result<(), Error> {
    // Create a span
    let span = trace_span!("process_order",
        "order.id" => order_id.to_string(),
        "order.priority" => "high"
    );

    // Do work...

    // Add events
    span_event!("order_validated");
    span_event!("payment_processed", "amount" => "99.99");

    Ok(())
}
```

### Span Macros

```rust
// Create a simple span
let span = trace_span!("my_operation");

// Create with attributes
let span = trace_span!("database_query",
    "db.system" => "postgresql",
    "db.statement" => "SELECT * FROM users"
);

// Add attribute to current span
span_attribute!("user.id", user_id.to_string());

// Record event
span_event!("cache_miss");

// Record event with attributes
span_event!("item_processed",
    "item.id" => item_id.to_string(),
    "item.status" => "complete"
);
```

### Distributed Tracing

Trace context is automatically propagated via HTTP headers:

```rust
use armature_opentelemetry::HeaderInjector;

async fn call_downstream_service() {
    let client = reqwest::Client::new();
    let mut headers = HashMap::new();

    // Inject trace context into headers
    opentelemetry::global::get_text_map_propagator(|propagator| {
        propagator.inject_context(
            &opentelemetry::Context::current(),
            &mut HeaderInjector(&mut headers)
        );
    });

    // Make request with propagated context
    client.get("http://downstream/api")
        .headers(/* convert headers */)
        .send()
        .await?;
}
```

## Metrics

### HTTP Metrics

Automatically collected when using the middleware:

- `http.server.request.count` - Total requests (counter)
- `http.server.request.duration` - Request duration in seconds (histogram)
- `http.server.active_requests` - Currently active requests (gauge)

All metrics include labels:
- `http.method` - Request method
- `http.route` - Request path
- `http.status_code` - Response status

### Custom Metrics

```rust
use armature_opentelemetry::*;
use opentelemetry::metrics::*;

// Get meter
let meter = get_meter("my-service");

// Counter
let orders_counter = meter
    .u64_counter("orders.total")
    .with_description("Total orders processed")
    .build();

orders_counter.add(1, &[
    KeyValue::new("order.type", "premium"),
    KeyValue::new("order.status", "completed"),
]);

// Gauge
let queue_size = meter
    .i64_up_down_counter("queue.size")
    .with_description("Current queue size")
    .build();

queue_size.add(10, &[]);
queue_size.add(-2, &[]);  // Decrement

// Histogram
let processing_time = meter
    .f64_histogram("processing.duration")
    .with_description("Processing duration in seconds")
    .with_unit("s")
    .build();

processing_time.record(0.523, &[
    KeyValue::new("operation", "image_resize"),
]);
```

### Business Metrics

```rust
#[derive(Clone)]
struct OrderService {
    meter: opentelemetry::metrics::Meter,
    orders_total: Counter<u64>,
    revenue_total: Histogram<f64>,
}

impl OrderService {
    fn new() -> Self {
        let meter = get_meter("order-service");

        let orders_total = meter
            .u64_counter("orders.total")
            .build();

        let revenue_total = meter
            .f64_histogram("revenue.total")
            .with_unit("USD")
            .build();

        Self { meter, orders_total, revenue_total }
    }

    async fn create_order(&self, amount: f64) -> Result<(), Error> {
        // Process order...

        // Record metrics
        self.orders_total.add(1, &[
            KeyValue::new("region", "us-west"),
        ]);

        self.revenue_total.record(amount, &[
            KeyValue::new("currency", "USD"),
        ]);

        Ok(())
    }
}
```

## Exporters

### OTLP (Recommended)

OpenTelemetry Protocol - works with multiple backends:

```rust
let telemetry = TelemetryBuilder::new("my-service")
    .with_otlp_endpoint("http://collector:4317")
    .with_tracing()
    .with_metrics()
    .build()
    .await?;
```

Backends that support OTLP:
- **Jaeger** (v1.35+)
- **Grafana Tempo**
- **Grafana Cloud**
- **Honeycomb**
- **New Relic**
- **Datadog**
- **AWS X-Ray**

### Jaeger

Direct export to Jaeger:

```toml
[dependencies]
armature-opentelemetry = { version = "0.1", features = ["jaeger"] }
```

```rust
let config = TelemetryConfig {
    tracing: TracingConfig {
        exporter: TracingExporter::Jaeger,
        jaeger_endpoint: Some("localhost:6831".to_string()),
        ..Default::default()
    },
    ..TelemetryConfig::new("my-service")
};
```

### Zipkin

Export to Zipkin:

```toml
[dependencies]
armature-opentelemetry = { version = "0.1", features = ["zipkin"] }
```

```rust
let config = TelemetryConfig {
    tracing: TracingConfig {
        exporter: TracingExporter::Zipkin,
        zipkin_endpoint: Some("http://localhost:9411/api/v2/spans".to_string()),
        ..Default::default()
    },
    ..TelemetryConfig::new("my-service")
};
```

### Prometheus

Expose metrics for Prometheus scraping:

```toml
[dependencies]
armature-opentelemetry = { version = "0.1", features = ["prometheus"] }
```

```rust
let telemetry = TelemetryBuilder::new("my-service")
    .with_metrics()
    .build()
    .await?;

// Add metrics endpoint
#[get("/metrics")]
async fn metrics() -> Result<String, Error> {
    // Prometheus exporter provides the metrics
    Ok("metrics data".to_string())
}
```

## Middleware

### Automatic Instrumentation

The telemetry middleware automatically:

1. **Creates spans** for each request
2. **Extracts trace context** from incoming headers
3. **Injects trace context** for distributed tracing
4. **Records metrics** (count, duration, active requests)
5. **Captures errors** and sets span status

### Usage

```rust
let app = Application::new(container, router)
    .with_middleware(telemetry.middleware());
```

### Multiple Middleware

Combine with other middleware:

```rust
let app = Application::new(container, router)
    .with_middleware(CorsMiddleware::permissive())
    .with_middleware(telemetry.middleware())  // Should be early in chain
    .with_middleware(AuthMiddleware::new());
```

## Best Practices

### 1. Use Semantic Conventions

Follow OpenTelemetry semantic conventions for attribute names:

```rust
// ✅ Good - semantic convention
span_attribute!("http.method", "GET");
span_attribute!("db.system", "postgresql");
span_attribute!("messaging.system", "rabbitmq");

// ❌ Bad - custom names
span_attribute!("method", "GET");
span_attribute!("database", "postgres");
```

See: https://opentelemetry.io/docs/specs/semconv/

### 2. Sample Appropriately

Don't trace everything in production:

```rust
// Development - trace everything
.with_sampling_ratio(1.0)

// Staging - trace 50%
.with_sampling_ratio(0.5)

// Production - trace 10%
.with_sampling_ratio(0.1)

// High-traffic production - trace 1%
.with_sampling_ratio(0.01)
```

### 3. Add Context

Include relevant business context:

```rust
span_attribute!("user.id", user_id.to_string());
span_attribute!("tenant.id", tenant_id.to_string());
span_attribute!("order.id", order_id.to_string());
span_attribute!("feature.flag", "new_checkout");
```

### 4. Record Important Events

```rust
span_event!("cache_hit");
span_event!("retry_attempt", "attempt" => "2");
span_event!("threshold_exceeded", "value" => "1000");
```

### 5. Graceful Shutdown

Always shutdown telemetry to flush data:

```rust
tokio::select! {
    _ = app.listen(3000) => {},
    _ = tokio::signal::ctrl_c() => {
        println!("Shutting down...");
        telemetry.shutdown().await?;
    }
}
```

### 6. Resource Attributes

Add deployment metadata:

```rust
let telemetry = TelemetryBuilder::new("my-service")
    .with_version(env!("CARGO_PKG_VERSION"))
    .with_environment("production")
    .with_namespace("payments")
    .with_attribute("k8s.pod.name", std::env::var("POD_NAME")?)
    .with_attribute("k8s.node.name", std::env::var("NODE_NAME")?)
    .with_attribute("region", "us-west-2")
    .build()
    .await?;
```

## Examples

### Complete Application

```rust
use armature_framework::prelude::*;
use armature_framework::armature_opentelemetry::*;

#[derive(Clone)]
#[injectable]
struct UserService;

impl UserService {
    async fn create_user(&self, name: String) -> Result<u64, Error> {
        span_attribute!("user.name", name);
        span_event!("user_created");
        Ok(42)
    }
}

#[controller("/api/users")]
struct UserController {
    user_service: UserService,
}

impl UserController {
    #[post("/")]
    async fn create(
        &self,
        #[Body] body: Json<serde_json::Value>,
    ) -> Result<Json<serde_json::Value>, Error> {
        let name = body.get("name")
            .and_then(|v| v.as_str())
            .ok_or_else(|| Error::BadRequest("name required".to_string()))?;

        let id = self.user_service.create_user(name.to_string()).await?;

        Ok(Json(serde_json::json!({ "id": id })))
    }
}

#[module]
struct AppModule;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let telemetry = TelemetryBuilder::new("user-service")
        .with_version("1.0.0")
        .with_environment("production")
        .with_otlp_endpoint("http://localhost:4317")
        .with_tracing()
        .with_metrics()
        .build()
        .await?;

    let app = Application::create::<AppModule>().await;

    tokio::select! {
        _ = app.listen(3000) => {},
        _ = tokio::signal::ctrl_c() => {
            telemetry.shutdown().await?;
        }
    }

    Ok(())
}
```

### Kubernetes Deployment

```yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: otel-config
data:
  OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel-collector:4317"
  OTEL_SERVICE_NAME: "user-service"
  OTEL_SERVICE_VERSION: "1.0.0"
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-service
spec:
  template:
    spec:
      containers:
      - name: user-service
        image: user-service:1.0.0
        envFrom:
        - configMapRef:
            name: otel-config
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
```

## Summary

**Key Features:**
- ✅ Automatic HTTP tracing with middleware
- ✅ Built-in metrics collection
- ✅ Multiple exporter support (OTLP, Jaeger, Zipkin, Prometheus)
- ✅ Distributed tracing with context propagation
- ✅ Flexible configuration and builder API
- ✅ Production-ready with sampling strategies

**When to Use:**
- Microservices architectures
- Production debugging
- Performance monitoring
- Distributed tracing
- SLA/SLO tracking

**Next Steps:**
1. Start with OTLP + Jaeger for development
2. Add sampling for production (10% or less)
3. Include business metrics
4. Set up alerting based on metrics
5. Create dashboards for visualization

Happy observability! 🔭📊