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                retry_info: crate::ActivityRetryInfo::new(number, None),
437                activity_execution_id: None,
438                workflow_id: task.workflow_id.clone(),
439                run_id: task.run_id.clone(),
440                task_queue: self.task_queue.clone(),
441                worker_id: self.worker_id.clone(),
442                claim_guard: None,
443                local_heartbeats: Some(reports.clone()),
444                worker_session: None,
445            };
446            let callback = self
447                .activities
448                .get(&activity_type)
449                .filter(|_| !total_deadline.is_some_and(|deadline| Instant::now() >= deadline));
450            let mut future: ActivityFuture = match callback {
451                Some(callback) => {
452                    self.activity_callback(callback, ctx, request.arguments.clone(), true)
453                }
454                None if total_deadline.is_some_and(|deadline| Instant::now() >= deadline) => {
455                    Box::pin(std::future::pending())
456                }
457                None => {
458                    let unknown = activity_type.clone();
459                    Box::pin(async move { Err(Error::ActivityNotRegistered(unknown)) })
460                }
461            };
462            let attempt_deadline = request
463                .options
464                .start_to_close_timeout
465                .map(|seconds| attempt_started + Duration::from_secs(seconds));
466            let outcome = loop {
467                let heartbeat_deadline = request
468                    .options
469                    .heartbeat_timeout
470                    .map(|seconds| {
471                        reports
472                            .lock()
473                            .map(|reports| reports.last + Duration::from_secs(seconds))
474                    })
475                    .transpose()
476                    .map_err(|_| Error::WorkflowStatePoisoned)?;
477                let next_timeout = [
478                    (total_deadline, "schedule_to_close"),
479                    (attempt_deadline, "start_to_close"),
480                    (heartbeat_deadline, "heartbeat"),
481                ]
482                .into_iter()
483                .filter_map(|(deadline, kind)| deadline.map(|d| (d, kind)))
484                .min_by_key(|(deadline, _)| *deadline);
485                let timeout_kind = next_timeout
486                    .map(|(_, kind)| kind)
487                    .unwrap_or("start_to_close");
488                let timeout = async {
489                    match next_timeout {
490                        Some((deadline, _)) => tokio::time::sleep_until(deadline.into()).await,
491                        None => std::future::pending::<()>().await,
492                    }
493                };
494                tokio::pin!(timeout);
495                tokio::select! {
496                    biased;
497                    _ = self.local_worker_stopped() => return Ok(None),
498                    _ = &mut timeout => {
499                        if timeout_kind == "heartbeat" && heartbeat_extended(&reports, request.options.heartbeat_timeout)? { continue; }
500                        break Err((format!("local activity exceeded {timeout_kind} timeout"), "LocalActivityTimeout".to_owned(), false, Some(timeout_kind)));
501                    },
502                    result = &mut future => break result.map_err(local_error),
503                    _ = tokio::time::sleep(LEASE_RENEWAL_INTERVAL) => {
504                        tokio::select! {
505                            biased;
506                            _ = &mut timeout => {
507                                if timeout_kind == "heartbeat" && heartbeat_extended(&reports, request.options.heartbeat_timeout)? { continue; }
508                                break Err((format!("local activity exceeded {timeout_kind} timeout"), "LocalActivityTimeout".to_owned(), false, Some(timeout_kind)));
509                            },
510                            active = self.local_claim_is_active(task) => { if !active { return Ok(None); } }
511                        }
512                    }
513                }
514            };
515            drop(future);
516            drop(close);
517            let (heartbeats, overflowed) = {
518                let mut reports = reports.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
519                (std::mem::take(&mut reports.reports), reports.overflowed)
520            };
521            heartbeat_count += heartbeats.len();
522            let outcome = if overflowed {
523                Err((
524                    "local activity exceeded 1000 heartbeat reports".into(),
525                    "LocalActivityHeartbeatLimit".into(),
526                    true,
527                    None,
528                ))
529            } else {
530                outcome
531            };
532            let mut report = json!({"attempt_number": number, "attempt_id": attempt_id,
533                "duration_ms": millis(attempt_started.elapsed()), "heartbeats": heartbeats});
534            let (result, failure) = match outcome {
535                Ok(result) => match encode_typed_envelope(&result, &task.payload_codec) {
536                    Ok(envelope) => {
537                        wire["result"] = envelope;
538                        (Some(result), None)
539                    }
540                    Err(error) => (
541                        None,
542                        Some((
543                            error.to_string(),
544                            "LocalActivityResultCodecError".into(),
545                            true,
546                            None,
547                        )),
548                    ),
549                },
550                Err(failure) => (None, Some(failure)),
551            };
552            if let Some((message, exception_type, mut non_retryable, timeout_kind)) = failure {
553                non_retryable |= policy
554                    .and_then(|policy| policy["non_retryable_error_types"].as_array())
555                    .is_some_and(|types| {
556                        types
557                            .iter()
558                            .any(|t| t.as_str() == Some(exception_type.as_str()))
559                    });
560                let status = if timeout_kind.is_some() {
561                    "timed_out"
562                } else {
563                    "failed"
564                };
565                report["outcome"] = json!(status);
566                report["message"] = json!(message);
567                report["exception_type"] = json!(exception_type);
568                report["non_retryable"] = json!(non_retryable);
569                if let Some(kind) = timeout_kind {
570                    report["timeout_kind"] = json!(kind);
571                }
572                let retry = number < max_attempts
573                    && !non_retryable
574                    && timeout_kind != Some("schedule_to_close");
575                if retry {
576                    let backoff = policy
577                        .and_then(|p| p["backoff_seconds"].get((number - 1) as usize))
578                        .and_then(Value::as_u64)
579                        .unwrap_or(0);
580                    report["retry_reason"] = json!(if timeout_kind.is_some() {
581                        "timeout"
582                    } else {
583                        "failure"
584                    });
585                    report["backoff_seconds"] = json!(backoff);
586                    attempts.push(report);
587                    let wake = Instant::now() + Duration::from_secs(backoff);
588                    while Instant::now() < wake {
589                        // An elapsed total deadline is reported as the next
590                        // terminal attempt, with no further callback invocation.
591                        if total_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
592                            break;
593                        }
594                        if !self.local_claim_is_active(task).await {
595                            return Ok(None);
596                        }
597                        let deadline = total_deadline.map_or(wake, |d| d.min(wake));
598                        tokio::time::sleep(
599                            deadline
600                                .saturating_duration_since(Instant::now())
601                                .min(LEASE_RENEWAL_INTERVAL),
602                        )
603                        .await;
604                    }
605                    continue;
606                }
607                attempts.push(report);
608                for field in [
609                    "outcome",
610                    "message",
611                    "exception_type",
612                    "non_retryable",
613                    "timeout_kind",
614                ] {
615                    if let Some(value) = attempts.last().unwrap().get(field) {
616                        wire[field] = value.clone();
617                    }
618                }
619                wire["attempts"] = json!(attempts);
620                // Match the terminal fields Server persists. Database-generated
621                // execution/failure IDs are only available on committed replay.
622                let mut payload = wire.clone();
623                payload["attempt_number"] = json!(number);
624                payload["failure_category"] = json!(if timeout_kind.is_some() {
625                    "timeout"
626                } else {
627                    "application"
628                });
629                if timeout_kind.is_some() {
630                    payload["exception_class"] = payload["exception_type"].take();
631                    payload.as_object_mut().unwrap().remove("exception_type");
632                    payload.as_object_mut().unwrap().remove("non_retryable");
633                }
634                let event = HistoryEvent {
635                    event_type: if timeout_kind.is_some() {
636                        "ActivityTimedOut"
637                    } else {
638                        "ActivityFailed"
639                    }
640                    .into(),
641                    payload,
642                    raw: HashMap::new(),
643                };
644                let result =
645                    activity_outcome(&event, &task.payload_codec, Some(activity_type.clone()))?;
646                if self
647                    .externalize_local_command(task, context, request.command_index, &mut wire)
648                    .await
649                    .is_err()
650                    || !self.local_claim_is_active(task).await
651                {
652                    return Ok(None);
653                }
654                return Ok(Some((wire, result)));
655            }
656            report["outcome"] = json!("completed");
657            attempts.push(report);
658            wire["outcome"] = json!("completed");
659            wire["attempts"] = json!(attempts);
660            if self
661                .externalize_local_command(task, context, request.command_index, &mut wire)
662                .await
663                .is_err()
664                || !self.local_claim_is_active(task).await
665            {
666                return Ok(None);
667            }
668            return Ok(Some((wire, Ok(result.unwrap()))));
669        }
670        unreachable!("validated local retry budget includes at least one attempt")
671    }
672}
673
674fn local_error(error: Error) -> (String, String, bool, Option<&'static str>) {
675    let failure = crate::ActivityError::from_error(&error, "RustActivityError");
676    (
677        failure.message,
678        failure.exception_type,
679        failure.non_retryable,
680        None,
681    )
682}
683
684fn heartbeat_extended(reports: &Arc<Mutex<Heartbeats>>, timeout: Option<u64>) -> Result<bool> {
685    let reports = reports.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
686    Ok(timeout.is_some_and(|seconds| reports.last + Duration::from_secs(seconds) > Instant::now()))
687}