servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! One observation follows the caller's future and then its response body.
use super::{
    ClientError,
    metrics::{Measurements, Outcome},
};
use tokio::time::Instant;

pub(super) struct Observation {
    pub span: tracing::Span,
    metrics: Measurements,
    began: Instant,
    acquiring: bool,
    active: bool,
    outcome: Outcome,
}
impl Observation {
    pub(super) fn new(metrics: Measurements, span: tracing::Span) -> Self {
        metrics.waiting.inc();
        Self {
            span,
            metrics,
            began: Instant::now(),
            acquiring: true,
            active: false,
            outcome: Outcome::Cancelled,
        }
    }
    pub(super) fn acquired(&mut self) {
        self.end_acquisition();
        self.metrics.active.inc();
        self.active = true;
    }
    pub(super) fn received(&mut self, status: u16) {
        self.metrics.received(status);
        self.span
            .record("http.response.status_code", i64::from(status));
        // Headers establish an HTTP failure even if the caller never polls the body.
        if status >= 400 {
            self.span.record("otel.status_code", "ERROR");
            self.span.record("error.type", Outcome::HttpError.label());
        }
    }
    pub(super) fn complete(&mut self, status: u16) {
        self.outcome = if status >= 400 {
            Outcome::HttpError
        } else {
            Outcome::Ok
        };
    }
    pub(super) fn failed(&mut self, error: ClientError) {
        self.outcome = Outcome::error(error);
    }
    fn end_acquisition(&mut self) {
        if self.acquiring {
            self.metrics
                .capacity_duration
                .observe(self.began.elapsed().as_secs_f64());
            self.metrics.waiting.dec();
            self.acquiring = false;
        }
    }
}
impl Drop for Observation {
    fn drop(&mut self) {
        self.end_acquisition();
        if self.active {
            self.metrics.active.dec();
        }
        self.metrics
            .duration
            .observe(self.began.elapsed().as_secs_f64());
        self.metrics.finish(self.outcome);
        self.span.record("outcome", self.outcome.label());
        // HTTP errors were recorded at headers; do not overwrite later app status.
        if !matches!(
            self.outcome,
            Outcome::Ok | Outcome::Cancelled | Outcome::HttpError
        ) {
            self.span.record("otel.status_code", "ERROR");
            self.span.record("error.type", self.outcome.label());
        }
    }
}

#[cfg(all(test, feature = "otel"))]
#[path = "observation_test.rs"]
mod observation_test;