Skip to main content

durable_workflow/
metrics.rs

1//! Stable client/worker metrics, with application-owned recording and export.
2//!
3//! Recorders must be fast and handle exporter errors locally. Panics are isolated
4//! from SDK operations. Durations use a monotonic clock and seconds; observations
5//! describe this process, not durable execution counts or billing units.
6use crate::{
7    Client, Error, JsonPayloads, JsonRequestOptions, RequestProtocol, Result, WorkerPollOutcome,
8};
9use serde::{de::DeserializeOwned, Serialize};
10use std::{
11    collections::BTreeMap,
12    fmt,
13    panic::{catch_unwind, AssertUnwindSafe},
14    sync::{
15        atomic::{AtomicU16, Ordering},
16        Arc,
17    },
18    time::{Duration, Instant},
19};
20
21#[cfg(feature = "metrics-prometheus")]
22mod prometheus;
23#[cfg(feature = "metrics-prometheus")]
24pub use prometheus::PrometheusMetrics;
25
26/// Exact core labels. Exporter resource labels are separate application policy.
27pub type MetricTags = BTreeMap<String, String>;
28pub const CLIENT_REQUESTS: &str = "durable_workflow_client_requests";
29pub const CLIENT_REQUEST_DURATION_SECONDS: &str =
30    "durable_workflow_client_request_duration_seconds";
31pub const WORKER_POLLS: &str = "durable_workflow_worker_polls";
32pub const WORKER_POLL_DURATION_SECONDS: &str = "durable_workflow_worker_poll_duration_seconds";
33pub const WORKER_TASKS: &str = "durable_workflow_worker_tasks";
34pub const WORKER_TASK_DURATION_SECONDS: &str = "durable_workflow_worker_task_duration_seconds";
35
36/// Server-measured eligibility-to-claim delay, in seconds.
37pub const WORKER_TASK_SCHEDULE_TO_START_SECONDS: &str =
38    "durable_workflow_worker_task_schedule_to_start_seconds";
39
40/// Pluggable, thread-safe recorder. Counter increments are counts; records are seconds.
41pub trait MetricsRecorder: Send + Sync + 'static {
42    fn increment(&self, name: &str, value: u64, tags: &MetricTags);
43    fn record(&self, name: &str, value: f64, tags: &MetricTags);
44}
45
46/// Explicit no-op recorder; omission has the same behavior.
47#[derive(Debug, Default)]
48pub struct NoopMetrics;
49impl MetricsRecorder for NoopMetrics {
50    fn increment(&self, _: &str, _: u64, _: &MetricTags) {}
51    fn record(&self, _: &str, _: f64, _: &MetricTags) {}
52}
53
54#[derive(Clone, Default)]
55pub(super) struct Metrics(Option<Arc<dyn MetricsRecorder>>);
56impl fmt::Debug for Metrics {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.debug_struct("Metrics")
59            .field("enabled", &self.0.is_some())
60            .finish()
61    }
62}
63impl Metrics {
64    pub(super) fn new(recorder: Arc<dyn MetricsRecorder>) -> Self {
65        Self(Some(recorder))
66    }
67
68    pub(super) fn ready_age(&self, kind: &str, queue: &str, age: Option<f64>) {
69        let (Some(recorder), Some(age)) = (&self.0, age) else {
70            return;
71        };
72        let tags = [
73            ("task_kind".into(), kind.into()),
74            ("task_queue".into(), queue.into()),
75        ]
76        .into();
77        let _ = catch_unwind(AssertUnwindSafe(|| {
78            recorder.record(WORKER_TASK_SCHEDULE_TO_START_SECONDS, age, &tags)
79        }));
80    }
81
82    fn pair(&self, counter: &str, histogram: &str, tags: &MetricTags, elapsed: f64) {
83        if let Some(recorder) = &self.0 {
84            let _ = catch_unwind(AssertUnwindSafe(|| recorder.increment(counter, 1, tags)));
85            let _ = catch_unwind(AssertUnwindSafe(|| {
86                recorder.record(histogram, elapsed, tags)
87            }));
88        }
89    }
90
91    pub(super) fn worker(&self, task: bool, kind: &str, queue: &str) -> WorkerObservation {
92        WorkerObservation {
93            metrics: self.clone(),
94            start: Instant::now(),
95            task,
96            tags: if self.0.is_some() {
97                [
98                    ("task_kind".into(), kind.into()),
99                    ("task_queue".into(), queue.into()),
100                    ("outcome".into(), "error".into()),
101                ]
102                .into()
103            } else {
104                MetricTags::new()
105            },
106        }
107    }
108}
109
110// This is producer data, not a wall-clock estimate. Missing/invalid data is
111// unavailable; in particular, never synthesize zero for an unsupported Server.
112pub(super) fn ready_age_from_poll(wire: &crate::Value) -> Option<f64> {
113    if wire["server_capabilities"]["claimed_task_ready_age"] != true {
114        return None;
115    }
116    let milliseconds = wire["task"]["ready_age_ms"].as_u64()?;
117    (milliseconds <= 9_007_199_254_740_991).then_some(milliseconds as f64 / 1000.0)
118}
119
120pub(super) struct WorkerObservation {
121    metrics: Metrics,
122    start: Instant,
123    task: bool,
124    tags: MetricTags,
125}
126impl WorkerObservation {
127    pub(super) fn outcome(&mut self, value: &str) {
128        if self.metrics.0.is_some() {
129            self.tags.insert("outcome".into(), value.into());
130        }
131    }
132    pub(super) fn poll<T>(
133        &mut self,
134        result: &Result<Option<T>>,
135        classify: impl FnOnce(&T) -> WorkerPollOutcome,
136    ) {
137        let outcome = match result {
138            Ok(Some(value)) => match classify(value) {
139                WorkerPollOutcome::Task => "task",
140                WorkerPollOutcome::Idle {
141                    poll_status,
142                    reason,
143                }
144                | WorkerPollOutcome::Stop {
145                    poll_status,
146                    reason,
147                } if poll_status.as_deref() == Some("backpressure")
148                    || reason.as_deref().is_some_and(|v| {
149                        matches!(
150                            v,
151                            "backpressure"
152                                | "worker_capacity_exhausted"
153                                | "storage_capacity_exhausted"
154                        )
155                    }) =>
156                {
157                    "backpressure"
158                }
159                _ => "empty",
160            },
161            Ok(None) => "empty",
162            Err(error) if crate::worker_poll_capacity_retry_after(error).is_some() => {
163                "backpressure"
164            }
165            Err(_) => "error",
166        };
167        self.outcome(outcome);
168    }
169}
170impl Drop for WorkerObservation {
171    fn drop(&mut self) {
172        let (counter, histogram) = if self.task {
173            (WORKER_TASKS, WORKER_TASK_DURATION_SECONDS)
174        } else {
175            (WORKER_POLLS, WORKER_POLL_DURATION_SECONDS)
176        };
177        self.metrics.pair(
178            counter,
179            histogram,
180            &self.tags,
181            self.start.elapsed().as_secs_f64(),
182        );
183    }
184}
185
186pub(super) struct ClientObservation {
187    metrics: Metrics,
188    start: Instant,
189    status: AtomicU16,
190    tags: MetricTags,
191}
192impl ClientObservation {
193    pub(super) fn new(
194        client: &Client,
195        method: &reqwest::Method,
196        path: &str,
197        protocol: RequestProtocol,
198    ) -> Self {
199        let plane = match protocol {
200            RequestProtocol::ControlPlane => "control",
201            _ => "worker",
202        };
203        Self {
204            metrics: client.metrics.clone(),
205            start: Instant::now(),
206            status: AtomicU16::new(0),
207            tags: if client.metrics.0.is_some() {
208                [
209                    ("method".into(), method.as_str().into()),
210                    ("route".into(), route(path).into()),
211                    ("plane".into(), plane.into()),
212                    ("status_code".into(), "none".into()),
213                    ("outcome".into(), "pending".into()),
214                ]
215                .into()
216            } else {
217                MetricTags::new()
218            },
219        }
220    }
221    pub(super) fn status(&self, status: reqwest::StatusCode) {
222        self.status.store(status.as_u16(), Ordering::Relaxed);
223    }
224    pub(super) fn finish<T>(&mut self, result: &Result<T>) {
225        if self.metrics.0.is_none() {
226            return;
227        }
228        let outcome = match result {
229            Ok(_) if self.status.load(Ordering::Relaxed) >= 400 => "http_error",
230            Ok(_) => "ok",
231            Err(Error::Http { .. }) => "http_error",
232            Err(Error::Protocol(_)) => "bridge_rejected",
233            Err(Error::Transport(_)) => "TransportError",
234            Err(Error::Timeout) => "TimeoutError",
235            Err(_) => "SdkError",
236        };
237        self.tags.insert("outcome".into(), outcome.into());
238    }
239}
240impl Drop for ClientObservation {
241    fn drop(&mut self) {
242        if self.metrics.0.is_none() {
243            return;
244        }
245        let status = self.status.load(Ordering::Relaxed);
246        if status != 0 {
247            self.tags.insert("status_code".into(), status.to_string());
248        }
249        self.metrics.pair(
250            CLIENT_REQUESTS,
251            CLIENT_REQUEST_DURATION_SECONDS,
252            &self.tags,
253            self.start.elapsed().as_secs_f64(),
254        );
255    }
256}
257
258impl Client {
259    /// Replace this client's recorder. Clones and new workers inherit it.
260    pub fn with_metrics_recorder(mut self, recorder: Arc<dyn MetricsRecorder>) -> Self {
261        self.metrics = Metrics::new(recorder);
262        self
263    }
264
265    pub(super) async fn metrics_request<T: DeserializeOwned, B: Serialize + ?Sized>(
266        &self,
267        method: reqwest::Method,
268        path: &str,
269        protocol: RequestProtocol,
270        body: Option<&B>,
271        timeout: Duration,
272        payloads: JsonPayloads,
273    ) -> Result<T> {
274        let mut observation = ClientObservation::new(self, &method, path, protocol);
275        let options = JsonRequestOptions { timeout, payloads };
276        let result = async {
277            if !payloads.resolve {
278                return Box::pin(self.send_json_with_timeout(
279                    method,
280                    path,
281                    protocol,
282                    body,
283                    options,
284                    &observation,
285                ))
286                .await;
287            }
288            let mut value: serde_json::Value = Box::pin(self.send_json_with_timeout(
289                method,
290                path,
291                protocol,
292                body,
293                options,
294                &observation,
295            ))
296            .await?;
297            self.resolve_runtime_payloads(
298                &mut value,
299                path,
300                self.worker_request_protocol(protocol)?,
301            )
302            .await?;
303            Ok(serde_json::from_value(value)?)
304        }
305        .await;
306        observation.finish(&result);
307        result
308    }
309
310    pub(super) async fn metrics_poll_request<T: DeserializeOwned, B: Serialize + ?Sized>(
311        &self,
312        path: &str,
313        protocol: RequestProtocol,
314        body: &B,
315        timeout: Duration,
316        max_retries: usize,
317        resolve: bool,
318    ) -> Result<T> {
319        let mut observation = ClientObservation::new(self, &reqwest::Method::POST, path, protocol);
320        let options = JsonRequestOptions {
321            timeout,
322            payloads: JsonPayloads::DEFAULT,
323        };
324        // A validator worker's workflow poll also leases update-validation tasks.
325        let multiplexed = self.multiplexed_workflow_poll_body(path, body)?;
326        let result = async {
327            let mut retries = 0;
328            loop {
329                let response = async {
330                    let mut value: serde_json::Value = match &multiplexed {
331                        Some(multiplexed) => {
332                            Box::pin(self.send_json_with_timeout(
333                                reqwest::Method::POST,
334                                path,
335                                protocol,
336                                Some(multiplexed),
337                                options,
338                                &observation,
339                            ))
340                            .await?
341                        }
342                        None => {
343                            Box::pin(self.send_json_with_timeout(
344                                reqwest::Method::POST,
345                                path,
346                                protocol,
347                                Some(body),
348                                options,
349                                &observation,
350                            ))
351                            .await?
352                        }
353                    };
354                    if resolve {
355                        self.resolve_runtime_payloads(
356                            &mut value,
357                            path,
358                            self.worker_request_protocol(protocol)?,
359                        )
360                        .await?;
361                    }
362                    Ok(value)
363                }
364                .await;
365                match response {
366                    Err(Error::Transport(_)) if retries < max_retries => retries += 1,
367                    response => {
368                        let mut value = crate::worker_poll_response(response)?;
369                        self.assert_protected_response_namespace(value.pointer("/task/namespace"))?;
370                        if value.get("task").is_some_and(|task| !task.is_null()) {
371                            if let Some(slot) = &self.worker_task_slot {
372                                slot.claimed();
373                            }
374                        }
375                        if multiplexed.is_some() {
376                            self.park_update_validation_task(&mut value)?;
377                        }
378                        return Ok(serde_json::from_value(value)?);
379                    }
380                }
381            }
382        }
383        .await;
384        observation.finish(&result);
385        result
386    }
387}
388
389/// Reviewed templates only; unknown operations use a single bounded value.
390fn route(path: &str) -> &'static str {
391    let clean = path.split(['?', '#']).next().unwrap_or_default();
392    ROUTES
393        .iter()
394        .copied()
395        .find(|template| {
396            let mut actual = clean.trim_matches('/').split('/');
397            for expected in template.trim_matches('/').split('/') {
398                let Some(segment) = actual.next() else {
399                    return false;
400                };
401                if expected != segment && (!expected.starts_with('{') || segment.is_empty()) {
402                    return false;
403                }
404            }
405            actual.next().is_none()
406        })
407        .unwrap_or("unknown")
408}
409
410include!("metrics/routes.rs");
411
412#[cfg(test)]
413mod tests;
414
415// A failed workflow command is a failed dispatch outcome, even when its failure receipt succeeds.
416pub(super) fn workflow_task_outcome(
417    decision: Option<&crate::WorkflowTaskDecision>,
418) -> &'static str {
419    match decision {
420        Some(decision)
421            if !decision.commands.iter().any(|command| {
422                command.get("type").and_then(serde_json::Value::as_str) == Some("fail_workflow")
423            }) =>
424        {
425            "completed"
426        }
427        _ => "failed",
428    }
429}