1use super::*;
2
3const MAX_ATTEMPTS: u64 = 100;
4const MAX_HEARTBEATS: usize = 1000;
5const LEASE_RENEWAL_INTERVAL: Duration = Duration::from_secs(1);
6
7#[derive(Clone, Debug, Default, PartialEq, Eq)]
12pub struct LocalActivityOptions {
13 pub retry_policy: Option<ActivityRetryPolicy>,
14 pub start_to_close_timeout: Option<Duration>,
15 pub schedule_to_close_timeout: Option<Duration>,
16 pub heartbeat_timeout: Option<Duration>,
17}
18
19impl LocalActivityOptions {
20 pub fn new() -> Self {
21 Self::default()
22 }
23 pub fn retry_policy(mut self, policy: ActivityRetryPolicy) -> Self {
24 self.retry_policy = Some(policy);
25 self
26 }
27 pub fn start_to_close_timeout(mut self, timeout: Duration) -> Self {
28 self.start_to_close_timeout = Some(timeout);
29 self
30 }
31 pub fn schedule_to_close_timeout(mut self, timeout: Duration) -> Self {
32 self.schedule_to_close_timeout = Some(timeout);
33 self
34 }
35 pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
36 self.heartbeat_timeout = Some(timeout);
37 self
38 }
39 fn into_activity_options(self) -> ActivityOptions {
40 ActivityOptions {
41 retry_policy: self.retry_policy,
42 start_to_close_timeout: self.start_to_close_timeout,
43 schedule_to_close_timeout: self.schedule_to_close_timeout,
44 heartbeat_timeout: self.heartbeat_timeout,
45 ..ActivityOptions::default()
46 }
47 }
48}
49
50pub(super) fn validate(options: &ValidatedActivityOptions) -> Result<()> {
51 let max_attempts = options
52 .retry_policy
53 .as_ref()
54 .and_then(|policy| policy["max_attempts"].as_u64())
55 .unwrap_or(1);
56 if max_attempts > MAX_ATTEMPTS {
57 return Err(Error::InvalidActivityOptions(ActivityOptionsError::new(
58 ActivityOptionsErrorKind::InvalidMaxAttempts,
59 Some("max_attempts"),
60 "local activities support at most 100 attempts",
61 )));
62 }
63 for seconds in [
64 options.start_to_close_timeout,
65 options.schedule_to_close_timeout,
66 options.heartbeat_timeout,
67 ]
68 .into_iter()
69 .flatten()
70 .chain(options.retry_policy.iter().flat_map(|p| {
71 p["backoff_seconds"]
72 .as_array()
73 .into_iter()
74 .flatten()
75 .filter_map(Value::as_u64)
76 })) {
77 if Instant::now()
78 .checked_add(Duration::from_secs(seconds))
79 .is_none()
80 {
81 return Err(Error::InvalidActivityOptions(ActivityOptionsError::new(
82 ActivityOptionsErrorKind::TimeoutOverflow,
83 Some("local_activity"),
84 "local timing exceeds the monotonic clock range",
85 )));
86 }
87 }
88 Ok(())
89}
90
91impl WorkflowContext {
92 #[track_caller]
98 pub fn local_activity<T: Serialize>(
99 &self,
100 activity_type: impl Into<String>,
101 args: T,
102 ) -> ActivityCall {
103 self.local_activity_with_options(activity_type, LocalActivityOptions::new(), args)
104 }
105
106 #[track_caller]
107 pub fn local_activity_with_options<T: Serialize>(
108 &self,
109 activity_type: impl Into<String>,
110 options: LocalActivityOptions,
111 args: T,
112 ) -> ActivityCall {
113 let mut call =
114 self.activity_with_options(activity_type, options.into_activity_options(), args);
115 call.local = true;
116 call
117 }
118
119 pub async fn local_activity_avro_value<T: Serialize>(
121 &self,
122 activity_type: impl Into<String>,
123 args: T,
124 ) -> Result<AvroValue> {
125 self.local_activity_avro_value_with_options(
126 activity_type,
127 LocalActivityOptions::new(),
128 args,
129 )
130 .await
131 }
132
133 pub async fn local_activity_avro_value_with_options<T: Serialize>(
134 &self,
135 activity_type: impl Into<String>,
136 options: LocalActivityOptions,
137 args: T,
138 ) -> Result<AvroValue> {
139 let mut call = self.local_activity_with_options(activity_type, options, args);
140 call.source = None;
141 std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
142 }
143
144 pub async fn local_activity_typed<I: Serialize, O: DeserializeOwned>(
145 &self,
146 activity_type: impl Into<String>,
147 args: I,
148 ) -> Result<O> {
149 self.local_activity_typed_with_options(activity_type, LocalActivityOptions::new(), args)
150 .await
151 }
152
153 pub async fn local_activity_typed_with_options<I: Serialize, O: DeserializeOwned>(
154 &self,
155 activity_type: impl Into<String>,
156 options: LocalActivityOptions,
157 args: I,
158 ) -> Result<O> {
159 let activity_type = activity_type.into();
160 let result = self
161 .local_activity_avro_value_with_options(activity_type.clone(), options, args)
162 .await?;
163 decode_handler_result(result, HandlerKind::Activity, &activity_type)
164 }
165}
166
167#[derive(Debug)]
168pub(super) struct Request {
169 pub command_index: usize,
170 pub options: ValidatedActivityOptions,
171 pub arguments: AvroValue,
172 pub result: Arc<Mutex<Option<ActivityOutcome>>>,
173}
174
175#[derive(Debug)]
176pub(super) struct Heartbeats {
177 active: bool,
178 started: Instant,
179 last: Instant,
180 reports: Vec<Value>,
181 capacity: usize,
182 overflowed: bool,
183}
184
185impl Heartbeats {
186 pub(super) fn captured_attempt() -> (Arc<Mutex<Self>>, impl Drop) {
187 let now = Instant::now();
188 let reports = Arc::new(Mutex::new(Self {
189 active: true,
190 started: now,
191 last: now,
192 reports: Vec::new(),
193 capacity: MAX_HEARTBEATS,
194 overflowed: false,
195 }));
196 let close = CloseAttempt(reports.clone());
197 (reports, close)
198 }
199
200 pub fn record<T: Serialize>(&mut self, details: T) -> Result<ActivityHeartbeatResponse> {
201 if !self.active {
202 return Ok(heartbeat_response(false));
203 }
204 if self.reports.len() >= self.capacity {
205 self.overflowed = true;
206 return Err(Error::WorkerLoop(
207 "local_activity_heartbeat_limit_exceeded: at most 1000 reports per local command"
208 .into(),
209 ));
210 }
211 let details = encode_typed_envelope(&AvroValue::from_serialize(&details)?, DEFAULT_CODEC)?;
212 let now = Instant::now();
213 self.reports.push(
214 json!({"elapsed_ms": millis(now.duration_since(self.started)), "details": details}),
215 );
216 self.last = now;
217 Ok(heartbeat_response(true))
218 }
219}
220
221fn heartbeat_response(active: bool) -> ActivityHeartbeatResponse {
222 ActivityHeartbeatResponse {
223 cancel_requested: false,
224 heartbeat_recorded: active,
225 can_continue: Some(active),
226 reason: (!active).then(|| "local_activity_attempt_closed".into()),
227 run_closed_reason: None,
228 run_closed_at: None,
229 lease_expires_at: None,
230 last_heartbeat_at: None,
231 }
232}
233
234struct CloseAttempt(Arc<Mutex<Heartbeats>>);
235impl Drop for CloseAttempt {
236 fn drop(&mut self) {
237 if let Ok(mut heartbeats) = self.0.lock() {
238 heartbeats.active = false;
239 }
240 }
241}
242
243fn millis(duration: Duration) -> u64 {
244 u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
245}
246
247impl Worker {
248 pub(super) async fn execute_workflow_with_local_activities(
249 &self,
250 task: WorkflowTask,
251 ) -> Result<Option<WorkflowTaskDecision>> {
252 #[cfg(feature = "telemetry")]
253 if let Some(telemetry) = &self.telemetry {
254 return telemetry
255 .run_observed(
256 "durable.workflow.task",
257 self.workflow_telemetry_fields(&task),
258 false,
259 self.workflow_observations(&task),
260 async {
261 let mut decision = self.intercepted_workflow_task(task).await?;
262 if let Some(decision) = &mut decision {
263 self.stamp_observability_commands(&mut decision.commands);
264 }
265 Ok(decision)
266 },
267 )
268 .await;
269 }
270 self.intercepted_workflow_task(task).await
271 }
272
273 async fn intercepted_workflow_task(
275 &self,
276 task: WorkflowTask,
277 ) -> Result<Option<WorkflowTaskDecision>> {
278 let context = self.workflow_task_interceptor_context(&task);
279 self.intercept_workflow_task(
280 context,
281 self.execute_workflow_with_local_activities_inner(task),
282 )
283 .await
284 }
285
286 async fn execute_workflow_with_local_activities_inner(
287 &self,
288 task: WorkflowTask,
289 ) -> Result<Option<WorkflowTaskDecision>> {
290 let (task, context, mut future) = match self.prepare_workflow_task_execution(task, None)? {
291 PreparedWorkflowTask::Decision(decision) => return Ok(Some(decision)),
292 PreparedWorkflowTask::Execution {
293 task,
294 context,
295 future,
296 } => (task, context, future),
297 };
298 loop {
299 let outcome = Self::poll_workflow_future(&context, &mut future)?;
300 let requests = {
301 let mut state = context
302 .state
303 .lock()
304 .map_err(|_| Error::WorkflowStatePoisoned)?;
305 std::mem::take(&mut state.local_activity_requests)
306 };
307 if requests.is_empty() {
308 return self
309 .finish_workflow_task_execution(&task, &context, outcome)
310 .map(Some);
311 }
312 if !self.client.local_activities_enabled {
313 return Err(Error::WorkerLoop("local_activities_not_enabled: opt in with Worker::local_activities(true) before executing inline local work".into()));
314 }
315 if !outcome.is_pending() {
318 return Err(Error::WorkflowYieldedWithoutCommand);
319 }
320 for request in requests {
321 let Some((wire, result)) = self
322 .execute_local_activity(&task, &context, &request)
323 .await?
324 else {
325 return Ok(None);
328 };
329 let mut state = context
330 .state
331 .lock()
332 .map_err(|_| Error::WorkflowStatePoisoned)?;
333 state.commands[request.command_index] = wire;
334 *request
335 .result
336 .lock()
337 .map_err(|_| Error::WorkflowStatePoisoned)? = Some(result);
338 }
339 }
340 }
341
342 async fn local_claim_is_active(&self, task: &WorkflowTask) -> bool {
343 tokio::select! {
344 biased;
345 _ = self.local_worker_stopped() => false,
346 receipt = self.client.heartbeat_workflow_task_with_protocol(task, None, MINIMUM_WORKER_PROTOCOL_VERSION) => {
347 receipt.is_ok_and(|receipt| receipt.cancellation_request.is_none())
348 }
349 }
350 }
351
352 async fn local_worker_stopped(&self) {
353 match &self.client.worker_storage_admission {
354 Some(admission) => wait_for_worker_stop(&admission.stop).await,
355 None => std::future::pending::<()>().await,
356 }
357 }
358
359 async fn externalize_local_command(
360 &self,
361 task: &WorkflowTask,
362 context: &WorkflowContext,
363 index: usize,
364 wire: &mut Value,
365 messages: &[(usize, crate::failure_reporting::LocalText)],
366 ) -> Result<()> {
367 let mut commands = context
368 .state
369 .lock()
370 .map_err(|_| Error::WorkflowStatePoisoned)?
371 .commands
372 .clone();
373 commands[index] = wire.clone();
374 let mut body = json!({"lease_owner": task.lease_owner, "workflow_task_attempt": task.workflow_task_attempt,
375 "commands": commands});
376 let path = format!("/worker/workflow-tasks/{}/complete", task.task_id);
377 let limit = self
378 .client
379 .known_failure_request_limit(RequestProtocol::DefaultWorker)?;
380 crate::failure_reporting::fit_local(&mut body, index, messages, limit)?;
381 self.client
382 .externalize_runtime_payloads(&mut body, &path, RequestProtocol::DefaultWorker)
383 .await?;
384 let limit = self
385 .client
386 .known_failure_request_limit(RequestProtocol::DefaultWorker)?;
387 crate::failure_reporting::fit_local(&mut body, index, messages, limit)?;
388 *wire = body["commands"][index].take();
389 Ok(())
390 }
391
392 async fn admit_local_command(
393 &self,
394 task: &WorkflowTask,
395 context: &WorkflowContext,
396 index: usize,
397 wire: &mut Value,
398 messages: &[(usize, crate::failure_reporting::LocalText)],
399 ) -> Result<bool> {
400 match self
401 .externalize_local_command(task, context, index, wire, messages)
402 .await
403 {
404 Ok(()) => Ok(true),
405 Err(error @ Error::FailureReporting(_)) => Err(error),
406 Err(_) => Ok(false),
407 }
408 }
409
410 async fn execute_local_activity(
411 &self,
412 task: &WorkflowTask,
413 context: &WorkflowContext,
414 request: &Request,
415 ) -> Result<Option<(Value, ActivityOutcome)>> {
416 let mut wire = context
417 .state
418 .lock()
419 .map_err(|_| Error::WorkflowStatePoisoned)?
420 .commands[request.command_index]
421 .clone();
422 if !self
424 .admit_local_command(task, context, request.command_index, &mut wire, &[])
425 .await?
426 {
427 return Ok(None);
428 }
429 let activity_type = wire["activity_type"]
430 .as_str()
431 .unwrap_or_default()
432 .to_owned();
433 let policy = request.options.retry_policy.as_ref();
434 let max_attempts = policy
435 .and_then(|policy| policy["max_attempts"].as_u64())
436 .unwrap_or(1);
437 let started = Instant::now();
438 let total_deadline = request
439 .options
440 .schedule_to_close_timeout
441 .map(|seconds| started + Duration::from_secs(seconds));
442 let mut attempts = Vec::new();
443 let mut messages = Vec::new();
444 let mut heartbeat_count = 0;
445 for number in 1..=max_attempts {
446 if !self.local_claim_is_active(task).await {
447 return Ok(None);
448 }
449 let attempt_started = Instant::now();
450 let reports = Arc::new(Mutex::new(Heartbeats {
451 active: true,
452 started: attempt_started,
453 last: attempt_started,
454 reports: Vec::new(),
455 capacity: MAX_HEARTBEATS - heartbeat_count,
456 overflowed: false,
457 }));
458 let close = CloseAttempt(reports.clone());
459 let attempt_id = format!(
460 "{:x}",
461 Sha256::digest(
462 format!(
463 "{}\0{}\0{}\0{}",
464 task.task_id, task.workflow_task_attempt, request.command_index, number
465 )
466 .as_bytes()
467 )
468 );
469 let ctx = ActivityContext {
470 client: self.client.clone(),
471 task_id: task.task_id.clone(),
472 activity_attempt_id: attempt_id.clone(),
473 lease_owner: task.lease_owner.clone().unwrap_or_default(),
474 activity_type: activity_type.clone(),
475 attempt_number: number,
476 retry_info: crate::ActivityRetryInfo::new(number, None),
477 heartbeat_resume: Default::default(),
478 activity_execution_id: None,
479 workflow_id: task.workflow_id.clone(),
480 run_id: task.run_id.clone(),
481 task_queue: self.task_queue.clone(),
482 worker_id: self.worker_id.clone(),
483 claim_guard: None,
484 local_heartbeats: Some(reports.clone()),
485 worker_session: None,
486 };
487 let callback = self
488 .activities
489 .get(&activity_type)
490 .filter(|_| total_deadline.is_none_or(|deadline| Instant::now() < deadline));
491 let mut future: ActivityFuture = match callback {
492 Some(callback) => {
493 self.activity_callback(callback, ctx, request.arguments.clone(), true)
494 }
495 None if total_deadline.is_some_and(|deadline| Instant::now() >= deadline) => {
496 Box::pin(std::future::pending())
497 }
498 None => {
499 let unknown = activity_type.clone();
500 Box::pin(async move { Err(Error::ActivityNotRegistered(unknown)) })
501 }
502 };
503 let attempt_deadline = request
504 .options
505 .start_to_close_timeout
506 .map(|seconds| attempt_started + Duration::from_secs(seconds));
507 let outcome = loop {
508 let heartbeat_deadline = request
509 .options
510 .heartbeat_timeout
511 .map(|seconds| {
512 reports
513 .lock()
514 .map(|reports| reports.last + Duration::from_secs(seconds))
515 })
516 .transpose()
517 .map_err(|_| Error::WorkflowStatePoisoned)?;
518 let next_timeout = [
519 (total_deadline, "schedule_to_close"),
520 (attempt_deadline, "start_to_close"),
521 (heartbeat_deadline, "heartbeat"),
522 ]
523 .into_iter()
524 .filter_map(|(deadline, kind)| deadline.map(|d| (d, kind)))
525 .min_by_key(|(deadline, _)| *deadline);
526 let timeout_kind = next_timeout
527 .map(|(_, kind)| kind)
528 .unwrap_or("start_to_close");
529 let timeout = async {
530 match next_timeout {
531 Some((deadline, _)) => tokio::time::sleep_until(deadline.into()).await,
532 None => std::future::pending::<()>().await,
533 }
534 };
535 tokio::pin!(timeout);
536 tokio::select! {
537 biased;
538 _ = self.local_worker_stopped() => return Ok(None),
539 _ = &mut timeout => {
540 if timeout_kind == "heartbeat" && heartbeat_extended(&reports, request.options.heartbeat_timeout)? { continue; }
541 break Err((format!("local activity exceeded {timeout_kind} timeout"), "LocalActivityTimeout".to_owned(), false, Some(timeout_kind)));
542 },
543 result = &mut future => break result.map_err(local_error),
544 _ = tokio::time::sleep(LEASE_RENEWAL_INTERVAL) => {
545 tokio::select! {
546 biased;
547 _ = &mut timeout => {
548 if timeout_kind == "heartbeat" && heartbeat_extended(&reports, request.options.heartbeat_timeout)? { continue; }
549 break Err((format!("local activity exceeded {timeout_kind} timeout"), "LocalActivityTimeout".to_owned(), false, Some(timeout_kind)));
550 },
551 active = self.local_claim_is_active(task) => { if !active { return Ok(None); } }
552 }
553 }
554 }
555 };
556 drop(future);
557 drop(close);
558 let (heartbeats, overflowed) = {
559 let mut reports = reports.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
560 (std::mem::take(&mut reports.reports), reports.overflowed)
561 };
562 heartbeat_count += heartbeats.len();
563 let outcome = if overflowed {
564 Err((
565 "local activity exceeded 1000 heartbeat reports".into(),
566 "LocalActivityHeartbeatLimit".into(),
567 true,
568 None,
569 ))
570 } else {
571 outcome
572 };
573 let mut report = json!({"attempt_number": number, "attempt_id": attempt_id,
574 "duration_ms": millis(attempt_started.elapsed()), "heartbeats": heartbeats});
575 let (result, failure) = match outcome {
576 Ok(result) => match encode_typed_envelope(&result, &task.payload_codec) {
577 Ok(envelope) => {
578 wire["result"] = envelope;
579 (Some(result), None)
580 }
581 Err(error) => (
582 None,
583 Some((
584 error.to_string(),
585 "LocalActivityResultCodecError".into(),
586 true,
587 None,
588 )),
589 ),
590 },
591 Err(failure) => (None, Some(failure)),
592 };
593 if let Some((message, exception_type, mut non_retryable, timeout_kind)) = failure {
594 non_retryable |= policy
595 .and_then(|policy| policy["non_retryable_error_types"].as_array())
596 .is_some_and(|types| {
597 types
598 .iter()
599 .any(|t| t.as_str() == Some(exception_type.as_str()))
600 });
601 let status = if timeout_kind.is_some() {
602 "timed_out"
603 } else {
604 "failed"
605 };
606 report["outcome"] = json!(status);
607 let original = crate::failure_reporting::LocalText::new(&message);
608 report["message"] = json!(original.render(crate::failure_reporting::MESSAGE_BYTES));
609 messages.push((attempts.len(), original));
610 report["exception_type"] = json!(exception_type);
611 report["non_retryable"] = json!(non_retryable);
612 if let Some(kind) = timeout_kind {
613 report["timeout_kind"] = json!(kind);
614 }
615 let retry = number < max_attempts
616 && !non_retryable
617 && timeout_kind != Some("schedule_to_close");
618 if retry {
619 let backoff = local_retry_backoff_seconds(policy, number);
620 report["retry_reason"] = json!(if timeout_kind.is_some() {
621 "timeout"
622 } else {
623 "failure"
624 });
625 report["backoff_seconds"] = json!(backoff);
626 attempts.push(report);
627 let wake = Instant::now() + Duration::from_secs(backoff);
628 while Instant::now() < wake {
629 if total_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
632 break;
633 }
634 if !self.local_claim_is_active(task).await {
635 return Ok(None);
636 }
637 let deadline = total_deadline.map_or(wake, |d| d.min(wake));
638 tokio::time::sleep(
639 deadline
640 .saturating_duration_since(Instant::now())
641 .min(LEASE_RENEWAL_INTERVAL),
642 )
643 .await;
644 }
645 continue;
646 }
647 attempts.push(report);
648 for field in [
649 "outcome",
650 "message",
651 "exception_type",
652 "non_retryable",
653 "timeout_kind",
654 ] {
655 if let Some(value) = attempts.last().unwrap().get(field) {
656 wire[field] = value.clone();
657 }
658 }
659 wire["attempts"] = json!(attempts);
660 if !self
661 .admit_local_command(task, context, request.command_index, &mut wire, &messages)
662 .await?
663 || !self.local_claim_is_active(task).await
664 {
665 return Ok(None);
666 }
667 let mut payload = wire.clone();
670 if let Some(message) = payload["message"].as_str() {
671 payload["message"] =
672 json!(crate::failure_reporting::committed_message(message));
673 }
674 payload["attempt_number"] = json!(number);
675 payload["failure_category"] = json!(if timeout_kind.is_some() {
676 "timeout"
677 } else {
678 "application"
679 });
680 if timeout_kind.is_some() {
681 payload["exception_class"] = payload["exception_type"].take();
682 payload.as_object_mut().unwrap().remove("exception_type");
683 payload.as_object_mut().unwrap().remove("non_retryable");
684 }
685 let event = HistoryEvent {
686 event_type: if timeout_kind.is_some() {
687 "ActivityTimedOut"
688 } else {
689 "ActivityFailed"
690 }
691 .into(),
692 payload,
693 raw: HashMap::new(),
694 };
695 let result =
696 activity_outcome(&event, &task.payload_codec, Some(activity_type.clone()))?;
697 return Ok(Some((wire, result)));
698 }
699 report["outcome"] = json!("completed");
700 attempts.push(report);
701 wire["outcome"] = json!("completed");
702 wire["attempts"] = json!(attempts);
703 if !self
704 .admit_local_command(task, context, request.command_index, &mut wire, &messages)
705 .await?
706 || !self.local_claim_is_active(task).await
707 {
708 return Ok(None);
709 }
710 return Ok(Some((wire, Ok(result.unwrap()))));
711 }
712 unreachable!("validated local retry budget includes at least one attempt")
713 }
714}
715
716fn local_error(error: Error) -> (String, String, bool, Option<&'static str>) {
717 let failure = crate::ActivityError::from_error(&error, "RustActivityError");
718 (
719 failure.message,
720 failure.exception_type,
721 failure.non_retryable,
722 None,
723 )
724}
725
726fn heartbeat_extended(reports: &Arc<Mutex<Heartbeats>>, timeout: Option<u64>) -> Result<bool> {
727 let reports = reports.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
728 Ok(timeout.is_some_and(|seconds| reports.last + Duration::from_secs(seconds) > Instant::now()))
729}
730
731fn local_retry_backoff_seconds(policy: Option<&Value>, number: u64) -> u64 {
736 policy
737 .and_then(|p| p["backoff_seconds"].as_array())
738 .and_then(|list| {
739 let index = usize::try_from(number)
740 .ok()?
741 .min(list.len())
742 .checked_sub(1)?;
743 list.get(index)
744 })
745 .and_then(Value::as_u64)
746 .unwrap_or(0)
747}
748
749#[cfg(test)]
750mod local_retry_backoff_tests {
751 use super::{local_retry_backoff_seconds, LocalActivityOptions};
752 use crate::ActivityRetryPolicy;
753 use serde_json::json;
754 use std::time::Duration;
755
756 fn local_delays(policy: ActivityRetryPolicy) -> (serde_json::Value, Vec<u64>) {
757 let validated = LocalActivityOptions::new()
758 .retry_policy(policy)
759 .into_activity_options()
760 .validate()
761 .expect("valid local policy");
762 let policy = validated.retry_policy.expect("encoded retry policy");
763 let attempts = policy["max_attempts"].as_u64().unwrap();
764 let delays = (1..attempts)
765 .map(|number| local_retry_backoff_seconds(Some(&policy), number))
766 .collect();
767 (policy, delays)
768 }
769
770 #[test]
771 fn capped_exponential_local_policy_keeps_waiting_the_cap() {
772 let (policy, delays) = local_delays(ActivityRetryPolicy::new(7).exponential_backoff(
775 Duration::from_secs(1),
776 2,
777 Some(Duration::from_secs(4)),
778 ));
779 assert_eq!(policy["backoff_seconds"], json!([1, 2, 4]));
780 assert_eq!(delays, vec![1, 2, 4, 4, 4, 4]);
781 }
782
783 #[test]
784 fn explicit_short_and_empty_local_lists_follow_the_documented_rule() {
785 let (_, short) = local_delays(
786 ActivityRetryPolicy::new(5)
787 .backoff_intervals([Duration::from_secs(1), Duration::from_secs(2)]),
788 );
789 assert_eq!(short, vec![1, 2, 2, 2]);
790 let (policy, empty) = local_delays(ActivityRetryPolicy::new(5).backoff_intervals([]));
791 assert_eq!(policy["backoff_seconds"], json!([]));
792 assert_eq!(empty, vec![0, 0, 0, 0]);
793 }
794
795 #[test]
796 fn repeats_the_final_entry_once_the_list_runs_out() {
797 let policy = json!({"max_attempts": 5, "backoff_seconds": [1, 2]});
798 let delays: Vec<u64> = (1..=4)
799 .map(|number| local_retry_backoff_seconds(Some(&policy), number))
800 .collect();
801 assert_eq!(delays, vec![1, 2, 2, 2]);
802 }
803
804 #[test]
805 fn no_list_or_no_policy_means_no_delay() {
806 let empty = json!({"max_attempts": 3, "backoff_seconds": []});
807 let missing = json!({"max_attempts": 3});
808 assert_eq!(local_retry_backoff_seconds(Some(&empty), 2), 0);
809 assert_eq!(local_retry_backoff_seconds(Some(&missing), 2), 0);
810 assert_eq!(local_retry_backoff_seconds(None, 1), 0);
811 }
812}