encore-dev 2.0.0

Rust SDK for Encore applications
Documentation
//! Spans reach the collector when the process is stopped with a signal. Each
//! test re-runs this binary as the app, exporting to an in-process OTLP
//! receiver, and stops it with SIGTERM.

use std::io::{BufRead, BufReader};
use std::process::{Command, ExitStatus, Stdio};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use encore::opentelemetry::trace::{Span as _, Tracer as _};
use encore_runtimecfg::pb;
use encore_telemetry::otlp::collector::trace::v1::trace_service_server::{
    TraceService, TraceServiceServer,
};
use encore_telemetry::otlp::collector::trace::v1::{
    ExportTraceServiceRequest, ExportTraceServiceResponse,
};

/// Set in the app process to the test it runs.
const APP_ENV: &str = "ENCORE_SHUTDOWN_TEST_APP";

/// Spans received, as (name, finished), each once its export has taken
/// `delay`.
#[derive(Default, Clone)]
struct Receiver {
    spans: Arc<Mutex<Vec<(String, bool)>>>,
    delay: Duration,
}

#[tonic::async_trait]
impl TraceService for Receiver {
    async fn export(
        &self,
        request: tonic::Request<ExportTraceServiceRequest>,
    ) -> Result<tonic::Response<ExportTraceServiceResponse>, tonic::Status> {
        // Dropped, unrecorded, when the app exits during it.
        tokio::time::sleep(self.delay).await;
        let spans = request
            .into_inner()
            .resource_spans
            .into_iter()
            .flat_map(|rs| rs.scope_spans)
            .flat_map(|ss| ss.spans)
            .map(|s| (s.name, s.end_time_unix_nano > 0));
        self.spans.lock().unwrap().extend(spans);
        Ok(tonic::Response::new(ExportTraceServiceResponse::default()))
    }
}

impl Receiver {
    fn finished(&self, name: &str) -> bool {
        self.spans
            .lock()
            .unwrap()
            .iter()
            .any(|(n, finished)| n == name && *finished)
    }
}

/// Serves a receiver taking `delay` per export on a free port; returns it
/// and its endpoint.
fn serve(rt: &tokio::runtime::Runtime, delay: Duration) -> (Receiver, String) {
    let receiver = Receiver {
        delay,
        ..Default::default()
    };
    let listener = rt
        .block_on(tokio::net::TcpListener::bind("127.0.0.1:0"))
        .unwrap();
    let endpoint = format!("http://{}", listener.local_addr().unwrap());
    let _guard = rt.enter();
    let incoming = tonic::transport::server::TcpIncoming::from(listener).with_nodelay(Some(true));
    rt.spawn(
        tonic::transport::Server::builder()
            .add_service(TraceServiceServer::new(receiver.clone()))
            .serve_with_incoming(incoming),
    );
    (receiver, endpoint)
}

fn runtime_config(collector: String, total: Duration) -> String {
    let cfg = pb::RuntimeConfig {
        environment: Some(pb::Environment {
            app_id: "app".into(),
            env_name: "test".into(),
            ..Default::default()
        }),
        deployment: Some(pb::Deployment {
            hosted_services: vec![pb::HostedService {
                name: "svc".into(),
                ..Default::default()
            }],
            observability: Some(pb::Observability {
                tracing: (vec![pb::TelemetryDestination {
                    rid: "collector".into(),
                    kind: Some(pb::telemetry_destination::Kind::OtlpGrpc(pb::OtlpGrpc {
                        auth: None,
                        endpoint: collector,
                        ..Default::default()
                    })),
                }])
                .into_iter()
                .map(encore_runtimecfg::pb::TracingProvider::from)
                .collect::<Vec<_>>(),

                telemetry: Some(pb::Telemetry {
                    ..Default::default()
                }),

                ..Default::default()
            }),
            graceful_shutdown: Some(pb::GracefulShutdown {
                total: Some(total.try_into().unwrap()),
                ..Default::default()
            }),
            ..Default::default()
        }),
        ..Default::default()
    };
    encore_runtimecfg::encoding::encode_env_value(&cfg)
}

/// Runs `app` in a child process, sends it SIGTERM once it prints `ready`,
/// and returns its exit status and the spans received.
fn run_app(app: &str) -> (ExitStatus, Receiver) {
    run_app_with(app, Duration::from_secs(5), Duration::ZERO)
}

