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