1use super::*;
2use chrono::{SecondsFormat, Utc};
3use std::sync::Weak;
4
5#[derive(Clone, Debug, PartialEq, Eq)]
7pub struct CancellationLineage {
8 request_id: String,
9 workflow_instance_id: String,
10 workflow_run_id: String,
11}
12
13impl CancellationLineage {
14 pub fn request_id(&self) -> &str {
15 &self.request_id
16 }
17
18 pub fn workflow_instance_id(&self) -> &str {
19 &self.workflow_instance_id
20 }
21
22 pub fn workflow_run_id(&self) -> &str {
23 &self.workflow_run_id
24 }
25
26 fn to_value(&self) -> Value {
27 json!({
28 "request_id": self.request_id,
29 "workflow_instance_id": self.workflow_instance_id,
30 "workflow_run_id": self.workflow_run_id,
31 })
32 }
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
45#[non_exhaustive]
46pub enum CancellationCause {
47 Requested,
49 Timeout,
51}
52
53impl CancellationCause {
54 pub fn is_timeout(self) -> bool {
56 self == Self::Timeout
57 }
58}
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62enum RecordedCause {
63 Cancellation,
64 Timeout,
65}
66
67#[derive(Clone, Debug)]
72pub struct CancellationContext {
73 request_id: String,
74 root_request_id: String,
75 root_workflow_instance_id: String,
76 root_workflow_run_id: String,
77 parent_request_id: Option<String>,
78 reason: Option<String>,
79 requester: BTreeMap<String, String>,
80 source: String,
81 requested_at: DateTime<Utc>,
82 cleanup_deadline_at: DateTime<Utc>,
83 lineage: Vec<CancellationLineage>,
84 cause: Option<RecordedCause>,
85 scope_origin: Option<Box<ScopedCancellationContext>>,
86 replay: Option<Weak<Mutex<WorkflowState>>>,
87}
88
89impl PartialEq for CancellationContext {
90 fn eq(&self, other: &Self) -> bool {
91 self.request_id == other.request_id
92 && self.root_request_id == other.root_request_id
93 && self.root_workflow_instance_id == other.root_workflow_instance_id
94 && self.root_workflow_run_id == other.root_workflow_run_id
95 && self.parent_request_id == other.parent_request_id
96 && self.reason == other.reason
97 && self.requester == other.requester
98 && self.source == other.source
99 && self.requested_at == other.requested_at
100 && self.cleanup_deadline_at == other.cleanup_deadline_at
101 && self.lineage == other.lineage
102 && self.cause == other.cause
103 && self.scope_origin == other.scope_origin
104 }
105}
106
107impl Eq for CancellationContext {}
108
109fn invalid_context(message: &str) -> Error {
110 Error::InvalidCooperativeCancellation(message.to_owned())
111}
112
113fn context_text<'a>(value: &'a Value, key: &str) -> Result<&'a str> {
114 value[key]
115 .as_str()
116 .filter(|text| !text.trim().is_empty())
117 .ok_or_else(|| invalid_context("cancellation context identity must be a non-empty string"))
118}
119
120fn nullable_text(value: &Value, key: &str, allow_empty: bool) -> Result<Option<String>> {
121 match value.get(key) {
122 None | Some(Value::Null) => Ok(None),
123 Some(Value::String(text)) if allow_empty || !text.is_empty() => Ok(Some(text.clone())),
124 _ => Err(invalid_context(
125 "cancellation parent identity or reason is invalid",
126 )),
127 }
128}
129
130fn read_cause(value: &Value) -> Result<Option<RecordedCause>> {
132 match value.get("cause") {
133 None | Some(Value::Null) => Ok(None),
134 Some(Value::String(cause)) if cause == "cancellation" => {
135 Ok(Some(RecordedCause::Cancellation))
136 }
137 Some(Value::String(cause)) if cause == "timeout" => Ok(Some(RecordedCause::Timeout)),
138 Some(_) => Err(invalid_context(
139 "cancellation cause must be cancellation or timeout",
140 )),
141 }
142}
143
144impl CancellationContext {
145 pub fn from_value(value: &Value) -> Result<Self> {
147 let scope_origin = match value["schema"].as_str() {
148 Some("durable-workflow.cancellation-context/v2") => Some(Box::new(
149 ScopedCancellationContext::from_value(&value["scope_origin"])?,
150 )),
151 Some("durable-workflow.cancellation-context/v1") => {
152 if value.get("scope_origin").is_some()
153 || value.get("scope_authority_deadline_at").is_some()
154 {
155 return Err(invalid_context(
156 "legacy cancellation context cannot discard a scoped origin",
157 ));
158 }
159 None
160 }
161 _ => return Err(invalid_context("unsupported cancellation context schema")),
162 };
163 let requester = value["requester"]
164 .as_object()
165 .filter(|requester| !requester.is_empty())
166 .ok_or_else(|| invalid_context("cancellation requester must identify its caller"))?;
167 let mut normalized_requester = BTreeMap::new();
168 for (key, value) in requester {
169 let text = value
170 .as_str()
171 .filter(|text| !text.is_empty())
172 .ok_or_else(|| {
173 invalid_context("cancellation requester contains unsupported metadata")
174 })?;
175 if !matches!(key.as_str(), "type" | "id" | "label") {
176 return Err(invalid_context(
177 "cancellation requester contains unsupported metadata",
178 ));
179 }
180 normalized_requester.insert(key.clone(), text.to_owned());
181 }
182 let lineage = value["lineage"]
183 .as_array()
184 .filter(|lineage| !lineage.is_empty())
185 .ok_or_else(|| invalid_context("cancellation lineage must contain the root request"))?;
186 let mut normalized = Vec::new();
187 for entry in lineage {
188 normalized.push(CancellationLineage {
189 request_id: context_text(entry, "request_id")?.to_owned(),
190 workflow_instance_id: context_text(entry, "workflow_instance_id")?.to_owned(),
191 workflow_run_id: context_text(entry, "workflow_run_id")?.to_owned(),
192 });
193 }
194 let request_id = context_text(value, "request_id")?.to_owned();
195 let root_request_id = context_text(value, "root_request_id")?.to_owned();
196 let root_workflow_instance_id =
197 context_text(value, "root_workflow_instance_id")?.to_owned();
198 let root_workflow_run_id = context_text(value, "root_workflow_run_id")?.to_owned();
199 let parent_request_id = nullable_text(value, "parent_request_id", false)?;
200 let reason = nullable_text(value, "reason", true)?;
201 let requests: BTreeSet<_> = normalized.iter().map(|entry| &entry.request_id).collect();
202 let runs: BTreeSet<_> = normalized
203 .iter()
204 .map(|entry| &entry.workflow_run_id)
205 .collect();
206 if requests.len() != normalized.len() || runs.len() != normalized.len() {
207 return Err(invalid_context(
208 "cancellation lineage cannot contain a cycle",
209 ));
210 }
211 let expected_parent = normalized
212 .iter()
213 .rev()
214 .nth(1)
215 .map(|entry| &entry.request_id);
216 if normalized[0].request_id != root_request_id
217 || normalized[0].workflow_instance_id != root_workflow_instance_id
218 || normalized[0].workflow_run_id != root_workflow_run_id
219 || normalized.last().unwrap().request_id != request_id
220 || (scope_origin.is_none() && parent_request_id.as_ref() != expected_parent)
221 {
222 return Err(invalid_context(
223 "cancellation lineage does not match its request identities",
224 ));
225 }
226 let requested_at = DateTime::parse_from_rfc3339(context_text(value, "requested_at")?)
227 .map_err(|_| invalid_context("cancellation request timestamp is invalid"))?
228 .with_timezone(&Utc);
229 let cleanup_deadline_at =
230 DateTime::parse_from_rfc3339(context_text(value, "cleanup_deadline_at")?)
231 .map_err(|_| invalid_context("cancellation deadline timestamp is invalid"))?
232 .with_timezone(&Utc);
233 if cleanup_deadline_at <= requested_at {
234 return Err(invalid_context(
235 "cancellation deadline must follow the original request",
236 ));
237 }
238 let cause = read_cause(value)?;
239 let context = Self {
240 request_id,
241 root_request_id,
242 root_workflow_instance_id,
243 root_workflow_run_id,
244 parent_request_id,
245 reason,
246 requester: normalized_requester,
247 source: context_text(value, "source")?.to_owned(),
248 requested_at,
249 cleanup_deadline_at,
250 lineage: normalized,
251 cause,
252 scope_origin,
253 replay: None,
254 };
255 context.assert_scope_origin(value)?;
256 Ok(context)
257 }
258
259 fn assert_scope_origin(&self, value: &Value) -> Result<()> {
260 let Some(origin) = self.scope_origin.as_deref() else {
261 return Ok(());
262 };
263 let root = &origin.root_context;
264 let last = self.lineage.last().unwrap();
265 let authority =
266 DateTime::parse_from_rfc3339(context_text(value, "scope_authority_deadline_at")?)
267 .map_err(|_| invalid_context("scoped cancellation authority timestamp is invalid"))?
268 .with_timezone(&Utc);
269 if self.parent_request_id.as_deref() != Some(origin.request_id())
270 || self.root_request_id != root.root_request_id
271 || self.root_workflow_instance_id != root.root_workflow_instance_id
272 || self.root_workflow_run_id != root.root_workflow_run_id
273 || self.reason != root.reason
274 || self.requester != root.requester
275 || self.source != root.source
276 || self.requested_at != root.requested_at
277 || self.cleanup_deadline_at != authority
278 || self.cleanup_deadline_at > origin.deadline()
279 || origin.lineage.iter().any(|entry| {
280 entry.request_id == last.request_id || entry.workflow_run_id == last.workflow_run_id
281 })
282 {
283 return Err(invalid_context(
284 "run cancellation does not preserve its original scope context",
285 ));
286 }
287 let mut expected = vec![root.lineage[0].clone()];
288 for entry in &origin.lineage {
289 if entry.workflow_run_id == root.root_workflow_run_id {
290 continue;
291 }
292 let address = CancellationLineage {
293 request_id: entry.request_id.clone(),
294 workflow_instance_id: entry.workflow_instance_id.clone(),
295 workflow_run_id: entry.workflow_run_id.clone(),
296 };
297 if expected.last().unwrap().workflow_run_id == entry.workflow_run_id {
298 *expected.last_mut().unwrap() = address;
299 } else {
300 expected.push(address);
301 }
302 }
303 expected.push(last.clone());
304 if self.lineage != expected {
305 return Err(invalid_context(
306 "run cancellation lineage discards or replaces its original scope ancestry",
307 ));
308 }
309 Ok(())
310 }
311
312 pub fn request_id(&self) -> &str {
313 &self.request_id
314 }
315 pub fn root_request_id(&self) -> &str {
316 &self.root_request_id
317 }
318 pub fn root_workflow_instance_id(&self) -> &str {
319 &self.root_workflow_instance_id
320 }
321 pub fn root_workflow_run_id(&self) -> &str {
322 &self.root_workflow_run_id
323 }
324 pub fn parent_request_id(&self) -> Option<&str> {
325 self.parent_request_id.as_deref()
326 }
327 pub fn reason(&self) -> Option<&str> {
328 self.reason.as_deref()
329 }
330 pub fn requester(&self) -> &BTreeMap<String, String> {
331 &self.requester
332 }
333 pub fn source(&self) -> &str {
334 &self.source
335 }
336 pub fn requested_at(&self) -> DateTime<Utc> {
337 self.requested_at
338 }
339 pub fn deadline(&self) -> DateTime<Utc> {
340 self.cleanup_deadline_at
341 }
342 pub fn scope_origin(&self) -> Option<&ScopedCancellationContext> {
343 self.scope_origin.as_deref()
344 }
345
346 pub fn cause(&self) -> CancellationCause {
348 match self.cause {
349 Some(RecordedCause::Timeout) => CancellationCause::Timeout,
350 _ => CancellationCause::Requested,
351 }
352 }
353
354 pub fn is_timeout(&self) -> bool {
356 self.cause == Some(RecordedCause::Timeout)
357 }
358
359 pub fn remaining(&self) -> Result<Duration> {
364 let state = self
365 .replay
366 .as_ref()
367 .and_then(Weak::upgrade)
368 .filter(cancellation_replay_clock::is_active)
369 .ok_or_else(|| {
370 invalid_context("remaining() is available only in its active workflow replay")
371 })?;
372 let time = state
373 .lock()
374 .map_err(|_| Error::WorkflowStatePoisoned)?
375 .cancellation_time()?;
376 Ok((self.cleanup_deadline_at - time)
377 .to_std()
378 .unwrap_or(Duration::ZERO))
379 }
380
381 pub(super) fn with_replay(mut self, replay: Option<Weak<Mutex<WorkflowState>>>) -> Self {
382 self.replay = replay;
383 self
384 }
385 pub fn lineage(&self) -> &[CancellationLineage] {
386 &self.lineage
387 }
388
389 pub fn to_value(&self) -> Value {
391 let mut value = json!({
392 "schema": if self.scope_origin.is_none() { "durable-workflow.cancellation-context/v1" }
393 else { "durable-workflow.cancellation-context/v2" },
394 "request_id": self.request_id, "root_request_id": self.root_request_id,
395 "root_workflow_instance_id": self.root_workflow_instance_id,
396 "root_workflow_run_id": self.root_workflow_run_id,
397 "parent_request_id": self.parent_request_id, "reason": self.reason,
398 "requester": self.requester, "source": self.source,
399 "requested_at": self.requested_at.to_rfc3339_opts(SecondsFormat::Micros, true),
400 "cleanup_deadline_at": self.cleanup_deadline_at.to_rfc3339_opts(SecondsFormat::Micros, true),
401 "lineage": self.lineage.iter().map(CancellationLineage::to_value).collect::<Vec<_>>(),
402 });
403 match self.cause {
404 Some(RecordedCause::Cancellation) => value["cause"] = json!("cancellation"),
405 Some(RecordedCause::Timeout) => value["cause"] = json!("timeout"),
406 None => {}
407 }
408 if let Some(origin) = &self.scope_origin {
409 value["scope_origin"] = origin.to_value();
410 value["scope_authority_deadline_at"] = value["cleanup_deadline_at"].clone();
411 }
412 value
413 }
414}
415
416#[derive(Clone, Debug, PartialEq, Eq)]
418pub struct ScopedCancellationLineage {
419 request_id: String,
420 workflow_instance_id: String,
421 workflow_run_id: String,
422 scope_id: String,
423 cleanup_deadline_at: DateTime<Utc>,
424}
425
426impl ScopedCancellationLineage {
427 pub fn request_id(&self) -> &str {
428 &self.request_id
429 }
430 pub fn workflow_instance_id(&self) -> &str {
431 &self.workflow_instance_id
432 }
433 pub fn workflow_run_id(&self) -> &str {
434 &self.workflow_run_id
435 }
436 pub fn scope_id(&self) -> &str {
437 &self.scope_id
438 }
439 pub fn deadline(&self) -> DateTime<Utc> {
440 self.cleanup_deadline_at
441 }
442
443 fn to_value(&self) -> Value {
444 json!({
445 "request_id": self.request_id, "workflow_instance_id": self.workflow_instance_id,
446 "workflow_run_id": self.workflow_run_id, "scope_id": self.scope_id,
447 "cleanup_deadline_at": self.cleanup_deadline_at.to_rfc3339_opts(SecondsFormat::Micros, true),
448 })
449 }
450}
451
452#[derive(Clone, Debug, PartialEq, Eq)]
455pub struct ScopedCancellationContext {
456 root_context: CancellationContext,
457 lineage: Vec<ScopedCancellationLineage>,
458}
459
460fn assert_context_keys(value: &Value, keys: &[&str]) -> Result<()> {
461 let object = value
462 .as_object()
463 .ok_or_else(|| invalid_context("scoped context must be an object"))?;
464 if object.len() != keys.len() || keys.iter().any(|key| !object.contains_key(*key)) {
465 return Err(invalid_context(
466 "scoped cancellation context has missing or unsupported fields",
467 ));
468 }
469 Ok(())
470}
471
472impl ScopedCancellationContext {
473 #[doc(hidden)]
475 pub fn remaining(&self) -> Result<Duration> {
476 let state = self
477 .root_context
478 .replay
479 .as_ref()
480 .and_then(Weak::upgrade)
481 .filter(cancellation_replay_clock::is_active)
482 .ok_or_else(|| {
483 invalid_context("remaining() is available only in its active scope replay")
484 })?;
485 let state = state.lock().map_err(|_| Error::WorkflowStatePoisoned)?;
486 let (_, ceiling) = state
487 .scope_delivery
488 .as_ref()
489 .and_then(|replay| replay.contexts.get(self.scope_id()))
490 .filter(|(original, _)| original == self)
491 .ok_or_else(|| {
492 invalid_context("scope remaining() requires its original consumed delivery")
493 })?;
494 Ok((self.deadline().min(*ceiling) - state.cancellation_time()?)
495 .to_std()
496 .unwrap_or(Duration::ZERO))
497 }
498
499 pub(super) fn with_replay(mut self, replay: Option<Weak<Mutex<WorkflowState>>>) -> Self {
500 self.root_context = self.root_context.with_replay(replay);
501 self
502 }
503
504 pub(super) fn from_run_context(context: &CancellationContext) -> Result<Self> {
505 let mut root = context.to_value();
506 let mut lineage = Vec::new();
507 if let Some(origin) = context.scope_origin() {
508 root = origin.root_context().to_value();
509 lineage.extend(
510 origin
511 .lineage()
512 .iter()
513 .map(ScopedCancellationLineage::to_value),
514 );
515 let local = context.lineage().last().unwrap();
516 lineage.push(json!({"request_id":context.request_id(),
517 "workflow_instance_id":local.workflow_instance_id(),
518 "workflow_run_id":local.workflow_run_id(), "scope_id":"root",
519 "cleanup_deadline_at":context.deadline().to_rfc3339_opts(SecondsFormat::Micros, true)}));
520 } else {
521 root["request_id"] = json!(context.root_request_id());
522 root["parent_request_id"] = Value::Null;
523 root["lineage"] = json!([context.lineage()[0].to_value()]);
524 lineage.extend(context.lineage().iter().map(|entry| json!({
525 "request_id":entry.request_id(), "workflow_instance_id":entry.workflow_instance_id(),
526 "workflow_run_id":entry.workflow_run_id(), "scope_id":"root",
527 "cleanup_deadline_at":context.deadline().to_rfc3339_opts(SecondsFormat::Micros, true)})));
528 }
529 Self::from_value(
530 &json!({"schema":"durable-workflow.scoped-cancellation-context/v1",
531 "root_context":root, "lineage":lineage}),
532 )
533 }
534
535 pub fn from_value(value: &Value) -> Result<Self> {
536 assert_context_keys(value, &["schema", "root_context", "lineage"])?;
537 if value["schema"] != "durable-workflow.scoped-cancellation-context/v1"
538 || value["root_context"]["schema"] != "durable-workflow.cancellation-context/v1"
539 {
540 return Err(invalid_context(
541 "scoped cancellation requires its original root context",
542 ));
543 }
544 let root = CancellationContext::from_value(&value["root_context"])?;
545 let root_value = root.to_value();
546 let root_keys: Vec<_> = root_value
547 .as_object()
548 .unwrap()
549 .keys()
550 .map(String::as_str)
551 .collect();
552 assert_context_keys(&value["root_context"], &root_keys)?;
553 if root.request_id != root.root_request_id
554 || root.parent_request_id.is_some()
555 || root.lineage.len() != 1
556 {
557 return Err(invalid_context(
558 "scoped cancellation root must contain the original root request",
559 ));
560 }
561 let lineage = value["lineage"]
562 .as_array()
563 .filter(|rows| !rows.is_empty())
564 .ok_or_else(|| {
565 invalid_context("scoped cancellation lineage must contain its root address")
566 })?;
567 let mut normalized = Vec::new();
568 let mut requests = BTreeSet::new();
569 let mut addresses = BTreeSet::new();
570 let mut instances_by_run = BTreeMap::new();
571 let mut last_run = String::new();
572 let mut deadline = root.deadline();
573 for (index, entry) in lineage.iter().enumerate() {
574 assert_context_keys(
575 entry,
576 &[
577 "request_id",
578 "workflow_instance_id",
579 "workflow_run_id",
580 "scope_id",
581 "cleanup_deadline_at",
582 ],
583 )?;
584 let address = ScopedCancellationLineage {
585 request_id: context_text(entry, "request_id")?.to_owned(),
586 workflow_instance_id: context_text(entry, "workflow_instance_id")?.to_owned(),
587 workflow_run_id: context_text(entry, "workflow_run_id")?.to_owned(),
588 scope_id: context_text(entry, "scope_id")?.to_owned(),
589 cleanup_deadline_at: DateTime::parse_from_rfc3339(context_text(
590 entry,
591 "cleanup_deadline_at",
592 )?)
593 .map_err(|_| invalid_context("scoped cancellation deadline timestamp is invalid"))?
594 .with_timezone(&Utc),
595 };
596 if index == 0
597 && (address.request_id != root.request_id
598 || address.workflow_instance_id != root.root_workflow_instance_id
599 || address.workflow_run_id != root.root_workflow_run_id
600 || address.cleanup_deadline_at != root.deadline())
601 {
602 return Err(invalid_context(
603 "scoped cancellation root address does not match its request",
604 ));
605 }
606 if !requests.insert(address.request_id.clone())
607 || !addresses.insert((address.workflow_run_id.clone(), address.scope_id.clone()))
608 {
609 return Err(invalid_context(
610 "scoped cancellation cannot repeat a request or address",
611 ));
612 }
613 if let Some(instance) = instances_by_run.get(&address.workflow_run_id) {
614 if instance != &address.workflow_instance_id || last_run != address.workflow_run_id
615 {
616 return Err(invalid_context(
617 "scoped cancellation cannot reenter or reassign an earlier run",
618 ));
619 }
620 }
621 if address.cleanup_deadline_at <= root.requested_at
622 || address.cleanup_deadline_at > deadline
623 {
624 return Err(invalid_context(
625 "scoped cancellation cannot extend a descendant budget",
626 ));
627 }
628 instances_by_run.insert(
629 address.workflow_run_id.clone(),
630 address.workflow_instance_id.clone(),
631 );
632 last_run = address.workflow_run_id.clone();
633 deadline = address.cleanup_deadline_at;
634 normalized.push(address);
635 }
636 Ok(Self {
637 root_context: root,
638 lineage: normalized,
639 })
640 }
641
642 pub fn root_context(&self) -> &CancellationContext {
643 &self.root_context
644 }
645 pub fn lineage(&self) -> &[ScopedCancellationLineage] {
646 &self.lineage
647 }
648 pub fn request_id(&self) -> &str {
649 &self.lineage.last().unwrap().request_id
650 }
651 pub fn parent_request_id(&self) -> Option<&str> {
652 self.lineage
653 .iter()
654 .rev()
655 .nth(1)
656 .map(|entry| entry.request_id.as_str())
657 }
658 pub fn workflow_instance_id(&self) -> &str {
659 &self.lineage.last().unwrap().workflow_instance_id
660 }
661 pub fn workflow_run_id(&self) -> &str {
662 &self.lineage.last().unwrap().workflow_run_id
663 }
664 pub fn scope_id(&self) -> &str {
665 &self.lineage.last().unwrap().scope_id
666 }
667 pub fn root_scope_id(&self) -> &str {
668 &self.lineage[0].scope_id
669 }
670 pub fn requested_at(&self) -> DateTime<Utc> {
671 self.root_context.requested_at()
672 }
673 pub fn root_deadline(&self) -> DateTime<Utc> {
674 self.root_context.deadline()
675 }
676 pub fn deadline(&self) -> DateTime<Utc> {
677 self.lineage.last().unwrap().cleanup_deadline_at
678 }
679 pub fn to_value(&self) -> Value {
680 json!({
681 "schema": "durable-workflow.scoped-cancellation-context/v1",
682 "root_context": self.root_context.to_value(),
683 "lineage": self.lineage.iter().map(ScopedCancellationLineage::to_value).collect::<Vec<_>>(),
684 })
685 }
686}