/// [`run_app`] with a shutdown deadline of `total`, and a receiver taking
/// `delay` per export.
fn run_app_with(app: &str, total: Duration, delay: Duration) -> (ExitStatus, Receiver) {
    let rt = tokio::runtime::Runtime::new().unwrap();
    let (receiver, endpoint) = serve(&rt, delay);
    let mut child = Command::new(std::env::current_exe().unwrap())
        .args([app, "--exact", "--nocapture", "--test-threads=1"])
        .env(APP_ENV, app)
        .env("ENCORE_RUNTIME_CONFIG", runtime_config(endpoint, total))
        // Nothing is exported on a timer while the test runs.
        .env("OTEL_BSP_SCHEDULE_DELAY", "60000")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();

    let stdout = BufReader::new(child.stdout.take().unwrap());
    let mut lines = stdout.lines();
    loop {
        match lines.next() {
            Some(Ok(line)) if line.trim() == "ready" => break,
            Some(Ok(_)) => continue,
            _ => panic!("app exited before it was ready: {:?}", child.wait()),
        }
    }
    let killed = Command::new("kill")
        .args(["-TERM", &child.id().to_string()])
        .status()
        .unwrap();
    assert!(killed.success());
    // Drain stdout so the child never blocks writing to it.
    std::thread::spawn(move || lines.for_each(drop));

    let deadline = std::time::Instant::now() + Duration::from_secs(20);
    let status = loop {
        if let Some(status) = child.try_wait().unwrap() {
            break status;
        }
        if std::time::Instant::now() > deadline {
            child.kill().unwrap();
            panic!("app did not exit after SIGTERM");
        }
        std::thread::sleep(Duration::from_millis(20));
    };
    drop(rt);
    (status, receiver)
}

/// Whether this process is the app for `test`.
fn is_app(test: &str) -> bool {
    std::env::var(APP_ENV).is_ok_and(|v| v == test)
}

fn ready() {
    use std::io::Write;
    let mut out = std::io::stdout();
    writeln!(out, "\nready").unwrap();
    out.flush().unwrap();
}

/// An app that ends a span, then serves until it is stopped, unaware of
/// shutdown.
#[test]
fn app_unaware() {
    if !is_app("app_unaware") {
        return;
    }
    encore::initialize();
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        encore::telemetry::tracer("app")
            .start("ended before signal")
            .end();
        ready();
        std::future::pending::<()>().await;
    });
}

#[test]
fn sigterm_flushes_ended_spans() {
    if std::env::var_os(APP_ENV).is_some() {
        return;
    }
    let (status, receiver) = run_app("app_unaware");
    assert!(
        receiver.finished("ended before signal"),
        "span lost; app exited with {status}"
    );
    assert!(status.success(), "app exited with {status}");
}

/// An app that drains in-flight work on the signal, ending a span after it,
/// then tells Encore it has drained.
#[test]
fn app_draining() {
    if !is_app("app_draining") {
        return;
    }
    encore::initialize();
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let span = encore::telemetry::tracer("app").start("in flight at signal");
        let signal = encore::shutdown::signal();
        ready();
        signal.await;
        tokio::time::sleep(Duration::from_millis(100)).await;
        drop(span);
        let result = encore::shutdown::drained().await;
        assert_eq!(result, encore::shutdown::ShutdownResult::Success);
    });
}

#[test]
fn sigterm_waits_for_app_to_drain() {
    if std::env::var_os(APP_ENV).is_some() {
        return;
    }
    let (status, receiver) = run_app("app_draining");
    assert!(
        receiver.finished("in flight at signal"),
        "span lost; app exited with {status}"
    );
    assert!(status.success(), "app exited with {status}");
}

/// An app that ends a span and listens for the signal, but never drains.
#[test]
fn app_stuck() {
    if !is_app("app_stuck") {
        return;
    }
    encore::initialize();
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        encore::telemetry::tracer("app")
            .start("ended before signal")
            .end();
        let signal = encore::shutdown::signal();
        ready();
        signal.await;
        std::future::pending::<()>().await;
    });
}

#[test]
fn a_timed_out_shutdown_still_flushes_ended_spans() {
    if std::env::var_os(APP_ENV).is_some() {
        return;
    }
    // The flush begins at the 1s deadline and takes 2s.
    let (status, receiver) =
        run_app_with("app_stuck", Duration::from_secs(1), Duration::from_secs(2));
    assert!(
        receiver.finished("ended before signal"),
        "span lost; app exited with {status}"
    );
    assert_eq!(status.code(), Some(1), "a timed-out shutdown");
}