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