1use crate::{
45 recorded_commands,
46 update_validation::{
47 UpdateRejection, UPDATE_VALIDATION_WORKER_FAILED, UPDATE_VALIDATOR_REJECTED,
48 },
49 ActivityContext, ActivityHandler, AvroValue, Error, QueryTask, QueryTaskExecutionFailure,
50 Result, Value, Worker, WorkflowIdentity, WorkflowReplayState, WorkflowTask,
51 WorkflowTaskDecision,
52};
53use std::{
54 fmt,
55 future::Future,
56 pin::Pin,
57 sync::{
58 atomic::{AtomicBool, AtomicUsize, Ordering},
59 Arc, Mutex,
60 },
61};
62
63pub type InterceptorFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
65
66pub trait WorkerInterceptor: Send + Sync + 'static {
102 fn execute_workflow_task<'a>(
108 &'a self,
109 context: &'a WorkflowTaskInterceptorContext,
110 next: WorkflowTaskNext<'a>,
111 ) -> InterceptorFuture<'a, Result<WorkflowTaskOutcome>> {
112 let _ = context;
113 next.run()
114 }
115
116 fn execute_activity(
123 &self,
124 context: ActivityInterceptorContext,
125 next: ActivityNext,
126 ) -> InterceptorFuture<'_, Result<AvroValue>> {
127 next.run(context)
128 }
129
130 fn execute_query_task<'a>(
132 &'a self,
133 context: &'a QueryTaskInterceptorContext,
134 next: QueryTaskNext<'a>,
135 ) -> InterceptorFuture<'a, std::result::Result<AvroValue, QueryTaskFailure>> {
136 let _ = context;
137 next.run()
138 }
139
140 fn execute_update_validation_task<'a>(
147 &'a self,
148 context: &'a UpdateValidationInterceptorContext,
149 next: UpdateValidationNext<'a>,
150 ) -> InterceptorFuture<'a, Result<UpdateValidationOutcome>> {
151 let _ = context;
152 next.run()
153 }
154}
155
156impl<T: WorkerInterceptor + ?Sized> WorkerInterceptor for Arc<T> {
157 fn execute_workflow_task<'a>(
158 &'a self,
159 context: &'a WorkflowTaskInterceptorContext,
160 next: WorkflowTaskNext<'a>,
161 ) -> InterceptorFuture<'a, Result<WorkflowTaskOutcome>> {
162 (**self).execute_workflow_task(context, next)
163 }
164
165 fn execute_activity(
166 &self,
167 context: ActivityInterceptorContext,
168 next: ActivityNext,
169 ) -> InterceptorFuture<'_, Result<AvroValue>> {
170 (**self).execute_activity(context, next)
171 }
172
173 fn execute_query_task<'a>(
174 &'a self,
175 context: &'a QueryTaskInterceptorContext,
176 next: QueryTaskNext<'a>,
177 ) -> InterceptorFuture<'a, std::result::Result<AvroValue, QueryTaskFailure>> {
178 (**self).execute_query_task(context, next)
179 }
180
181 fn execute_update_validation_task<'a>(
182 &'a self,
183 context: &'a UpdateValidationInterceptorContext,
184 next: UpdateValidationNext<'a>,
185 ) -> InterceptorFuture<'a, Result<UpdateValidationOutcome>> {
186 (**self).execute_update_validation_task(context, next)
187 }
188}
189
190#[derive(Clone, Copy, Debug, Default)]
192pub struct PassthroughWorkerInterceptor;
193
194impl WorkerInterceptor for PassthroughWorkerInterceptor {}
195
196#[derive(Clone)]
197pub(crate) struct RegisteredInterceptor {
198 name: &'static str,
199 interceptor: Arc<dyn WorkerInterceptor>,
200}
201
202impl RegisteredInterceptor {
203 pub(crate) fn new<I: WorkerInterceptor>(interceptor: I) -> Self {
204 Self {
205 name: std::any::type_name::<I>(),
206 interceptor: Arc::new(interceptor),
207 }
208 }
209}
210
211impl fmt::Debug for RegisteredInterceptor {
212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213 f.write_str(self.name)
214 }
215}
216
217#[derive(Clone, Debug)]
223pub struct WorkflowTaskInterceptorContext {
224 worker_id: String,
225 task_queue: String,
226 namespace: String,
227 task_id: String,
228 workflow_id: Option<String>,
229 run_id: Option<String>,
230 workflow_type: String,
231 attempt: u64,
232 history_event_count: usize,
233 total_history_events: Option<u64>,
234 history_size_bytes: Option<u64>,
235 cancel_requested: bool,
236 observability_context: Option<Value>,
237 replay_state: WorkflowReplayState,
238}
239
240impl WorkflowTaskInterceptorContext {
241 pub fn worker_id(&self) -> &str {
242 &self.worker_id
243 }
244 pub fn task_queue(&self) -> &str {
245 &self.task_queue
246 }
247 pub fn namespace(&self) -> &str {
248 &self.namespace
249 }
250 pub fn task_id(&self) -> &str {
251 &self.task_id
252 }
253 pub fn workflow_id(&self) -> Option<&str> {
254 self.workflow_id.as_deref()
255 }
256 pub fn run_id(&self) -> Option<&str> {
257 self.run_id.as_deref()
258 }
259 pub fn workflow_type(&self) -> &str {
260 &self.workflow_type
261 }
262 pub fn attempt(&self) -> u64 {
264 self.attempt
265 }
266 pub fn history_event_count(&self) -> usize {
268 self.history_event_count
269 }
270 pub fn total_history_events(&self) -> Option<u64> {
272 self.total_history_events
273 }
274 pub fn history_size_bytes(&self) -> Option<u64> {
276 self.history_size_bytes
277 }
278 pub fn cancel_requested(&self) -> bool {
279 self.cancel_requested
280 }
281 pub fn observability_context(&self) -> Option<&Value> {
283 self.observability_context.as_ref()
284 }
285 pub fn replay_state(&self) -> WorkflowReplayState {
298 self.replay_state
299 }
300}
301
302#[derive(Clone, Debug)]
307pub struct WorkflowTaskOutcome {
308 commands: Option<Arc<Vec<Value>>>,
309}
310
311impl WorkflowTaskOutcome {
312 pub fn commands(&self) -> &[Value] {
321 self.commands.as_deref().map_or(&[], Vec::as_slice)
322 }
323
324 pub fn is_lease_lost(&self) -> bool {
326 self.commands.is_none()
327 }
328}
329
330#[derive(Clone)]
336pub struct WorkflowTaskFailure(Arc<FailureView>);
337
338struct FailureView {
339 kind: String,
340 message: String,
341 debug: String,
342}
343
344impl WorkflowTaskFailure {
345 fn describe(error: &Error) -> Self {
346 let debug = format!("{error:?}");
347 let kind = debug
348 .split(|c: char| !(c.is_alphanumeric() || c == '_'))
349 .next()
350 .unwrap_or_default()
351 .to_owned();
352 Self(Arc::new(FailureView {
353 kind,
354 message: error.to_string(),
355 debug,
356 }))
357 }
358
359 pub fn kind(&self) -> &str {
361 &self.0.kind
362 }
363
364 pub fn message(&self) -> &str {
366 &self.0.message
367 }
368
369 pub fn debug(&self) -> &str {
371 &self.0.debug
372 }
373}
374
375impl fmt::Debug for WorkflowTaskFailure {
376 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 f.write_str(&self.0.debug)
378 }
379}
380
381impl fmt::Display for WorkflowTaskFailure {
382 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383 f.write_str(&self.0.message)
384 }
385}
386
387impl std::error::Error for WorkflowTaskFailure {}
388
389type WorkflowCoreResult = Result<Option<WorkflowTaskDecision>>;
390
391enum CoreRecord {
392 Completed {
393 decision: WorkflowTaskDecision,
394 commands: Arc<Vec<Value>>,
395 },
396 LeaseLost,
397 Failed(Error),
398}
399
400struct WorkflowCore<'a> {
401 future: InterceptorFuture<'a, WorkflowCoreResult>,
402 record: &'a Mutex<Option<CoreRecord>>,
403 started: &'a AtomicBool,
404}
405
406#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub(crate) enum CoreProgress {
409 NotStarted,
411 Abandoned,
413 Completed,
415}
416
417pub struct WorkflowTaskNext<'a> {
419 chain: &'a [RegisteredInterceptor],
420 index: usize,
421 reached: &'a AtomicUsize,
422 context: &'a WorkflowTaskInterceptorContext,
423 core: WorkflowCore<'a>,
424}
425
426impl<'a> WorkflowTaskNext<'a> {
427 pub fn run(self) -> InterceptorFuture<'a, Result<WorkflowTaskOutcome>> {
431 if let Some(registered) = self.chain.get(self.index) {
432 let (reached, index) = (self.reached, self.index);
435 let next = WorkflowTaskNext {
436 index: self.index + 1,
437 ..self
438 };
439 let hook = registered
440 .interceptor
441 .execute_workflow_task(next.context, next);
442 return Box::pin(async move {
443 reached.fetch_max(index, Ordering::SeqCst);
444 hook.await
445 });
446 }
447 let WorkflowCore {
448 future,
449 record,
450 started,
451 } = self.core;
452 Box::pin(async move {
453 started.store(true, Ordering::SeqCst);
454 let (stored, outcome) = match future.await {
455 Ok(Some(mut decision)) => {
456 let commands = Arc::new(std::mem::take(&mut decision.commands));
457 let outcome = WorkflowTaskOutcome {
458 commands: Some(commands.clone()),
459 };
460 (CoreRecord::Completed { decision, commands }, Ok(outcome))
461 }
462 Ok(None) => (
463 CoreRecord::LeaseLost,
464 Ok(WorkflowTaskOutcome { commands: None }),
465 ),
466 Err(error) => {
467 let failure = WorkflowTaskFailure::describe(&error);
468 (
469 CoreRecord::Failed(error),
470 Err(Error::WorkflowTaskFailed(failure)),
471 )
472 }
473 };
474 if let Ok(mut slot) = record.lock() {
475 *slot = Some(stored);
476 }
477 outcome
478 })
479 }
480}
481
482impl Worker {
483 pub(crate) fn workflow_task_interceptor_context(
485 &self,
486 task: &WorkflowTask,
487 ) -> Option<WorkflowTaskInterceptorContext> {
488 if self.interceptors.is_empty() {
489 return None;
490 }
491 Some(WorkflowTaskInterceptorContext {
492 worker_id: self.worker_id.clone(),
493 task_queue: self.task_queue.clone(),
494 namespace: self.client.namespace.clone(),
495 task_id: task.task_id.clone(),
496 workflow_id: task.workflow_id.clone(),
497 run_id: task.run_id.clone(),
498 workflow_type: task.workflow_type.clone(),
499 attempt: task.workflow_task_attempt,
500 history_event_count: task.history_events.len(),
501 total_history_events: task.total_history_events,
502 history_size_bytes: task.history_size_bytes,
503 cancel_requested: task.cancel_requested,
504 observability_context: task.observability_context.clone(),
505 replay_state: task_replay_state(task),
506 })
507 }
508
509 pub(crate) async fn intercept_workflow_task<F>(
515 &self,
516 context: Option<WorkflowTaskInterceptorContext>,
517 core: F,
518 ) -> WorkflowCoreResult
519 where
520 F: Future<Output = WorkflowCoreResult> + Send,
521 {
522 self.intercept_workflow_task_tracked(context, core).await.0
523 }
524
525 pub(crate) async fn intercept_workflow_task_tracked<F>(
527 &self,
528 context: Option<WorkflowTaskInterceptorContext>,
529 core: F,
530 ) -> (WorkflowCoreResult, CoreProgress)
531 where
532 F: Future<Output = WorkflowCoreResult> + Send,
533 {
534 let Some(context) = context else {
535 return (core.await, CoreProgress::Completed);
536 };
537 let record = Mutex::new(None);
538 let reached = AtomicUsize::new(0);
539 let started = AtomicBool::new(false);
540 let chain = WorkflowTaskNext {
541 chain: &self.interceptors,
542 index: 0,
543 reached: &reached,
544 context: &context,
545 core: WorkflowCore {
546 future: Box::pin(core),
547 record: &record,
548 started: &started,
549 },
550 }
551 .run()
552 .await
553 .map(drop);
554 let Some(record) = record.into_inner().ok().flatten() else {
555 let error = match &chain {
556 Ok(()) => String::new(),
557 Err(error) => format!(": {error}"),
558 };
559 if started.load(Ordering::SeqCst) {
560 return (
561 Err(Error::WorkflowTaskInterceptor(format!(
562 "a workflow task interceptor dropped the workflow task before it completed{error}"
563 ))),
564 CoreProgress::Abandoned,
565 );
566 }
567 let skipped = &self.interceptors[reached
568 .load(Ordering::SeqCst)
569 .min(self.interceptors.len() - 1)];
570 let message = match chain {
571 Ok(()) => format!(
572 "workflow task interceptor {} returned without running next",
573 skipped.name
574 ),
575 Err(_) => format!(
576 "workflow task interceptor {} failed without running next{error}",
577 skipped.name
578 ),
579 };
580 return (
581 Err(Error::WorkflowTaskInterceptor(message)),
582 CoreProgress::NotStarted,
583 );
584 };
585 let result = match record {
586 CoreRecord::Failed(error) => Err(error),
587 CoreRecord::LeaseLost => Ok(None),
588 CoreRecord::Completed {
589 mut decision,
590 commands,
591 } => match chain {
592 Ok(()) => {
593 decision.commands =
594 Arc::try_unwrap(commands).unwrap_or_else(|retained| (*retained).clone());
595 Ok(Some(decision))
596 }
597 Err(error) => Err(Error::WorkflowTaskInterceptor(format!(
598 "workflow task interceptor failed: {error}"
599 ))),
600 },
601 };
602 (result, CoreProgress::Completed)
603 }
604}
605
606fn task_replay_state(task: &WorkflowTask) -> WorkflowReplayState {
608 match recorded_commands(
609 &task.history_events,
610 &task.payload_codec,
611 WorkflowIdentity {
612 workflow_id: task.workflow_id.clone(),
613 run_id: task.run_id.clone(),
614 },
615 ) {
616 Ok(commands) if commands.is_empty() => WorkflowReplayState::Executing,
617 Ok(_) => WorkflowReplayState::Replaying,
618 Err(_) => WorkflowReplayState::Unavailable,
619 }
620}
621
622#[derive(Clone, Debug)]
628pub struct ActivityInterceptorContext {
629 activity: ActivityContext,
630 args: AvroValue,
631 local: bool,
632}
633
634impl ActivityInterceptorContext {
635 pub fn worker_id(&self) -> &str {
636 &self.activity.worker_id
637 }
638 pub fn task_queue(&self) -> &str {
639 &self.activity.task_queue
640 }
641 pub fn namespace(&self) -> &str {
642 &self.activity.client.namespace
643 }
644 pub fn task_id(&self) -> &str {
645 &self.activity.task_id
646 }
647 pub fn activity_attempt_id(&self) -> &str {
648 &self.activity.activity_attempt_id
649 }
650 pub fn activity_type(&self) -> &str {
651 &self.activity.activity_type
652 }
653 pub fn attempt(&self) -> u64 {
654 self.activity.attempt_number
655 }
656 pub fn workflow_id(&self) -> Option<&str> {
657 self.activity.workflow_id()
658 }
659 pub fn run_id(&self) -> Option<&str> {
660 self.activity.run_id()
661 }
662 pub fn is_local(&self) -> bool {
664 self.local
665 }
666 pub fn args(&self) -> &AvroValue {
668 &self.args
669 }
670 pub fn activity_context(&self) -> &ActivityContext {
672 &self.activity
673 }
674 pub fn with_args(mut self, args: AvroValue) -> Self {
676 self.args = args;
677 self
678 }
679}
680
681pub struct ActivityNext {
683 chain: Arc<[RegisteredInterceptor]>,
684 index: usize,
685 handler: ActivityHandler,
686}
687
688impl ActivityNext {
689 pub fn run(
691 self,
692 context: ActivityInterceptorContext,
693 ) -> InterceptorFuture<'static, Result<AvroValue>> {
694 let Some(registered) = self.chain.get(self.index) else {
695 return (self.handler)(context.activity, context.args);
696 };
697 let interceptor = registered.interceptor.clone();
698 let next = ActivityNext {
699 index: self.index + 1,
700 ..self
701 };
702 Box::pin(async move { interceptor.execute_activity(context, next).await })
703 }
704}
705
706impl fmt::Debug for ActivityNext {
707 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
708 f.debug_struct("ActivityNext")
709 .field(
710 "remaining",
711 &&self.chain[self.index.min(self.chain.len())..],
712 )
713 .finish()
714 }
715}
716
717pub(crate) fn intercept_activity(
719 chain: &Arc<[RegisteredInterceptor]>,
720 handler: &ActivityHandler,
721 activity: ActivityContext,
722 args: AvroValue,
723 local: bool,
724) -> InterceptorFuture<'static, Result<AvroValue>> {
725 if chain.is_empty() {
726 return handler(activity, args);
727 }
728 ActivityNext {
729 chain: chain.clone(),
730 index: 0,
731 handler: handler.clone(),
732 }
733 .run(ActivityInterceptorContext {
734 activity,
735 args,
736 local,
737 })
738}
739
740#[derive(Clone, Debug)]
746pub struct QueryTaskInterceptorContext {
747 worker_id: String,
748 task_queue: String,
749 namespace: String,
750 query_task_id: String,
751 attempt: u64,
752 workflow_id: Option<String>,
753 run_id: Option<String>,
754 workflow_type: String,
755 query_name: String,
756 observability_context: Option<Value>,
757}
758
759impl QueryTaskInterceptorContext {
760 pub fn worker_id(&self) -> &str {
761 &self.worker_id
762 }
763 pub fn task_queue(&self) -> &str {
764 &self.task_queue
765 }
766 pub fn namespace(&self) -> &str {
767 &self.namespace
768 }
769 pub fn query_task_id(&self) -> &str {
770 &self.query_task_id
771 }
772 pub fn attempt(&self) -> u64 {
773 self.attempt
774 }
775 pub fn workflow_id(&self) -> Option<&str> {
776 self.workflow_id.as_deref()
777 }
778 pub fn run_id(&self) -> Option<&str> {
779 self.run_id.as_deref()
780 }
781 pub fn workflow_type(&self) -> &str {
782 &self.workflow_type
783 }
784 pub fn query_name(&self) -> &str {
785 &self.query_name
786 }
787 pub fn observability_context(&self) -> Option<&Value> {
789 self.observability_context.as_ref()
790 }
791}
792
793#[derive(Clone, Debug, PartialEq, Eq)]
795pub struct QueryTaskFailure {
796 reason: String,
797 message: String,
798 failure_type: String,
799}
800
801impl QueryTaskFailure {
802 pub fn new(
804 reason: impl Into<String>,
805 message: impl Into<String>,
806 failure_type: impl Into<String>,
807 ) -> Self {
808 Self {
809 reason: reason.into(),
810 message: message.into(),
811 failure_type: failure_type.into(),
812 }
813 }
814 pub fn reason(&self) -> &str {
815 &self.reason
816 }
817 pub fn message(&self) -> &str {
818 &self.message
819 }
820 pub fn failure_type(&self) -> &str {
821 &self.failure_type
822 }
823}
824
825impl fmt::Display for QueryTaskFailure {
826 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
827 write!(f, "{}: {}", self.reason, self.message)
828 }
829}
830
831impl std::error::Error for QueryTaskFailure {}
832
833impl From<QueryTaskExecutionFailure> for QueryTaskFailure {
834 fn from(failure: QueryTaskExecutionFailure) -> Self {
835 Self {
836 reason: failure.reason,
837 message: failure.message,
838 failure_type: failure.failure_type,
839 }
840 }
841}
842
843impl From<QueryTaskFailure> for QueryTaskExecutionFailure {
844 fn from(failure: QueryTaskFailure) -> Self {
845 Self {
846 reason: failure.reason,
847 message: failure.message,
848 failure_type: failure.failure_type,
849 }
850 }
851}
852
853type QueryResult = std::result::Result<AvroValue, QueryTaskFailure>;
854
855pub struct QueryTaskNext<'a> {
857 chain: &'a [RegisteredInterceptor],
858 context: &'a QueryTaskInterceptorContext,
859 core: InterceptorFuture<'a, QueryResult>,
860}
861
862impl<'a> QueryTaskNext<'a> {
863 pub fn run(self) -> InterceptorFuture<'a, QueryResult> {
865 match self.chain.split_first() {
866 Some((registered, rest)) => registered.interceptor.execute_query_task(
867 self.context,
868 QueryTaskNext {
869 chain: rest,
870 ..self
871 },
872 ),
873 None => self.core,
874 }
875 }
876}
877
878impl Worker {
879 pub(crate) fn query_task_interceptor_context(
881 &self,
882 task: &QueryTask,
883 ) -> Option<QueryTaskInterceptorContext> {
884 if self.interceptors.is_empty() {
885 return None;
886 }
887 Some(QueryTaskInterceptorContext {
888 worker_id: self.worker_id.clone(),
889 task_queue: self.task_queue.clone(),
890 namespace: self.client.namespace.clone(),
891 query_task_id: task.query_task_id.clone(),
892 attempt: task.query_task_attempt,
893 workflow_id: task.workflow_id.clone(),
894 run_id: task.run_id.clone(),
895 workflow_type: task.workflow_type.clone(),
896 query_name: task.query_name.clone(),
897 observability_context: task.observability_context.clone(),
898 })
899 }
900
901 pub(crate) async fn intercept_query_task<F>(
903 &self,
904 context: Option<QueryTaskInterceptorContext>,
905 core: F,
906 ) -> std::result::Result<AvroValue, QueryTaskExecutionFailure>
907 where
908 F: Future<Output = std::result::Result<AvroValue, QueryTaskExecutionFailure>> + Send,
909 {
910 let Some(context) = context else {
911 return core.await;
912 };
913 QueryTaskNext {
914 chain: &self.interceptors,
915 context: &context,
916 core: Box::pin(async move { core.await.map_err(QueryTaskFailure::from) }),
917 }
918 .run()
919 .await
920 .map_err(QueryTaskExecutionFailure::from)
921 }
922}
923
924#[derive(Clone, Debug)]
930pub struct UpdateValidationInterceptorContext {
931 worker_id: String,
932 task_queue: String,
933 namespace: String,
934 update_validation_task_id: String,
935 attempt: u64,
936 workflow_id: Option<String>,
937 run_id: Option<String>,
938 workflow_type: String,
939 update_name: String,
940 observability_context: Option<Value>,
941}
942
943impl UpdateValidationInterceptorContext {
944 pub fn worker_id(&self) -> &str {
945 &self.worker_id
946 }
947 pub fn task_queue(&self) -> &str {
948 &self.task_queue
949 }
950 pub fn namespace(&self) -> &str {
951 &self.namespace
952 }
953 pub fn update_validation_task_id(&self) -> &str {
954 &self.update_validation_task_id
955 }
956 pub fn attempt(&self) -> u64 {
958 self.attempt
959 }
960 pub fn workflow_id(&self) -> Option<&str> {
961 self.workflow_id.as_deref()
962 }
963 pub fn run_id(&self) -> Option<&str> {
964 self.run_id.as_deref()
965 }
966 pub fn workflow_type(&self) -> &str {
967 &self.workflow_type
968 }
969 pub fn update_name(&self) -> &str {
970 &self.update_name
971 }
972 pub fn observability_context(&self) -> Option<&Value> {
974 self.observability_context.as_ref()
975 }
976}
977
978#[derive(Clone, Debug, PartialEq, Eq)]
983pub struct UpdateValidationOutcome {
984 rejection: Option<(&'static str, UpdateRejection)>,
985}
986
987impl UpdateValidationOutcome {
988 pub fn is_approved(&self) -> bool {
990 self.rejection.is_none()
991 }
992 pub fn is_rejected(&self) -> bool {
994 matches!(self.rejection, Some((UPDATE_VALIDATOR_REJECTED, _)))
995 }
996 pub fn is_worker_failure(&self) -> bool {
998 matches!(self.rejection, Some((UPDATE_VALIDATION_WORKER_FAILED, _)))
999 }
1000 pub fn reason(&self) -> Option<&str> {
1002 self.rejection.as_ref().map(|(reason, _)| *reason)
1003 }
1004 pub fn rejection(&self) -> Option<&UpdateRejection> {
1006 self.rejection.as_ref().map(|(_, rejection)| rejection)
1007 }
1008}
1009
1010pub(crate) type ValidationDecision = std::result::Result<(), (&'static str, UpdateRejection)>;
1012
1013struct ValidationCore<'a> {
1014 future: InterceptorFuture<'a, ValidationDecision>,
1015 record: &'a Mutex<Option<ValidationDecision>>,
1016 started: &'a AtomicBool,
1017}
1018
1019pub struct UpdateValidationNext<'a> {
1021 chain: &'a [RegisteredInterceptor],
1022 index: usize,
1023 reached: &'a AtomicUsize,
1024 context: &'a UpdateValidationInterceptorContext,
1025 core: ValidationCore<'a>,
1026}
1027
1028impl<'a> UpdateValidationNext<'a> {
1029 pub fn run(self) -> InterceptorFuture<'a, Result<UpdateValidationOutcome>> {
1031 if let Some(registered) = self.chain.get(self.index) {
1032 let (reached, index) = (self.reached, self.index);
1033 let next = UpdateValidationNext {
1034 index: self.index + 1,
1035 ..self
1036 };
1037 let hook = registered
1038 .interceptor
1039 .execute_update_validation_task(next.context, next);
1040 return Box::pin(async move {
1041 reached.fetch_max(index, Ordering::SeqCst);
1042 hook.await
1043 });
1044 }
1045 let ValidationCore {
1046 future,
1047 record,
1048 started,
1049 } = self.core;
1050 Box::pin(async move {
1051 started.store(true, Ordering::SeqCst);
1052 let decision = future.await;
1053 let outcome = UpdateValidationOutcome {
1054 rejection: decision.clone().err(),
1055 };
1056 if let Ok(mut slot) = record.lock() {
1057 *slot = Some(decision);
1058 }
1059 Ok(outcome)
1060 })
1061 }
1062}
1063
1064impl Worker {
1065 pub(crate) fn update_validation_interceptor_context(
1067 &self,
1068 task: &Value,
1069 ) -> Option<UpdateValidationInterceptorContext> {
1070 if self.interceptors.is_empty() {
1071 return None;
1072 }
1073 let text = |field: &str| task[field].as_str().map(str::to_string);
1074 Some(UpdateValidationInterceptorContext {
1075 worker_id: self.worker_id.clone(),
1076 task_queue: self.task_queue.clone(),
1077 namespace: self.client.namespace.clone(),
1078 update_validation_task_id: text("update_validation_task_id").unwrap_or_default(),
1079 attempt: task["update_validation_attempt"].as_u64().unwrap_or(1),
1080 workflow_id: text("workflow_id"),
1081 run_id: text("run_id"),
1082 workflow_type: text("workflow_type").unwrap_or_default(),
1083 update_name: text("update_name").unwrap_or_default(),
1084 observability_context: task
1085 .get("observability_context")
1086 .filter(|value| !value.is_null())
1087 .cloned(),
1088 })
1089 }
1090
1091 pub(crate) async fn intercept_update_validation<F>(
1096 &self,
1097 context: Option<UpdateValidationInterceptorContext>,
1098 core: F,
1099 ) -> ValidationDecision
1100 where
1101 F: Future<Output = ValidationDecision> + Send,
1102 {
1103 let Some(context) = context else {
1104 return core.await;
1105 };
1106 let record = Mutex::new(None);
1107 let reached = AtomicUsize::new(0);
1108 let started = AtomicBool::new(false);
1109 let chain = UpdateValidationNext {
1110 chain: &self.interceptors,
1111 index: 0,
1112 reached: &reached,
1113 context: &context,
1114 core: ValidationCore {
1115 future: Box::pin(core),
1116 record: &record,
1117 started: &started,
1118 },
1119 }
1120 .run()
1121 .await
1122 .map(drop);
1123 let failed = |message: String| {
1124 Err((
1125 UPDATE_VALIDATION_WORKER_FAILED,
1126 UpdateRejection::new(message).with_type("UpdateValidationInterceptor"),
1127 ))
1128 };
1129 let Some(decision) = record.into_inner().ok().flatten() else {
1130 let error = match &chain {
1131 Ok(()) => String::new(),
1132 Err(error) => format!(": {error}"),
1133 };
1134 if started.load(Ordering::SeqCst) {
1135 return failed(format!(
1136 "an update validation interceptor dropped the validation before it completed{error}"
1137 ));
1138 }
1139 let skipped = &self.interceptors[reached
1140 .load(Ordering::SeqCst)
1141 .min(self.interceptors.len() - 1)];
1142 return failed(match chain {
1143 Ok(()) => format!(
1144 "update validation interceptor {} returned without running next",
1145 skipped.name
1146 ),
1147 Err(_) => format!(
1148 "update validation interceptor {} failed without running next{error}",
1149 skipped.name
1150 ),
1151 });
1152 };
1153 match chain {
1154 Ok(()) => decision,
1155 Err(error) => failed(format!("update validation interceptor failed: {error}")),
1156 }
1157 }
1158}