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