Skip to main content

durable_workflow/
local_activity.rs

1use super::*;
2
3const MAX_ATTEMPTS: u64 = 100;
4const MAX_HEARTBEATS: usize = 1000;
5const LEASE_RENEWAL_INTERVAL: Duration = Duration::from_secs(1);
6
7/// Retry and timeout settings for an activity executed by the workflow worker.
8///
9/// Local activities bypass the activity queue. They do not accept routing,
10/// schedule-to-start timeouts, or remote activity cancellation policies.
11#[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    /// Execute a registered activity in this workflow worker and record its outcome.
93    ///
94    /// Committed results are replayed without executing the callback. A worker
95    /// lost before acknowledgment can execute the callback again, so side effects
96    /// must be idempotent. Callbacks must yield to Tokio and avoid blocking work.
97    pub fn local_activity<T: Serialize>(
98        &self,
99        activity_type: impl Into<String>,
100        args: T,
101    ) -> ActivityCall {
102        self.local_activity_with_options(activity_type, LocalActivityOptions::new(), args)
103    }
104
105    pub fn local_activity_with_options<T: Serialize>(
106        &self,
107        activity_type: impl Into<String>,
108        options: LocalActivityOptions,
109        args: T,
110    ) -> ActivityCall {
111        let mut call =
112            self.activity_with_options(activity_type, options.into_activity_options(), args);
113        call.local = true;
114        call
115    }
116
117    /// Lossless Avro result, including bytes and large integers.
118    pub async fn local_activity_avro_value<T: Serialize>(
119        &self,
120        activity_type: impl Into<String>,
121        args: T,
122    ) -> Result<AvroValue> {
123        self.local_activity_avro_value_with_options(
124            activity_type,
125            LocalActivityOptions::new(),
126            args,
127        )
128        .await
129    }
130
131    pub async fn local_activity_avro_value_with_options<T: Serialize>(
132        &self,
133        activity_type: impl Into<String>,
134        options: LocalActivityOptions,
135        args: T,
136    ) -> Result<AvroValue> {
137        let mut call = self.local_activity_with_options(activity_type, options, args);
138        std::future::poll_fn(|cx| Pin::new(&mut call).poll_avro_value(cx)).await
139    }
140
141    pub async fn local_activity_typed<I: Serialize, O: DeserializeOwned>(
142        &self,
143        activity_type: impl Into<String>,
144        args: I,
145    ) -> Result<O> {
146        self.local_activity_typed_with_options(activity_type, LocalActivityOptions::new(), args)
147            .await
148    }
149
150    pub async fn local_activity_typed_with_options<I: Serialize, O: DeserializeOwned>(
151        &self,
152        activity_type: impl Into<String>,
153        options: LocalActivityOptions,
154        args: I,
155    ) -> Result<O> {
156        let activity_type = activity_type.into();
157        let result = self
158            .local_activity_avro_value_with_options(activity_type.clone(), options, args)
159            .await?;
160        decode_handler_result(result, HandlerKind::Activity, &activity_type)
161    }
162}
163
164#[derive(Debug)]
165pub(super) struct Request {
166    pub command_index: usize,
167    pub options: ValidatedActivityOptions,
168    pub arguments: AvroValue,
169    pub result: Arc<Mutex<Option<ActivityOutcome>>>,
170}
171
172#[derive(Debug)]
173pub(super) struct Heartbeats {
174    active: bool,
175    started: Instant,
176    last: Instant,
177    reports: Vec<Value>,
178    capacity: usize,
179    overflowed: bool,
180}
181
182impl Heartbeats {
183    pub(super) fn captured_attempt() -> (Arc<Mutex<Self>>, impl Drop) {
184        let now = Instant::now();
185        let reports = Arc::new(Mutex::new(Self {
186            active: true,
187            started: now,
188            last: now,
189            reports: Vec::new(),
190            capacity: MAX_HEARTBEATS,
191            overflowed: false,
192        }));
193        let close = CloseAttempt(reports.clone());
194        (reports, close)
195    }
196
197    pub fn record<T: Serialize>(&mut self, details: T) -> Result<ActivityHeartbeatResponse> {
198        if !self.active {
199            return Ok(heartbeat_response(false));
200        }
201        if self.reports.len() >= self.capacity {
202            self.overflowed = true;
203            return Err(Error::WorkerLoop(
204                "local_activity_heartbeat_limit_exceeded: at most 1000 reports per local command"
205                    .into(),
206            ));
207        }
208        let details = encode_typed_envelope(&AvroValue::from_serialize(&details)?, DEFAULT_CODEC)?;
209        let now = Instant::now();
210        self.reports.push(
211            json!({"elapsed_ms": millis(now.duration_since(self.started)), "details": details}),
212        );
213        self.last = now;
214        Ok(heartbeat_response(true))
215    }
216}
217
218fn heartbeat_response(active: bool) -> ActivityHeartbeatResponse {
219    ActivityHeartbeatResponse {
220        cancel_requested: false,
221        heartbeat_recorded: active,
222        can_continue: Some(active),
223        reason: (!active).then(|| "local_activity_attempt_closed".into()),
224        run_closed_reason: None,
225        run_closed_at: None,
226        lease_expires_at: None,
227        last_heartbeat_at: None,
228    }
229}
230
231struct CloseAttempt(Arc<Mutex<Heartbeats>>);
232impl Drop for CloseAttempt {
233    fn drop(&mut self) {
234        if let Ok(mut heartbeats) = self.0.lock() {
235            heartbeats.active = false;
236        }
237    }
238}
239
240fn millis(duration: Duration) -> u64 {
241    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
242}
243
244impl Worker {
245    pub(super) async fn execute_workflow_with_local_activities(
246        &self,
247        task: WorkflowTask,
248    ) -> Result<Option<WorkflowTaskDecision>> {
249        #[cfg(feature = "telemetry")]
250        if let Some(telemetry) = &self.telemetry {
251            return telemetry
252                .run_observed(
253                    "durable.workflow.task",
254                    self.workflow_telemetry_fields(&task),
255                    false,
256                    self.workflow_observations(&task),
257                    async {
258                        let mut decision = self
259                            .execute_workflow_with_local_activities_inner(task)
260                            .await?;
261                        if let Some(decision) = &mut decision {
262                            self.stamp_observability_commands(&mut decision.commands);
263                        }
264                        Ok(decision)
265                    },
266                )
267                .await;
268        }
269        self.execute_workflow_with_local_activities_inner(task)
270            .await
271    }
272
273    async fn execute_workflow_with_local_activities_inner(
274        &self,
275        task: WorkflowTask,
276    ) -> Result<Option<WorkflowTaskDecision>> {
277        let (task, context, mut future) = match self.prepare_workflow_task_execution(task, None)? {
278            PreparedWorkflowTask::Decision(decision) => return Ok(Some(decision)),
279            PreparedWorkflowTask::Execution {
280                task,
281                context,
282                future,
283            } => (task, context, future),
284        };
285        loop {
286            let outcome = Self::poll_workflow_future(&context, &mut future)?;
287            let requests = {
288                let mut state = context
289                    .state
290                    .lock()
291                    .map_err(|_| Error::WorkflowStatePoisoned)?;
292                std::mem::take(&mut state.local_activity_requests)
293            };
294            if requests.is_empty() {
295                return self
296                    .finish_workflow_task_execution(&task, &context, outcome)
297                    .map(Some);
298            }
299            if !self.client.local_activities_enabled {
300                return Err(Error::WorkerLoop("local_activities_not_enabled: opt in with Worker::local_activities(true) before executing inline local work".into()));
301            }
302            // A custom future cannot publish a terminal decision while ignoring
303            // an unresolved local call. Resolve only genuinely suspended work.
304            if !outcome.is_pending() {
305                return Err(Error::WorkflowYieldedWithoutCommand);
306            }
307            for request in requests {
308                let Some((wire, result)) = self
309                    .execute_local_activity(&task, &context, &request)
310                    .await?
311                else {
312                    // Do not fail, complete, or continue the workflow after a
313                    // refused or uncertain lease. Reclaim owns subsequent work.
314                    return Ok(None);
315                };
316                let mut state = context
317                    .state
318                    .lock()
319                    .map_err(|_| Error::WorkflowStatePoisoned)?;
320                state.commands[request.command_index] = wire;
321                *request
322                    .result
323                    .lock()
324                    .map_err(|_| Error::WorkflowStatePoisoned)? = Some(result);
325            }
326        }
327    }
328
329    async fn local_claim_is_active(&self, task: &WorkflowTask) -> bool {
330        tokio::select! {
331            biased;
332            _ = self.local_worker_stopped() => false,
333            receipt = self.client.heartbeat_workflow_task_with_protocol(task, None, MINIMUM_WORKER_PROTOCOL_VERSION) => {
334                receipt.is_ok_and(|receipt| receipt.cancellation_request.is_none())
335            }
336        }
337    }
338
339    async fn local_worker_stopped(&self) {
340        match &self.client.worker_storage_admission {
341            Some(admission) => wait_for_worker_stop(&admission.stop).await,
342            None => std::future::pending::<()>().await,
343        }
344    }
345
346    async fn externalize_local_command(
347        &self,
348        task: &WorkflowTask,
349        context: &WorkflowContext,
350        index: usize,
351        wire: &mut Value,
352    ) -> Result<()> {
353        let mut commands = context
354            .state
355            .lock()
356            .map_err(|_| Error::WorkflowStatePoisoned)?
357            .commands
358            .clone();
359        commands[index] = wire.clone();
360        let mut body = json!({"lease_owner": task.lease_owner, "workflow_task_attempt": task.workflow_task_attempt,
361            "commands": commands});
362        let path = format!("/worker/workflow-tasks/{}/complete", task.task_id);
363        self.client
364            .externalize_runtime_payloads(&mut body, &path, RequestProtocol::DefaultWorker)
365            .await?;
366        *wire = body["commands"][index].take();
367        Ok(())
368    }
369
370    async fn execute_local_activity(
371        &self,
372        task: &WorkflowTask,
373        context: &WorkflowContext,
374        request: &Request,
375    ) -> Result<Option<(Value, ActivityOutcome)>> {
376        let mut wire = context
377            .state
378            .lock()
379            .map_err(|_| Error::WorkflowStatePoisoned)?
380            .commands[request.command_index]
381            .clone();
382        // Serialize and admit input before the callback can produce side effects.
383        if self
384            .externalize_local_command(task, context, request.command_index, &mut wire)
385            .await
386            .is_err()
387        {
388            return Ok(None);
389        }
390        let activity_type = wire["activity_type"]
391            .as_str()
392            .unwrap_or_default()
393            .to_owned();
394        let policy = request.options.retry_policy.as_ref();
395        let max_attempts = policy
396            .and_then(|policy| policy["max_attempts"].as_u64())
397            .unwrap_or(1);
398        let started = Instant::now();
399        let total_deadline = request
400            .options
401            .schedule_to_close_timeout
402            .map(|seconds| started + Duration::from_secs(seconds));
403        let mut attempts = Vec::new();
404        let mut heartbeat_count = 0;
405        for number in 1..=max_attempts {
406            if !self.local_claim_is_active(task).await {
407                return Ok(None);
408            }
409            let attempt_started = Instant::now();
410            let reports = Arc::new(Mutex::new(Heartbeats {
411                active: true,
412                started: attempt_started,
413                last: attempt_started,
414                reports: Vec::new(),
415                capacity: MAX_HEARTBEATS - heartbeat_count,
416                overflowed: false,
417            }));
418            let close = CloseAttempt(reports.clone());
419            let attempt_id = format!(
420                "{:x}",
421                Sha256::digest(
422                    format!(
423                        "{}\0{}\0{}\0{}",
424                        task.task_id, task.workflow_task_attempt, request.command_index, number
425                    )
426                    .as_bytes()
427                )
428            );
429            let ctx = ActivityContext {
430                client: self.client.clone(),
431                task_id: task.task_id.clone(),
432                activity_attempt_id: attempt_id.clone(),
433                lease_owner: task.lease_owner.clone().unwrap_or_default(),
434                activity_type: activity_type.clone(),
435                attempt_number: number,
436                task_queue: self.task_queue.clone(),
437                worker_id: self.worker_id.clone(),
438                claim_guard: None,
439                local_heartbeats: Some(reports.clone()),
440                worker_session: None,
441            };
442            let callback = self
443                .activities
444                .get(&activity_type)
445                .filter(|_| !total_deadline.is_some_and(|deadline| Instant::now() >= deadline));
446            let mut future: ActivityFuture = match callback {
447                Some(callback) => {
448                    self.activity_callback(callback, ctx, request.arguments.clone(), true)
449                }
450                None if total_deadline.is_some_and(|deadline| Instant::now() >= deadline) => {
451                    Box::pin(std::future::pending())
452                }
453                None => {
454                    let unknown = activity_type.clone();
455                    Box::pin(async move { Err(Error::ActivityNotRegistered(unknown)) })
456                }
457            };
458            let attempt_deadline = request
459                .options
460                .start_to_close_timeout
461                .map(|seconds| attempt_started + Duration::from_secs(seconds));
462            let outcome = loop {
463                let heartbeat_deadline = request
464                    .options
465                    .heartbeat_timeout
466                    .map(|seconds| {
467                        reports
468                            .lock()
469                            .map(|reports| reports.last + Duration::from_secs(seconds))
470                    })
471                    .transpose()
472                    .map_err(|_| Error::WorkflowStatePoisoned)?;
473                let next_timeout = [
474                    (total_deadline, "schedule_to_close"),
475                    (attempt_deadline, "start_to_close"),
476                    (heartbeat_deadline, "heartbeat"),
477                ]
478                .into_iter()
479                .filter_map(|(deadline, kind)| deadline.map(|d| (d, kind)))
480                .min_by_key(|(deadline, _)| *deadline);
481                let timeout_kind = next_timeout
482                    .map(|(_, kind)| kind)
483                    .unwrap_or("start_to_close");
484                let timeout = async {
485                    match next_timeout {
486                        Some((deadline, _)) => tokio::time::sleep_until(deadline.into()).await,
487                        None => std::future::pending::<()>().await,
488                    }
489                };
490                tokio::pin!(timeout);
491                tokio::select! {
492                    biased;
493                    _ = self.local_worker_stopped() => return Ok(None),
494                    _ = &mut timeout => {
495                        if timeout_kind == "heartbeat" && heartbeat_extended(&reports, request.options.heartbeat_timeout)? { continue; }
496                        break Err((format!("local activity exceeded {timeout_kind} timeout"), "LocalActivityTimeout".to_owned(), false, Some(timeout_kind)));
497                    },
498                    result = &mut future => break result.map_err(local_error),
499                    _ = tokio::time::sleep(LEASE_RENEWAL_INTERVAL) => {
500                        tokio::select! {
501                            biased;
502                            _ = &mut timeout => {
503                                if timeout_kind == "heartbeat" && heartbeat_extended(&reports, request.options.heartbeat_timeout)? { continue; }
504                                break Err((format!("local activity exceeded {timeout_kind} timeout"), "LocalActivityTimeout".to_owned(), false, Some(timeout_kind)));
505                            },
506                            active = self.local_claim_is_active(task) => { if !active { return Ok(None); } }
507                        }
508                    }
509                }
510            };
511            drop(future);
512            drop(close);
513            let (heartbeats, overflowed) = {
514                let mut reports = reports.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
515                (std::mem::take(&mut reports.reports), reports.overflowed)
516            };
517            heartbeat_count += heartbeats.len();
518            let outcome = if overflowed {
519                Err((
520                    "local activity exceeded 1000 heartbeat reports".into(),
521                    "LocalActivityHeartbeatLimit".into(),
522                    true,
523                    None,
524                ))
525            } else {
526                outcome
527            };
528            let mut report = json!({"attempt_number": number, "attempt_id": attempt_id,
529                "duration_ms": millis(attempt_started.elapsed()), "heartbeats": heartbeats});
530            let (result, failure) = match outcome {
531                Ok(result) => match encode_typed_envelope(&result, &task.payload_codec) {
532                    Ok(envelope) => {
533                        wire["result"] = envelope;
534                        (Some(result), None)
535                    }
536                    Err(error) => (
537                        None,
538                        Some((
539                            error.to_string(),
540                            "LocalActivityResultCodecError".into(),
541                            true,
542                            None,
543                        )),
544                    ),
545                },
546                Err(failure) => (None, Some(failure)),
547            };
548            if let Some((message, exception_type, mut non_retryable, timeout_kind)) = failure {
549                non_retryable |= policy
550                    .and_then(|policy| policy["non_retryable_error_types"].as_array())
551                    .is_some_and(|types| {
552                        types
553                            .iter()
554                            .any(|t| t.as_str() == Some(exception_type.as_str()))
555                    });
556                let status = if timeout_kind.is_some() {
557                    "timed_out"
558                } else {
559                    "failed"
560                };
561                report["outcome"] = json!(status);
562                report["message"] = json!(message);
563                report["exception_type"] = json!(exception_type);
564                report["non_retryable"] = json!(non_retryable);
565                if let Some(kind) = timeout_kind {
566                    report["timeout_kind"] = json!(kind);
567                }
568                let retry = number < max_attempts
569                    && !non_retryable
570                    && timeout_kind != Some("schedule_to_close");
571                if retry {
572                    let backoff = policy
573                        .and_then(|p| p["backoff_seconds"].get((number - 1) as usize))
574                        .and_then(Value::as_u64)
575                        .unwrap_or(0);
576                    report["retry_reason"] = json!(if timeout_kind.is_some() {
577                        "timeout"
578                    } else {
579                        "failure"
580                    });
581                    report["backoff_seconds"] = json!(backoff);
582                    attempts.push(report);
583                    let wake = Instant::now() + Duration::from_secs(backoff);
584                    while Instant::now() < wake {
585                        // An elapsed total deadline is reported as the next
586                        // terminal attempt, with no further callback invocation.
587                        if total_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
588                            break;
589                        }
590                        if !self.local_claim_is_active(task).await {
591                            return Ok(None);
592                        }
593                        let deadline = total_deadline.map_or(wake, |d| d.min(wake));
594                        tokio::time::sleep(
595                            deadline
596                                .saturating_duration_since(Instant::now())
597                                .min(LEASE_RENEWAL_INTERVAL),
598                        )
599                        .await;
600                    }
601                    continue;
602                }
603                attempts.push(report);
604                for field in [
605                    "outcome",
606                    "message",
607                    "exception_type",
608                    "non_retryable",
609                    "timeout_kind",
610                ] {
611                    if let Some(value) = attempts.last().unwrap().get(field) {
612                        wire[field] = value.clone();
613                    }
614                }
615                wire["attempts"] = json!(attempts);
616                // Match the terminal fields Server persists. Database-generated
617                // execution/failure IDs are only available on committed replay.
618                let mut payload = wire.clone();
619                payload["attempt_number"] = json!(number);
620                payload["failure_category"] = json!(if timeout_kind.is_some() {
621                    "timeout"
622                } else {
623                    "application"
624                });
625                if timeout_kind.is_some() {
626                    payload["exception_class"] = payload["exception_type"].take();
627                    payload.as_object_mut().unwrap().remove("exception_type");
628                    payload.as_object_mut().unwrap().remove("non_retryable");
629                }
630                let event = HistoryEvent {
631                    event_type: if timeout_kind.is_some() {
632                        "ActivityTimedOut"
633                    } else {
634                        "ActivityFailed"
635                    }
636                    .into(),
637                    payload,
638                    raw: HashMap::new(),
639                };
640                let result =
641                    activity_outcome(&event, &task.payload_codec, Some(activity_type.clone()))?;
642                if self
643                    .externalize_local_command(task, context, request.command_index, &mut wire)
644                    .await
645                    .is_err()
646                    || !self.local_claim_is_active(task).await
647                {
648                    return Ok(None);
649                }
650                return Ok(Some((wire, result)));
651            }
652            report["outcome"] = json!("completed");
653            attempts.push(report);
654            wire["outcome"] = json!("completed");
655            wire["attempts"] = json!(attempts);
656            if self
657                .externalize_local_command(task, context, request.command_index, &mut wire)
658                .await
659                .is_err()
660                || !self.local_claim_is_active(task).await
661            {
662                return Ok(None);
663            }
664            return Ok(Some((wire, Ok(result.unwrap()))));
665        }
666        unreachable!("validated local retry budget includes at least one attempt")
667    }
668}
669
670fn local_error(error: Error) -> (String, String, bool, Option<&'static str>) {
671    let failure = crate::ActivityError::from_error(&error, "RustActivityError");
672    (
673        failure.message,
674        failure.exception_type,
675        failure.non_retryable,
676        None,
677    )
678}
679
680fn heartbeat_extended(reports: &Arc<Mutex<Heartbeats>>, timeout: Option<u64>) -> Result<bool> {
681    let reports = reports.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
682    Ok(timeout.is_some_and(|seconds| reports.last + Duration::from_secs(seconds) > Instant::now()))
683}