use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;
use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue, LabelValueEncoder};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::metrics::gauge::Gauge;
use prometheus_client::metrics::histogram::Histogram;
use prometheus_client::registry::Registry;
use tower::{Layer, Service};
use super::buckets;
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum RpcOutcome {
Ok,
InvalidArgument,
NotFound,
BackendError,
Unauthenticated,
Cancelled,
Error,
}
impl RpcOutcome {
const fn as_str(self) -> &'static str {
match self {
Self::Ok => "ok",
Self::InvalidArgument => "invalid_argument",
Self::NotFound => "not_found",
Self::BackendError => "backend_error",
Self::Unauthenticated => "unauthenticated",
Self::Cancelled => "cancelled",
Self::Error => "error",
}
}
fn from_code(code: tonic::Code) -> Self {
match code {
tonic::Code::Ok => Self::Ok,
tonic::Code::InvalidArgument => Self::InvalidArgument,
tonic::Code::NotFound => Self::NotFound,
tonic::Code::Unauthenticated | tonic::Code::PermissionDenied => Self::Unauthenticated,
tonic::Code::Unavailable => Self::BackendError,
_ => Self::Error,
}
}
}
impl EncodeLabelValue for RpcOutcome {
fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
EncodeLabelValue::encode(&self.as_str(), encoder)
}
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct RpcLabels {
pub method: &'static str,
pub outcome: RpcOutcome,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct MethodLabel {
pub method: &'static str,
}
fn fast_histogram() -> Histogram {
Histogram::new(buckets::FAST)
}
type LatencyFamily = Family<RpcLabels, Histogram, fn() -> Histogram>;
#[derive(Clone)]
pub struct GrpcMetrics {
requests: Family<RpcLabels, Counter>,
latency: LatencyFamily,
in_flight: Family<MethodLabel, Gauge>,
}
impl GrpcMetrics {
pub fn register(registry: &mut Registry) -> Self {
let requests = Family::<RpcLabels, Counter>::default();
let latency: LatencyFamily =
Family::new_with_constructor(fast_histogram as fn() -> Histogram);
let in_flight = Family::<MethodLabel, Gauge>::default();
let grpc = registry.sub_registry_with_prefix("grpc");
grpc.register(
"requests",
"gRPC requests by method and resolved outcome",
requests.clone(),
);
grpc.register(
"request_seconds",
"gRPC handler latency by method and resolved outcome",
latency.clone(),
);
grpc.register(
"requests_in_flight",
"gRPC requests currently being handled, by method",
in_flight.clone(),
);
Self {
requests,
latency,
in_flight,
}
}
fn record(&self, labels: &RpcLabels, elapsed_seconds: f64) {
self.requests.get_or_create(labels).inc();
self.latency.get_or_create(labels).observe(elapsed_seconds);
}
fn in_flight_inc(&self, method: &'static str) {
self.in_flight.get_or_create(&MethodLabel { method }).inc();
}
fn in_flight_dec(&self, method: &'static str) {
self.in_flight.get_or_create(&MethodLabel { method }).dec();
}
fn record_cancelled(&self, method: &'static str) {
self.requests
.get_or_create(&RpcLabels {
method,
outcome: RpcOutcome::Cancelled,
})
.inc();
}
}
#[must_use]
pub fn method_label(path: &str) -> &'static str {
match path {
"/model_express.api.ApiService/SendRequest" => "ApiService/SendRequest",
"/model_express.health.HealthService/GetHealth" => "HealthService/GetHealth",
"/model_express.model.ModelService/EnsureModelDownloaded" => {
"ModelService/EnsureModelDownloaded"
}
"/model_express.model.ModelService/StreamModelFiles" => "ModelService/StreamModelFiles",
"/model_express.model.ModelService/ListModelFiles" => "ModelService/ListModelFiles",
"/model_express.model.ModelService/DeleteModel" => "ModelService/DeleteModel",
"/model_express.p2p.P2pService/PublishMetadata" => "P2pService/PublishMetadata",
"/model_express.p2p.P2pService/ListSources" => "P2pService/ListSources",
"/model_express.p2p.P2pService/GetMetadata" => "P2pService/GetMetadata",
"/model_express.p2p.P2pService/UpdateStatus" => "P2pService/UpdateStatus",
"/model_express.refit.RefitService/CreateTrainerMesh" => "RefitService/CreateTrainerMesh",
"/model_express.refit.RefitService/GetTrainerMesh" => "RefitService/GetTrainerMesh",
"/model_express.refit.RefitService/UpdateTrainerMesh" => "RefitService/UpdateTrainerMesh",
"/model_express.refit.RefitService/DeleteTrainerMesh" => "RefitService/DeleteTrainerMesh",
"/model_express.refit.RefitService/CreateWeightVersion" => {
"RefitService/CreateWeightVersion"
}
"/model_express.refit.RefitService/GetWeightVersion" => "RefitService/GetWeightVersion",
"/model_express.refit.RefitService/ListWeightVersions" => "RefitService/ListWeightVersions",
"/model_express.refit.RefitService/DeleteWeightVersion" => {
"RefitService/DeleteWeightVersion"
}
"/model_express.refit.RefitService/UpdateWeightVersionState" => {
"RefitService/UpdateWeightVersionState"
}
"/model_express.refit.RefitService/RegisterWorker" => "RefitService/RegisterWorker",
"/model_express.refit.RefitService/CreateWeightVersionShard" => {
"RefitService/CreateWeightVersionShard"
}
"/model_express.refit.RefitService/ListWeightVersionShards" => {
"RefitService/ListWeightVersionShards"
}
"/model_express.refit.RefitService/DeleteWeightVersionShard" => {
"RefitService/DeleteWeightVersionShard"
}
"/model_express.refit.RefitService/RegisterVersionLease" => {
"RefitService/RegisterVersionLease"
}
"/model_express.refit.RefitService/DeleteVersionLease" => "RefitService/DeleteVersionLease",
"/grpc.health.v1.Health/Check" => "Health/Check",
"/grpc.health.v1.Health/Watch" => "Health/Watch",
_ => "other",
}
}
fn resolves_at_head(method: &str) -> bool {
matches!(
method,
"ModelService/EnsureModelDownloaded" | "ModelService/StreamModelFiles" | "Health/Watch"
)
}
fn resolve_outcome<B>(response: &http::Response<B>) -> RpcOutcome {
if let Some(outcome) = response.extensions().get::<RpcOutcome>() {
return *outcome;
}
if let Some(status) = response.extensions().get::<tonic::Status>() {
return RpcOutcome::from_code(status.code());
}
RpcOutcome::Ok
}
struct InFlightGuard {
metrics: GrpcMetrics,
method: &'static str,
pending: bool,
}
impl InFlightGuard {
fn enter(metrics: GrpcMetrics, method: &'static str) -> Self {
metrics.in_flight_inc(method);
Self {
metrics,
method,
pending: true,
}
}
}
impl Drop for InFlightGuard {
fn drop(&mut self) {
self.metrics.in_flight_dec(self.method);
if self.pending {
self.metrics.record_cancelled(self.method);
}
}
}
#[derive(Clone)]
pub struct GrpcMetricsLayer {
metrics: GrpcMetrics,
}
impl GrpcMetricsLayer {
#[must_use]
pub fn new(metrics: GrpcMetrics) -> Self {
Self { metrics }
}
}
impl<S> Layer<S> for GrpcMetricsLayer {
type Service = GrpcMetricsService<S>;
fn layer(&self, inner: S) -> Self::Service {
GrpcMetricsService {
inner,
metrics: self.metrics.clone(),
}
}
}
#[derive(Clone)]
pub struct GrpcMetricsService<S> {
inner: S,
metrics: GrpcMetrics,
}
impl<S, ReqBody, ResBody> Service<http::Request<ReqBody>> for GrpcMetricsService<S>
where
S: Service<http::Request<ReqBody>, Response = http::Response<ResBody>> + Clone + Send + 'static,
S::Future: Send + 'static,
ReqBody: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: http::Request<ReqBody>) -> Self::Future {
let method = method_label(request.uri().path());
let record = !resolves_at_head(method);
let metrics = self.metrics.clone();
let ready = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, ready);
Box::pin(async move {
let mut guard = record.then(|| InFlightGuard::enter(metrics.clone(), method));
let started = Instant::now();
let result = inner.call(request).await;
if let Some(guard) = guard.as_mut() {
guard.pending = false;
}
if record && let Ok(response) = &result {
let labels = RpcLabels {
method,
outcome: resolve_outcome(response),
};
metrics.record(&labels, started.elapsed().as_secs_f64());
}
result
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::metrics::{encode_text, new_registry};
#[test]
fn families_encode_under_the_documented_names() {
let mut registry = new_registry();
let metrics = GrpcMetrics::register(&mut registry);
metrics.record(
&RpcLabels {
method: "P2pService/ListSources",
outcome: RpcOutcome::BackendError,
},
0.5,
);
metrics.record_cancelled("P2pService/GetMetadata");
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(
r#"mx_grpc_requests_total{method="P2pService/ListSources",outcome="backend_error"} 1"#
),
"{encoded}"
);
assert!(
encoded.contains(
r#"mx_grpc_requests_total{method="P2pService/GetMetadata",outcome="cancelled"} 1"#
),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_grpc_request_seconds_count{method="P2pService/ListSources"#),
"{encoded}"
);
assert!(
!encoded.contains(r#"mx_grpc_request_seconds_count{method="P2pService/GetMetadata"#),
"a cancellation wrote a latency sample: {encoded}"
);
assert!(
encoded.contains("# TYPE mx_grpc_request_seconds histogram"),
"{encoded}"
);
assert!(!encoded.contains("_total_total"), "{encoded}");
}
#[test]
fn the_in_flight_gauge_returns_to_zero() {
let mut registry = new_registry();
let metrics = GrpcMetrics::register(&mut registry);
let guard = InFlightGuard::enter(metrics.clone(), "P2pService/ListSources");
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(r#"mx_grpc_requests_in_flight{method="P2pService/ListSources"} 1"#),
"{encoded}"
);
drop(guard);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(r#"mx_grpc_requests_in_flight{method="P2pService/ListSources"} 0"#),
"{encoded}"
);
assert!(
encoded.contains(
r#"mx_grpc_requests_total{method="P2pService/ListSources",outcome="cancelled"} 1"#
),
"{encoded}"
);
}
#[test]
fn outcome_labels_are_snake_case() {
assert_eq!(RpcOutcome::BackendError.as_str(), "backend_error");
assert_eq!(RpcOutcome::InvalidArgument.as_str(), "invalid_argument");
assert_eq!(RpcOutcome::Ok.as_str(), "ok");
}
#[test]
fn unknown_paths_collapse_to_other() {
assert_eq!(
method_label("/model_express.p2p.P2pService/ListSources"),
"P2pService/ListSources"
);
assert_eq!(method_label("/grpc.health.v1.Health/Check"), "Health/Check");
assert_eq!(method_label("/model_express.p2p.P2pService/Bogus"), "other");
assert_eq!(method_label("/nonsense"), "other");
assert_eq!(method_label(""), "other");
}
#[test]
fn handler_set_outcome_wins_over_the_status_code() {
let mut response = http::Response::new(());
response.extensions_mut().insert(RpcOutcome::BackendError);
response.extensions_mut().insert(tonic::Status::ok(""));
assert_eq!(resolve_outcome(&response), RpcOutcome::BackendError);
}
#[test]
fn status_is_used_when_the_handler_did_not_tag() {
let response = tonic::Status::not_found("nope").into_http::<()>();
assert_eq!(resolve_outcome(&response), RpcOutcome::NotFound);
let response = tonic::Status::unavailable("redis down").into_http::<()>();
assert_eq!(resolve_outcome(&response), RpcOutcome::BackendError);
}
const SERVED_SERVICES: [&str; 5] = [
"ApiService",
"HealthService",
"ModelService",
"P2pService",
"RefitService",
];
fn routed_paths(proto: &str) -> Vec<(String, String, bool)> {
let mut package = String::new();
let mut service = String::new();
let mut paths = Vec::new();
for line in proto.lines() {
let line = line.trim();
if let Some(rest) = line.strip_prefix("package ") {
package = rest.trim_end_matches(';').trim().to_string();
} else if let Some(rest) = line.strip_prefix("service ") {
service = rest
.split_whitespace()
.next()
.unwrap_or_default()
.to_string();
} else if let Some(rest) = line.strip_prefix("rpc ")
&& let Some(name) = rest.split('(').next()
{
paths.push((
service.clone(),
format!("/{package}.{service}/{}", name.trim()),
rest.contains("returns (stream "),
));
}
}
paths
}
#[test]
fn every_routed_proto_rpc_has_a_method_label_arm() {
const PROTOS: [&str; 5] = [
include_str!("../../../modelexpress_common/proto/api.proto"),
include_str!("../../../modelexpress_common/proto/health.proto"),
include_str!("../../../modelexpress_common/proto/model.proto"),
include_str!("../../../modelexpress_common/proto/p2p.proto"),
include_str!("../../../modelexpress_common/proto/refit.proto"),
];
let mut checked = 0;
for proto in PROTOS {
for (service, path, is_streaming) in routed_paths(proto) {
if !SERVED_SERVICES.contains(&service.as_str()) {
continue;
}
let method = method_label(&path);
assert_ne!(
method, "other",
"{path} has no method_label arm, so it would be recorded as `other`"
);
assert_eq!(
resolves_at_head(method),
is_streaming,
"{path} is {} in the proto but {} excluded by resolves_at_head",
if is_streaming { "streaming" } else { "unary" },
if resolves_at_head(method) {
"is"
} else {
"is not"
}
);
checked += 1;
}
}
assert_eq!(
checked, 25,
"expected 25 routed server RPCs, parsed {checked}"
);
}
#[test]
fn streaming_methods_are_not_recorded() {
assert!(resolves_at_head("ModelService/EnsureModelDownloaded"));
assert!(resolves_at_head("ModelService/StreamModelFiles"));
assert!(resolves_at_head("Health/Watch"));
assert!(!resolves_at_head("P2pService/ListSources"));
assert!(!resolves_at_head("ModelService/ListModelFiles"));
assert!(!resolves_at_head("Health/Check"));
assert!(!resolves_at_head("other"));
}
#[test]
fn an_untagged_success_is_ok() {
let response = http::Response::new(());
assert_eq!(resolve_outcome(&response), RpcOutcome::Ok);
}
}