Skip to main content

modelexpress_server/metrics/
grpc.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Per-RPC metrics for every gRPC service the server exposes.
5//!
6//! # Why the outcome is not the gRPC status code
7//!
8//! Several handlers report failure *in band*: they catch a backend error, log
9//! it, and return `Ok` with an empty or defaulted response body. `ListSources`
10//! is the clearest case — a Redis outage and "no peers have published yet" are
11//! the same `Ok(ListSourcesResponse { instances: [] })` on the wire. A metric
12//! derived from the status code would therefore read 100% success straight
13//! through a total backend outage, which is precisely the incident it exists to
14//! surface.
15//!
16//! So the outcome is resolved in three steps, in order:
17//!
18//! 1. An [`RpcOutcome`] the handler itself inserted into the response
19//!    extensions. This is the authoritative value and the only one that can see
20//!    an in-band failure.
21//! 2. Otherwise a [`tonic::Status`] in the response extensions. Every
22//!    `Err(Status)` path puts itself there — `Status::into_http` does
23//!    `response.extensions_mut().insert(self)` — so handlers that fail honestly
24//!    need no edit at all, and neither do auth rejections or tonic's own
25//!    `unimplemented` fallback for an unrouted path.
26//! 3. Otherwise success. A successful unary response carries `grpc-status` in
27//!    the HTTP/2 trailers, not the head, so its absence here is the success
28//!    signal.
29//!
30//! Step 2 is why instrumenting 21 routed paths costs a handful of one-line tags
31//! rather than 21 rewrites: only handlers that lie about their outcome need
32//! touching.
33
34use std::future::Future;
35use std::pin::Pin;
36use std::task::{Context, Poll};
37use std::time::Instant;
38
39use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue, LabelValueEncoder};
40use prometheus_client::metrics::counter::Counter;
41use prometheus_client::metrics::family::Family;
42use prometheus_client::metrics::gauge::Gauge;
43use prometheus_client::metrics::histogram::Histogram;
44use prometheus_client::registry::Registry;
45use tower::{Layer, Service};
46
47use super::buckets;
48
49/// Outcome of one RPC.
50///
51/// A closed enum, deliberately: `method` is already a 22-value label, so an
52/// open-ended outcome would multiply an unbounded domain into it. Anything that
53/// does not map onto a named variant becomes [`RpcOutcome::Error`].
54#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
55pub enum RpcOutcome {
56    /// The handler completed and reported no failure.
57    Ok,
58    /// The caller's request was malformed.
59    InvalidArgument,
60    /// The requested model, source, or version does not exist. Distinct from
61    /// [`RpcOutcome::BackendError`] because it is a normal, expected answer.
62    NotFound,
63    /// A backend the handler depends on failed. This is the variant a
64    /// status-code-derived metric cannot see, and the reason this module exists.
65    ///
66    /// Wider than the metadata store: every `Code::Unavailable` maps here, which
67    /// includes the auth layer's `Status::unavailable` when the Kubernetes
68    /// TokenReview API is down. Because this layer sits outside `AuthLayer`, that
69    /// case appears on every method at once and can read like a total
70    /// metadata-store outage. `mx_backend_ops_total` disambiguates: a real store
71    /// outage lights that family up too.
72    BackendError,
73    /// Rejected by the ServiceAccount auth layer.
74    Unauthenticated,
75    /// The caller went away before the handler finished: client disconnect,
76    /// `RST_STREAM`, or a deadline. Recorded from a drop guard, never from a
77    /// response, because in this case there is no response.
78    Cancelled,
79    /// Any other failure.
80    Error,
81}
82
83impl RpcOutcome {
84    /// Wire form. `snake_case`, matching every other label value in the schema.
85    const fn as_str(self) -> &'static str {
86        match self {
87            Self::Ok => "ok",
88            Self::InvalidArgument => "invalid_argument",
89            Self::NotFound => "not_found",
90            Self::BackendError => "backend_error",
91            Self::Unauthenticated => "unauthenticated",
92            Self::Cancelled => "cancelled",
93            Self::Error => "error",
94        }
95    }
96
97    /// Map a gRPC status code onto the closed domain.
98    fn from_code(code: tonic::Code) -> Self {
99        match code {
100            tonic::Code::Ok => Self::Ok,
101            tonic::Code::InvalidArgument => Self::InvalidArgument,
102            tonic::Code::NotFound => Self::NotFound,
103            tonic::Code::Unauthenticated | tonic::Code::PermissionDenied => Self::Unauthenticated,
104            tonic::Code::Unavailable => Self::BackendError,
105            _ => Self::Error,
106        }
107    }
108}
109
110// Hand-written rather than derived: the derive encodes `stringify!(Variant)`,
111// which would emit `BackendError`. Renaming the variants to match the wire form
112// would trip `non_camel_case_types` under `-D warnings`, so the mapping lives in
113// `as_str` instead.
114impl EncodeLabelValue for RpcOutcome {
115    fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
116        EncodeLabelValue::encode(&self.as_str(), encoder)
117    }
118}
119
120/// Label set for the per-RPC families.
121#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
122pub struct RpcLabels {
123    /// `Service/Method`, drawn from a closed set by [`method_label`].
124    pub method: &'static str,
125    /// Resolved outcome; see the module docs for the resolution order.
126    pub outcome: RpcOutcome,
127}
128
129/// Label set for in-flight tracking. No `outcome`: a request that is still
130/// running does not have one yet.
131#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
132pub struct MethodLabel {
133    /// `Service/Method`, from [`method_label`].
134    pub method: &'static str,
135}
136
137fn fast_histogram() -> Histogram {
138    Histogram::new(buckets::FAST)
139}
140
141type LatencyFamily = Family<RpcLabels, Histogram, fn() -> Histogram>;
142
143/// Handles for the per-RPC families.
144///
145/// Cloning is cheap and shares the underlying storage: every family in
146/// `prometheus_client` is `Arc`-backed, so the clone held by the tower layer and
147/// the clone held by the registry are the same counters.
148#[derive(Clone)]
149pub struct GrpcMetrics {
150    requests: Family<RpcLabels, Counter>,
151    latency: LatencyFamily,
152    in_flight: Family<MethodLabel, Gauge>,
153}
154
155impl GrpcMetrics {
156    /// Register the families on `registry` and return handles to them.
157    ///
158    /// Counters are registered **without** the `_total` suffix. The OpenMetrics
159    /// encoder appends it, so registering `requests_total` would export
160    /// `mx_grpc_requests_total_total`. The unit tests assert the encoded names
161    /// rather than the registered ones for exactly this reason.
162    pub fn register(registry: &mut Registry) -> Self {
163        let requests = Family::<RpcLabels, Counter>::default();
164        let latency: LatencyFamily =
165            Family::new_with_constructor(fast_histogram as fn() -> Histogram);
166        let in_flight = Family::<MethodLabel, Gauge>::default();
167
168        let grpc = registry.sub_registry_with_prefix("grpc");
169        grpc.register(
170            "requests",
171            "gRPC requests by method and resolved outcome",
172            requests.clone(),
173        );
174        grpc.register(
175            "request_seconds",
176            "gRPC handler latency by method and resolved outcome",
177            latency.clone(),
178        );
179
180        // A plain Gauge, deliberately, unlike the counter pairs the client side
181        // uses. That pattern exists because `prometheus_client` multiprocess mode
182        // cannot reclaim a gauge owned by a rank that was SIGKILLed, so an
183        // in-flight gauge wedges forever. The server is a single process with an
184        // in-process registry: if it dies the registry dies with it, so there is
185        // nothing to wedge and the direct reading is worth more than a
186        // subtraction.
187        grpc.register(
188            "requests_in_flight",
189            "gRPC requests currently being handled, by method",
190            in_flight.clone(),
191        );
192
193        Self {
194            requests,
195            latency,
196            in_flight,
197        }
198    }
199
200    /// Record one completed RPC.
201    ///
202    /// Each `get_or_create` is a complete statement. The guard it returns is
203    /// `!Send`, so holding one across an `.await` would make the enclosing future
204    /// non-`Send` and break the tonic handler bound, with an error that points at
205    /// lock internals rather than at this line.
206    fn record(&self, labels: &RpcLabels, elapsed_seconds: f64) {
207        self.requests.get_or_create(labels).inc();
208        self.latency.get_or_create(labels).observe(elapsed_seconds);
209    }
210
211    /// Mark one request as started.
212    fn in_flight_inc(&self, method: &'static str) {
213        self.in_flight.get_or_create(&MethodLabel { method }).inc();
214    }
215
216    /// Mark one request as finished, however it finished.
217    fn in_flight_dec(&self, method: &'static str) {
218        self.in_flight.get_or_create(&MethodLabel { method }).dec();
219    }
220
221    /// Count a request whose future was dropped before it produced a response.
222    ///
223    /// The counter only. Writing the elapsed time into the histogram would
224    /// manufacture a short-latency sample for a request that was still running,
225    /// skewing the distribution worse than the gap it closes.
226    fn record_cancelled(&self, method: &'static str) {
227        self.requests
228            .get_or_create(&RpcLabels {
229                method,
230                outcome: RpcOutcome::Cancelled,
231            })
232            .inc();
233    }
234}
235
236/// Map a request path onto the closed `method` domain.
237///
238/// The layer wraps the whole router, so it sees every path that reaches the
239/// listener, including ones no service claims. Taking the label straight from
240/// the URI would let any caller mint a new series per request, so unknown paths
241/// collapse to `other`.
242#[must_use]
243pub fn method_label(path: &str) -> &'static str {
244    match path {
245        "/model_express.api.ApiService/SendRequest" => "ApiService/SendRequest",
246        "/model_express.health.HealthService/GetHealth" => "HealthService/GetHealth",
247
248        "/model_express.model.ModelService/EnsureModelDownloaded" => {
249            "ModelService/EnsureModelDownloaded"
250        }
251        "/model_express.model.ModelService/StreamModelFiles" => "ModelService/StreamModelFiles",
252        "/model_express.model.ModelService/ListModelFiles" => "ModelService/ListModelFiles",
253        "/model_express.model.ModelService/DeleteModel" => "ModelService/DeleteModel",
254
255        "/model_express.p2p.P2pService/PublishMetadata" => "P2pService/PublishMetadata",
256        "/model_express.p2p.P2pService/ListSources" => "P2pService/ListSources",
257        "/model_express.p2p.P2pService/GetMetadata" => "P2pService/GetMetadata",
258        "/model_express.p2p.P2pService/UpdateStatus" => "P2pService/UpdateStatus",
259
260        "/model_express.refit.RefitService/CreateTrainerMesh" => "RefitService/CreateTrainerMesh",
261        "/model_express.refit.RefitService/GetTrainerMesh" => "RefitService/GetTrainerMesh",
262        "/model_express.refit.RefitService/UpdateTrainerMesh" => "RefitService/UpdateTrainerMesh",
263        "/model_express.refit.RefitService/DeleteTrainerMesh" => "RefitService/DeleteTrainerMesh",
264        "/model_express.refit.RefitService/CreateWeightVersion" => {
265            "RefitService/CreateWeightVersion"
266        }
267        "/model_express.refit.RefitService/GetWeightVersion" => "RefitService/GetWeightVersion",
268        "/model_express.refit.RefitService/ListWeightVersions" => "RefitService/ListWeightVersions",
269        "/model_express.refit.RefitService/DeleteWeightVersion" => {
270            "RefitService/DeleteWeightVersion"
271        }
272        "/model_express.refit.RefitService/UpdateWeightVersionState" => {
273            "RefitService/UpdateWeightVersionState"
274        }
275        "/model_express.refit.RefitService/RegisterWorker" => "RefitService/RegisterWorker",
276        "/model_express.refit.RefitService/CreateWeightVersionShard" => {
277            "RefitService/CreateWeightVersionShard"
278        }
279        "/model_express.refit.RefitService/ListWeightVersionShards" => {
280            "RefitService/ListWeightVersionShards"
281        }
282        "/model_express.refit.RefitService/DeleteWeightVersionShard" => {
283            "RefitService/DeleteWeightVersionShard"
284        }
285        "/model_express.refit.RefitService/RegisterVersionLease" => {
286            "RefitService/RegisterVersionLease"
287        }
288        "/model_express.refit.RefitService/DeleteVersionLease" => "RefitService/DeleteVersionLease",
289
290        // The standard health service, served for kubelet probes. Counted
291        // deliberately: it is the cheapest evidence that the gRPC listener is
292        // answering at all, including during the drain window.
293        "/grpc.health.v1.Health/Check" => "Health/Check",
294        "/grpc.health.v1.Health/Watch" => "Health/Watch",
295
296        _ => "other",
297    }
298}
299
300/// Methods whose response head is produced before the work happens.
301///
302/// `EnsureModelDownloaded` and `StreamModelFiles` return
303/// `Ok(Response::new(ReceiverStream::new(rx)))` once a task is spawned, and report
304/// failure as a stream item or a trailer -- `EnsureModelDownloaded` sends
305/// `ModelStatus::ERROR` as an item. `Health/Watch` is long-lived by design. For
306/// all three, this layer's future resolves at stream setup, so it would record
307/// `outcome="ok"` and a sub-millisecond duration for work that can run for forty
308/// minutes and fail.
309///
310/// They are therefore not recorded at all. A confidently wrong number is worse
311/// than an absent one, and this module exists to remove exactly that class of
312/// lie. Covering them means timing the response body and reading the trailer,
313/// which is a separate change.
314fn resolves_at_head(method: &str) -> bool {
315    matches!(
316        method,
317        "ModelService/EnsureModelDownloaded" | "ModelService/StreamModelFiles" | "Health/Watch"
318    )
319}
320
321/// Resolve the outcome of a response. See the module docs for the ordering.
322///
323/// Everything readable here comes from the response *head*. A failure raised
324/// while hyper drains the body lands in the HTTP/2 trailers instead, after this
325/// has already run: `map_response` is not async, so the future this layer awaits
326/// resolves once the body is wrapped, not once it is encoded. The reachable case
327/// is a unary response exceeding `max_encoding_message_size`, which
328/// `finish_encoding` rejects during the drain -- the client sees an error and the
329/// server records a success. Streaming methods are excluded separately by
330/// [`resolves_at_head`].
331fn resolve_outcome<B>(response: &http::Response<B>) -> RpcOutcome {
332    if let Some(outcome) = response.extensions().get::<RpcOutcome>() {
333        return *outcome;
334    }
335    if let Some(status) = response.extensions().get::<tonic::Status>() {
336        return RpcOutcome::from_code(status.code());
337    }
338    RpcOutcome::Ok
339}
340
341/// Tracks one in-flight request, and records a cancellation if the future is
342/// dropped before it produced a response.
343///
344/// Both signals hang off the same `Drop` because they answer the same question
345/// from opposite ends. hyper drops the handler future on client disconnect,
346/// `RST_STREAM`, or a deadline, and the recording after the await then never
347/// runs -- and that gap is not uniform, because the requests most likely to be
348/// cancelled are the slow ones. Left alone, the latency histogram ends up
349/// conditioned on completion, with a tail that looks healthy precisely because
350/// the slowest samples are the ones missing.
351///
352/// The gauge is the direct reading of the same situation: a backend that wedges
353/// while its peers serve normally shows up immediately as requests accumulating,
354/// rather than having to be inferred from an absence.
355struct InFlightGuard {
356    metrics: GrpcMetrics,
357    method: &'static str,
358    /// Cleared once the call resolves. Still set at drop means cancelled.
359    pending: bool,
360}
361
362impl InFlightGuard {
363    fn enter(metrics: GrpcMetrics, method: &'static str) -> Self {
364        metrics.in_flight_inc(method);
365        Self {
366            metrics,
367            method,
368            pending: true,
369        }
370    }
371}
372
373impl Drop for InFlightGuard {
374    fn drop(&mut self) {
375        // Runs on every exit path, so the gauge cannot drift.
376        self.metrics.in_flight_dec(self.method);
377        if self.pending {
378            self.metrics.record_cancelled(self.method);
379        }
380    }
381}
382
383/// Tower layer recording [`GrpcMetrics`] for every request that reaches the router.
384///
385/// Applied once, to the whole router, rather than per service: it then also
386/// covers the health services and any service added later without a second edit.
387/// It sits outside the auth layer, so rejected calls are counted as
388/// `outcome="unauthenticated"` rather than vanishing.
389#[derive(Clone)]
390pub struct GrpcMetricsLayer {
391    metrics: GrpcMetrics,
392}
393
394impl GrpcMetricsLayer {
395    #[must_use]
396    pub fn new(metrics: GrpcMetrics) -> Self {
397        Self { metrics }
398    }
399}
400
401impl<S> Layer<S> for GrpcMetricsLayer {
402    type Service = GrpcMetricsService<S>;
403
404    fn layer(&self, inner: S) -> Self::Service {
405        GrpcMetricsService {
406            inner,
407            metrics: self.metrics.clone(),
408        }
409    }
410}
411
412/// The service produced by [`GrpcMetricsLayer`].
413#[derive(Clone)]
414pub struct GrpcMetricsService<S> {
415    inner: S,
416    metrics: GrpcMetrics,
417}
418
419impl<S, ReqBody, ResBody> Service<http::Request<ReqBody>> for GrpcMetricsService<S>
420where
421    S: Service<http::Request<ReqBody>, Response = http::Response<ResBody>> + Clone + Send + 'static,
422    S::Future: Send + 'static,
423    ReqBody: Send + 'static,
424{
425    type Response = S::Response;
426    type Error = S::Error;
427    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
428
429    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
430        self.inner.poll_ready(cx)
431    }
432
433    fn call(&mut self, request: http::Request<ReqBody>) -> Self::Future {
434        let method = method_label(request.uri().path());
435        // See `resolves_at_head`: for streaming methods this future resolves before
436        // the work does, so anything recorded here would describe stream setup
437        // while claiming to describe the call.
438        let record = !resolves_at_head(method);
439        let metrics = self.metrics.clone();
440
441        // Readiness was established on `self.inner` by `poll_ready` and does not
442        // transfer to a clone. Swap so the future drives the ready service and
443        // the fresh clone is the one polled ready next time.
444        let ready = self.inner.clone();
445        let mut inner = std::mem::replace(&mut self.inner, ready);
446
447        Box::pin(async move {
448            // Streaming methods are excluded from this too: their future resolves
449            // at the head, so the gauge would decrement immediately and read zero
450            // for a stream that is still running.
451            let mut guard = record.then(|| InFlightGuard::enter(metrics.clone(), method));
452            let started = Instant::now();
453            let result = inner.call(request).await;
454            if let Some(guard) = guard.as_mut() {
455                guard.pending = false;
456            }
457
458            if record && let Ok(response) = &result {
459                let labels = RpcLabels {
460                    method,
461                    outcome: resolve_outcome(response),
462                };
463                // `Duration::as_secs_f64` is float division, which
464                // `arithmetic_side_effects` permits; `Instant - Instant` is not.
465                metrics.record(&labels, started.elapsed().as_secs_f64());
466            }
467            result
468        })
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475    use crate::metrics::{encode_text, new_registry};
476
477    /// The encoder appends `_total` to counters, so the registered name and the
478    /// exported name differ. Assert the exported one.
479    #[test]
480    fn families_encode_under_the_documented_names() {
481        let mut registry = new_registry();
482        let metrics = GrpcMetrics::register(&mut registry);
483
484        metrics.record(
485            &RpcLabels {
486                method: "P2pService/ListSources",
487                outcome: RpcOutcome::BackendError,
488            },
489            0.5,
490        );
491        metrics.record_cancelled("P2pService/GetMetadata");
492
493        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
494
495        assert!(
496            encoded.contains(
497                r#"mx_grpc_requests_total{method="P2pService/ListSources",outcome="backend_error"} 1"#
498            ),
499            "{encoded}"
500        );
501        assert!(
502            encoded.contains(
503                r#"mx_grpc_requests_total{method="P2pService/GetMetadata",outcome="cancelled"} 1"#
504            ),
505            "{encoded}"
506        );
507        // A cancellation contributes no latency sample: only the one real
508        // observation reaches the histogram.
509        assert!(
510            encoded.contains(r#"mx_grpc_request_seconds_count{method="P2pService/ListSources"#),
511            "{encoded}"
512        );
513        assert!(
514            !encoded.contains(r#"mx_grpc_request_seconds_count{method="P2pService/GetMetadata"#),
515            "a cancellation wrote a latency sample: {encoded}"
516        );
517        assert!(
518            encoded.contains("# TYPE mx_grpc_request_seconds histogram"),
519            "{encoded}"
520        );
521        // Not `_total_total`.
522        assert!(!encoded.contains("_total_total"), "{encoded}");
523    }
524
525    /// The guard decrements on every exit path, so the gauge must come back to
526    /// zero whether the request completed or was dropped.
527    #[test]
528    fn the_in_flight_gauge_returns_to_zero() {
529        let mut registry = new_registry();
530        let metrics = GrpcMetrics::register(&mut registry);
531
532        let guard = InFlightGuard::enter(metrics.clone(), "P2pService/ListSources");
533        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
534        assert!(
535            encoded.contains(r#"mx_grpc_requests_in_flight{method="P2pService/ListSources"} 1"#),
536            "{encoded}"
537        );
538
539        drop(guard);
540        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
541        assert!(
542            encoded.contains(r#"mx_grpc_requests_in_flight{method="P2pService/ListSources"} 0"#),
543            "{encoded}"
544        );
545        // Dropped while still pending, so it also counts as a cancellation.
546        assert!(
547            encoded.contains(
548                r#"mx_grpc_requests_total{method="P2pService/ListSources",outcome="cancelled"} 1"#
549            ),
550            "{encoded}"
551        );
552    }
553
554    #[test]
555    fn outcome_labels_are_snake_case() {
556        // The derive would have emitted `BackendError` here.
557        assert_eq!(RpcOutcome::BackendError.as_str(), "backend_error");
558        assert_eq!(RpcOutcome::InvalidArgument.as_str(), "invalid_argument");
559        assert_eq!(RpcOutcome::Ok.as_str(), "ok");
560    }
561
562    /// The cardinality guard: an unknown path must not mint a series.
563    #[test]
564    fn unknown_paths_collapse_to_other() {
565        assert_eq!(
566            method_label("/model_express.p2p.P2pService/ListSources"),
567            "P2pService/ListSources"
568        );
569        assert_eq!(method_label("/grpc.health.v1.Health/Check"), "Health/Check");
570        assert_eq!(method_label("/model_express.p2p.P2pService/Bogus"), "other");
571        assert_eq!(method_label("/nonsense"), "other");
572        assert_eq!(method_label(""), "other");
573    }
574
575    /// A handler-set outcome outranks anything derivable from the status.
576    ///
577    /// This covers the resolution order only. It cannot cover the propagation
578    /// step -- `tonic::Response::into_http`, which copies handler extensions onto
579    /// the `http::Response`, is `pub(crate)`, so no test outside tonic can drive
580    /// it directly. That half is covered end to end by the `in_process_server`
581    /// integration test, which drives a real client against a real server.
582    #[test]
583    fn handler_set_outcome_wins_over_the_status_code() {
584        let mut response = http::Response::new(());
585        response.extensions_mut().insert(RpcOutcome::BackendError);
586        // A conflicting status is present and must lose.
587        response.extensions_mut().insert(tonic::Status::ok(""));
588        assert_eq!(resolve_outcome(&response), RpcOutcome::BackendError);
589    }
590
591    #[test]
592    fn status_is_used_when_the_handler_did_not_tag() {
593        let response = tonic::Status::not_found("nope").into_http::<()>();
594        assert_eq!(resolve_outcome(&response), RpcOutcome::NotFound);
595
596        let response = tonic::Status::unavailable("redis down").into_http::<()>();
597        assert_eq!(resolve_outcome(&response), RpcOutcome::BackendError);
598    }
599
600    /// Services this server actually routes. `WorkerService` is served by the
601    /// Python client and `RefitWorkerService` has no ModelExpress-owned server,
602    /// so neither reaches this layer.
603    const SERVED_SERVICES: [&str; 5] = [
604        "ApiService",
605        "HealthService",
606        "ModelService",
607        "P2pService",
608        "RefitService",
609    ];
610
611    /// Extract `/package.Service/Method` for every RPC a proto declares.
612    fn routed_paths(proto: &str) -> Vec<(String, String, bool)> {
613        let mut package = String::new();
614        let mut service = String::new();
615        let mut paths = Vec::new();
616        for line in proto.lines() {
617            let line = line.trim();
618            if let Some(rest) = line.strip_prefix("package ") {
619                package = rest.trim_end_matches(';').trim().to_string();
620            } else if let Some(rest) = line.strip_prefix("service ") {
621                service = rest
622                    .split_whitespace()
623                    .next()
624                    .unwrap_or_default()
625                    .to_string();
626            } else if let Some(rest) = line.strip_prefix("rpc ")
627                && let Some(name) = rest.split('(').next()
628            {
629                paths.push((
630                    service.clone(),
631                    format!("/{package}.{service}/{}", name.trim()),
632                    rest.contains("returns (stream "),
633                ));
634            }
635        }
636        paths
637    }
638
639    /// Every routed RPC must have a `method_label` arm.
640    ///
641    /// Without this, adding an RPC to a proto silently lands it in `other` --
642    /// and because `resolves_at_head("other")` is false, a *streaming* RPC added
643    /// that way would be treated as unary and recorded with a bogus `ok` and a
644    /// stream-setup duration. This fails the build instead.
645    #[test]
646    fn every_routed_proto_rpc_has_a_method_label_arm() {
647        const PROTOS: [&str; 5] = [
648            include_str!("../../../modelexpress_common/proto/api.proto"),
649            include_str!("../../../modelexpress_common/proto/health.proto"),
650            include_str!("../../../modelexpress_common/proto/model.proto"),
651            include_str!("../../../modelexpress_common/proto/p2p.proto"),
652            include_str!("../../../modelexpress_common/proto/refit.proto"),
653        ];
654
655        let mut checked = 0;
656        for proto in PROTOS {
657            for (service, path, is_streaming) in routed_paths(proto) {
658                if !SERVED_SERVICES.contains(&service.as_str()) {
659                    continue;
660                }
661                let method = method_label(&path);
662                assert_ne!(
663                    method, "other",
664                    "{path} has no method_label arm, so it would be recorded as `other`"
665                );
666                // Derived from the proto rather than from a hand-kept list, so
667                // adding a streaming RPC and its arm -- but forgetting
668                // `resolves_at_head` -- fails here instead of silently recording
669                // `ok` with a stream-setup duration.
670                assert_eq!(
671                    resolves_at_head(method),
672                    is_streaming,
673                    "{path} is {} in the proto but {} excluded by resolves_at_head",
674                    if is_streaming { "streaming" } else { "unary" },
675                    if resolves_at_head(method) {
676                        "is"
677                    } else {
678                        "is not"
679                    }
680                );
681                checked += 1;
682            }
683        }
684        // Guards the parser itself: a change that stopped matching `rpc` lines
685        // would otherwise make this test pass by checking nothing.
686        assert_eq!(
687            checked, 25,
688            "expected 25 routed server RPCs, parsed {checked}"
689        );
690    }
691
692    /// `Health/Watch` is long-lived but is not declared in our protos, so
693    /// `every_routed_proto_rpc_has_a_method_label_arm` cannot derive it. The two
694    /// model.proto streams are pinned there against the proto itself; they are
695    /// repeated here only to keep this test readable on its own.
696    #[test]
697    fn streaming_methods_are_not_recorded() {
698        assert!(resolves_at_head("ModelService/EnsureModelDownloaded"));
699        assert!(resolves_at_head("ModelService/StreamModelFiles"));
700        assert!(resolves_at_head("Health/Watch"));
701
702        // Everything unary is recorded.
703        assert!(!resolves_at_head("P2pService/ListSources"));
704        assert!(!resolves_at_head("ModelService/ListModelFiles"));
705        assert!(!resolves_at_head("Health/Check"));
706        assert!(!resolves_at_head("other"));
707    }
708
709    #[test]
710    fn an_untagged_success_is_ok() {
711        let response = http::Response::new(());
712        assert_eq!(resolve_outcome(&response), RpcOutcome::Ok);
713    }
714}