|
| 1 | +//! # Example: Axum Streaming Responses on AWS Lambda with OTel |
| 2 | +//! |
| 3 | +//! Demonstrates serving **incremental streaming responses** from Axum handlers |
| 4 | +//! running in AWS Lambda using a **custom** `lambda_runtime::Runtime` with |
| 5 | +//! OpenTelemetry (OTel) support. |
| 6 | +//! |
| 7 | +//! - Runs with a custom `Runtime` + `StreamAdapter`, which convert Axum |
| 8 | +//! responses into streaming bodies delivered as data is produced (unlike the |
| 9 | +//! default `run_with_streaming_response` helper). |
| 10 | +
|
| 11 | +use axum::{ |
| 12 | + body::Body, |
| 13 | + http::{ |
| 14 | + self, |
| 15 | + header::{CACHE_CONTROL, CONTENT_TYPE}, |
| 16 | + StatusCode, |
| 17 | + }, |
| 18 | + response::{IntoResponse, Response}, |
| 19 | + routing::get, |
| 20 | + Router, |
| 21 | +}; |
| 22 | +use bytes::Bytes; |
| 23 | +use core::{convert::Infallible, time::Duration}; |
| 24 | +use lambda_http::{ |
| 25 | + lambda_runtime::{ |
| 26 | + layers::{OpenTelemetryFaasTrigger, OpenTelemetryLayer as OtelLayer}, |
| 27 | + tracing::Instrument, |
| 28 | + Runtime, |
| 29 | + }, |
| 30 | + tracing, Error, StreamAdapter, |
| 31 | +}; |
| 32 | +use opentelemetry::trace::TracerProvider; |
| 33 | +use opentelemetry_sdk::trace; |
| 34 | +use thiserror::Error; |
| 35 | +use tokio::sync::mpsc; |
| 36 | +use tokio_stream::wrappers::ReceiverStream; |
| 37 | +use tracing_subscriber::prelude::*; |
| 38 | + |
| 39 | +#[derive(Debug, Error)] |
| 40 | +pub enum AppError { |
| 41 | + #[error("{0}")] |
| 42 | + Http(#[from] http::Error), |
| 43 | +} |
| 44 | + |
| 45 | +impl IntoResponse for AppError { |
| 46 | + fn into_response(self) -> Response { |
| 47 | + (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()).into_response() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +#[tracing::instrument(skip_all)] |
| 52 | +async fn stream_words() -> Result<Response, AppError> { |
| 53 | + let (tx, rx) = mpsc::channel::<Result<Bytes, Infallible>>(8); |
| 54 | + let body = Body::from_stream(ReceiverStream::new(rx)); |
| 55 | + |
| 56 | + tokio::spawn( |
| 57 | + async move { |
| 58 | + for (idx, msg) in ["Hello", "world", "from", "Lambda!"].iter().enumerate() { |
| 59 | + tokio::time::sleep(Duration::from_millis(500)).await; |
| 60 | + let line = format!("{msg}\n"); |
| 61 | + tracing::info!(chunk.idx = idx, bytes = line.len(), "emit"); |
| 62 | + if tx.send(Ok(Bytes::from(line))).await.is_err() { |
| 63 | + break; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + .instrument(tracing::info_span!("producer.stream_words")), |
| 68 | + ); |
| 69 | + |
| 70 | + Ok(Response::builder() |
| 71 | + .status(StatusCode::OK) |
| 72 | + .header(CONTENT_TYPE, "text/plain; charset=utf-8") |
| 73 | + .header(CACHE_CONTROL, "no-cache") |
| 74 | + .body(body)?) |
| 75 | +} |
| 76 | + |
| 77 | +#[tokio::main] |
| 78 | +async fn main() -> Result<(), Error> { |
| 79 | + // Set up OpenTelemetry tracer provider that writes spans to stdout for |
| 80 | + // debugging purposes |
| 81 | + let exporter = opentelemetry_stdout::SpanExporter::default(); |
| 82 | + let tracer_provider = trace::SdkTracerProvider::builder() |
| 83 | + .with_batch_exporter(exporter) |
| 84 | + .build(); |
| 85 | + |
| 86 | + // Set up link between OpenTelemetry and tracing crate |
| 87 | + tracing_subscriber::registry() |
| 88 | + .with(tracing_opentelemetry::OpenTelemetryLayer::new( |
| 89 | + tracer_provider.tracer("my-streaming-app"), |
| 90 | + )) |
| 91 | + .init(); |
| 92 | + |
| 93 | + let svc = Router::new().route("/", get(stream_words)); |
| 94 | + |
| 95 | + // Initialize the Lambda runtime and add OpenTelemetry tracing |
| 96 | + let runtime = Runtime::new(StreamAdapter::from(svc)).layer( |
| 97 | + OtelLayer::new(|| { |
| 98 | + if let Err(err) = tracer_provider.force_flush() { |
| 99 | + eprintln!("Error flushing traces: {err:#?}"); |
| 100 | + } |
| 101 | + }) |
| 102 | + .with_trigger(OpenTelemetryFaasTrigger::Http), |
| 103 | + ); |
| 104 | + |
| 105 | + runtime.run().await |
| 106 | +} |
0 commit comments