Skip to content
Durable Workflowrust

durable_workflow/
interceptors.rs

1//! Ordered worker interceptors around workflow tasks, activities, queries and
2//! update validations.
3//!
4//! Register interceptors with [`Worker::interceptor`](crate::Worker::interceptor)
5//! or [`Worker::interceptors`](crate::Worker::interceptors). The first
6//! registered interceptor is the outermost wrapper: it runs first before the
7//! core and last after it. Each hook receives a context and a `next` handle;
8//! running `next` continues the chain and the innermost `next` runs the
9//! SDK's real handling. Every hook has a passthrough default, so an
10//! interceptor implements only the hooks it needs.
11//!
12//! | Hook | Wraps | Context | `next` returns |
13//! | --- | --- | --- | --- |
14//! | [`WorkerInterceptor::execute_workflow_task`] | one workflow task (replay plus new execution) | [`WorkflowTaskInterceptorContext`] | [`WorkflowTaskOutcome`] |
15//! | [`WorkerInterceptor::execute_activity`] | one activity or local activity attempt | [`ActivityInterceptorContext`] | the activity result |
16//! | [`WorkerInterceptor::execute_query_task`] | one query task | [`QueryTaskInterceptorContext`] | the query result or [`QueryTaskFailure`] |
17//! | [`WorkerInterceptor::execute_update_validation_task`] | one update-validation task | [`UpdateValidationInterceptorContext`] | a read-only [`UpdateValidationOutcome`] |
18//!
19//! Workflow-task interceptors cannot change what the workflow records. The
20//! core always runs the task as received ([`WorkflowTaskNext::run`] takes no
21//! input) and the worker submits exactly the commands the core produced. The
22//! outcome an interceptor sees is a read-only view. If the core fails, the
23//! worker reports that failure even when an interceptor returns `Ok`. If an
24//! interceptor fails after the core succeeded, or returns without running
25//! `next`, the worker fails the workflow task ([`Error::WorkflowTaskInterceptor`]);
26//! nothing is recorded and the Server retries the task. Interceptors run on
27//! every workflow task. [`WorkflowTaskInterceptorContext::replay_state`] says
28//! whether the task first re-ran a committed history prefix; the worker never
29//! resubmits replayed commands, so an outcome's commands are always new for
30//! that task. A failed task's retry can repeat an outcome; use
31//! [`WorkflowTaskInterceptorContext::attempt`] to detect retries.
32//!
33//! Update-validation interceptors observe a validator's decision and cannot
34//! change it. The validator always runs on the task as received
35//! ([`UpdateValidationNext::run`] takes no input) and the worker sends the
36//! validator's own approval or rejection. If an interceptor fails, returns
37//! without running `next`, or drops the validation partway, the worker reports
38//! `update_validation_worker_failed` instead: the update is not accepted, and
39//! the caller's retry with the same request id asks the validator again.
40//!
41//! Built-in [`ExecutionTelemetry`](crate::telemetry::ExecutionTelemetry) stays
42//! outermost: its spans wrap the whole interceptor chain.
43
44use 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
63/// The boxed `Send` future an interceptor hook returns.
64pub type InterceptorFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
65
66/// Ordered hooks around worker task execution.
67///
68/// Every method defaults to calling `next` unchanged, so implement only the
69/// hooks you need. Hooks return boxed futures, typically
70/// `Box::pin(async move { ... })`.
71///
72/// ```
73/// use durable_workflow::interceptors::{
74///     InterceptorFuture, WorkerInterceptor, WorkflowTaskInterceptorContext, WorkflowTaskNext,
75///     WorkflowTaskOutcome,
76/// };
77/// use durable_workflow::Result;
78///
79/// struct AuditLog;
80///
81/// impl WorkerInterceptor for AuditLog {
82///     fn execute_workflow_task<'a>(
83///         &'a self,
84///         context: &'a WorkflowTaskInterceptorContext,
85///         next: WorkflowTaskNext<'a>,
86///     ) -> InterceptorFuture<'a, Result<WorkflowTaskOutcome>> {
87///         Box::pin(async move {
88///             let outcome = next.run().await?;
89///             // The commands are always new for this task; a retry has attempt > 1.
90///             println!(
91///                 "{} attempt {} produced {} commands",
92///                 context.task_id(),
93///                 context.attempt(),
94///                 outcome.commands().len()
95///             );
96///             Ok(outcome)
97///         })
98///     }
99/// }
100/// ```
101pub trait WorkerInterceptor: Send + Sync + 'static {
102    /// Wrap one workflow task. Run `next` exactly once.
103    ///
104    /// The returned outcome is ignored: the worker settles the core's own
105    /// decision. Returning an error after the core succeeded fails the
106    /// workflow task (not the workflow).
107    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    /// Wrap one activity attempt, remote or local.
117    ///
118    /// Pass the context to `next`, optionally with transformed arguments
119    /// ([`ActivityInterceptorContext::with_args`]). The returned value is the
120    /// activity result the worker reports, so an interceptor may transform it,
121    /// handle an error, or skip `next` entirely.
122    fn execute_activity(
123        &self,
124        context: ActivityInterceptorContext,
125        next: ActivityNext,
126    ) -> InterceptorFuture<'_, Result<AvroValue>> {
127        next.run(context)
128    }
129
130    /// Wrap one query task. The returned value is what the worker reports.
131    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    /// Wrap one update-validation task. Run `next` exactly once.
141    ///
142    /// The returned outcome is ignored: the worker sends the validator's own
143    /// approval or rejection. Returning an error, returning without running
144    /// `next`, or dropping it partway makes the worker report
145    /// `update_validation_worker_failed`, so the update is not accepted.
146    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/// An interceptor that only calls `next`; a base for partial interceptors.
191#[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// ---------------------------------------------------------------------------
218// Workflow tasks
219// ---------------------------------------------------------------------------
220
221/// Read-only context of one workflow task.
222#[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    /// The workflow-task attempt; above 1 when the Server retries the task.
263    pub fn attempt(&self) -> u64 {
264        self.attempt
265    }
266    /// Number of history events delivered with the task.
267    pub fn history_event_count(&self) -> usize {
268        self.history_event_count
269    }
270    /// The Server's committed history length, when it reported one.
271    pub fn total_history_events(&self) -> Option<u64> {
272        self.total_history_events
273    }
274    /// The Server's committed history size, when it reported one.
275    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    /// The task's optional, untrusted observability metadata (trace carrier).
282    pub fn observability_context(&self) -> Option<&Value> {
283        self.observability_context.as_ref()
284    }
285    /// Whether this task re-runs a committed history prefix before new execution.
286    ///
287    /// [`WorkflowReplayState::Replaying`]: the history holds commands that
288    /// earlier workflow tasks committed, so workflow code re-runs them before
289    /// any new execution. [`WorkflowReplayState::Executing`]: no committed
290    /// prefix. [`WorkflowReplayState::Unavailable`]: the history could not be
291    /// read (the core reports why).
292    ///
293    /// Replayed commands are never resubmitted, so the outcome's commands are
294    /// new for this task in every state. Do not skip auditing a task because it
295    /// replayed. A retry of a failed task (`attempt() > 1`) can repeat an
296    /// outcome.
297    pub fn replay_state(&self) -> WorkflowReplayState {
298        self.replay_state
299    }
300}
301
302/// A read-only view of what the workflow-task core produced.
303///
304/// It is only obtained from [`WorkflowTaskNext::run`]. The worker settles
305/// the core's own decision, never a returned outcome.
306#[derive(Clone, Debug)]
307pub struct WorkflowTaskOutcome {
308    commands: Option<Arc<Vec<Value>>>,
309}
310
311impl WorkflowTaskOutcome {
312    /// The commands the worker will submit, in order. Empty when the lease
313    /// was lost or the task only waits for more history.
314    ///
315    /// This is the view before built-in
316    /// [`ExecutionTelemetry`](crate::telemetry::ExecutionTelemetry) stamps its
317    /// observability fields: with telemetry enabled, the submitted commands
318    /// also carry those fields. Their order and content are otherwise the
319    /// same.
320    pub fn commands(&self) -> &[Value] {
321        self.commands.as_deref().map_or(&[], Vec::as_slice)
322    }
323
324    /// The worker lost or released the task's lease; nothing is reported.
325    pub fn is_lease_lost(&self) -> bool {
326        self.commands.is_none()
327    }
328}
329
330/// A read-only description of the workflow-task core's own error.
331///
332/// [`WorkflowTaskNext::run`] returns it as [`Error::WorkflowTaskFailed`]. It
333/// does not own the error: the worker keeps the original and reports it
334/// whatever an interceptor returns or retains.
335#[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    /// The [`Error`](enum@crate::Error) variant name, such as `"WorkflowNotRegistered"`.
360    pub fn kind(&self) -> &str {
361        &self.0.kind
362    }
363
364    /// The error's display text.
365    pub fn message(&self) -> &str {
366        &self.0.message
367    }
368
369    /// The error's debug text.
370    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/// How far the workflow-task core got inside the interceptor chain.
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub(crate) enum CoreProgress {
409    /// The core never began; nothing it does happened.
410    NotStarted,
411    /// The core began but an interceptor dropped it before it finished.
412    Abandoned,
413    /// The core finished and its result was recorded.
414    Completed,
415}
416
417/// Continues a workflow-task chain; the innermost `next` runs the task.
418pub 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    /// Run the rest of the chain and the core with the task as received.
428    ///
429    /// A core failure is returned as [`Error::WorkflowTaskFailed`].
430    pub fn run(self) -> InterceptorFuture<'a, Result<WorkflowTaskOutcome>> {
431        if let Some(registered) = self.chain.get(self.index) {
432            // Record the deepest hook that actually began running, on its
433            // first poll: creating `next.run()` and dropping it is not running it.
434            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    /// The interceptor context for a workflow task, or `None` without interceptors.
484    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    /// Run one workflow task's core inside the interceptor chain.
510    ///
511    /// Returns exactly the core's decision or error. An interceptor failure
512    /// after core success, or a chain that never ran the core, becomes
513    /// [`Error::WorkflowTaskInterceptor`].
514    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    /// [`Self::intercept_workflow_task`], also reporting how far the core got.
526    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
606/// Whether the task's history holds commands committed by earlier tasks.
607fn 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// ---------------------------------------------------------------------------
623// Activities
624// ---------------------------------------------------------------------------
625
626/// Context of one activity attempt; owns the arguments passed down the chain.
627#[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    /// Whether this is an inline local activity run by a workflow task.
663    pub fn is_local(&self) -> bool {
664        self.local
665    }
666    /// The decoded arguments the activity will receive.
667    pub fn args(&self) -> &AvroValue {
668        &self.args
669    }
670    /// The [`ActivityContext`] the activity handler will receive.
671    pub fn activity_context(&self) -> &ActivityContext {
672        &self.activity
673    }
674    /// Replace the arguments passed to the rest of the chain.
675    pub fn with_args(mut self, args: AvroValue) -> Self {
676        self.args = args;
677        self
678    }
679}
680
681/// Continues an activity chain; the innermost `next` runs the activity.
682pub struct ActivityNext {
683    chain: Arc<[RegisteredInterceptor]>,
684    index: usize,
685    handler: ActivityHandler,
686}
687
688impl ActivityNext {
689    /// Run the rest of the chain and the activity handler.
690    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
717/// Run an activity handler inside the interceptor chain.
718pub(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// ---------------------------------------------------------------------------
741// Queries
742// ---------------------------------------------------------------------------
743
744/// Read-only context of one query task.
745#[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    /// The task's optional, untrusted observability metadata (trace carrier).
788    pub fn observability_context(&self) -> Option<&Value> {
789        self.observability_context.as_ref()
790    }
791}
792
793/// A query task failure the worker reports to the Server.
794#[derive(Clone, Debug, PartialEq, Eq)]
795pub struct QueryTaskFailure {
796    reason: String,
797    message: String,
798    failure_type: String,
799}
800
801impl QueryTaskFailure {
802    /// A failure with a machine `reason`, human `message` and `failure_type`.
803    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
855/// Continues a query chain; the innermost `next` answers the query.
856pub struct QueryTaskNext<'a> {
857    chain: &'a [RegisteredInterceptor],
858    context: &'a QueryTaskInterceptorContext,
859    core: InterceptorFuture<'a, QueryResult>,
860}
861
862impl<'a> QueryTaskNext<'a> {
863    /// Run the rest of the chain and the query handler.
864    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    /// The interceptor context for a query task, or `None` without interceptors.
880    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    /// Run one query task's core inside the interceptor chain.
902    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// ---------------------------------------------------------------------------
925// Update validation
926// ---------------------------------------------------------------------------
927
928/// Read-only context of one update-validation task.
929#[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    /// The validation attempt; above 1 when the Server redelivers the task.
957    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    /// The task's optional, untrusted observability metadata (trace carrier).
973    pub fn observability_context(&self) -> Option<&Value> {
974        self.observability_context.as_ref()
975    }
976}
977
978/// A read-only view of the decision the validator produced.
979///
980/// It is only obtained from [`UpdateValidationNext::run`]. The worker sends
981/// the validator's own decision, never a returned outcome.
982#[derive(Clone, Debug, PartialEq, Eq)]
983pub struct UpdateValidationOutcome {
984    rejection: Option<(&'static str, UpdateRejection)>,
985}
986
987impl UpdateValidationOutcome {
988    /// The validator approved the update.
989    pub fn is_approved(&self) -> bool {
990        self.rejection.is_none()
991    }
992    /// The validator refused the update (`update_validator_rejected`).
993    pub fn is_rejected(&self) -> bool {
994        matches!(self.rejection, Some((UPDATE_VALIDATOR_REJECTED, _)))
995    }
996    /// The validator could not run (`update_validation_worker_failed`).
997    pub fn is_worker_failure(&self) -> bool {
998        matches!(self.rejection, Some((UPDATE_VALIDATION_WORKER_FAILED, _)))
999    }
1000    /// The failure reason the worker reports, or `None` for an approval.
1001    pub fn reason(&self) -> Option<&str> {
1002        self.rejection.as_ref().map(|(reason, _)| *reason)
1003    }
1004    /// The rejection or failure the worker reports, or `None` for an approval.
1005    pub fn rejection(&self) -> Option<&UpdateRejection> {
1006        self.rejection.as_ref().map(|(_, rejection)| rejection)
1007    }
1008}
1009
1010/// The validator's decision: approve, or the failure reason and rejection.
1011pub(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
1019/// Continues an update-validation chain; the innermost `next` runs the validator.
1020pub 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    /// Run the rest of the chain and the validator with the task as received.
1030    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    /// The interceptor context for an update-validation task, or `None` without interceptors.
1066    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    /// Run one validator inside the interceptor chain.
1092    ///
1093    /// Returns exactly the validator's decision. A broken chain becomes an
1094    /// `update_validation_worker_failed` rejection, so nothing is accepted.
1095    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}