1use std::fmt;
15
16use schemars::JsonSchema;
17use serde::{Deserialize, Deserializer, Serialize, de};
18use thiserror::Error;
19
20use crate::{
21 Digest, EventId, InterruptId, JournalHead, JournalPayload, PrincipalIdentity, RunId,
22 RunInterrupt, RunInterruptKind, RunTimer, RunTimerKind, ScopeSet, TenantId, TimerId, Timestamp,
23};
24
25const INTERRUPT_INTENT_DIGEST_DOMAIN: &[u8] = b"stateknot-interrupt-intent-v1\0";
26const INTERRUPT_REQUEST_DIGEST_DOMAIN: &[u8] = b"stateknot-interrupt-request-v1\0";
27const INTERRUPT_RESOLUTION_INTENT_DIGEST_DOMAIN: &[u8] =
28 b"stateknot-interrupt-resolution-intent-v1\0";
29const INTERRUPT_RESOLUTION_DIGEST_DOMAIN: &[u8] = b"stateknot-interrupt-resolution-v1\0";
30const TIMER_INTENT_DIGEST_DOMAIN: &[u8] = b"stateknot-timer-intent-v1\0";
31const TIMER_DIGEST_DOMAIN: &[u8] = b"stateknot-timer-v1\0";
32const TIMER_FIRING_INTENT_DIGEST_DOMAIN: &[u8] = b"stateknot-timer-firing-intent-v1\0";
33const TIMER_FIRING_DIGEST_DOMAIN: &[u8] = b"stateknot-timer-firing-v1\0";
34
35#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
43#[serde(deny_unknown_fields)]
44pub struct InterruptRequestIntent {
45 tenant_id: TenantId,
46 run_id: RunId,
47 interrupt_id: InterruptId,
48 request_event_id: EventId,
49 kind: RunInterruptKind,
50 request_payload: JournalPayload,
51 action_digest: Digest,
52 #[serde(skip_serializing_if = "Option::is_none")]
53 required_principal: Option<PrincipalIdentity>,
54 required_scopes: ScopeSet,
55 #[serde(skip_serializing_if = "Option::is_none")]
56 expires_at: Option<Timestamp>,
57 intent_digest: Digest,
58}
59
60impl InterruptRequestIntent {
61 #[allow(clippy::too_many_arguments)]
71 pub fn new(
72 tenant_id: TenantId,
73 run_id: RunId,
74 interrupt_id: InterruptId,
75 request_event_id: EventId,
76 kind: RunInterruptKind,
77 request_payload: JournalPayload,
78 action_digest: Digest,
79 required_principal: Option<PrincipalIdentity>,
80 required_scopes: ScopeSet,
81 expires_at: Option<Timestamp>,
82 ) -> Result<Self, DurableWaitError> {
83 let intent_digest = compute_digest(
84 INTERRUPT_INTENT_DIGEST_DOMAIN,
85 &InterruptIntentDigestWire {
86 tenant_id: &tenant_id,
87 run_id,
88 interrupt_id,
89 request_event_id,
90 kind,
91 request_payload_digest: request_payload.digest(),
92 action_digest,
93 required_principal: required_principal.as_ref(),
94 required_scopes: &required_scopes,
95 expires_at,
96 },
97 )?;
98 Ok(Self {
99 tenant_id,
100 run_id,
101 interrupt_id,
102 request_event_id,
103 kind,
104 request_payload,
105 action_digest,
106 required_principal,
107 required_scopes,
108 expires_at,
109 intent_digest,
110 })
111 }
112
113 #[allow(clippy::too_many_arguments)]
119 pub fn restore(
120 tenant_id: TenantId,
121 run_id: RunId,
122 interrupt_id: InterruptId,
123 request_event_id: EventId,
124 kind: RunInterruptKind,
125 request_payload: JournalPayload,
126 action_digest: Digest,
127 required_principal: Option<PrincipalIdentity>,
128 required_scopes: ScopeSet,
129 expires_at: Option<Timestamp>,
130 intent_digest: Digest,
131 ) -> Result<Self, DurableWaitError> {
132 let restored = Self::new(
133 tenant_id,
134 run_id,
135 interrupt_id,
136 request_event_id,
137 kind,
138 request_payload,
139 action_digest,
140 required_principal,
141 required_scopes,
142 expires_at,
143 )?;
144 if restored.intent_digest != intent_digest {
145 return Err(DurableWaitError::IntentDigestMismatch);
146 }
147 Ok(restored)
148 }
149
150 #[must_use]
152 pub const fn tenant_id(&self) -> &TenantId {
153 &self.tenant_id
154 }
155
156 #[must_use]
158 pub const fn run_id(&self) -> RunId {
159 self.run_id
160 }
161
162 #[must_use]
164 pub const fn interrupt_id(&self) -> InterruptId {
165 self.interrupt_id
166 }
167
168 #[must_use]
170 pub const fn request_event_id(&self) -> EventId {
171 self.request_event_id
172 }
173
174 #[must_use]
176 pub const fn kind(&self) -> RunInterruptKind {
177 self.kind
178 }
179
180 #[must_use]
182 pub const fn request_payload(&self) -> &JournalPayload {
183 &self.request_payload
184 }
185
186 #[must_use]
188 pub const fn action_digest(&self) -> Digest {
189 self.action_digest
190 }
191
192 #[must_use]
194 pub const fn required_principal(&self) -> Option<&PrincipalIdentity> {
195 self.required_principal.as_ref()
196 }
197
198 #[must_use]
200 pub const fn required_scopes(&self) -> &ScopeSet {
201 &self.required_scopes
202 }
203
204 #[must_use]
206 pub const fn expires_at(&self) -> Option<Timestamp> {
207 self.expires_at
208 }
209
210 #[must_use]
212 pub const fn intent_digest(&self) -> Digest {
213 self.intent_digest
214 }
215}
216
217impl fmt::Debug for InterruptRequestIntent {
218 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
219 formatter
220 .debug_struct("InterruptRequestIntent")
221 .field("tenant_id", &self.tenant_id)
222 .field("run_id", &self.run_id)
223 .field("interrupt_id", &self.interrupt_id)
224 .field("request_event_id", &self.request_event_id)
225 .field("kind", &self.kind)
226 .field("request_payload", &self.request_payload)
227 .field("action_digest", &self.action_digest)
228 .field("required_principal", &self.required_principal)
229 .field("required_scopes", &self.required_scopes)
230 .field("expires_at", &self.expires_at)
231 .field("intent_digest", &self.intent_digest)
232 .finish_non_exhaustive()
233 }
234}
235
236impl<'de> Deserialize<'de> for InterruptRequestIntent {
237 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
238 where
239 D: Deserializer<'de>,
240 {
241 #[derive(Deserialize)]
242 #[serde(deny_unknown_fields)]
243 struct Wire {
244 tenant_id: TenantId,
245 run_id: RunId,
246 interrupt_id: InterruptId,
247 request_event_id: EventId,
248 kind: RunInterruptKind,
249 request_payload: JournalPayload,
250 action_digest: Digest,
251 required_principal: Option<PrincipalIdentity>,
252 required_scopes: ScopeSet,
253 expires_at: Option<Timestamp>,
254 intent_digest: Digest,
255 }
256
257 let wire = Wire::deserialize(deserializer)?;
258 Self::restore(
259 wire.tenant_id,
260 wire.run_id,
261 wire.interrupt_id,
262 wire.request_event_id,
263 wire.kind,
264 wire.request_payload,
265 wire.action_digest,
266 wire.required_principal,
267 wire.required_scopes,
268 wire.expires_at,
269 wire.intent_digest,
270 )
271 .map_err(de::Error::custom)
272 }
273}
274
275#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
277#[serde(deny_unknown_fields)]
278pub struct InterruptRequest {
279 intent: InterruptRequestIntent,
280 marker: RunInterrupt,
281 journal: JournalHead,
282 digest: Digest,
283}
284
285impl InterruptRequest {
286 pub fn commit(
293 intent: InterruptRequestIntent,
294 journal: JournalHead,
295 ) -> Result<Self, DurableWaitError> {
296 validate_journal_scope(
297 intent.tenant_id(),
298 intent.run_id(),
299 intent.request_event_id(),
300 &journal,
301 )?;
302 let marker = RunInterrupt::new(
303 intent.interrupt_id(),
304 intent.kind(),
305 journal.recorded_at(),
306 intent.expires_at(),
307 )
308 .map_err(|_| DurableWaitError::InterruptExpiryNotAfterRegistration)?;
309 let digest = compute_interrupt_request_digest(&intent, &marker, &journal)?;
310 Ok(Self {
311 intent,
312 marker,
313 journal,
314 digest,
315 })
316 }
317
318 pub fn restore(
324 intent: InterruptRequestIntent,
325 marker: &RunInterrupt,
326 journal: JournalHead,
327 digest: Digest,
328 ) -> Result<Self, DurableWaitError> {
329 let restored = Self::commit(intent, journal)?;
330 if &restored.marker != marker {
331 return Err(DurableWaitError::LifecycleMarkerMismatch);
332 }
333 if restored.digest != digest {
334 return Err(DurableWaitError::RecordDigestMismatch);
335 }
336 Ok(restored)
337 }
338
339 #[must_use]
341 pub const fn intent(&self) -> &InterruptRequestIntent {
342 &self.intent
343 }
344
345 #[must_use]
347 pub const fn marker(&self) -> &RunInterrupt {
348 &self.marker
349 }
350
351 #[must_use]
353 pub const fn journal(&self) -> &JournalHead {
354 &self.journal
355 }
356
357 #[must_use]
359 pub const fn digest(&self) -> Digest {
360 self.digest
361 }
362
363 #[must_use]
365 pub fn head(&self) -> InterruptRequestHead {
366 InterruptRequestHead {
367 tenant_id: self.intent.tenant_id.clone(),
368 run_id: self.intent.run_id,
369 marker: self.marker.clone(),
370 request_payload_digest: self.intent.request_payload.digest(),
371 action_digest: self.intent.action_digest,
372 required_principal: self.intent.required_principal.clone(),
373 required_scopes: self.intent.required_scopes.clone(),
374 intent_digest: self.intent.intent_digest,
375 journal: self.journal.clone(),
376 digest: self.digest,
377 }
378 }
379}
380
381impl fmt::Debug for InterruptRequest {
382 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
383 formatter
384 .debug_struct("InterruptRequest")
385 .field("intent", &self.intent)
386 .field("marker", &self.marker)
387 .field("journal", &self.journal)
388 .field("digest", &self.digest)
389 .finish_non_exhaustive()
390 }
391}
392
393impl<'de> Deserialize<'de> for InterruptRequest {
394 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
395 where
396 D: Deserializer<'de>,
397 {
398 #[derive(Deserialize)]
399 #[serde(deny_unknown_fields)]
400 struct Wire {
401 intent: InterruptRequestIntent,
402 marker: RunInterrupt,
403 journal: JournalHead,
404 digest: Digest,
405 }
406
407 let wire = Wire::deserialize(deserializer)?;
408 Self::restore(wire.intent, &wire.marker, wire.journal, wire.digest)
409 .map_err(de::Error::custom)
410 }
411}
412
413#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
415#[serde(deny_unknown_fields)]
416pub struct InterruptRequestHead {
417 tenant_id: TenantId,
418 run_id: RunId,
419 marker: RunInterrupt,
420 request_payload_digest: Digest,
421 action_digest: Digest,
422 #[serde(skip_serializing_if = "Option::is_none")]
423 required_principal: Option<PrincipalIdentity>,
424 required_scopes: ScopeSet,
425 intent_digest: Digest,
426 journal: JournalHead,
427 digest: Digest,
428}
429
430impl InterruptRequestHead {
431 #[allow(clippy::too_many_arguments)]
437 pub fn restore(
438 tenant_id: TenantId,
439 run_id: RunId,
440 marker: RunInterrupt,
441 request_payload_digest: Digest,
442 action_digest: Digest,
443 required_principal: Option<PrincipalIdentity>,
444 required_scopes: ScopeSet,
445 intent_digest: Digest,
446 journal: JournalHead,
447 digest: Digest,
448 ) -> Result<Self, DurableWaitError> {
449 if journal.tenant_id() != &tenant_id {
450 return Err(DurableWaitError::JournalTenantMismatch);
451 }
452 if journal.run_id() != run_id {
453 return Err(DurableWaitError::JournalRunMismatch);
454 }
455 if journal.recorded_at() != marker.requested_at() {
456 return Err(DurableWaitError::LifecycleMarkerMismatch);
457 }
458 if let Some(expires_at) = marker.expires_at() {
459 if expires_at <= marker.requested_at() {
460 return Err(DurableWaitError::InterruptExpiryNotAfterRegistration);
461 }
462 }
463 let expected_intent = compute_digest(
464 INTERRUPT_INTENT_DIGEST_DOMAIN,
465 &InterruptIntentDigestWire {
466 tenant_id: &tenant_id,
467 run_id,
468 interrupt_id: marker.interrupt_id(),
469 request_event_id: journal.event_id(),
470 kind: marker.kind(),
471 request_payload_digest,
472 action_digest,
473 required_principal: required_principal.as_ref(),
474 required_scopes: &required_scopes,
475 expires_at: marker.expires_at(),
476 },
477 )?;
478 if expected_intent != intent_digest {
479 return Err(DurableWaitError::IntentDigestMismatch);
480 }
481 let expected = compute_digest(
482 INTERRUPT_REQUEST_DIGEST_DOMAIN,
483 &InterruptRequestDigestWire {
484 intent_digest,
485 marker: &marker,
486 journal: &journal,
487 },
488 )?;
489 if expected != digest {
490 return Err(DurableWaitError::RecordDigestMismatch);
491 }
492 Ok(Self {
493 tenant_id,
494 run_id,
495 marker,
496 request_payload_digest,
497 action_digest,
498 required_principal,
499 required_scopes,
500 intent_digest,
501 journal,
502 digest,
503 })
504 }
505
506 #[must_use]
508 pub const fn tenant_id(&self) -> &TenantId {
509 &self.tenant_id
510 }
511
512 #[must_use]
514 pub const fn run_id(&self) -> RunId {
515 self.run_id
516 }
517
518 #[must_use]
520 pub const fn marker(&self) -> &RunInterrupt {
521 &self.marker
522 }
523
524 #[must_use]
526 pub const fn interrupt_id(&self) -> InterruptId {
527 self.marker.interrupt_id()
528 }
529
530 #[must_use]
532 pub const fn request_payload_digest(&self) -> Digest {
533 self.request_payload_digest
534 }
535
536 #[must_use]
538 pub const fn action_digest(&self) -> Digest {
539 self.action_digest
540 }
541
542 #[must_use]
544 pub const fn required_principal(&self) -> Option<&PrincipalIdentity> {
545 self.required_principal.as_ref()
546 }
547
548 #[must_use]
550 pub const fn required_scopes(&self) -> &ScopeSet {
551 &self.required_scopes
552 }
553
554 #[must_use]
556 pub const fn intent_digest(&self) -> Digest {
557 self.intent_digest
558 }
559
560 #[must_use]
562 pub const fn journal(&self) -> &JournalHead {
563 &self.journal
564 }
565
566 #[must_use]
568 pub const fn digest(&self) -> Digest {
569 self.digest
570 }
571}
572
573impl fmt::Debug for InterruptRequestHead {
574 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
575 formatter
576 .debug_struct("InterruptRequestHead")
577 .field("tenant_id", &self.tenant_id)
578 .field("run_id", &self.run_id)
579 .field("marker", &self.marker)
580 .field("request_payload_digest", &self.request_payload_digest)
581 .field("action_digest", &self.action_digest)
582 .field("required_principal", &self.required_principal)
583 .field("required_scopes", &self.required_scopes)
584 .field("intent_digest", &self.intent_digest)
585 .field("journal", &self.journal)
586 .field("digest", &self.digest)
587 .finish_non_exhaustive()
588 }
589}
590
591impl<'de> Deserialize<'de> for InterruptRequestHead {
592 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
593 where
594 D: Deserializer<'de>,
595 {
596 #[derive(Deserialize)]
597 #[serde(deny_unknown_fields)]
598 struct Wire {
599 tenant_id: TenantId,
600 run_id: RunId,
601 marker: RunInterrupt,
602 request_payload_digest: Digest,
603 action_digest: Digest,
604 required_principal: Option<PrincipalIdentity>,
605 required_scopes: ScopeSet,
606 intent_digest: Digest,
607 journal: JournalHead,
608 digest: Digest,
609 }
610
611 let wire = Wire::deserialize(deserializer)?;
612 Self::restore(
613 wire.tenant_id,
614 wire.run_id,
615 wire.marker,
616 wire.request_payload_digest,
617 wire.action_digest,
618 wire.required_principal,
619 wire.required_scopes,
620 wire.intent_digest,
621 wire.journal,
622 wire.digest,
623 )
624 .map_err(de::Error::custom)
625 }
626}
627
628#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
634#[serde(deny_unknown_fields)]
635pub struct InterruptResolver {
636 principal: PrincipalIdentity,
637 granted_scopes: ScopeSet,
638}
639
640impl InterruptResolver {
641 #[must_use]
643 pub const fn new(principal: PrincipalIdentity, granted_scopes: ScopeSet) -> Self {
644 Self {
645 principal,
646 granted_scopes,
647 }
648 }
649
650 #[must_use]
652 pub const fn principal(&self) -> &PrincipalIdentity {
653 &self.principal
654 }
655
656 #[must_use]
658 pub const fn granted_scopes(&self) -> &ScopeSet {
659 &self.granted_scopes
660 }
661}
662
663#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
665#[serde(deny_unknown_fields)]
666pub struct InterruptResolutionIntent {
667 request: InterruptRequestHead,
668 resolution_event_id: EventId,
669 resolution_payload: JournalPayload,
670 resolver: InterruptResolver,
671 intent_digest: Digest,
672}
673
674impl InterruptResolutionIntent {
675 pub fn new(
685 request: &InterruptRequest,
686 resolution_event_id: EventId,
687 resolution_payload: JournalPayload,
688 resolver: InterruptResolver,
689 ) -> Result<Self, DurableWaitError> {
690 let request = request.head();
691 authorize_resolver(&request, &resolver)?;
692 Self::from_head(request, resolution_event_id, resolution_payload, resolver)
693 }
694
695 fn from_head(
696 request: InterruptRequestHead,
697 resolution_event_id: EventId,
698 resolution_payload: JournalPayload,
699 resolver: InterruptResolver,
700 ) -> Result<Self, DurableWaitError> {
701 authorize_resolver(&request, &resolver)?;
702 let intent_digest = compute_digest(
703 INTERRUPT_RESOLUTION_INTENT_DIGEST_DOMAIN,
704 &InterruptResolutionIntentDigestWire {
705 request: &request,
706 resolution_event_id,
707 resolution_payload_digest: resolution_payload.digest(),
708 resolver: &resolver,
709 },
710 )?;
711 Ok(Self {
712 request,
713 resolution_event_id,
714 resolution_payload,
715 resolver,
716 intent_digest,
717 })
718 }
719
720 pub fn restore(
726 request: InterruptRequestHead,
727 resolution_event_id: EventId,
728 resolution_payload: JournalPayload,
729 resolver: InterruptResolver,
730 intent_digest: Digest,
731 ) -> Result<Self, DurableWaitError> {
732 let restored = Self::from_head(request, resolution_event_id, resolution_payload, resolver)?;
733 if restored.intent_digest != intent_digest {
734 return Err(DurableWaitError::IntentDigestMismatch);
735 }
736 Ok(restored)
737 }
738
739 #[must_use]
741 pub const fn request(&self) -> &InterruptRequestHead {
742 &self.request
743 }
744
745 #[must_use]
747 pub const fn resolution_event_id(&self) -> EventId {
748 self.resolution_event_id
749 }
750
751 #[must_use]
753 pub const fn resolution_payload(&self) -> &JournalPayload {
754 &self.resolution_payload
755 }
756
757 #[must_use]
759 pub const fn resolver(&self) -> &InterruptResolver {
760 &self.resolver
761 }
762
763 #[must_use]
765 pub const fn intent_digest(&self) -> Digest {
766 self.intent_digest
767 }
768}
769
770impl fmt::Debug for InterruptResolutionIntent {
771 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
772 formatter
773 .debug_struct("InterruptResolutionIntent")
774 .field("request", &self.request)
775 .field("resolution_event_id", &self.resolution_event_id)
776 .field("resolution_payload", &self.resolution_payload)
777 .field("resolver", &self.resolver)
778 .field("intent_digest", &self.intent_digest)
779 .finish_non_exhaustive()
780 }
781}
782
783impl<'de> Deserialize<'de> for InterruptResolutionIntent {
784 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
785 where
786 D: Deserializer<'de>,
787 {
788 #[derive(Deserialize)]
789 #[serde(deny_unknown_fields)]
790 struct Wire {
791 request: InterruptRequestHead,
792 resolution_event_id: EventId,
793 resolution_payload: JournalPayload,
794 resolver: InterruptResolver,
795 intent_digest: Digest,
796 }
797
798 let wire = Wire::deserialize(deserializer)?;
799 Self::restore(
800 wire.request,
801 wire.resolution_event_id,
802 wire.resolution_payload,
803 wire.resolver,
804 wire.intent_digest,
805 )
806 .map_err(de::Error::custom)
807 }
808}
809
810#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
812#[serde(deny_unknown_fields)]
813pub struct InterruptResolution {
814 intent: InterruptResolutionIntent,
815 journal: JournalHead,
816 digest: Digest,
817}
818
819impl InterruptResolution {
820 pub fn commit(
829 intent: InterruptResolutionIntent,
830 journal: JournalHead,
831 ) -> Result<Self, DurableWaitError> {
832 validate_journal_scope(
833 intent.request.tenant_id(),
834 intent.request.run_id(),
835 intent.resolution_event_id(),
836 &journal,
837 )?;
838 validate_terminal_causality(intent.request.journal(), &journal)?;
839 authorize_resolver(&intent.request, &intent.resolver)?;
840 if journal.recorded_at() < intent.request.marker.requested_at() {
841 return Err(DurableWaitError::ResolutionBeforeRegistration);
842 }
843 if let Some(expires_at) = intent.request.marker.expires_at() {
844 if journal.recorded_at() >= expires_at {
845 return Err(DurableWaitError::InterruptExpired);
846 }
847 }
848 let digest = compute_digest(
849 INTERRUPT_RESOLUTION_DIGEST_DOMAIN,
850 &TerminalDigestWire {
851 intent_digest: intent.intent_digest,
852 journal: &journal,
853 },
854 )?;
855 Ok(Self {
856 intent,
857 journal,
858 digest,
859 })
860 }
861
862 pub fn restore(
868 intent: InterruptResolutionIntent,
869 journal: JournalHead,
870 digest: Digest,
871 ) -> Result<Self, DurableWaitError> {
872 let restored = Self::commit(intent, journal)?;
873 if restored.digest != digest {
874 return Err(DurableWaitError::RecordDigestMismatch);
875 }
876 Ok(restored)
877 }
878
879 #[must_use]
881 pub const fn intent(&self) -> &InterruptResolutionIntent {
882 &self.intent
883 }
884
885 #[must_use]
887 pub const fn journal(&self) -> &JournalHead {
888 &self.journal
889 }
890
891 #[must_use]
893 pub const fn resolved_at(&self) -> Timestamp {
894 self.journal.recorded_at()
895 }
896
897 #[must_use]
899 pub const fn digest(&self) -> Digest {
900 self.digest
901 }
902}
903
904impl fmt::Debug for InterruptResolution {
905 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
906 formatter
907 .debug_struct("InterruptResolution")
908 .field("intent", &self.intent)
909 .field("journal", &self.journal)
910 .field("digest", &self.digest)
911 .finish_non_exhaustive()
912 }
913}
914
915impl<'de> Deserialize<'de> for InterruptResolution {
916 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
917 where
918 D: Deserializer<'de>,
919 {
920 #[derive(Deserialize)]
921 #[serde(deny_unknown_fields)]
922 struct Wire {
923 intent: InterruptResolutionIntent,
924 journal: JournalHead,
925 digest: Digest,
926 }
927
928 let wire = Wire::deserialize(deserializer)?;
929 Self::restore(wire.intent, wire.journal, wire.digest).map_err(de::Error::custom)
930 }
931}
932
933#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
935#[serde(deny_unknown_fields)]
936pub struct InterruptRecord {
937 request: InterruptRequest,
938 #[serde(skip_serializing_if = "Option::is_none")]
939 resolution: Option<InterruptResolution>,
940}
941
942impl InterruptRecord {
943 #[must_use]
945 pub const fn unresolved(request: InterruptRequest) -> Self {
946 Self {
947 request,
948 resolution: None,
949 }
950 }
951
952 pub fn restore(
959 request: InterruptRequest,
960 resolution: Option<InterruptResolution>,
961 ) -> Result<Self, DurableWaitError> {
962 if resolution
963 .as_ref()
964 .is_some_and(|value| value.intent.request != request.head())
965 {
966 return Err(DurableWaitError::InterruptRequestMismatch);
967 }
968 Ok(Self {
969 request,
970 resolution,
971 })
972 }
973
974 #[must_use]
976 pub const fn request(&self) -> &InterruptRequest {
977 &self.request
978 }
979
980 #[must_use]
982 pub const fn resolution(&self) -> Option<&InterruptResolution> {
983 self.resolution.as_ref()
984 }
985
986 #[must_use]
988 pub const fn is_outstanding(&self) -> bool {
989 self.resolution.is_none()
990 }
991}
992
993impl<'de> Deserialize<'de> for InterruptRecord {
994 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
995 where
996 D: Deserializer<'de>,
997 {
998 #[derive(Deserialize)]
999 #[serde(deny_unknown_fields)]
1000 struct Wire {
1001 request: InterruptRequest,
1002 resolution: Option<InterruptResolution>,
1003 }
1004
1005 let wire = Wire::deserialize(deserializer)?;
1006 Self::restore(wire.request, wire.resolution).map_err(de::Error::custom)
1007 }
1008}
1009
1010#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
1012#[serde(deny_unknown_fields)]
1013pub struct TimerRegistrationIntent {
1014 tenant_id: TenantId,
1015 run_id: RunId,
1016 timer_id: TimerId,
1017 registration_event_id: EventId,
1018 kind: RunTimerKind,
1019 due_at: Timestamp,
1020 intent_digest: Digest,
1021}
1022
1023impl TimerRegistrationIntent {
1024 pub fn new(
1034 tenant_id: TenantId,
1035 run_id: RunId,
1036 timer_id: TimerId,
1037 registration_event_id: EventId,
1038 kind: RunTimerKind,
1039 due_at: Timestamp,
1040 ) -> Result<Self, DurableWaitError> {
1041 let intent_digest = compute_digest(
1042 TIMER_INTENT_DIGEST_DOMAIN,
1043 &TimerIntentDigestWire {
1044 tenant_id: &tenant_id,
1045 run_id,
1046 timer_id,
1047 registration_event_id,
1048 kind,
1049 due_at,
1050 },
1051 )?;
1052 Ok(Self {
1053 tenant_id,
1054 run_id,
1055 timer_id,
1056 registration_event_id,
1057 kind,
1058 due_at,
1059 intent_digest,
1060 })
1061 }
1062
1063 #[allow(clippy::too_many_arguments)]
1069 pub fn restore(
1070 tenant_id: TenantId,
1071 run_id: RunId,
1072 timer_id: TimerId,
1073 registration_event_id: EventId,
1074 kind: RunTimerKind,
1075 due_at: Timestamp,
1076 intent_digest: Digest,
1077 ) -> Result<Self, DurableWaitError> {
1078 let restored = Self::new(
1079 tenant_id,
1080 run_id,
1081 timer_id,
1082 registration_event_id,
1083 kind,
1084 due_at,
1085 )?;
1086 if restored.intent_digest != intent_digest {
1087 return Err(DurableWaitError::IntentDigestMismatch);
1088 }
1089 Ok(restored)
1090 }
1091
1092 #[must_use]
1094 pub const fn tenant_id(&self) -> &TenantId {
1095 &self.tenant_id
1096 }
1097
1098 #[must_use]
1100 pub const fn run_id(&self) -> RunId {
1101 self.run_id
1102 }
1103
1104 #[must_use]
1106 pub const fn timer_id(&self) -> TimerId {
1107 self.timer_id
1108 }
1109
1110 #[must_use]
1112 pub const fn registration_event_id(&self) -> EventId {
1113 self.registration_event_id
1114 }
1115
1116 #[must_use]
1118 pub const fn kind(&self) -> RunTimerKind {
1119 self.kind
1120 }
1121
1122 #[must_use]
1124 pub const fn due_at(&self) -> Timestamp {
1125 self.due_at
1126 }
1127
1128 #[must_use]
1130 pub const fn intent_digest(&self) -> Digest {
1131 self.intent_digest
1132 }
1133}
1134
1135impl fmt::Debug for TimerRegistrationIntent {
1136 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1137 formatter
1138 .debug_struct("TimerRegistrationIntent")
1139 .field("tenant_id", &self.tenant_id)
1140 .field("run_id", &self.run_id)
1141 .field("timer_id", &self.timer_id)
1142 .field("registration_event_id", &self.registration_event_id)
1143 .field("kind", &self.kind)
1144 .field("due_at", &self.due_at)
1145 .field("intent_digest", &self.intent_digest)
1146 .finish_non_exhaustive()
1147 }
1148}
1149
1150impl<'de> Deserialize<'de> for TimerRegistrationIntent {
1151 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1152 where
1153 D: Deserializer<'de>,
1154 {
1155 #[derive(Deserialize)]
1156 #[serde(deny_unknown_fields)]
1157 struct Wire {
1158 tenant_id: TenantId,
1159 run_id: RunId,
1160 timer_id: TimerId,
1161 registration_event_id: EventId,
1162 kind: RunTimerKind,
1163 due_at: Timestamp,
1164 intent_digest: Digest,
1165 }
1166
1167 let wire = Wire::deserialize(deserializer)?;
1168 Self::restore(
1169 wire.tenant_id,
1170 wire.run_id,
1171 wire.timer_id,
1172 wire.registration_event_id,
1173 wire.kind,
1174 wire.due_at,
1175 wire.intent_digest,
1176 )
1177 .map_err(de::Error::custom)
1178 }
1179}
1180
1181#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
1183#[serde(deny_unknown_fields)]
1184pub struct DurableTimer {
1185 intent: TimerRegistrationIntent,
1186 marker: RunTimer,
1187 journal: JournalHead,
1188 digest: Digest,
1189}
1190
1191impl DurableTimer {
1192 pub fn commit(
1199 intent: TimerRegistrationIntent,
1200 journal: JournalHead,
1201 ) -> Result<Self, DurableWaitError> {
1202 validate_journal_scope(
1203 intent.tenant_id(),
1204 intent.run_id(),
1205 intent.registration_event_id(),
1206 &journal,
1207 )?;
1208 let marker = RunTimer::new(
1209 intent.timer_id(),
1210 intent.kind(),
1211 journal.recorded_at(),
1212 intent.due_at(),
1213 )
1214 .map_err(|_| DurableWaitError::TimerDueNotAfterRegistration)?;
1215 let digest = compute_digest(
1216 TIMER_DIGEST_DOMAIN,
1217 &TimerDigestWire {
1218 intent_digest: intent.intent_digest,
1219 marker: &marker,
1220 journal: &journal,
1221 },
1222 )?;
1223 Ok(Self {
1224 intent,
1225 marker,
1226 journal,
1227 digest,
1228 })
1229 }
1230
1231 pub fn restore(
1237 intent: TimerRegistrationIntent,
1238 marker: &RunTimer,
1239 journal: JournalHead,
1240 digest: Digest,
1241 ) -> Result<Self, DurableWaitError> {
1242 let restored = Self::commit(intent, journal)?;
1243 if &restored.marker != marker {
1244 return Err(DurableWaitError::LifecycleMarkerMismatch);
1245 }
1246 if restored.digest != digest {
1247 return Err(DurableWaitError::RecordDigestMismatch);
1248 }
1249 Ok(restored)
1250 }
1251
1252 #[must_use]
1254 pub const fn intent(&self) -> &TimerRegistrationIntent {
1255 &self.intent
1256 }
1257
1258 #[must_use]
1260 pub const fn marker(&self) -> &RunTimer {
1261 &self.marker
1262 }
1263
1264 #[must_use]
1266 pub const fn journal(&self) -> &JournalHead {
1267 &self.journal
1268 }
1269
1270 #[must_use]
1272 pub const fn digest(&self) -> Digest {
1273 self.digest
1274 }
1275
1276 #[must_use]
1278 pub fn head(&self) -> DurableTimerHead {
1279 DurableTimerHead {
1280 tenant_id: self.intent.tenant_id.clone(),
1281 run_id: self.intent.run_id,
1282 marker: self.marker.clone(),
1283 intent_digest: self.intent.intent_digest,
1284 journal: self.journal.clone(),
1285 digest: self.digest,
1286 }
1287 }
1288}
1289
1290impl fmt::Debug for DurableTimer {
1291 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1292 formatter
1293 .debug_struct("DurableTimer")
1294 .field("intent", &self.intent)
1295 .field("marker", &self.marker)
1296 .field("journal", &self.journal)
1297 .field("digest", &self.digest)
1298 .finish_non_exhaustive()
1299 }
1300}
1301
1302impl<'de> Deserialize<'de> for DurableTimer {
1303 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1304 where
1305 D: Deserializer<'de>,
1306 {
1307 #[derive(Deserialize)]
1308 #[serde(deny_unknown_fields)]
1309 struct Wire {
1310 intent: TimerRegistrationIntent,
1311 marker: RunTimer,
1312 journal: JournalHead,
1313 digest: Digest,
1314 }
1315
1316 let wire = Wire::deserialize(deserializer)?;
1317 Self::restore(wire.intent, &wire.marker, wire.journal, wire.digest)
1318 .map_err(de::Error::custom)
1319 }
1320}
1321
1322#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
1324#[serde(deny_unknown_fields)]
1325pub struct DurableTimerHead {
1326 tenant_id: TenantId,
1327 run_id: RunId,
1328 marker: RunTimer,
1329 intent_digest: Digest,
1330 journal: JournalHead,
1331 digest: Digest,
1332}
1333
1334impl DurableTimerHead {
1335 pub fn restore(
1341 tenant_id: TenantId,
1342 run_id: RunId,
1343 marker: RunTimer,
1344 intent_digest: Digest,
1345 journal: JournalHead,
1346 digest: Digest,
1347 ) -> Result<Self, DurableWaitError> {
1348 if journal.tenant_id() != &tenant_id {
1349 return Err(DurableWaitError::JournalTenantMismatch);
1350 }
1351 if journal.run_id() != run_id {
1352 return Err(DurableWaitError::JournalRunMismatch);
1353 }
1354 if journal.recorded_at() != marker.scheduled_at() {
1355 return Err(DurableWaitError::LifecycleMarkerMismatch);
1356 }
1357 if marker.due_at() <= marker.scheduled_at() {
1358 return Err(DurableWaitError::TimerDueNotAfterRegistration);
1359 }
1360 let expected_intent = compute_digest(
1361 TIMER_INTENT_DIGEST_DOMAIN,
1362 &TimerIntentDigestWire {
1363 tenant_id: &tenant_id,
1364 run_id,
1365 timer_id: marker.timer_id(),
1366 registration_event_id: journal.event_id(),
1367 kind: marker.kind(),
1368 due_at: marker.due_at(),
1369 },
1370 )?;
1371 if expected_intent != intent_digest {
1372 return Err(DurableWaitError::IntentDigestMismatch);
1373 }
1374 let expected = compute_digest(
1375 TIMER_DIGEST_DOMAIN,
1376 &TimerDigestWire {
1377 intent_digest,
1378 marker: &marker,
1379 journal: &journal,
1380 },
1381 )?;
1382 if expected != digest {
1383 return Err(DurableWaitError::RecordDigestMismatch);
1384 }
1385 Ok(Self {
1386 tenant_id,
1387 run_id,
1388 marker,
1389 intent_digest,
1390 journal,
1391 digest,
1392 })
1393 }
1394
1395 #[must_use]
1397 pub const fn tenant_id(&self) -> &TenantId {
1398 &self.tenant_id
1399 }
1400
1401 #[must_use]
1403 pub const fn run_id(&self) -> RunId {
1404 self.run_id
1405 }
1406
1407 #[must_use]
1409 pub const fn marker(&self) -> &RunTimer {
1410 &self.marker
1411 }
1412
1413 #[must_use]
1415 pub const fn timer_id(&self) -> TimerId {
1416 self.marker.timer_id()
1417 }
1418
1419 #[must_use]
1421 pub const fn intent_digest(&self) -> Digest {
1422 self.intent_digest
1423 }
1424
1425 #[must_use]
1427 pub const fn journal(&self) -> &JournalHead {
1428 &self.journal
1429 }
1430
1431 #[must_use]
1433 pub const fn digest(&self) -> Digest {
1434 self.digest
1435 }
1436}
1437
1438impl<'de> Deserialize<'de> for DurableTimerHead {
1439 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1440 where
1441 D: Deserializer<'de>,
1442 {
1443 #[derive(Deserialize)]
1444 #[serde(deny_unknown_fields)]
1445 struct Wire {
1446 tenant_id: TenantId,
1447 run_id: RunId,
1448 marker: RunTimer,
1449 intent_digest: Digest,
1450 journal: JournalHead,
1451 digest: Digest,
1452 }
1453
1454 let wire = Wire::deserialize(deserializer)?;
1455 Self::restore(
1456 wire.tenant_id,
1457 wire.run_id,
1458 wire.marker,
1459 wire.intent_digest,
1460 wire.journal,
1461 wire.digest,
1462 )
1463 .map_err(de::Error::custom)
1464 }
1465}
1466
1467#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
1469#[serde(deny_unknown_fields)]
1470pub struct TimerFiringIntent {
1471 timer: DurableTimerHead,
1472 firing_event_id: EventId,
1473 intent_digest: Digest,
1474}
1475
1476impl TimerFiringIntent {
1477 pub fn new(timer: &DurableTimer, firing_event_id: EventId) -> Result<Self, DurableWaitError> {
1484 Self::from_head(timer.head(), firing_event_id)
1485 }
1486
1487 fn from_head(
1488 timer: DurableTimerHead,
1489 firing_event_id: EventId,
1490 ) -> Result<Self, DurableWaitError> {
1491 let intent_digest = compute_digest(
1492 TIMER_FIRING_INTENT_DIGEST_DOMAIN,
1493 &TimerFiringIntentDigestWire {
1494 timer: &timer,
1495 firing_event_id,
1496 },
1497 )?;
1498 Ok(Self {
1499 timer,
1500 firing_event_id,
1501 intent_digest,
1502 })
1503 }
1504
1505 pub fn restore(
1511 timer: DurableTimerHead,
1512 firing_event_id: EventId,
1513 intent_digest: Digest,
1514 ) -> Result<Self, DurableWaitError> {
1515 let restored = Self::from_head(timer, firing_event_id)?;
1516 if restored.intent_digest != intent_digest {
1517 return Err(DurableWaitError::IntentDigestMismatch);
1518 }
1519 Ok(restored)
1520 }
1521
1522 #[must_use]
1524 pub const fn timer(&self) -> &DurableTimerHead {
1525 &self.timer
1526 }
1527
1528 #[must_use]
1530 pub const fn firing_event_id(&self) -> EventId {
1531 self.firing_event_id
1532 }
1533
1534 #[must_use]
1536 pub const fn intent_digest(&self) -> Digest {
1537 self.intent_digest
1538 }
1539}
1540
1541impl<'de> Deserialize<'de> for TimerFiringIntent {
1542 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1543 where
1544 D: Deserializer<'de>,
1545 {
1546 #[derive(Deserialize)]
1547 #[serde(deny_unknown_fields)]
1548 struct Wire {
1549 timer: DurableTimerHead,
1550 firing_event_id: EventId,
1551 intent_digest: Digest,
1552 }
1553
1554 let wire = Wire::deserialize(deserializer)?;
1555 Self::restore(wire.timer, wire.firing_event_id, wire.intent_digest)
1556 .map_err(de::Error::custom)
1557 }
1558}
1559
1560#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
1562#[serde(deny_unknown_fields)]
1563pub struct TimerFiring {
1564 intent: TimerFiringIntent,
1565 journal: JournalHead,
1566 digest: Digest,
1567}
1568
1569impl TimerFiring {
1570 pub fn commit(
1577 intent: TimerFiringIntent,
1578 journal: JournalHead,
1579 ) -> Result<Self, DurableWaitError> {
1580 validate_journal_scope(
1581 intent.timer.tenant_id(),
1582 intent.timer.run_id(),
1583 intent.firing_event_id(),
1584 &journal,
1585 )?;
1586 validate_terminal_causality(intent.timer.journal(), &journal)?;
1587 if journal.recorded_at() < intent.timer.marker.due_at() {
1588 return Err(DurableWaitError::TimerNotDue);
1589 }
1590 let digest = compute_digest(
1591 TIMER_FIRING_DIGEST_DOMAIN,
1592 &TerminalDigestWire {
1593 intent_digest: intent.intent_digest,
1594 journal: &journal,
1595 },
1596 )?;
1597 Ok(Self {
1598 intent,
1599 journal,
1600 digest,
1601 })
1602 }
1603
1604 pub fn restore(
1610 intent: TimerFiringIntent,
1611 journal: JournalHead,
1612 digest: Digest,
1613 ) -> Result<Self, DurableWaitError> {
1614 let restored = Self::commit(intent, journal)?;
1615 if restored.digest != digest {
1616 return Err(DurableWaitError::RecordDigestMismatch);
1617 }
1618 Ok(restored)
1619 }
1620
1621 #[must_use]
1623 pub const fn intent(&self) -> &TimerFiringIntent {
1624 &self.intent
1625 }
1626
1627 #[must_use]
1629 pub const fn journal(&self) -> &JournalHead {
1630 &self.journal
1631 }
1632
1633 #[must_use]
1635 pub const fn fired_at(&self) -> Timestamp {
1636 self.journal.recorded_at()
1637 }
1638
1639 #[must_use]
1641 pub const fn digest(&self) -> Digest {
1642 self.digest
1643 }
1644}
1645
1646impl<'de> Deserialize<'de> for TimerFiring {
1647 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1648 where
1649 D: Deserializer<'de>,
1650 {
1651 #[derive(Deserialize)]
1652 #[serde(deny_unknown_fields)]
1653 struct Wire {
1654 intent: TimerFiringIntent,
1655 journal: JournalHead,
1656 digest: Digest,
1657 }
1658
1659 let wire = Wire::deserialize(deserializer)?;
1660 Self::restore(wire.intent, wire.journal, wire.digest).map_err(de::Error::custom)
1661 }
1662}
1663
1664#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
1666#[serde(deny_unknown_fields)]
1667pub struct DurableTimerRecord {
1668 timer: DurableTimer,
1669 #[serde(skip_serializing_if = "Option::is_none")]
1670 firing: Option<TimerFiring>,
1671}
1672
1673impl DurableTimerRecord {
1674 #[must_use]
1676 pub const fn pending(timer: DurableTimer) -> Self {
1677 Self {
1678 timer,
1679 firing: None,
1680 }
1681 }
1682
1683 pub fn restore(
1690 timer: DurableTimer,
1691 firing: Option<TimerFiring>,
1692 ) -> Result<Self, DurableWaitError> {
1693 if firing
1694 .as_ref()
1695 .is_some_and(|value| value.intent.timer != timer.head())
1696 {
1697 return Err(DurableWaitError::TimerRegistrationMismatch);
1698 }
1699 Ok(Self { timer, firing })
1700 }
1701
1702 #[must_use]
1704 pub const fn timer(&self) -> &DurableTimer {
1705 &self.timer
1706 }
1707
1708 #[must_use]
1710 pub const fn firing(&self) -> Option<&TimerFiring> {
1711 self.firing.as_ref()
1712 }
1713
1714 #[must_use]
1716 pub const fn is_pending(&self) -> bool {
1717 self.firing.is_none()
1718 }
1719}
1720
1721impl<'de> Deserialize<'de> for DurableTimerRecord {
1722 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1723 where
1724 D: Deserializer<'de>,
1725 {
1726 #[derive(Deserialize)]
1727 #[serde(deny_unknown_fields)]
1728 struct Wire {
1729 timer: DurableTimer,
1730 firing: Option<TimerFiring>,
1731 }
1732
1733 let wire = Wire::deserialize(deserializer)?;
1734 Self::restore(wire.timer, wire.firing).map_err(de::Error::custom)
1735 }
1736}
1737
1738#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
1740#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1741#[allow(clippy::large_enum_variant)]
1742pub enum WaitRegistrationIntent {
1743 Interrupt {
1745 request: InterruptRequestIntent,
1747 },
1748 Timer {
1750 timer: TimerRegistrationIntent,
1752 },
1753}
1754
1755impl WaitRegistrationIntent {
1756 #[must_use]
1758 pub const fn interrupt(request: InterruptRequestIntent) -> Self {
1759 Self::Interrupt { request }
1760 }
1761
1762 #[must_use]
1764 pub const fn timer(timer: TimerRegistrationIntent) -> Self {
1765 Self::Timer { timer }
1766 }
1767
1768 #[must_use]
1770 pub const fn tenant_id(&self) -> &TenantId {
1771 match self {
1772 Self::Interrupt { request } => request.tenant_id(),
1773 Self::Timer { timer } => timer.tenant_id(),
1774 }
1775 }
1776
1777 #[must_use]
1779 pub const fn run_id(&self) -> RunId {
1780 match self {
1781 Self::Interrupt { request } => request.run_id(),
1782 Self::Timer { timer } => timer.run_id(),
1783 }
1784 }
1785
1786 #[must_use]
1788 pub const fn registration_event_id(&self) -> EventId {
1789 match self {
1790 Self::Interrupt { request } => request.request_event_id(),
1791 Self::Timer { timer } => timer.registration_event_id(),
1792 }
1793 }
1794
1795 pub fn commit(self, journal: JournalHead) -> Result<DurableWait, DurableWaitError> {
1802 match self {
1803 Self::Interrupt { request } => {
1804 InterruptRequest::commit(request, journal).map(|request| DurableWait::Interrupt {
1805 request: Box::new(request),
1806 })
1807 }
1808 Self::Timer { timer } => {
1809 DurableTimer::commit(timer, journal).map(|timer| DurableWait::Timer {
1810 timer: Box::new(timer),
1811 })
1812 }
1813 }
1814 }
1815}
1816
1817#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
1819#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
1820pub enum DurableWait {
1821 Interrupt {
1823 request: Box<InterruptRequest>,
1825 },
1826 Timer {
1828 timer: Box<DurableTimer>,
1830 },
1831}
1832
1833impl DurableWait {
1834 #[must_use]
1836 pub const fn tenant_id(&self) -> &TenantId {
1837 match self {
1838 Self::Interrupt { request } => request.intent().tenant_id(),
1839 Self::Timer { timer } => timer.intent().tenant_id(),
1840 }
1841 }
1842
1843 #[must_use]
1845 pub const fn run_id(&self) -> RunId {
1846 match self {
1847 Self::Interrupt { request } => request.intent().run_id(),
1848 Self::Timer { timer } => timer.intent().run_id(),
1849 }
1850 }
1851
1852 #[must_use]
1854 pub const fn journal(&self) -> &JournalHead {
1855 match self {
1856 Self::Interrupt { request } => request.journal(),
1857 Self::Timer { timer } => timer.journal(),
1858 }
1859 }
1860
1861 #[must_use]
1863 pub fn marker(&self) -> crate::RunWait {
1864 match self {
1865 Self::Interrupt { request } => crate::RunWait::interrupt(request.marker().clone()),
1866 Self::Timer { timer } => crate::RunWait::timer(timer.marker().clone()),
1867 }
1868 }
1869}
1870
1871#[derive(Clone, Debug, Eq, Error, PartialEq)]
1873#[non_exhaustive]
1874pub enum DurableWaitError {
1875 #[error("durable wait canonical serialization failed")]
1877 CanonicalSerialization,
1878 #[error("durable wait intent digest does not match its canonical fields")]
1880 IntentDigestMismatch,
1881 #[error("durable wait record digest does not match its canonical fields")]
1883 RecordDigestMismatch,
1884 #[error("durable wait journal anchor crossed the tenant boundary")]
1886 JournalTenantMismatch,
1887 #[error("durable wait journal anchor belonged to another run")]
1889 JournalRunMismatch,
1890 #[error("durable wait journal event does not match the intent")]
1892 JournalEventMismatch,
1893 #[error("durable wait lifecycle marker does not match the durable record")]
1895 LifecycleMarkerMismatch,
1896 #[error("interrupt expiry must be later than its registration observation")]
1898 InterruptExpiryNotAfterRegistration,
1899 #[error("timer due instant must be later than its registration observation")]
1901 TimerDueNotAfterRegistration,
1902 #[error("interrupt resolution does not belong to the durable request")]
1904 InterruptRequestMismatch,
1905 #[error("timer firing does not belong to the durable timer")]
1907 TimerRegistrationMismatch,
1908 #[error("interrupt resolver principal does not satisfy the request")]
1910 ResolverPrincipalMismatch,
1911 #[error("interrupt resolver scopes do not satisfy the request")]
1913 ResolverScopesInsufficient,
1914 #[error("interrupt resolution preceded its registration observation")]
1916 ResolutionBeforeRegistration,
1917 #[error("interrupt resolution arrived outside its exclusive validity window")]
1919 InterruptExpired,
1920 #[error("timer firing preceded its inclusive due instant")]
1922 TimerNotDue,
1923 #[error("durable wait completion must follow its registration journal event")]
1925 TerminalJournalNotAfterRegistration,
1926}
1927
1928#[derive(Serialize)]
1929struct InterruptIntentDigestWire<'a> {
1930 tenant_id: &'a TenantId,
1931 run_id: RunId,
1932 interrupt_id: InterruptId,
1933 request_event_id: EventId,
1934 kind: RunInterruptKind,
1935 request_payload_digest: Digest,
1936 action_digest: Digest,
1937 required_principal: Option<&'a PrincipalIdentity>,
1938 required_scopes: &'a ScopeSet,
1939 expires_at: Option<Timestamp>,
1940}
1941
1942#[derive(Serialize)]
1943struct InterruptRequestDigestWire<'a> {
1944 intent_digest: Digest,
1945 marker: &'a RunInterrupt,
1946 journal: &'a JournalHead,
1947}
1948
1949#[derive(Serialize)]
1950struct InterruptResolutionIntentDigestWire<'a> {
1951 request: &'a InterruptRequestHead,
1952 resolution_event_id: EventId,
1953 resolution_payload_digest: Digest,
1954 resolver: &'a InterruptResolver,
1955}
1956
1957#[derive(Serialize)]
1958struct TimerIntentDigestWire<'a> {
1959 tenant_id: &'a TenantId,
1960 run_id: RunId,
1961 timer_id: TimerId,
1962 registration_event_id: EventId,
1963 kind: RunTimerKind,
1964 due_at: Timestamp,
1965}
1966
1967#[derive(Serialize)]
1968struct TimerDigestWire<'a> {
1969 intent_digest: Digest,
1970 marker: &'a RunTimer,
1971 journal: &'a JournalHead,
1972}
1973
1974#[derive(Serialize)]
1975struct TimerFiringIntentDigestWire<'a> {
1976 timer: &'a DurableTimerHead,
1977 firing_event_id: EventId,
1978}
1979
1980#[derive(Serialize)]
1981struct TerminalDigestWire<'a> {
1982 intent_digest: Digest,
1983 journal: &'a JournalHead,
1984}
1985
1986fn compute_interrupt_request_digest(
1987 intent: &InterruptRequestIntent,
1988 marker: &RunInterrupt,
1989 journal: &JournalHead,
1990) -> Result<Digest, DurableWaitError> {
1991 compute_digest(
1992 INTERRUPT_REQUEST_DIGEST_DOMAIN,
1993 &InterruptRequestDigestWire {
1994 intent_digest: intent.intent_digest,
1995 marker,
1996 journal,
1997 },
1998 )
1999}
2000
2001fn compute_digest<T: Serialize>(domain: &[u8], value: &T) -> Result<Digest, DurableWaitError> {
2002 let canonical = serde_json_canonicalizer::to_vec(value)
2003 .map_err(|_| DurableWaitError::CanonicalSerialization)?;
2004 let mut preimage = Vec::with_capacity(domain.len() + canonical.len());
2005 preimage.extend_from_slice(domain);
2006 preimage.extend_from_slice(&canonical);
2007 Ok(Digest::sha256(preimage))
2008}
2009
2010fn validate_journal_scope(
2011 tenant_id: &TenantId,
2012 run_id: RunId,
2013 event_id: EventId,
2014 journal: &JournalHead,
2015) -> Result<(), DurableWaitError> {
2016 if journal.tenant_id() != tenant_id {
2017 return Err(DurableWaitError::JournalTenantMismatch);
2018 }
2019 if journal.run_id() != run_id {
2020 return Err(DurableWaitError::JournalRunMismatch);
2021 }
2022 if journal.event_id() != event_id {
2023 return Err(DurableWaitError::JournalEventMismatch);
2024 }
2025 Ok(())
2026}
2027
2028fn authorize_resolver(
2029 request: &InterruptRequestHead,
2030 resolver: &InterruptResolver,
2031) -> Result<(), DurableWaitError> {
2032 if request
2033 .required_principal()
2034 .is_some_and(|required| required != resolver.principal())
2035 {
2036 return Err(DurableWaitError::ResolverPrincipalMismatch);
2037 }
2038 if !request
2039 .required_scopes()
2040 .is_subset(resolver.granted_scopes())
2041 {
2042 return Err(DurableWaitError::ResolverScopesInsufficient);
2043 }
2044 Ok(())
2045}
2046
2047fn validate_terminal_causality(
2048 registration: &JournalHead,
2049 terminal: &JournalHead,
2050) -> Result<(), DurableWaitError> {
2051 if terminal.sequence().get() <= registration.sequence().get()
2052 || terminal.event_id() == registration.event_id()
2053 {
2054 return Err(DurableWaitError::TerminalJournalNotAfterRegistration);
2055 }
2056 Ok(())
2057}
2058
2059#[cfg(test)]
2060mod tests {
2061 use proptest::prelude::*;
2062 use serde_json::{from_value, json, to_value};
2063
2064 use super::*;
2065 use crate::{
2066 BoundedJson, IssuerId, JournalEventKind, JournalSequence, SchemaId, SchemaReference, Scope,
2067 SubjectId, Version,
2068 };
2069
2070 fn id<T: std::str::FromStr>(suffix: u8) -> T
2071 where
2072 T::Err: fmt::Debug,
2073 {
2074 format!("01912345-6789-7abc-8def-0123456789{suffix:02x}")
2075 .parse()
2076 .unwrap()
2077 }
2078
2079 fn at(seconds: i64) -> Timestamp {
2080 Timestamp::from_unix_micros(1_893_456_000_000_000 + seconds * 1_000_000).unwrap()
2081 }
2082
2083 fn payload(kind: &str, secret: &str) -> JournalPayload {
2084 JournalPayload::new(
2085 SchemaReference::new(
2086 format!("https://stateknot.github.io/schema/wait/{kind}/1.0.0")
2087 .parse::<SchemaId>()
2088 .unwrap(),
2089 Version::new(1, 0, 0),
2090 Digest::sha256(format!("{kind}-schema")),
2091 ),
2092 JournalEventKind::new(kind).unwrap(),
2093 BoundedJson::try_from_value(json!({"secret": secret})).unwrap(),
2094 )
2095 .unwrap()
2096 }
2097
2098 fn principal(subject: &str) -> PrincipalIdentity {
2099 PrincipalIdentity::new(
2100 "https://issuer.example.com/tenant"
2101 .parse::<IssuerId>()
2102 .unwrap(),
2103 subject.parse::<SubjectId>().unwrap(),
2104 )
2105 }
2106
2107 fn scopes(values: &[&str]) -> ScopeSet {
2108 ScopeSet::try_new(values.iter().map(|value| value.parse::<Scope>().unwrap())).unwrap()
2109 }
2110
2111 fn head(
2112 tenant_id: TenantId,
2113 run_id: RunId,
2114 event_id: EventId,
2115 sequence: u64,
2116 recorded_at: Timestamp,
2117 ) -> JournalHead {
2118 JournalHead::new(
2119 tenant_id,
2120 run_id,
2121 JournalSequence::new(sequence).unwrap(),
2122 event_id,
2123 recorded_at,
2124 Digest::sha256(format!("event-{sequence}")),
2125 )
2126 }
2127
2128 fn request(expires_at: Option<Timestamp>) -> InterruptRequest {
2129 let tenant_id = TenantId::new("tenant-wait").unwrap();
2130 let run_id = id::<RunId>(0x10);
2131 let event_id = id::<EventId>(0x12);
2132 let intent = InterruptRequestIntent::new(
2133 tenant_id.clone(),
2134 run_id,
2135 id::<InterruptId>(0x11),
2136 event_id,
2137 RunInterruptKind::Approval,
2138 payload("approval-request", "request-secret"),
2139 Digest::sha256(b"bound-action"),
2140 Some(principal("approver")),
2141 scopes(&["agent.approve", "run.resolve"]),
2142 expires_at,
2143 )
2144 .unwrap();
2145 InterruptRequest::commit(intent, head(tenant_id, run_id, event_id, 7, at(0))).unwrap()
2146 }
2147
2148 fn resolution(
2149 request: &InterruptRequest,
2150 resolved_at: Timestamp,
2151 ) -> Result<InterruptResolution, DurableWaitError> {
2152 let event_id = id::<EventId>(0x13);
2153 let intent = InterruptResolutionIntent::new(
2154 request,
2155 event_id,
2156 payload("approval-resolution", "resolution-secret"),
2157 InterruptResolver::new(
2158 principal("approver"),
2159 scopes(&["agent.approve", "run.resolve", "audit.read"]),
2160 ),
2161 )?;
2162 InterruptResolution::commit(
2163 intent,
2164 head(
2165 request.intent().tenant_id().clone(),
2166 request.intent().run_id(),
2167 event_id,
2168 8,
2169 resolved_at,
2170 ),
2171 )
2172 }
2173
2174 fn timer() -> DurableTimer {
2175 let tenant_id = TenantId::new("tenant-wait").unwrap();
2176 let run_id = id::<RunId>(0x10);
2177 let event_id = id::<EventId>(0x20);
2178 let intent = TimerRegistrationIntent::new(
2179 tenant_id.clone(),
2180 run_id,
2181 id::<TimerId>(0x21),
2182 event_id,
2183 RunTimerKind::RetryBackoff,
2184 at(5),
2185 )
2186 .unwrap();
2187 DurableTimer::commit(intent, head(tenant_id, run_id, event_id, 9, at(0))).unwrap()
2188 }
2189
2190 #[test]
2191 fn interrupt_authorization_timing_history_and_redaction_are_exact() {
2192 let request = request(Some(at(10)));
2193 let committed_resolution = resolution(&request, at(5)).unwrap();
2194 let record =
2195 InterruptRecord::restore(request.clone(), Some(committed_resolution.clone())).unwrap();
2196 assert!(!record.is_outstanding());
2197 assert_eq!(record.resolution().unwrap().resolved_at(), at(5));
2198 assert_eq!(record.request().marker().requested_at(), at(0));
2199
2200 let wire = to_value(&record).unwrap();
2201 assert_eq!(from_value::<InterruptRecord>(wire).unwrap(), record);
2202 let debug = format!("{record:?}");
2203 assert!(!debug.contains("request-secret"));
2204 assert!(!debug.contains("resolution-secret"));
2205 assert!(!debug.contains("approver"));
2206
2207 assert_eq!(
2208 resolution(&request, at(10)),
2209 Err(DurableWaitError::InterruptExpired)
2210 );
2211 assert_eq!(
2212 resolution(&request, at(-1)),
2213 Err(DurableWaitError::ResolutionBeforeRegistration)
2214 );
2215 }
2216
2217 #[test]
2218 fn interrupt_resolution_requires_exact_principal_and_scope_subset() {
2219 let request = request(None);
2220 let wrong_principal = InterruptResolutionIntent::new(
2221 &request,
2222 id::<EventId>(0x30),
2223 payload("approval-resolution", "safe"),
2224 InterruptResolver::new(
2225 principal("other"),
2226 scopes(&["agent.approve", "run.resolve"]),
2227 ),
2228 );
2229 assert_eq!(
2230 wrong_principal,
2231 Err(DurableWaitError::ResolverPrincipalMismatch)
2232 );
2233
2234 let missing_scope = InterruptResolutionIntent::new(
2235 &request,
2236 id::<EventId>(0x31),
2237 payload("approval-resolution", "safe"),
2238 InterruptResolver::new(principal("approver"), scopes(&["agent.approve"])),
2239 );
2240 assert_eq!(
2241 missing_scope,
2242 Err(DurableWaitError::ResolverScopesInsufficient)
2243 );
2244 }
2245
2246 #[test]
2247 fn timer_firing_uses_an_inclusive_due_boundary_and_exact_history() {
2248 let timer = timer();
2249 let firing_event_id = id::<EventId>(0x22);
2250 let early_intent = TimerFiringIntent::new(&timer, firing_event_id).unwrap();
2251 assert_eq!(
2252 TimerFiring::commit(
2253 early_intent,
2254 head(
2255 timer.intent().tenant_id().clone(),
2256 timer.intent().run_id(),
2257 firing_event_id,
2258 10,
2259 at(4),
2260 ),
2261 ),
2262 Err(DurableWaitError::TimerNotDue)
2263 );
2264
2265 let intent = TimerFiringIntent::new(&timer, firing_event_id).unwrap();
2266 let firing = TimerFiring::commit(
2267 intent,
2268 head(
2269 timer.intent().tenant_id().clone(),
2270 timer.intent().run_id(),
2271 firing_event_id,
2272 10,
2273 at(5),
2274 ),
2275 )
2276 .unwrap();
2277 let record = DurableTimerRecord::restore(timer, Some(firing)).unwrap();
2278 assert!(!record.is_pending());
2279 assert_eq!(record.firing().unwrap().fired_at(), at(5));
2280 let wire = to_value(&record).unwrap();
2281 assert_eq!(from_value::<DurableTimerRecord>(wire).unwrap(), record);
2282 }
2283
2284 #[test]
2285 fn every_integrity_and_scope_layer_fails_closed_after_tampering() {
2286 let request = request(Some(at(10)));
2287 let resolution = resolution(&request, at(5)).unwrap();
2288 let timer = timer();
2289
2290 let mut changed_action = to_value(&request).unwrap();
2291 changed_action["intent"]["action_digest"] = json!(Digest::sha256(b"changed"));
2292 assert!(from_value::<InterruptRequest>(changed_action).is_err());
2293
2294 let mut changed_authority = to_value(request.head()).unwrap();
2295 changed_authority["required_scopes"] = json!(["run.resolve"]);
2296 assert!(from_value::<InterruptRequestHead>(changed_authority).is_err());
2297
2298 let mut changed_resolution = to_value(&resolution).unwrap();
2299 changed_resolution["intent"]["resolution_payload"]["data"] = json!({"approved": false});
2300 assert!(from_value::<InterruptResolution>(changed_resolution).is_err());
2301
2302 let mut changed_due = to_value(&timer).unwrap();
2303 changed_due["intent"]["due_at"] = json!(at(6));
2304 assert!(from_value::<DurableTimer>(changed_due).is_err());
2305
2306 let other_tenant = TenantId::new("tenant-other").unwrap();
2307 assert_eq!(
2308 InterruptRequest::commit(
2309 request.intent().clone(),
2310 head(
2311 other_tenant,
2312 request.intent().run_id(),
2313 request.intent().request_event_id(),
2314 7,
2315 at(0),
2316 ),
2317 ),
2318 Err(DurableWaitError::JournalTenantMismatch)
2319 );
2320 }
2321
2322 #[test]
2323 fn registration_enum_materializes_the_exact_lifecycle_marker() {
2324 let request = request(Some(at(10)));
2325 let intent = WaitRegistrationIntent::interrupt(request.intent().clone());
2326 let committed = intent.commit(request.journal().clone()).unwrap();
2327 assert_eq!(committed.marker().as_interrupt(), Some(request.marker()));
2328
2329 let timer = timer();
2330 let intent = WaitRegistrationIntent::timer(timer.intent().clone());
2331 let committed = intent.commit(timer.journal().clone()).unwrap();
2332 assert_eq!(committed.marker().as_timer(), Some(timer.marker()));
2333 }
2334
2335 #[test]
2336 fn terminal_records_must_causally_follow_registration() {
2337 let request = request(None);
2338 let resolution_event_id = id::<EventId>(0x70);
2339 let intent = InterruptResolutionIntent::new(
2340 &request,
2341 resolution_event_id,
2342 payload("approval-resolution", "safe"),
2343 InterruptResolver::new(
2344 principal("approver"),
2345 scopes(&["agent.approve", "run.resolve"]),
2346 ),
2347 )
2348 .unwrap();
2349 assert_eq!(
2350 InterruptResolution::commit(
2351 intent,
2352 head(
2353 request.intent().tenant_id().clone(),
2354 request.intent().run_id(),
2355 resolution_event_id,
2356 request.journal().sequence().get(),
2357 at(1),
2358 ),
2359 ),
2360 Err(DurableWaitError::TerminalJournalNotAfterRegistration)
2361 );
2362 }
2363
2364 proptest! {
2365 #[test]
2366 fn timer_accepts_exactly_strict_registration_and_inclusive_firing_offsets(
2367 due_offset in 1_i64..=86_400,
2368 firing_offset in -10_i64..=86_410,
2369 ) {
2370 let tenant_id = TenantId::new("tenant-property").unwrap();
2371 let run_id = id::<RunId>(0x40);
2372 let registration_event_id = id::<EventId>(0x41);
2373 let intent = TimerRegistrationIntent::new(
2374 tenant_id.clone(),
2375 run_id,
2376 id::<TimerId>(0x42),
2377 registration_event_id,
2378 RunTimerKind::Sleep,
2379 at(due_offset),
2380 ).unwrap();
2381 let timer = DurableTimer::commit(
2382 intent,
2383 head(tenant_id.clone(), run_id, registration_event_id, 1, at(0)),
2384 ).unwrap();
2385 let firing_event_id = id::<EventId>(0x43);
2386 let firing_intent = TimerFiringIntent::new(&timer, firing_event_id).unwrap();
2387 let result = TimerFiring::commit(
2388 firing_intent,
2389 head(tenant_id, run_id, firing_event_id, 2, at(firing_offset)),
2390 );
2391 prop_assert_eq!(result.is_ok(), firing_offset >= due_offset);
2392 }
2393
2394 #[test]
2395 fn interrupt_exclusive_expiry_matches_all_observation_offsets(
2396 expiry_offset in 1_i64..=86_400,
2397 resolution_offset in -10_i64..=86_410,
2398 ) {
2399 let request = request(Some(at(expiry_offset)));
2400 let result = resolution(&request, at(resolution_offset));
2401 prop_assert_eq!(
2402 result.is_ok(),
2403 (0..expiry_offset).contains(&resolution_offset)
2404 );
2405 }
2406 }
2407}