1use super::*;
2use std::collections::BTreeSet;
3
4const CONTROL_BUDGET: Duration = Duration::from_secs(5);
5const MAX_REFRESH_PAGES: usize = 128;
6
7pub(super) fn assert_cancellation_scope_replay_supported(
8 events: &[HistoryEvent],
9 allow_authoring: bool,
10 allow_delivery: bool,
11) -> Result<()> {
12 if allow_delivery && !allow_authoring {
13 return Err(Error::CancellationScopeExecutionUnavailable);
14 }
15 for event in events {
16 let scope_marker = matches!(
17 event.event_type.as_str(),
18 "CancellationScopeRequested"
19 | "CancellationScopeDeliveryPrepared"
20 | "CancellationScopeDelivered"
21 | "CancellationScopeRequestConflicted"
22 );
23 let scoped_membership = std::iter::once(&event.payload)
24 .chain(
25 ["activity", "timer", "child_workflow"]
26 .iter()
27 .filter_map(|name| event.payload.get(name)),
28 )
29 .any(|payload| {
30 payload
31 .get("cancellation_scope_id")
32 .is_some_and(|scope| scope.as_str() != Some("root"))
33 });
34 if (scope_marker && !allow_delivery)
35 || (!allow_authoring
36 && (event.event_type == "CancellationScopeOpened" || scoped_membership))
37 {
38 return Err(Error::CancellationScopeExecutionUnavailable);
39 }
40 }
41 Ok(())
42}
43
44#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct CancellationDeliveryReceipt {
47 pub task_id: String,
48 pub run_id: String,
49 pub delivery: CancellationDelivery,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq)]
54pub enum CancellationDeliveryReply {
55 Delivered(CancellationDeliveryReceipt),
56 ClaimReleased {
59 task_id: String,
60 run_id: String,
61 },
62}
63
64#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct WorkflowTaskHeartbeat {
67 pub task_id: String,
68 pub workflow_task_attempt: u64,
69 pub lease_owner: String,
70 pub lease_expires_at: String,
71 pub run_status: String,
72 pub cancellation_request: Option<CancellationRequest>,
73}
74
75#[derive(Clone, Debug)]
80pub struct CooperativeWorkflowTask {
81 task: WorkflowTask,
82 cancellation_request: Option<CancellationRequest>,
83}
84
85impl CooperativeWorkflowTask {
86 pub fn task(&self) -> &WorkflowTask {
87 &self.task
88 }
89
90 pub fn cancellation_request(&self) -> Option<&CancellationRequest> {
91 self.cancellation_request.as_ref()
92 }
93
94 pub async fn heartbeat(&mut self, client: &Client) -> Result<WorkflowTaskHeartbeat> {
98 let receipt = client
99 .heartbeat_workflow_task(&self.task, self.cancellation_request.as_ref())
100 .await?;
101 self.cancellation_request = receipt.cancellation_request.clone();
102 Ok(receipt)
103 }
104}
105
106#[derive(Clone, Debug)]
108pub struct CooperativeWorkflowTaskPoll {
109 pub task: Option<CooperativeWorkflowTask>,
110 pub outcome: WorkerPollOutcome,
111 pub protocol_version: Option<String>,
112 pub server_capabilities: Option<Value>,
113}
114
115#[derive(Clone, Debug, Default, Serialize)]
117pub struct CooperativeCancellationOptions {
118 #[serde(skip_serializing_if = "Option::is_none")]
119 pub reason: Option<String>,
120 #[serde(skip_serializing_if = "Option::is_none")]
121 pub cleanup_timeout_seconds: Option<u64>,
122}
123
124#[derive(Clone, Debug, PartialEq, Eq)]
126pub struct CancellationRequest {
127 pub request_id: String,
128 pub requested_at: String,
129 pub cleanup_deadline_at: String,
130 pub history_refresh_page_token: Option<String>,
131 pub context: Option<CancellationContext>,
132}
133
134#[derive(Clone, Debug, PartialEq, Eq)]
136pub struct WorkflowCancellationRequest {
137 pub workflow_id: String,
138 pub run_id: String,
139 pub duplicate: bool,
140 pub cancellation_request: CancellationRequest,
141}
142
143#[derive(Clone, Debug, Error, PartialEq, Eq)]
145#[error("workflow cancellation {request_id} was requested", request_id = .request.request_id)]
146pub struct CooperativeCancellationRequested {
147 pub request: CancellationRequest,
148 pub delivery: CancellationDelivery,
149}
150
151#[derive(Debug)]
155pub struct CancellationShield {
156 state: Arc<Mutex<WorkflowState>>,
157}
158
159impl Drop for CancellationShield {
160 fn drop(&mut self) {
161 if let Ok(mut state) = self.state.lock() {
162 state.cancellation_shield_depth = state.cancellation_shield_depth.saturating_sub(1);
163 }
164 }
165}
166
167fn invalid(detail: impl Into<String>) -> Error {
168 Error::InvalidCooperativeCancellation(detail.into())
169}
170
171fn text<'a>(value: &'a Value, field: &str) -> Result<&'a str> {
172 value
173 .get(field)
174 .and_then(Value::as_str)
175 .filter(|text| !text.trim().is_empty())
176 .ok_or_else(|| invalid(format!("{field} must be a non-empty string")))
177}
178
179impl CancellationRequest {
180 pub(super) fn preserve_observation(&self, current: &Self) -> Result<Self> {
181 self.validate_observation()?;
182 current.validate_observation()?;
183 if self.request_id != current.request_id
184 || DateTime::parse_from_rfc3339(&self.requested_at).unwrap()
185 != DateTime::parse_from_rfc3339(¤t.requested_at).unwrap()
186 || DateTime::parse_from_rfc3339(&self.cleanup_deadline_at).unwrap()
187 != DateTime::parse_from_rfc3339(¤t.cleanup_deadline_at).unwrap()
188 {
189 return Err(invalid(
190 "observation changed the original request or cleanup deadline",
191 ));
192 }
193 Ok(self.clone())
194 }
195
196 pub(super) fn validate_observation(&self) -> Result<()> {
197 Self::from_observation(&json!({
198 "request_id":self.request_id, "requested_at":self.requested_at,
199 "cleanup_deadline_at":self.cleanup_deadline_at,
200 "history_refresh_page_token":self.history_refresh_page_token,
201 }))
202 .map(|_| ())
203 }
204
205 pub(crate) fn from_observation(value: &Value) -> Result<Self> {
206 let requested_at = text(value, "requested_at")?;
207 let cleanup_deadline_at = text(value, "cleanup_deadline_at")?;
208 let requested = DateTime::parse_from_rfc3339(requested_at)
209 .map_err(|_| invalid("requested_at must be a timestamp with a timezone"))?;
210 let deadline = DateTime::parse_from_rfc3339(cleanup_deadline_at)
211 .map_err(|_| invalid("cleanup_deadline_at must be a timestamp with a timezone"))?;
212 if deadline <= requested {
213 return Err(invalid("cleanup deadline must follow the original request"));
214 }
215 Ok(Self {
216 request_id: text(value, "request_id")?.to_owned(),
217 requested_at: requested_at.to_owned(),
218 cleanup_deadline_at: cleanup_deadline_at.to_owned(),
219 history_refresh_page_token: Some(text(value, "history_refresh_page_token")?.to_owned()),
220 context: None,
221 })
222 }
223}
224
225const REQUEST_EVENT: &str = "CooperativeCancellationRequested";
226const DELIVERY_EVENT: &str = "CooperativeCancellationDelivered";
227const MAX_SEQUENCE: u64 = i64::MAX as u64;
228
229#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
231#[serde(rename_all = "snake_case")]
232pub enum CancellationCallKind {
233 Activity,
234 LocalActivity,
235 Timer,
236 Condition,
237 Signal,
238 Child,
239 Parallel,
240 SelectionHandle,
241}
242
243#[derive(Clone, Debug, PartialEq, Eq)]
245pub struct CancellationDelivery {
246 pub request_id: String,
247 pub sequence: u64,
248 pub call_kind: CancellationCallKind,
249 pub sequence_span: u64,
250 pub operation_sequence: Option<u64>,
251 pub operation_sequence_span: u64,
252}
253
254fn positive(value: &Value, field: &str, maximum: u64) -> Result<u64> {
255 value
256 .as_u64()
257 .filter(|number| (1..=maximum).contains(number))
258 .ok_or_else(|| {
259 invalid(format!(
260 "{field} must be a positive integer within {maximum}"
261 ))
262 })
263}
264
265impl CancellationDelivery {
266 pub(crate) fn from_payload(value: &Value) -> Result<Self> {
267 let sequence = positive(&value["sequence"], "sequence", MAX_SEQUENCE)?;
268 let call_kind: CancellationCallKind = serde_json::from_value(value["call_kind"].clone())
269 .map_err(|_| invalid("delivery must name a supported durable call kind"))?;
270 let span = positive(
271 value.get("sequence_span").unwrap_or(&json!(1)),
272 "sequence_span",
273 1000,
274 )?;
275 let operation_span = positive(
276 value.get("operation_sequence_span").unwrap_or(&json!(1)),
277 "operation_sequence_span",
278 1000,
279 )?;
280 let operation = value
281 .get("operation_sequence")
282 .filter(|value| !value.is_null());
283 if (call_kind != CancellationCallKind::Parallel && span != 1)
284 || sequence > MAX_SEQUENCE - span
285 {
286 return Err(invalid(
287 "delivery call span is invalid or overflows the portable sequence range",
288 ));
289 }
290 let operation_sequence = if call_kind == CancellationCallKind::SelectionHandle {
291 let base = positive(
292 operation.unwrap_or(&Value::Null),
293 "operation_sequence",
294 MAX_SEQUENCE,
295 )?;
296 if base >= sequence || operation_span > sequence - base {
297 return Err(invalid(
298 "selection handle must name a complete earlier operation range",
299 ));
300 }
301 Some(base)
302 } else {
303 if operation.is_some() || operation_span != 1 {
304 return Err(invalid(
305 "only selection handles may name an operation range",
306 ));
307 }
308 None
309 };
310 Ok(Self {
311 request_id: text(value, "workflow_command_id")?.to_owned(),
312 sequence,
313 call_kind,
314 sequence_span: span,
315 operation_sequence,
316 operation_sequence_span: operation_span,
317 })
318 }
319
320 fn range(&self) -> (u64, u64) {
321 self.operation_sequence
322 .map_or((self.sequence, self.sequence_span), |base| {
323 (base, self.operation_sequence_span)
324 })
325 }
326
327 pub fn interrupts(&self, sequence: u64) -> bool {
329 let (base, span) = self.range();
330 sequence >= base && sequence - base < span
331 }
332}
333
334#[derive(Clone, Debug)]
339pub struct CancellationHistory {
340 pub request: Option<CancellationRequest>,
341 pub delivery: Option<CancellationDelivery>,
342 pub request_index: usize,
343 pub delivery_index: Option<usize>,
344 resolved_before_request: BTreeSet<u64>,
345 latest_condition_sequences_before_request: BTreeMap<u64, u64>,
346 failed_before_request: BTreeSet<u64>,
347 selected_before_request: BTreeSet<(u64, u64)>,
348}
349
350impl CancellationHistory {
351 pub(super) fn bind_commands(
352 &self,
353 mut commands: Vec<RecordedCommand>,
354 ) -> Result<Vec<RecordedCommand>> {
355 let Some(delivery) = &self.delivery else {
356 return Ok(commands);
357 };
358 if delivery.call_kind == CancellationCallKind::Parallel {
359 let index = commands.partition_point(|command| command.sequence() < delivery.sequence);
360 let end = commands.partition_point(|command| {
361 command.sequence() < delivery.sequence + delivery.sequence_span
362 });
363 if commands.get(index).map(RecordedCommand::sequence) != Some(delivery.sequence) {
364 let previous = index
365 .checked_sub(1)
366 .map_or(0, |index| commands[index].sequence());
367 if previous.checked_add(1) != Some(delivery.sequence) {
368 return Err(invalid_recorded_history(
369 "cooperative_cancellation_call_mismatch",
370 delivery.sequence,
371 "next authored parallel group",
372 "missing earlier call",
373 "parallel cancellation marker skips an unrecorded authored command",
374 ));
375 }
376 }
377 let original = commands.drain(index..end).collect();
378 commands.insert(
379 index,
380 RecordedCommand::CancellationGroup {
381 sequence: delivery.sequence,
382 span: delivery.sequence_span,
383 original,
384 },
385 );
386 for command in &mut commands[index + 1..] {
390 let RecordedCommand::ConditionWait {
391 sequence,
392 parallel_group_path: Some(path),
393 ..
394 } = command
395 else {
396 continue;
397 };
398 if self.resolved_before_request.contains(sequence)
399 || !path.first().is_some_and(|group| {
400 group.parallel_group_base_sequence == delivery.sequence
401 && group.parallel_group_size as u64 == delivery.sequence_span
402 })
403 {
404 continue;
405 }
406 *command = RecordedCommand::CancellationBoundary {
407 sequence: *sequence,
408 call_kind: CancellationCallKind::Condition,
409 original: Some(Box::new(command.clone())),
410 };
411 }
412 return Ok(commands);
413 }
414 if !matches!(
415 delivery.call_kind,
416 CancellationCallKind::Activity
417 | CancellationCallKind::Timer
418 | CancellationCallKind::Condition
419 | CancellationCallKind::Signal
420 | CancellationCallKind::Child
421 | CancellationCallKind::SelectionHandle
422 ) {
423 return Ok(commands);
424 }
425 let index = commands.partition_point(|command| command.sequence() < delivery.sequence);
426 let original = if commands
427 .get(index)
428 .is_some_and(|command| command.sequence() == delivery.sequence)
429 {
430 Some(Box::new(commands.remove(index)))
431 } else {
432 let previous = index
433 .checked_sub(1)
434 .map_or(0, |index| commands[index].sequence());
435 if previous.checked_add(1) != Some(delivery.sequence) {
436 return Err(invalid_recorded_history(
437 "cooperative_cancellation_call_mismatch",
438 delivery.sequence,
439 "next authored durable call",
440 "missing earlier call",
441 "cancellation marker skips an unrecorded authored command",
442 ));
443 }
444 None
445 };
446 commands.insert(
447 index,
448 RecordedCommand::CancellationBoundary {
449 sequence: delivery.sequence,
450 call_kind: delivery.call_kind,
451 original,
452 },
453 );
454 Ok(commands)
455 }
456
457 pub fn from_events(
459 events: &[HistoryEvent],
460 run_id: &str,
461 observation: Option<&CancellationRequest>,
462 ) -> Result<Self> {
463 Self::read(events, run_id, observation).map_err(|error| {
464 invalid_recorded_history(
465 "cooperative_cancellation_history_invalid",
466 0,
467 "one canonical request and matching authored delivery",
468 "invalid cancellation history",
469 &error.to_string(),
470 )
471 })
472 }
473
474 fn read(
475 events: &[HistoryEvent],
476 run_id: &str,
477 observation: Option<&CancellationRequest>,
478 ) -> Result<Self> {
479 if let Some(observed) = observation {
480 let requested = DateTime::parse_from_rfc3339(&observed.requested_at)
481 .map_err(|_| invalid("observed request timestamp is invalid"))?;
482 let deadline = DateTime::parse_from_rfc3339(&observed.cleanup_deadline_at)
483 .map_err(|_| invalid("observed cleanup deadline is invalid"))?;
484 if observed.request_id.trim().is_empty()
485 || deadline <= requested
486 || observed
487 .history_refresh_page_token
488 .as_ref()
489 .is_some_and(|token| token.trim().is_empty())
490 {
491 return Err(invalid(
492 "observed request identity, deadline or history token is invalid",
493 ));
494 }
495 }
496 let mut state = Self {
497 request: observation.cloned().map(|mut request| {
498 request.context = None;
499 request
500 }),
501 delivery: None,
502 request_index: events.len(),
503 delivery_index: None,
504 resolved_before_request: BTreeSet::new(),
505 latest_condition_sequences_before_request: BTreeMap::new(),
506 failed_before_request: BTreeSet::new(),
507 selected_before_request: BTreeSet::new(),
508 };
509 let mut saw_request = false;
510 for (index, event) in events.iter().enumerate() {
511 if !matches!(event.event_type.as_str(), REQUEST_EVENT | DELIVERY_EVENT) {
512 continue;
513 }
514 let request_id = text(&event.payload, "workflow_command_id")?;
515 let event_run = text(&event.payload, "workflow_run_id")?;
516 if event
517 .raw
518 .get("workflow_command_id")
519 .is_some_and(|value| value.as_str() != Some(request_id))
520 || (!run_id.is_empty() && event_run != run_id)
521 {
522 return Err(invalid(
523 "canonical event does not match its request or workflow run",
524 ));
525 }
526 if event.event_type == REQUEST_EVENT {
527 if saw_request || state.delivery.is_some() {
528 return Err(invalid("history must contain one request before delivery"));
529 }
530 let recorded_at = event
531 .raw
532 .get("recorded_at")
533 .or_else(|| event.raw.get("timestamp"))
534 .and_then(Value::as_str)
535 .ok_or_else(|| invalid("canonical request lacks its recorded timestamp"))?;
536 let requested = DateTime::parse_from_rfc3339(recorded_at)
537 .map_err(|_| invalid("canonical request timestamp is invalid"))?;
538 let deadline_text = text(&event.payload, "cleanup_deadline_at")?;
539 let deadline = DateTime::parse_from_rfc3339(deadline_text)
540 .map_err(|_| invalid("canonical cleanup deadline is invalid"))?;
541 let context = event
542 .payload
543 .get("cancellation")
544 .map(CancellationContext::from_value)
545 .transpose()?;
546 if let Some(context) = &context {
547 let local = context.lineage().last().unwrap();
548 if context.request_id() != request_id
549 || local.workflow_run_id() != event_run
550 || event
551 .payload
552 .get("workflow_instance_id")
553 .is_some_and(|instance| {
554 instance.as_str() != Some(local.workflow_instance_id())
555 })
556 || context.deadline() != deadline
557 || context.requested_at() > requested
558 || event
559 .payload
560 .get("reason")
561 .is_some_and(|reason| match reason {
562 Value::Null => context.reason().is_some(),
563 Value::String(reason) => Some(reason.as_str()) != context.reason(),
564 _ => true,
565 })
566 {
567 return Err(invalid(
568 "canonical cancellation context does not match its request event",
569 ));
570 }
571 } else if deadline <= requested {
572 return Err(invalid(
573 "canonical cleanup deadline must follow the request",
574 ));
575 }
576 if let Some(observed) = observation {
577 let observed_deadline =
578 DateTime::parse_from_rfc3339(&observed.cleanup_deadline_at)
579 .map_err(|_| invalid("observed cleanup deadline is invalid"))?;
580 if observed.request_id != request_id || observed_deadline != deadline {
581 return Err(invalid(
582 "observation changes the original request or cleanup deadline",
583 ));
584 }
585 }
586 if context.is_some() || observation.is_none() {
587 state.request = Some(CancellationRequest {
588 request_id: request_id.to_owned(),
589 requested_at: context.as_ref().map_or_else(
590 || recorded_at.to_owned(),
591 |context| {
592 context
593 .requested_at()
594 .to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
595 },
596 ),
597 cleanup_deadline_at: deadline_text.to_owned(),
598 history_refresh_page_token: observation
599 .and_then(|request| request.history_refresh_page_token.clone()),
600 context,
601 });
602 }
603 state.request_index = index;
604 saw_request = true;
605 } else {
606 if !saw_request || state.delivery.is_some() {
607 return Err(invalid(
608 "delivery requires one earlier request and one marker",
609 ));
610 }
611 let delivery = CancellationDelivery::from_payload(&event.payload)?;
612 if state
613 .request
614 .as_ref()
615 .map(|request| request.request_id.as_str())
616 != Some(delivery.request_id.as_str())
617 {
618 return Err(invalid("delivery names a different original request"));
619 }
620 if let Some(snapshot) = event.payload.get("cancellation") {
621 let context = CancellationContext::from_value(snapshot)?;
622 if state
623 .request
624 .as_ref()
625 .and_then(|request| request.context.as_ref())
626 != Some(&context)
627 {
628 return Err(invalid(
629 "delivery changes the canonical cancellation context",
630 ));
631 }
632 }
633 state.delivery = Some(delivery);
634 state.delivery_index = Some(index);
635 }
636 }
637 if state.request.is_none() {
638 return Ok(state);
639 }
640 let mut condition_occurrences = BTreeMap::new();
641 for event in &events[..state.request_index] {
642 if matches!(
643 event.event_type.as_str(),
644 "SelectionResolved" | "SelectionOperationCancelled"
645 ) {
646 let (base_field, span_field) = if event.event_type == "SelectionResolved" {
647 ("selection_group_base_sequence", "selection_group_size")
648 } else {
649 ("member_base_sequence", "member_size")
650 };
651 if let (Ok(base), Ok(span)) = (
652 positive(&event.payload[base_field], base_field, MAX_SEQUENCE),
653 positive(&event.payload[span_field], span_field, 1000),
654 ) {
655 if base <= MAX_SEQUENCE - span {
656 if event.event_type == "SelectionResolved" {
657 state.selected_before_request.insert((base, span));
658 } else {
659 state.resolved_before_request.extend(base..base + span);
660 }
661 }
662 }
663 }
664 let Ok(sequence) = positive(&event.payload["sequence"], "sequence", MAX_SEQUENCE)
665 else {
666 continue;
667 };
668 if event.event_type == "ConditionWaitOpened"
671 && (event.payload["parallel_group_id"].is_string()
672 || event.payload["parallel_group_path"]
673 .as_array()
674 .is_some_and(|path| !path.is_empty()))
675 {
676 if let Some(occurrence) = event.payload["condition_wait_occurrence_id"].as_str() {
677 let authored = *condition_occurrences.entry(occurrence).or_insert(sequence);
678 state
679 .latest_condition_sequences_before_request
680 .insert(authored, sequence);
681 }
682 }
683 if matches!(
684 event.event_type.as_str(),
685 "ActivityCompleted"
686 | "ActivityFailed"
687 | "ActivityCancelled"
688 | "ActivityTimedOut"
689 | "TimerFired"
690 | "TimerCancelled"
691 | "ConditionWaitSatisfied"
692 | "ConditionWaitTimedOut"
693 | "SignalApplied"
694 | "ChildRunCompleted"
695 | "ChildRunFailed"
696 | "ChildRunCancelled"
697 | "ChildRunTerminated"
698 ) {
699 state.resolved_before_request.insert(sequence);
700 if matches!(
701 event.event_type.as_str(),
702 "ActivityFailed"
703 | "ActivityCancelled"
704 | "ActivityTimedOut"
705 | "ChildRunFailed"
706 | "ChildRunCancelled"
707 | "ChildRunTerminated"
708 ) {
709 state.failed_before_request.insert(sequence);
710 }
711 }
712 }
713 if let Some(delivery) = &state.delivery {
714 let (base, span) = delivery.range();
715 if !state.range_eligible(base, span) {
716 return Err(invalid(
717 "delivery cannot replace an earlier committed result",
718 ));
719 }
720 }
721 Ok(state)
722 }
723
724 fn range_eligible(&self, sequence: u64, span: u64) -> bool {
725 (1..=1000).contains(&span)
726 && sequence > 0
727 && sequence <= MAX_SEQUENCE - span
728 && !(sequence..sequence + span).all(|sequence| {
729 let latest = self
730 .latest_condition_sequences_before_request
731 .get(&sequence)
732 .unwrap_or(&sequence);
733 self.resolved_before_request.contains(latest)
734 })
735 && !(sequence..sequence + span)
736 .any(|sequence| self.failed_before_request.contains(&sequence))
737 && !self.selected_before_request.contains(&(sequence, span))
738 }
739
740 pub fn eligible(&self, sequence: u64, span: u64) -> bool {
742 self.request.is_some() && self.delivery.is_none() && self.range_eligible(sequence, span)
743 }
744}
745
746impl WorkflowState {
747 fn next_cancellation_sequence(&self) -> Result<u64> {
748 self.recorded_commands.get(self.command_cursor).map_or_else(
749 || {
750 self.recorded_commands
751 .last()
752 .map_or(0, RecordedCommand::sequence)
753 .checked_add(self.commands.len() as u64)
754 .and_then(|sequence| sequence.checked_add(1))
755 .filter(|sequence| *sequence < MAX_SEQUENCE)
756 .ok_or_else(|| invalid("authored cancellation sequence overflowed"))
757 },
758 |command| Ok(command.sequence()),
759 )
760 }
761
762 fn prepare_cancellation_delivery(&mut self, delivery: CancellationDelivery) -> Result<bool> {
763 if !self.cancellation_delivery_enabled || self.cancellation_shield_depth > 0 {
764 return Ok(false);
765 }
766 self.assert_root_cancellation_membership()?;
767 if self.cancellation_delivery_intent.is_some() {
768 self.matched_recorded_pending = true;
769 return Ok(true);
770 }
771 let (base, span) = delivery.range();
772 if !self.cancellation_history.eligible(base, span) {
773 return Ok(false);
774 }
775 let payload = json!({
776 "workflow_command_id":delivery.request_id, "sequence":delivery.sequence,
777 "call_kind":delivery.call_kind, "sequence_span":delivery.sequence_span,
778 "operation_sequence":delivery.operation_sequence,
779 "operation_sequence_span":delivery.operation_sequence_span,
780 });
781 CancellationDelivery::from_payload(&payload)?;
782 self.cancellation_delivery_command_count = self.commands.len();
783 self.cancellation_delivery_intent = Some(delivery);
784 self.matched_recorded_pending = true;
785 Ok(true)
786 }
787
788 fn assert_root_cancellation_membership(&self) -> Result<()> {
789 if self
790 .scope_delivery
791 .as_ref()
792 .is_some_and(|replay| replay.active_scope != "root")
793 {
794 return Err(Error::CancellationScopeExecutionUnavailable);
795 }
796 Ok(())
797 }
798
799 pub(super) fn prepare_scalar_cancellation(
800 &mut self,
801 index: usize,
802 kind: CancellationCallKind,
803 group_path: &[ParallelGroupMetadata],
804 ) -> Result<bool> {
805 if self.prepare_scalar_scope_cancellation(index, kind, group_path)? {
806 return Ok(true);
807 }
808 if !self.cancellation_delivery_enabled || self.cancellation_shield_depth > 0 {
809 return Ok(false);
810 }
811 if !group_path.is_empty() && self.cancellation_delivery_intent.is_none() {
814 return Ok(false);
815 }
816 let Some(request) = self.cancellation_history.request.as_ref() else {
817 return Ok(false);
818 };
819 let sequence = self.recorded_commands.get(index).map_or_else(
820 || self.next_cancellation_sequence(),
821 |command| Ok(command.sequence()),
822 )?;
823 let pending = self.prepare_cancellation_delivery(CancellationDelivery {
824 request_id: request.request_id.clone(),
825 sequence,
826 call_kind: kind,
827 sequence_span: 1,
828 operation_sequence: None,
829 operation_sequence_span: 1,
830 })?;
831 if pending && index < self.recorded_commands.len() {
832 self.command_cursor = index + 1;
833 }
834 Ok(pending)
835 }
836
837 pub(super) fn prepare_group_cancellation(
838 &mut self,
839 descriptors: &[ParallelDescriptor],
840 ) -> Result<()> {
841 let Some(request) = self.cancellation_history.request.as_ref() else {
842 return Ok(());
843 };
844 let Some(group) = descriptors.first().and_then(|leaf| leaf.group_path.first()) else {
845 return Ok(());
846 };
847 self.prepare_cancellation_delivery(CancellationDelivery {
848 request_id: request.request_id.clone(),
849 sequence: group.parallel_group_base_sequence,
850 call_kind: CancellationCallKind::Parallel,
851 sequence_span: descriptors.len() as u64,
852 operation_sequence: None,
853 operation_sequence_span: 1,
854 })?;
855 Ok(())
856 }
857
858 pub(super) fn prepare_selection_handle_cancellation(
859 &mut self,
860 handle: &DurableOperationHandle,
861 ) -> Result<bool> {
862 if !self.cancellation_delivery_enabled || self.cancellation_shield_depth > 0 {
863 return Ok(false);
864 }
865 validate_selection_delivery_handle(self, handle)?;
866 if !self
867 .cancellation_history
868 .eligible(handle.base_sequence, handle.size as u64)
869 {
870 return Ok(false);
871 }
872 let request_id = self
873 .cancellation_history
874 .request
875 .as_ref()
876 .expect("eligible request")
877 .request_id
878 .clone();
879 self.prepare_cancellation_delivery(CancellationDelivery {
880 request_id,
881 sequence: self.next_cancellation_sequence()?,
882 call_kind: CancellationCallKind::SelectionHandle,
883 sequence_span: 1,
884 operation_sequence: Some(handle.base_sequence),
885 operation_sequence_span: handle.size as u64,
886 })
887 }
888
889 pub(super) fn expand_cancellation_group(
890 &mut self,
891 descriptors: &[ParallelDescriptor],
892 ) -> Result<()> {
893 let Some(RecordedCommand::CancellationGroup {
894 sequence,
895 span,
896 original,
897 }) = self.recorded_commands.get(self.command_cursor).cloned()
898 else {
899 return Ok(());
900 };
901 self.validate_cancellation_call(
902 sequence,
903 CancellationCallKind::Parallel,
904 CancellationCallKind::Parallel,
905 )?;
906 if descriptors.len() as u64 != span {
907 return Err(invalid_recorded_history(
908 "cooperative_cancellation_call_mismatch",
909 sequence,
910 &format!("parallel group with {span} durable leaves"),
911 &format!("{} durable leaves", descriptors.len()),
912 "authored parallel group span differs from its committed cancellation",
913 ));
914 }
915 let mut original = original.into_iter().peekable();
916 let mut leaves = Vec::with_capacity(descriptors.len());
917 for descriptor in descriptors {
918 let leaf_sequence = sequence + descriptor.offset as u64;
919 let command = if original.peek().map(RecordedCommand::sequence) == Some(leaf_sequence) {
920 original.next()
921 } else {
922 None
923 };
924 if self
925 .cancellation_history
926 .resolved_before_request
927 .contains(&leaf_sequence)
928 {
929 let command = command.ok_or_else(|| {
930 invalid_recorded_history(
931 "cooperative_cancellation_call_mismatch",
932 leaf_sequence,
933 "recorded earlier result",
934 "missing durable call",
935 "parallel cancellation cannot discard an earlier committed result",
936 )
937 })?;
938 leaves.push(command);
939 continue;
940 }
941 let kind = match &descriptor.operation {
942 ParallelOperation::Activity { .. } => CancellationCallKind::Activity,
943 ParallelOperation::ChildWorkflow { .. } => CancellationCallKind::Child,
944 ParallelOperation::Timer(_) => CancellationCallKind::Timer,
945 ParallelOperation::Signal(_) => CancellationCallKind::Signal,
946 ParallelOperation::Condition { .. } => CancellationCallKind::Condition,
947 ParallelOperation::Group(_) => unreachable!("descriptor is a durable leaf"),
948 };
949 leaves.push(RecordedCommand::CancellationBoundary {
950 sequence: leaf_sequence,
951 call_kind: kind,
952 original: command.map(Box::new),
953 });
954 }
955 self.recorded_commands
956 .splice(self.command_cursor..=self.command_cursor, leaves);
957 Ok(())
958 }
959
960 pub(super) fn cancellation_error(&mut self) -> Error {
961 if self.cancellation_consumed {
962 self.start_cancellation_clock();
963 }
964 match (
965 &self.cancellation_history.request,
966 &self.cancellation_history.delivery,
967 ) {
968 (Some(request), Some(delivery)) => {
969 let mut request = request.clone();
970 request.context = request.context.map(|context| {
971 context.with_replay(cancellation_replay_clock::active_binding())
972 });
973 Error::CooperativeCancellationRequested(CooperativeCancellationRequested {
974 request,
975 delivery: delivery.clone(),
976 })
977 }
978 _ => Error::WorkflowCancellationRequested(WorkflowCancellationRequested),
979 }
980 }
981
982 fn validate_cancellation_call(
983 &self,
984 sequence: u64,
985 kind: CancellationCallKind,
986 recorded_kind: CancellationCallKind,
987 ) -> Result<()> {
988 if kind != recorded_kind || self.cancellation_shield_depth > 0 {
989 return Err(invalid_recorded_history(
990 "cooperative_cancellation_call_mismatch",
991 sequence,
992 "matching unshielded authored call",
993 &format!("{kind:?}"),
994 "committed cancellation call kind or cleanup scope changed",
995 ));
996 }
997 Ok(())
998 }
999
1000 pub(super) fn cancellation_replay_command(
1001 &mut self,
1002 index: usize,
1003 kind: CancellationCallKind,
1004 ) -> Result<Option<RecordedCommand>> {
1005 match self.recorded_commands.get(index).cloned() {
1006 Some(RecordedCommand::CancellationBoundary {
1007 sequence,
1008 call_kind,
1009 original,
1010 }) => {
1011 if let Some(original) = original {
1012 return Ok(Some(*original));
1013 }
1014 self.replay_scope_cancellation_at(index, kind)?;
1015 self.assert_root_cancellation_membership()?;
1016 self.validate_cancellation_call(sequence, kind, call_kind)?;
1017 self.cancellation_consumed = true;
1018 self.cancel_requested = true;
1019 self.command_cursor = index + 1;
1020 Err(self.cancellation_error())
1021 }
1022 command => Ok(command),
1023 }
1024 }
1025
1026 pub(super) fn replay_cancellation_at(
1027 &mut self,
1028 index: usize,
1029 kind: CancellationCallKind,
1030 ) -> Result<()> {
1031 self.replay_scope_cancellation_at(index, kind)?;
1032 if let Some(RecordedCommand::CancellationBoundary {
1033 sequence,
1034 call_kind,
1035 ..
1036 }) = self.recorded_commands.get(index)
1037 {
1038 self.assert_root_cancellation_membership()?;
1039 self.validate_cancellation_call(*sequence, kind, *call_kind)?;
1040 self.cancellation_consumed = true;
1041 self.cancel_requested = true;
1042 self.command_cursor = index + 1;
1043 return Err(self.cancellation_error());
1044 }
1045 Ok(())
1046 }
1047
1048 pub(super) fn replay_selection_handle_cancellation(
1049 &mut self,
1050 handle: &DurableOperationHandle,
1051 ) -> Result<()> {
1052 let Some(RecordedCommand::CancellationBoundary {
1053 sequence,
1054 call_kind,
1055 original,
1056 }) = self.recorded_commands.get(self.command_cursor)
1057 else {
1058 return Ok(());
1059 };
1060 self.validate_cancellation_call(
1061 *sequence,
1062 CancellationCallKind::SelectionHandle,
1063 *call_kind,
1064 )?;
1065 let delivery = self
1066 .cancellation_history
1067 .delivery
1068 .as_ref()
1069 .expect("bound canonical delivery");
1070 if original.is_some()
1071 || delivery.operation_sequence != Some(handle.base_sequence)
1072 || delivery.operation_sequence_span != handle.size as u64
1073 {
1074 return Err(invalid_recorded_history(
1075 "cooperative_cancellation_call_mismatch",
1076 *sequence,
1077 "selection handle for the committed operation range",
1078 &format!("{}:{}", handle.base_sequence, handle.size),
1079 "cancellation delivery targets a different authored selection member",
1080 ));
1081 }
1082 validate_selection_delivery_handle(self, handle)?;
1083 self.replay_cancellation_at(self.command_cursor, CancellationCallKind::SelectionHandle)
1084 }
1085}
1086
1087impl WorkflowContext {
1088 pub fn cancellation_context(&self) -> Result<Option<CancellationContext>> {
1090 let state = self
1091 .state
1092 .lock()
1093 .map_err(|_| Error::WorkflowStatePoisoned)?;
1094 Ok(
1095 if state.cancellation_consumed && self.cancellation_scope_id == "root" {
1096 state
1097 .cancellation_history
1098 .request
1099 .as_ref()
1100 .and_then(|request| request.context.clone())
1101 .map(|context| context.with_replay(Some(Arc::downgrade(&self.state))))
1102 } else {
1103 None
1104 },
1105 )
1106 }
1107
1108 pub fn cancellation_shield(&self) -> Result<CancellationShield> {
1113 let mut state = self
1114 .state
1115 .lock()
1116 .map_err(|_| Error::WorkflowStatePoisoned)?;
1117 state.cancellation_shield_depth = state
1118 .cancellation_shield_depth
1119 .checked_add(1)
1120 .ok_or_else(|| invalid("cancellation shield nesting overflowed"))?;
1121 Ok(CancellationShield {
1122 state: Arc::clone(&self.state),
1123 })
1124 }
1125}
1126
1127pub(super) fn supports_protocol(version: &str) -> bool {
1128 let Some((major, minor)) = version.split_once('.') else {
1129 return false;
1130 };
1131 major == "1"
1132 && !minor.is_empty()
1133 && minor.bytes().all(|byte| byte.is_ascii_digit())
1134 && minor.parse::<u64>().is_ok_and(|minor| minor >= 20)
1135}
1136
1137fn require_discovery(info: &Value) -> Result<()> {
1138 let protocol = &info["worker_protocol"];
1139 if protocol["server_capabilities"]["cooperative_cancellation"].as_bool() != Some(true)
1140 || !protocol["version"].as_str().is_some_and(supports_protocol)
1141 {
1142 return Err(Error::CooperativeCancellationUnavailable(
1143 "runtime discovery must explicitly advertise support and compatible protocol 1.20"
1144 .to_string(),
1145 ));
1146 }
1147 Ok(())
1148}
1149
1150fn acknowledgment(
1151 value: &Value,
1152 workflow_id: &str,
1153 selected_run: Option<&str>,
1154) -> Result<WorkflowCancellationRequest> {
1155 if value["accepted"].as_bool() != Some(true)
1156 || text(value, "workflow_id")? != workflow_id
1157 || selected_run.is_some_and(|run| value["run_id"].as_str() != Some(run))
1158 {
1159 return Err(invalid(
1160 "acknowledgment does not match the accepted workflow/run request",
1161 ));
1162 }
1163 Ok(WorkflowCancellationRequest {
1164 workflow_id: workflow_id.to_owned(),
1165 run_id: text(value, "run_id")?.to_owned(),
1166 duplicate: value["duplicate"]
1167 .as_bool()
1168 .ok_or_else(|| invalid("duplicate must be a boolean"))?,
1169 cancellation_request: CancellationRequest::from_observation(
1170 &value["cancellation_request"],
1171 )?,
1172 })
1173}
1174
1175impl Client {
1176 pub async fn acknowledge_activity_cancellation(
1182 &self,
1183 task_id: &str,
1184 activity_attempt_id: &str,
1185 lease_owner: &str,
1186 request_id: &str,
1187 ) -> Result<Value> {
1188 if [task_id, activity_attempt_id, lease_owner, request_id]
1189 .iter()
1190 .any(|value| value.trim().is_empty() || value.len() > 255)
1191 {
1192 return Err(invalid(
1193 "activity stop receipt requires bounded original claim and request identities",
1194 ));
1195 }
1196 tokio::time::timeout(CONTROL_BUDGET, async {
1197 let value: Value = activity_task_response(
1198 self.request_json(
1199 reqwest::Method::POST,
1200 &format!("/worker/activity-tasks/{}/acknowledge-cancellation", percent_encode_path_segment(task_id)),
1201 RequestProtocol::Worker("1.20"),
1202 Some(&json!({"activity_attempt_id":activity_attempt_id,"lease_owner":lease_owner,"request_id":request_id})),
1203 ).await,
1204 "acknowledge-cancellation", task_id, activity_attempt_id,
1205 )?;
1206 if value["task_id"].as_str() != Some(task_id)
1207 || value["activity_attempt_id"].as_str() != Some(activity_attempt_id)
1208 || value["lease_owner"].as_str() != Some(lease_owner)
1209 || value["request_id"].as_str() != Some(request_id)
1210 || value["acknowledged"].as_bool() != Some(true)
1211 || value["duplicate"].as_bool().is_none()
1212 || value.get("reason") != Some(&Value::Null)
1213 || value["heartbeat_recorded"].as_bool() != Some(false)
1214 || text(&value, "history_event_id").is_err()
1215 {
1216 return Err(invalid("activity callback-stop acknowledgment did not prove the original claim and receipt"));
1217 }
1218 Ok(value)
1219 }).await.map_err(|_| Error::Timeout)?
1220 }
1221
1222 pub async fn activity_task_status(
1228 &self,
1229 task_id: &str,
1230 activity_attempt_id: &str,
1231 lease_owner: &str,
1232 ) -> Result<Value> {
1233 if [task_id, activity_attempt_id, lease_owner]
1234 .iter()
1235 .any(|value| value.trim().is_empty())
1236 {
1237 return Err(invalid("activity observation requires the actual claim"));
1238 }
1239 tokio::time::timeout(CONTROL_BUDGET, async {
1240 let value: Value = activity_task_response(
1241 self.request_json(
1242 reqwest::Method::POST,
1243 &format!(
1244 "/worker/activity-tasks/{}/status",
1245 percent_encode_path_segment(task_id)
1246 ),
1247 RequestProtocol::Worker("1.20"),
1248 Some(&json!({
1249 "activity_attempt_id":activity_attempt_id,"lease_owner":lease_owner
1250 })),
1251 )
1252 .await,
1253 "status",
1254 task_id,
1255 activity_attempt_id,
1256 )?;
1257 if value["task_id"].as_str() != Some(task_id)
1258 || value["activity_attempt_id"].as_str() != Some(activity_attempt_id)
1259 || value["lease_owner"].as_str() != Some(lease_owner)
1260 || value["can_continue"].as_bool().is_none()
1261 || value["cancel_requested"].as_bool().is_none()
1262 || value["heartbeat_recorded"].as_bool() != Some(false)
1263 {
1264 return Err(invalid(
1265 "activity observation did not acknowledge the exact claim",
1266 ));
1267 }
1268 Ok(value)
1269 })
1270 .await
1271 .map_err(|_| Error::Timeout)?
1272 }
1273
1274 pub async fn poll_cooperative_workflow_task(
1282 &self,
1283 worker_id: &str,
1284 task_queue: &str,
1285 timeout: Duration,
1286 ) -> Result<CooperativeWorkflowTaskPoll> {
1287 self.poll_cooperative_workflow_task_with_request_id(
1288 worker_id,
1289 task_queue,
1290 timeout,
1291 &unique_request_id("rust-workflow-poll"),
1292 1,
1293 )
1294 .await
1295 }
1296
1297 async fn poll_cooperative_workflow_task_with_request_id(
1298 &self,
1299 worker_id: &str,
1300 task_queue: &str,
1301 timeout: Duration,
1302 poll_request_id: &str,
1303 transport_retries: usize,
1304 ) -> Result<CooperativeWorkflowTaskPoll> {
1305 if worker_id.trim().is_empty()
1306 || task_queue.trim().is_empty()
1307 || poll_request_id.trim().is_empty()
1308 {
1309 return Err(invalid(
1310 "cooperative polling requires a worker and task queue",
1311 ));
1312 }
1313 let budget = timeout
1314 .checked_add(CONTROL_BUDGET)
1315 .ok_or_else(|| invalid("cooperative poll timeout exceeds its supported budget"))?;
1316 let body = json!({
1317 "worker_id":worker_id, "task_queue":task_queue,
1318 "poll_request_id":poll_request_id,
1319 "timeout_seconds":long_poll_timeout_seconds(timeout),
1320 "history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1321 });
1322 tokio::time::timeout(budget, async {
1323 let value: Value = self
1324 .poll_request_json(
1325 "/worker/workflow-tasks/poll",
1326 RequestProtocol::Worker("1.20"),
1327 &body,
1328 budget,
1329 transport_retries,
1330 )
1331 .await?;
1332 let mut response: PollWorkflowTaskResponse = serde_json::from_value(value.clone())
1333 .map_err(|_| invalid("cooperative poll returned a malformed envelope or task"))?;
1334 let outcome = response.outcome();
1335 let task = if let Some(task) = response.task.take() {
1336 let (owner, _) = cancellation_claim(&task)?;
1337 if owner != worker_id
1338 || value["task"]["workflow_task_attempt"].as_u64()
1339 != Some(task.workflow_task_attempt)
1340 {
1341 return Err(invalid(
1342 "cooperative poll did not return the caller's actual owner and attempt",
1343 ));
1344 }
1345 let cancellation_request = match value["task"].get("cancellation_request") {
1346 None | Some(Value::Null) => None,
1347 Some(observation) => Some(CancellationRequest::from_observation(observation)?),
1348 };
1349 let mut claim = CooperativeWorkflowTask {
1350 task,
1351 cancellation_request,
1352 };
1353 self.load_cooperative_claim_history(&mut claim).await?;
1354 Some(claim)
1355 } else {
1356 None
1357 };
1358 Ok(CooperativeWorkflowTaskPoll {
1359 task,
1360 outcome,
1361 protocol_version: response.protocol_version,
1362 server_capabilities: response.server_capabilities,
1363 })
1364 })
1365 .await
1366 .map_err(|_| Error::Timeout)?
1367 }
1368
1369 async fn load_cooperative_claim_history(
1370 &self,
1371 claim: &mut CooperativeWorkflowTask,
1372 ) -> Result<()> {
1373 let (owner, _) = cancellation_claim(&claim.task)?;
1374 let owner = owner.to_owned();
1375 let mut token = claim.task.next_history_page_token.clone();
1376 let mut seen = BTreeSet::new();
1377 while let Some(current) = token.take() {
1378 if current.trim().is_empty()
1379 || seen.len() >= MAX_REFRESH_PAGES
1380 || !seen.insert(current.clone())
1381 {
1382 return Err(invalid(
1383 "claim history exceeded its page bound or returned an invalid/repeated token",
1384 ));
1385 }
1386 let body = json!({
1387 "lease_owner":owner,"workflow_task_attempt":claim.task.workflow_task_attempt,
1388 "next_history_page_token":current,"history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1389 });
1390 let value: Value = self
1391 .request_json(
1392 reqwest::Method::POST,
1393 &format!(
1394 "/worker/workflow-tasks/{}/history",
1395 percent_encode_path_segment(&claim.task.task_id)
1396 ),
1397 RequestProtocol::Worker("1.20"),
1398 Some(&body),
1399 )
1400 .await?;
1401 if value["task_id"].as_str() != Some(claim.task.task_id.as_str())
1402 || value["workflow_task_attempt"].as_u64() != Some(claim.task.workflow_task_attempt)
1403 {
1404 return Err(invalid(
1405 "claim history changed the selected task or attempt",
1406 ));
1407 }
1408 let events = value["history_events"]
1409 .as_array()
1410 .ok_or_else(|| invalid("claim history page must contain an event array"))?;
1411 if events.len() > WORKFLOW_HISTORY_PAGE_SIZE as usize {
1412 return Err(invalid(
1413 "claim history page exceeds its requested event limit",
1414 ));
1415 }
1416 token = match value.get("next_history_page_token") {
1417 Some(Value::Null) => None,
1418 Some(Value::String(next)) if !next.trim().is_empty() && !events.is_empty() => {
1419 Some(next.clone())
1420 }
1421 _ => return Err(invalid("claim history page token or progress is invalid")),
1422 };
1423 let page: WorkflowTaskHistoryPage = serde_json::from_value(value)
1424 .map_err(|_| invalid("claim history page contains malformed fields or events"))?;
1425 if page
1426 .history_events
1427 .iter()
1428 .any(|event| event.event_type.trim().is_empty())
1429 {
1430 return Err(invalid("claim history event type must be non-empty"));
1431 }
1432 claim.task.append_history_page(page);
1433 }
1434 Ok(())
1435 }
1436
1437 pub async fn heartbeat_workflow_task(
1442 &self,
1443 task: &WorkflowTask,
1444 original: Option<&CancellationRequest>,
1445 ) -> Result<WorkflowTaskHeartbeat> {
1446 let (owner, _) = cancellation_claim(task)?;
1447 if let Some(original) = original {
1448 original.validate_observation()?;
1449 }
1450 tokio::time::timeout(CONTROL_BUDGET, async {
1451 let response: Value = self.request_json(
1452 reqwest::Method::POST,
1453 &format!("/worker/workflow-tasks/{}/heartbeat", percent_encode_path_segment(&task.task_id)),
1454 RequestProtocol::Worker("1.20"),
1455 Some(&json!({"lease_owner":owner,"workflow_task_attempt":task.workflow_task_attempt})),
1456 ).await?;
1457 if response["task_id"].as_str() != Some(task.task_id.as_str())
1458 || response["workflow_task_attempt"].as_u64() != Some(task.workflow_task_attempt)
1459 || response["lease_owner"].as_str() != Some(owner)
1460 || response["renewed"].as_bool() != Some(true)
1461 || response.get("reason") != Some(&Value::Null)
1462 || response["task_status"].as_str() != Some("leased")
1463 {
1464 return Err(invalid("workflow heartbeat did not acknowledge the exact leased claim"));
1465 }
1466 let expires = text(&response, "lease_expires_at")?;
1467 DateTime::parse_from_rfc3339(expires).map_err(|_| invalid("workflow heartbeat lease expiry must include a timezone"))?;
1468 let run_status = text(&response, "run_status")?;
1469 if !matches!(run_status, "pending" | "running" | "waiting") {
1470 return Err(invalid("workflow heartbeat did not acknowledge an active run"));
1471 }
1472 let cancellation_request = match response.get("cancellation_request") {
1473 None | Some(Value::Null) if original.is_none() => None,
1474 None | Some(Value::Null) => return Err(invalid("workflow heartbeat omitted its original pending request")),
1475 Some(observation) => {
1476 let current = CancellationRequest::from_observation(observation)?;
1477 Some(match original {
1478 Some(original) => original.preserve_observation(¤t)?,
1479 None => current,
1480 })
1481 },
1482 };
1483 Ok(WorkflowTaskHeartbeat {
1484 task_id:task.task_id.clone(), workflow_task_attempt:task.workflow_task_attempt,
1485 lease_owner:owner.to_owned(), lease_expires_at:expires.to_owned(),
1486 run_status:run_status.to_owned(), cancellation_request,
1487 })
1488 }).await.map_err(|_| Error::Timeout)?
1489 }
1490
1491 pub async fn deliver_workflow_cancellation(
1499 &self,
1500 task: &WorkflowTask,
1501 delivery: &CancellationDelivery,
1502 ) -> Result<CancellationDeliveryReply> {
1503 let (owner, run_id) = cancellation_claim(task)?;
1504 let body = json!({
1505 "lease_owner":owner, "workflow_task_attempt":task.workflow_task_attempt,
1506 "request_id":delivery.request_id, "sequence":delivery.sequence,
1507 "call_kind":delivery.call_kind, "sequence_span":delivery.sequence_span,
1508 "operation_sequence":delivery.operation_sequence,
1509 "operation_sequence_span":delivery.operation_sequence_span
1510 });
1511 let mut payload = body.clone();
1512 payload["workflow_command_id"] = json!(delivery.request_id);
1513 if CancellationDelivery::from_payload(&payload)? != *delivery {
1514 return Err(invalid(
1515 "delivery must name a valid authored operation range",
1516 ));
1517 }
1518 tokio::time::timeout(CONTROL_BUDGET, async {
1519 let path = format!(
1520 "/worker/workflow-tasks/{}/deliver-cancellation",
1521 percent_encode_path_segment(&task.task_id)
1522 );
1523 let response: Value = self
1524 .request_json(
1525 reqwest::Method::POST,
1526 &path,
1527 RequestProtocol::Worker("1.20"),
1528 Some(&body),
1529 )
1530 .await?;
1531 if response["delivered"].as_bool() == Some(false)
1532 && match response["reason"].as_str() {
1533 Some("cancellation_waiting_for_child") => matches!(
1534 delivery.call_kind,
1535 CancellationCallKind::Child
1536 | CancellationCallKind::Parallel
1537 | CancellationCallKind::SelectionHandle
1538 ),
1539 Some("cancellation_waiting_for_activity") => matches!(
1540 delivery.call_kind,
1541 CancellationCallKind::Activity
1542 | CancellationCallKind::LocalActivity
1543 | CancellationCallKind::Parallel
1544 | CancellationCallKind::SelectionHandle
1545 ),
1546 _ => false,
1547 }
1548 && response["claim_released"].as_bool() == Some(true)
1549 && response["task_id"].as_str() == Some(task.task_id.as_str())
1550 && response["workflow_run_id"].as_str() == Some(run_id)
1551 && [
1552 "request_id",
1553 "sequence",
1554 "call_kind",
1555 "sequence_span",
1556 "operation_sequence",
1557 "operation_sequence_span",
1558 ]
1559 .iter()
1560 .all(|field| response.get(*field).is_none_or(Value::is_null))
1561 {
1562 return Ok(CancellationDeliveryReply::ClaimReleased {
1563 task_id: task.task_id.clone(),
1564 run_id: run_id.to_owned(),
1565 });
1566 }
1567 if response["delivered"].as_bool() != Some(true)
1568 || response["task_id"].as_str() != Some(task.task_id.as_str())
1569 || response["workflow_run_id"].as_str() != Some(run_id)
1570 || response.get("reason") != Some(&Value::Null)
1571 || [
1572 "sequence_span",
1573 "operation_sequence",
1574 "operation_sequence_span",
1575 ]
1576 .iter()
1577 .any(|field| response.get(*field).is_none())
1578 {
1579 return Err(invalid(
1580 "delivery acknowledgment does not match the selected task/run",
1581 ));
1582 }
1583 let mut recorded = response.clone();
1584 recorded["workflow_command_id"] = response["request_id"].clone();
1585 if CancellationDelivery::from_payload(&recorded)? != *delivery {
1586 return Err(invalid(
1587 "delivery acknowledgment changed its authored operation range",
1588 ));
1589 }
1590 Ok(CancellationDeliveryReply::Delivered(
1591 CancellationDeliveryReceipt {
1592 task_id: task.task_id.clone(),
1593 run_id: run_id.to_owned(),
1594 delivery: delivery.clone(),
1595 },
1596 ))
1597 })
1598 .await
1599 .map_err(|_| Error::Timeout)?
1600 }
1601
1602 pub async fn refresh_workflow_cancellation_history(
1609 &self,
1610 task: &WorkflowTask,
1611 observation: &CancellationRequest,
1612 ) -> Result<Vec<HistoryEvent>> {
1613 let (owner, run_id) = cancellation_claim(task)?;
1614 observation.validate_observation()?;
1615 let first_token = observation
1616 .history_refresh_page_token
1617 .clone()
1618 .expect("validated history token");
1619 tokio::time::timeout(CONTROL_BUDGET, async {
1620 let path = format!("/worker/workflow-tasks/{}/history", percent_encode_path_segment(&task.task_id));
1621 let mut token = Some(first_token);
1622 let mut seen = BTreeSet::new();
1623 let mut history = Vec::new();
1624 while let Some(current) = token.take() {
1625 if seen.len() >= MAX_REFRESH_PAGES || !seen.insert(current.clone()) {
1626 return Err(invalid("canonical history refresh exceeded its page bound or repeated a token"));
1627 }
1628 let body = json!({
1629 "lease_owner":owner, "workflow_task_attempt":task.workflow_task_attempt,
1630 "next_history_page_token":current, "history_page_size":WORKFLOW_HISTORY_PAGE_SIZE,
1631 });
1632 let page: Value = self.request_json(
1633 reqwest::Method::POST, &path, RequestProtocol::Worker("1.20"), Some(&body),
1634 ).await?;
1635 if page["task_id"].as_str() != Some(task.task_id.as_str())
1636 || page["workflow_task_attempt"].as_u64() != Some(task.workflow_task_attempt)
1637 {
1638 return Err(invalid("canonical history page changed the selected task/attempt"));
1639 }
1640 let events = page["history_events"].as_array().ok_or_else(|| invalid("canonical history page must contain an event array"))?;
1641 if events.len() > WORKFLOW_HISTORY_PAGE_SIZE as usize {
1642 return Err(invalid("canonical history page exceeds its requested event limit"));
1643 }
1644 token = match page.get("next_history_page_token") {
1645 Some(Value::Null) => None,
1646 Some(Value::String(next)) if !next.is_empty() && !events.is_empty() => Some(next.clone()),
1647 _ => return Err(invalid("canonical history page token or progress is invalid")),
1648 };
1649 for event in events {
1650 let event: HistoryEvent = serde_json::from_value(event.clone()).map_err(|_| invalid("canonical history page contains a malformed event"))?;
1651 if event.event_type.trim().is_empty() {
1652 return Err(invalid("canonical history event type must be non-empty"));
1653 }
1654 history.push(event);
1655 }
1656 }
1657 let canonical = CancellationHistory::from_events(&history, run_id, Some(observation))?;
1658 if canonical.request_index >= history.len() {
1659 return Err(invalid("canonical refresh omitted the original request event"));
1660 }
1661 Ok(history)
1662 }).await.map_err(|_| Error::Timeout)?
1663 }
1664
1665 pub async fn request_workflow_cancellation(
1672 &self,
1673 workflow_id: &str,
1674 options: CooperativeCancellationOptions,
1675 ) -> Result<WorkflowCancellationRequest> {
1676 self.request_workflow_cancellation_target(workflow_id, None, options)
1677 .await
1678 }
1679
1680 pub async fn request_workflow_run_cancellation(
1682 &self,
1683 workflow_id: &str,
1684 run_id: &str,
1685 options: CooperativeCancellationOptions,
1686 ) -> Result<WorkflowCancellationRequest> {
1687 self.request_workflow_cancellation_target(workflow_id, Some(run_id), options)
1688 .await
1689 }
1690
1691 async fn request_workflow_cancellation_target(
1692 &self,
1693 workflow_id: &str,
1694 run_id: Option<&str>,
1695 options: CooperativeCancellationOptions,
1696 ) -> Result<WorkflowCancellationRequest> {
1697 if workflow_id.trim().is_empty() || run_id.is_some_and(|id| id.trim().is_empty()) {
1698 return Err(invalid(
1699 "workflow and selected run identities must be non-empty",
1700 ));
1701 }
1702 if options
1703 .cleanup_timeout_seconds
1704 .is_some_and(|seconds| !(1..=3600).contains(&seconds))
1705 || options
1706 .reason
1707 .as_ref()
1708 .is_some_and(|reason| reason.chars().count() > 1000)
1709 {
1710 return Err(invalid(
1711 "cleanup timeout must be 1..3600 seconds and reason at most 1000 characters",
1712 ));
1713 }
1714
1715 tokio::time::timeout(CONTROL_BUDGET, async {
1717 let info: Value = self
1718 .request_json(
1719 reqwest::Method::GET,
1720 "/cluster/info",
1721 RequestProtocol::ControlPlane,
1722 Option::<&Value>::None,
1723 )
1724 .await?;
1725 require_discovery(&info)?;
1726 let mut path = format!("/workflows/{}", percent_encode_path_segment(workflow_id));
1727 if let Some(run_id) = run_id {
1728 path.push_str(&format!("/runs/{}", percent_encode_path_segment(run_id)));
1729 }
1730 path.push_str("/request-cancellation");
1731 let response: Value = self
1732 .request_json(
1733 reqwest::Method::POST,
1734 &path,
1735 RequestProtocol::ControlPlane,
1736 Some(&options),
1737 )
1738 .await?;
1739 acknowledgment(&response, workflow_id, run_id)
1740 })
1741 .await
1742 .map_err(|_| Error::Timeout)?
1743 }
1744}
1745
1746impl Worker {
1747 pub(super) async fn poll_cooperative_activity_once(&self) -> Result<ManagedPollOutcome> {
1748 let poll_request_id = unique_request_id("rust-activity-poll");
1749 let response = self
1750 .retry_worker_operation(|| {
1751 self.client.poll_activity_task_response_with_request_id(
1752 &self.worker_id,
1753 &self.task_queue,
1754 self.poll_timeout,
1755 &poll_request_id,
1756 0,
1757 )
1758 })
1759 .await;
1760 let Some(response) = self.settle_worker_poll_response(response).await? else {
1761 return Ok(ManagedPollOutcome::Idle);
1762 };
1763 if response.outcome().should_stop() {
1764 return Ok(ManagedPollOutcome::Stop);
1765 }
1766 let Some(task) = response.task else {
1767 return Ok(ManagedPollOutcome::Idle);
1768 };
1769 let guard = ActivityClaimGuard::new(&self.client, &task, &self.worker_id)?;
1770 let _abandon_on_drop = AbandonActivityOnDrop(guard.clone());
1771 if guard.observe().await.is_err() {
1772 return Ok(ManagedPollOutcome::Handled);
1773 }
1774 let mut callback_started = false;
1775 let result = {
1776 let invocation =
1777 self.execute_cooperative_activity_task(&task, &guard, &mut callback_started);
1778 tokio::pin!(invocation);
1779 loop {
1780 tokio::select! {
1781 biased;
1782 _ = guard.wait_for_shutdown() => {
1783 guard.abandon();
1784 break None;
1785 }
1786 result = &mut invocation => break Some(result),
1787 _ = tokio::time::sleep(Duration::from_secs(1)) => {
1788 if guard.observe().await.is_err() {
1789 break None;
1790 }
1791 }
1792 }
1793 }
1794 };
1795 let Some(result) = result else {
1797 if callback_started {
1798 guard.acknowledge_stopped().await?;
1799 }
1800 return Ok(ManagedPollOutcome::Handled);
1801 };
1802 if matches!(result, Err(Error::ActivityExecutionAbandoned(_)))
1805 || guard.observe().await.is_err()
1806 {
1807 if callback_started {
1808 guard.acknowledge_stopped().await?;
1809 }
1810 return Ok(ManagedPollOutcome::Handled);
1811 }
1812 let settlement = match result {
1813 Ok(value) => {
1814 self.client
1815 .complete_activity_task(
1816 &guard.task_id,
1817 &guard.attempt_id,
1818 &guard.owner,
1819 value,
1820 &task.payload_codec,
1821 )
1822 .await
1823 }
1824 Err(error) if worker_storage_admission_body(&error).is_some() => return Err(error),
1825 Err(error) => {
1826 self.client
1827 .fail_activity_task(
1828 &guard.task_id,
1829 &guard.attempt_id,
1830 &guard.owner,
1831 error.to_string(),
1832 false,
1833 )
1834 .await
1835 }
1836 };
1837 if let Err(error) = settlement {
1838 if !activity_task_rejection_is_final(&error) {
1839 return Err(error);
1840 }
1841 }
1842 Ok(ManagedPollOutcome::Handled)
1843 }
1844
1845 async fn execute_cooperative_activity_task(
1846 &self,
1847 task: &ActivityTask,
1848 guard: &ActivityClaimGuard,
1849 callback_started: &mut bool,
1850 ) -> Result<AvroValue> {
1851 validate_activity_task_payloads(task)?;
1852 let handler = self
1853 .activities
1854 .get(&task.activity_type)
1855 .ok_or_else(|| Error::ActivityNotRegistered(task.activity_type.clone()))?;
1856 let args = decode_task_avro_arguments(task.arguments.as_ref(), &task.payload_codec)?;
1857 let context = ActivityContext {
1858 client: self.client.clone(),
1859 task_id: guard.task_id.clone(),
1860 activity_attempt_id: guard.attempt_id.clone(),
1861 lease_owner: guard.owner.clone(),
1862 activity_type: task.activity_type.clone(),
1863 attempt_number: task.attempt_number,
1864 task_queue: self.task_queue.clone(),
1865 worker_id: self.worker_id.clone(),
1866 claim_guard: Some(guard.clone()),
1867 };
1868 guard.boundary()?;
1869 *callback_started = true;
1870 handler(context, args).await
1871 }
1872
1873 pub(super) async fn poll_cooperative_workflow_once(&self) -> Result<ManagedPollOutcome> {
1874 let poll_request_id = unique_request_id("rust-workflow-poll");
1875 let response = self
1876 .retry_worker_operation(|| {
1877 self.client.poll_cooperative_workflow_task_with_request_id(
1878 &self.worker_id,
1879 &self.task_queue,
1880 self.poll_timeout,
1881 &poll_request_id,
1882 0,
1883 )
1884 })
1885 .await;
1886 let Some(response) = self.settle_worker_poll_response(response).await? else {
1887 return Ok(ManagedPollOutcome::Idle);
1888 };
1889 if response.outcome.should_stop() {
1890 return Ok(ManagedPollOutcome::Stop);
1891 }
1892 let memo_updates_supported =
1893 runtime_supports_workflow_memo_updates(response.server_capabilities.as_ref());
1894 let Some(claim) = response.task else {
1895 return Ok(ManagedPollOutcome::Idle);
1896 };
1897 let Some(decision) = self.replay_cooperative_workflow_claim(&claim).await? else {
1900 return Ok(ManagedPollOutcome::Handled);
1901 };
1902 let (owner, _) = cancellation_claim(&claim.task)?;
1903 self.settle_workflow_task_decision(
1904 &claim.task.task_id,
1905 owner,
1906 claim.task.workflow_task_attempt,
1907 claim.task.run_id.as_deref(),
1908 Ok(decision),
1909 memo_updates_supported,
1910 )
1911 .await
1912 }
1913
1914 async fn replay_cooperative_workflow_claim(
1915 &self,
1916 claim: &CooperativeWorkflowTask,
1917 ) -> Result<Option<WorkflowTaskDecision>> {
1918 let (owner, run_id) = cancellation_claim(&claim.task)?;
1919 if owner != self.worker_id {
1920 return Err(invalid(
1921 "cooperative replay requires this worker's actual claim",
1922 ));
1923 }
1924 let mut task = claim.task.clone();
1925 let Some(observation) = claim.cancellation_request.as_ref() else {
1926 let canonical = CancellationHistory::from_events(&task.history_events, run_id, None)?;
1927 if canonical.request.is_some() {
1928 return Err(invalid(
1929 "cooperative replay omitted its original pending observation",
1930 ));
1931 }
1932 for _ in 0..1000 {
1933 let mut decision = self.execute_workflow_task_decision(task.clone())?;
1934 if let Some(intent) = decision.cancellation_scope_delivery.as_ref() {
1935 if !decision.commands.is_empty() {
1936 decision.cancellation_scope_delivery = None;
1937 return Ok(Some(decision));
1938 }
1939 let mut budget = CancellationScopeDeliveryBudget::new();
1940 budget.restrict(intent.context.deadline())?;
1941 let prepared = self
1942 .client
1943 .prepare_cancellation_scope_on_claim(
1944 &task,
1945 &intent.context,
1946 &intent.boundary,
1947 &budget,
1948 )
1949 .await?;
1950 budget.restrict(prepared.authority_deadline())?;
1951 let delivered = self
1952 .client
1953 .deliver_cancellation_scope_on_claim(&task, &prepared, &budget)
1954 .await?;
1955 task.history_events = delivered.history().to_vec();
1956 task.total_history_events = None;
1957 task.history_size_bytes = None;
1958 continue;
1959 }
1960 let Some(opening) = decision.cancellation_scope_opening.as_ref() else {
1961 return Ok(Some(decision));
1962 };
1963 if !decision.commands.is_empty() {
1964 decision.cancellation_scope_opening = None;
1965 return Ok(Some(decision));
1966 }
1967 let receipt = self
1968 .client
1969 .open_cancellation_scope_on_claim(
1970 &task,
1971 opening.sequence,
1972 &opening.parent_scope_id,
1973 opening.shield_parent,
1974 )
1975 .await?;
1976 task.history_events = receipt.history().to_vec();
1977 task.total_history_events = None;
1978 task.history_size_bytes = None;
1979 }
1980 return Err(invalid(
1981 "workflow exceeded the canonical scope opening replay limit",
1982 ));
1983 };
1984 task.history_events = self
1985 .client
1986 .refresh_workflow_cancellation_history(&claim.task, observation)
1987 .await?;
1988 for _ in 0..1000 {
1989 task.total_history_events = None;
1992 task.history_size_bytes = None;
1993 let mut decision = self.execute_workflow_task_decision_with_cancellation(
1994 task.clone(),
1995 Some(observation),
1996 )?;
1997 if let Some(intent) = decision.cancellation_scope_delivery.as_ref() {
1998 if !decision.commands.is_empty() {
1999 decision.cancellation_scope_delivery = None;
2000 return Ok(Some(decision));
2001 }
2002 let mut budget = CancellationScopeDeliveryBudget::new();
2003 budget.restrict(intent.context.deadline())?;
2004 let prepared = self
2005 .client
2006 .prepare_cancellation_scope_on_claim(
2007 &task,
2008 &intent.context,
2009 &intent.boundary,
2010 &budget,
2011 )
2012 .await?;
2013 budget.restrict(prepared.authority_deadline())?;
2014 let delivered = self
2015 .client
2016 .deliver_cancellation_scope_on_claim(&task, &prepared, &budget)
2017 .await?;
2018 task.history_events = delivered.history().to_vec();
2019 continue;
2020 }
2021 let Some(intent) = decision.cancellation_delivery.as_ref() else {
2022 return Ok(Some(decision));
2023 };
2024 if !decision.commands.is_empty() {
2025 decision.cancellation_delivery = None;
2029 return Ok(Some(decision));
2030 }
2031 let delivery_error = match self
2032 .client
2033 .deliver_workflow_cancellation(&claim.task, intent)
2034 .await
2035 {
2036 Ok(CancellationDeliveryReply::ClaimReleased { .. }) => return Ok(None),
2037 Ok(CancellationDeliveryReply::Delivered(_)) => None,
2038 Err(error) => Some(error),
2039 };
2040 task.history_events = self
2041 .client
2042 .refresh_workflow_cancellation_history(&claim.task, observation)
2043 .await?;
2044 let canonical =
2045 CancellationHistory::from_events(&task.history_events, run_id, Some(observation))?;
2046 if canonical.delivery.as_ref() != Some(intent) {
2047 return Err(delivery_error.unwrap_or_else(|| {
2048 invalid(
2049 "canonical history did not prove the exact intended cancellation delivery",
2050 )
2051 }));
2052 }
2053 }
2054 Err(invalid(
2055 "workflow replay did not converge on its canonical cancellation delivery",
2056 ))
2057 }
2058}
2059
2060#[derive(Clone, Debug)]
2061pub(super) struct ActivityClaimGuard {
2062 client: Client,
2063 task_id: String,
2064 attempt_id: String,
2065 owner: String,
2066 active: Arc<AtomicBool>,
2067 cancellation_receipt: Arc<Mutex<Option<Value>>>,
2068 stop: Option<Arc<AtomicBool>>,
2069}
2070
2071struct AbandonActivityOnDrop(ActivityClaimGuard);
2072
2073impl Drop for AbandonActivityOnDrop {
2074 fn drop(&mut self) {
2075 self.0.abandon();
2076 }
2077}
2078
2079impl ActivityClaimGuard {
2080 fn new(client: &Client, task: &ActivityTask, worker_id: &str) -> Result<Self> {
2081 let owner = task.lease_owner.as_deref().unwrap_or_default();
2082 let attempt = task
2083 .activity_attempt_id
2084 .as_deref()
2085 .or(task.attempt_id.as_deref())
2086 .unwrap_or_default();
2087 if task.task_id.trim().is_empty()
2088 || attempt.trim().is_empty()
2089 || owner.trim().is_empty()
2090 || owner != worker_id
2091 || matches!((&task.activity_attempt_id, &task.attempt_id), (Some(left), Some(right)) if left != right)
2092 {
2093 return Err(invalid(
2094 "activity execution requires the worker's actual immutable claim",
2095 ));
2096 }
2097 Ok(Self {
2098 client: client.clone(),
2099 task_id: task.task_id.clone(),
2100 attempt_id: attempt.to_owned(),
2101 owner: owner.to_owned(),
2102 active: Arc::new(AtomicBool::new(true)),
2103 cancellation_receipt: Arc::new(Mutex::new(None)),
2104 stop: client
2105 .worker_storage_admission
2106 .as_ref()
2107 .map(|admission| Arc::clone(&admission.stop)),
2108 })
2109 }
2110
2111 fn abandon(&self) {
2112 self.active.store(false, Ordering::SeqCst);
2113 }
2114
2115 async fn acknowledge_stopped(&self) -> Result<()> {
2117 self.abandon();
2118 let receipt = self
2119 .cancellation_receipt
2120 .lock()
2121 .map_err(|_| invalid("activity cancellation receipt lock was poisoned"))?
2122 .clone();
2123 if let Some(receipt) = receipt {
2124 self.client
2125 .acknowledge_activity_cancellation(
2126 &self.task_id,
2127 &self.attempt_id,
2128 &self.owner,
2129 text(&receipt, "request_id")?,
2130 )
2131 .await?;
2132 }
2133 Ok(())
2134 }
2135
2136 fn retain_cancellation_receipt(&self, value: &Value) -> Result<()> {
2137 if value["can_continue"].as_bool() != Some(false)
2138 || value["cancel_requested"].as_bool() != Some(true)
2139 {
2140 return Ok(());
2141 }
2142 let Some(receipt) = value
2143 .get("cancellation_acknowledgement")
2144 .filter(|receipt| receipt.is_object())
2145 else {
2146 return Ok(());
2147 };
2148 if !matches!(
2149 receipt["callback_state"].as_str(),
2150 Some("unknown" | "stopped")
2151 ) || [
2152 "request_id",
2153 "root_request_id",
2154 "cleanup_deadline_at",
2155 "cancellation_history_event_id",
2156 ]
2157 .iter()
2158 .any(|field| text(receipt, field).is_err())
2159 || DateTime::parse_from_rfc3339(text(receipt, "cleanup_deadline_at")?).is_err()
2160 {
2161 return Ok(());
2162 }
2163 let mut retained = self
2164 .cancellation_receipt
2165 .lock()
2166 .map_err(|_| invalid("activity cancellation receipt lock was poisoned"))?;
2167 if let Some(original) = retained.as_ref() {
2168 if [
2169 "request_id",
2170 "root_request_id",
2171 "cleanup_deadline_at",
2172 "cancellation_history_event_id",
2173 ]
2174 .iter()
2175 .any(|field| original[*field] != receipt[*field])
2176 {
2177 return Err(invalid(
2178 "activity cancellation observation changed its original identity or deadline",
2179 ));
2180 }
2181 } else {
2182 *retained = Some(receipt.clone());
2183 }
2184 Ok(())
2185 }
2186
2187 fn boundary(&self) -> Result<()> {
2188 if !self.active.load(Ordering::SeqCst)
2189 || self
2190 .stop
2191 .as_ref()
2192 .is_some_and(|stop| stop.load(Ordering::SeqCst))
2193 {
2194 self.abandon();
2195 return Err(Error::ActivityExecutionAbandoned(
2196 "callback completed, was abandoned, or its worker is stopping".into(),
2197 ));
2198 }
2199 Ok(())
2200 }
2201
2202 async fn wait_for_shutdown(&self) {
2203 if let Some(stop) = &self.stop {
2204 wait_for_worker_stop(stop).await;
2205 } else {
2206 std::future::pending::<()>().await;
2207 }
2208 }
2209
2210 async fn observe(&self) -> Result<()> {
2211 self.boundary()?;
2212 let result = self
2213 .client
2214 .activity_task_status(&self.task_id, &self.attempt_id, &self.owner)
2215 .await
2216 .and_then(|value| {
2217 self.retain_cancellation_receipt(&value)?;
2218 if value["can_continue"].as_bool() != Some(true)
2219 || value["cancel_requested"].as_bool() != Some(false)
2220 || value.get("reason") != Some(&Value::Null)
2221 || value["task_status"].as_str() != Some("leased")
2222 || value["attempt_status"].as_str() != Some("running")
2223 || value["activity_status"].as_str() != Some("running")
2224 {
2225 return Err(invalid("activity observation refused continuation"));
2226 }
2227 let mut bounds = vec![text(&value, "lease_expires_at")?];
2228 if let Some(deadlines) = value.get("deadlines").filter(|v| !v.is_null()) {
2229 if !deadlines.is_object() {
2230 return Err(invalid("activity execution deadlines must be an object"));
2231 }
2232 for kind in ["heartbeat", "start_to_close", "schedule_to_close"] {
2233 if let Some(deadline) = deadlines.get(kind).filter(|v| !v.is_null()) {
2234 bounds.push(
2235 deadline
2236 .as_str()
2237 .ok_or_else(|| invalid("invalid activity deadline"))?,
2238 );
2239 }
2240 }
2241 }
2242 if let Some(session) = value.get("worker_session").filter(|v| !v.is_null()) {
2243 if session["status"].as_str() != Some("active")
2244 || session["lease_owner"].as_str() != Some(self.owner.as_str())
2245 {
2246 return Err(invalid(
2247 "activity no longer owns its required worker session",
2248 ));
2249 }
2250 bounds.push(text(session, "lease_expires_at")?);
2251 bounds.push(text(session, "ttl_expires_at")?);
2252 }
2253 for bound in bounds {
2254 let deadline = DateTime::parse_from_rfc3339(bound)
2255 .map_err(|_| invalid("activity deadline must include a timezone"))?;
2256 let now = SystemTime::now()
2257 .duration_since(UNIX_EPOCH)
2258 .map_err(|_| invalid("activity observation clock precedes the epoch"))?;
2259 if !u128::try_from(deadline.timestamp_millis())
2260 .is_ok_and(|millis| millis > now.as_millis())
2261 {
2262 return Err(invalid("activity ownership or execution deadline elapsed"));
2263 }
2264 }
2265 self.boundary()
2266 });
2267 result.map_err(|error| {
2268 self.abandon();
2269 Error::ActivityExecutionAbandoned(error.to_string())
2270 })
2271 }
2272
2273 pub(super) async fn heartbeat<T: Serialize>(
2274 &self,
2275 context: &ActivityContext,
2276 details: T,
2277 ) -> Result<ActivityHeartbeatResponse> {
2278 if context.task_id != self.task_id
2279 || context.activity_attempt_id != self.attempt_id
2280 || context.lease_owner != self.owner
2281 || context.worker_id != self.owner
2282 {
2283 self.abandon();
2284 return Err(Error::ActivityExecutionAbandoned(
2285 "activity context changed its original claim".into(),
2286 ));
2287 }
2288 self.observe().await?;
2289 let result = tokio::time::timeout(CONTROL_BUDGET, async {
2290 let details = encode_typed_envelope(&AvroValue::from_serialize(&details)?, DEFAULT_CODEC)?;
2291 self.boundary()?;
2292 let value: Value = self.client.request_json(
2293 reqwest::Method::POST,
2294 &format!("/worker/activity-tasks/{}/heartbeat", percent_encode_path_segment(&self.task_id)),
2295 RequestProtocol::Worker("1.20"),
2296 Some(&json!({"activity_attempt_id":self.attempt_id,"lease_owner":self.owner,"details":details})),
2297 ).await?;
2298 if value["task_id"].as_str() != Some(self.task_id.as_str())
2299 || value["activity_attempt_id"].as_str() != Some(self.attempt_id.as_str())
2300 || value["lease_owner"].as_str() != Some(self.owner.as_str())
2301 || value["can_continue"].as_bool() != Some(true)
2302 || value["cancel_requested"].as_bool() != Some(false)
2303 || value["heartbeat_recorded"].as_bool() != Some(true)
2304 {
2305 return Err(invalid("activity heartbeat lost its original claim"));
2306 }
2307 serde_json::from_value(value).map_err(Error::from)
2308 }).await.map_err(|_| Error::Timeout).and_then(|result| result);
2309 let response = result.map_err(|error| {
2310 self.abandon();
2311 Error::ActivityExecutionAbandoned(error.to_string())
2312 })?;
2313 self.observe().await?;
2314 Ok(response)
2315 }
2316}
2317
2318pub(super) fn cancellation_claim(task: &WorkflowTask) -> Result<(&str, &str)> {
2319 let owner = task
2320 .lease_owner
2321 .as_deref()
2322 .filter(|owner| !owner.trim().is_empty());
2323 let run = task.run_id.as_deref().filter(|run| !run.trim().is_empty());
2324 if task.task_id.trim().is_empty()
2325 || task.workflow_task_attempt == 0
2326 || task.workflow_task_attempt > MAX_SEQUENCE
2327 {
2328 return Err(invalid(
2329 "cancellation transport requires a valid task and attempt",
2330 ));
2331 }
2332 Ok((
2333 owner.ok_or_else(|| invalid("cancellation transport requires the actual lease owner"))?,
2334 run.ok_or_else(|| invalid("cancellation transport requires the selected durable run"))?,
2335 ))
2336}
2337
2338impl WorkflowHandle {
2339 pub async fn request_cancellation(
2341 &self,
2342 options: CooperativeCancellationOptions,
2343 ) -> Result<WorkflowCancellationRequest> {
2344 self.client
2345 .request_workflow_cancellation(&self.workflow_id, options)
2346 .await
2347 }
2348
2349 pub async fn request_selected_run_cancellation(
2351 &self,
2352 options: CooperativeCancellationOptions,
2353 ) -> Result<WorkflowCancellationRequest> {
2354 let run_id = self
2355 .run_id
2356 .as_deref()
2357 .ok_or_else(|| invalid("selected run_id is required"))?;
2358 self.client
2359 .request_workflow_run_cancellation(&self.workflow_id, run_id, options)
2360 .await
2361 }
2362}