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