Skip to content
Durable Workflowrust

durable_workflow/
external_signal.rs

1//! Signal another workflow from workflow code as a durable command
2//! (durable-workflow/.github#223, Server #1134).
3//!
4//! The command is recorded once in the sender's history as
5//! `ExternalSignalRequested`, followed in the same transaction by exactly one
6//! `ExternalSignalDelivered` or `ExternalSignalFailed` at the same sequence.
7//! Replay resolves the call from that recorded outcome and never submits the
8//! signal again.
9
10use super::{
11    command_mismatch, decode_wire_avro_value, encode_typed_envelope, invalid_recorded_history,
12    normalize_avro_arguments, AvroValue, Error, HistoryEvent, RecordedCommand, ReplayFailure,
13    Result, Value, WorkflowContext,
14};
15use serde::Serialize;
16use std::{
17    future::Future,
18    pin::Pin,
19    task::{Context as TaskContext, Poll},
20};
21
22pub(super) const COMMAND: &str = "signal_external_workflow";
23pub(super) const CAPABILITY: &str = "signal_external_workflow";
24pub(super) const REQUESTED: &str = "ExternalSignalRequested";
25pub(super) const DELIVERED: &str = "ExternalSignalDelivered";
26pub(super) const FAILED: &str = "ExternalSignalFailed";
27
28const MAX_WORKFLOW_ID_CHARS: usize = 191;
29const MAX_SIGNAL_NAME_CHARS: usize = 191;
30const MAX_SIGNAL_NAME_BYTES: usize = 255;
31
32/// The recorded outcome of a signal sent with
33/// [`WorkflowContext::signal_external_workflow`].
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35#[non_exhaustive]
36pub enum ExternalSignalOutcome {
37    /// The target run admitted the signal (`SignalReceived` in its history).
38    Delivered,
39    /// No workflow instance has that id in the namespace, or the requested
40    /// run is not a run of it.
41    TargetNotFound,
42    /// The target run has closed, or the requested run was replaced.
43    TargetClosed,
44    /// The target's signal admission, or the Server, refused the signal.
45    Rejected,
46}
47
48impl ExternalSignalOutcome {
49    /// The wire value recorded in history.
50    pub fn as_str(self) -> &'static str {
51        match self {
52            Self::Delivered => "delivered",
53            Self::TargetNotFound => "target_not_found",
54            Self::TargetClosed => "target_closed",
55            Self::Rejected => "rejected",
56        }
57    }
58
59    fn parse(value: &str) -> Option<Self> {
60        Some(match value {
61            "delivered" => Self::Delivered,
62            "target_not_found" => Self::TargetNotFound,
63            "target_closed" => Self::TargetClosed,
64            "rejected" => Self::Rejected,
65            _ => return None,
66        })
67    }
68}
69
70impl std::fmt::Display for ExternalSignalOutcome {
71    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        formatter.write_str(self.as_str())
73    }
74}
75
76/// The outcome of an external signal as recorded in the sender's history.
77///
78/// A failed delivery is a recorded result, not an error: inspect
79/// [`outcome`](Self::outcome) and [`reason`](Self::reason) (for example
80/// `instance_not_found`, `run_not_active` or `unknown_signal`) and decide in
81/// workflow code what to do. Replay returns the same value.
82#[derive(Clone, Debug, PartialEq, Eq)]
83#[non_exhaustive]
84pub struct ExternalSignalResult {
85    pub outcome: ExternalSignalOutcome,
86    /// The stable reason for a failed outcome; `None` when delivered.
87    pub reason: Option<String>,
88    /// The Server's human-readable detail for a failed outcome.
89    pub message: Option<String>,
90    pub target_workflow_id: String,
91    /// The run that received the signal, or for a failure the run that was
92    /// resolved (`None` when no run was resolved).
93    pub target_run_id: Option<String>,
94    pub signal_name: String,
95    /// The command key (`workflow-signal:<sender run id>:<sequence>`).
96    pub request_id: Option<String>,
97    /// The command recorded on the target, when the target recorded one.
98    pub target_command_id: Option<String>,
99    /// The target's signal record, when delivered.
100    pub target_signal_id: Option<String>,
101    /// True when the same command key had already been delivered.
102    pub retained: bool,
103}
104
105impl ExternalSignalResult {
106    pub fn is_delivered(&self) -> bool {
107        self.outcome == ExternalSignalOutcome::Delivered
108    }
109}
110
111/// The intent recorded by `ExternalSignalRequested`.
112#[derive(Clone, Debug, PartialEq)]
113pub(super) struct RecordedRequest {
114    target_workflow_id: String,
115    target_run_id: Option<String>,
116    signal_name: String,
117    arguments: Option<AvroValue>,
118}
119
120/// Whether the connected Server advertises the `signal_external_workflow`
121/// workflow-task command in its worker `server_capabilities`.
122pub(super) fn runtime_supports(capabilities: Option<&Value>) -> bool {
123    let Some(capabilities) = capabilities.and_then(Value::as_object) else {
124        return false;
125    };
126    let flag = match capabilities.get(CAPABILITY) {
127        Some(Value::Bool(supported)) => *supported,
128        Some(Value::Object(capability)) => capability.get("supported") == Some(&Value::Bool(true)),
129        _ => false,
130    };
131    let command_advertised = capabilities
132        .get("supported_workflow_task_commands")
133        .and_then(Value::as_array)
134        .is_some_and(|commands| commands.iter().any(|command| command == COMMAND));
135    flag && command_advertised
136}
137
138pub(super) fn is_event(event: &HistoryEvent) -> bool {
139    matches!(event.event_type.as_str(), REQUESTED | DELIVERED | FAILED)
140}
141
142fn optional_string(event: &HistoryEvent, field: &str) -> Option<String> {
143    event
144        .payload
145        .get(field)
146        .and_then(Value::as_str)
147        .filter(|value| !value.is_empty())
148        .map(str::to_string)
149}
150
151fn required_string(event: &HistoryEvent, field: &str, sequence: u64) -> Result<String> {
152    optional_string(event, field).ok_or_else(|| {
153        invalid_recorded_history(
154            "external_signal_field_missing",
155            sequence,
156            &format!("non-empty {field}"),
157            &format!("missing or invalid {field} on {}", event.event_type),
158            "external-signal history is missing a required field",
159        )
160    })
161}
162
163/// Build the recorded command for one sequence from its external-signal
164/// events.
165pub(super) fn recorded(
166    events: &[&HistoryEvent],
167    sequence: u64,
168    fallback_codec: &str,
169) -> Result<RecordedCommand> {
170    let requested: Vec<_> = events
171        .iter()
172        .copied()
173        .filter(|event| event.event_type == REQUESTED)
174        .collect();
175    if requested.len() != 1 {
176        return Err(invalid_recorded_history(
177            "external_signal_request_count",
178            sequence,
179            &format!("one {REQUESTED} event"),
180            &format!("{} {REQUESTED} events", requested.len()),
181            "external-signal history must record exactly one request per workflow sequence",
182        ));
183    }
184    let requested = requested[0];
185    let resolutions: Vec<_> = events
186        .iter()
187        .copied()
188        .filter(|event| event.event_type != REQUESTED)
189        .collect();
190    if resolutions.len() > 1 {
191        return Err(invalid_recorded_history(
192            "external_signal_resolution_count",
193            sequence,
194            "at most one ExternalSignalDelivered or ExternalSignalFailed event",
195            &format!("{} resolution events", resolutions.len()),
196            "external-signal history resolves one request more than once",
197        ));
198    }
199
200    let target_workflow_id = required_string(requested, "target_workflow_instance_id", sequence)?;
201    let signal_name = required_string(requested, "signal_name", sequence)?;
202    let codec = requested
203        .payload
204        .get("payload_codec")
205        .and_then(Value::as_str)
206        .unwrap_or(fallback_codec);
207    let arguments = match requested
208        .payload
209        .get("arguments")
210        .filter(|value| !value.is_null())
211    {
212        Some(envelope) => Some(normalize_avro_arguments(
213            decode_wire_avro_value(envelope, codec).map_err(|error| {
214                if error.to_string().contains("unsupported_payload_codec") {
215                    return error;
216                }
217                invalid_recorded_history(
218                    "external_signal_arguments_incompatible",
219                    sequence,
220                    &format!("valid {codec} payload envelope"),
221                    &error.to_string(),
222                    "external-signal history arguments cannot be decoded with their recorded codec",
223                )
224            })?,
225        )),
226        None => None,
227    };
228    let request = RecordedRequest {
229        target_workflow_id,
230        target_run_id: optional_string(requested, "target_workflow_run_id"),
231        signal_name,
232        arguments,
233    };
234
235    let outcome = match resolutions.first() {
236        None => None,
237        Some(resolution) => Some(resolution_result(
238            resolution, &request, requested, sequence,
239        )?),
240    };
241    Ok(RecordedCommand::ExternalSignal {
242        sequence,
243        request,
244        outcome,
245    })
246}
247
248fn resolution_result(
249    event: &HistoryEvent,
250    request: &RecordedRequest,
251    requested: &HistoryEvent,
252    sequence: u64,
253) -> Result<ExternalSignalResult> {
254    for (field, expected) in [
255        (
256            "target_workflow_instance_id",
257            Some(request.target_workflow_id.as_str()),
258        ),
259        ("signal_name", Some(request.signal_name.as_str())),
260    ] {
261        let actual = event.payload.get(field).and_then(Value::as_str);
262        if actual.is_some() && actual != expected {
263            return Err(invalid_recorded_history(
264                "external_signal_identity_mismatch",
265                sequence,
266                expected.unwrap_or_default(),
267                actual.unwrap_or_default(),
268                "external-signal resolution disagrees with its recorded request",
269            ));
270        }
271    }
272    let request_id = optional_string(event, "request_id");
273    if let (Some(resolved), Some(recorded)) = (
274        request_id.as_deref(),
275        optional_string(requested, "request_id"),
276    ) {
277        if resolved != recorded {
278            return Err(invalid_recorded_history(
279                "external_signal_identity_mismatch",
280                sequence,
281                &recorded,
282                resolved,
283                "external-signal resolution disagrees with its recorded command key",
284            ));
285        }
286    }
287    let raw_outcome = event
288        .payload
289        .get("outcome")
290        .and_then(Value::as_str)
291        .unwrap_or(if event.event_type == DELIVERED {
292            "delivered"
293        } else {
294            ""
295        });
296    let outcome = ExternalSignalOutcome::parse(raw_outcome)
297        .filter(|outcome| {
298            (*outcome == ExternalSignalOutcome::Delivered) == (event.event_type == DELIVERED)
299        })
300        .ok_or_else(|| {
301            invalid_recorded_history(
302                "external_signal_outcome_invalid",
303                sequence,
304                if event.event_type == DELIVERED {
305                    "delivered"
306                } else {
307                    "target_not_found, target_closed or rejected"
308                },
309                raw_outcome,
310                "external-signal resolution records an unknown outcome",
311            )
312        })?;
313    let reason = optional_string(event, "reason");
314    if outcome != ExternalSignalOutcome::Delivered && reason.is_none() {
315        return Err(invalid_recorded_history(
316            "external_signal_field_missing",
317            sequence,
318            "non-empty reason",
319            &format!("missing reason on {}", event.event_type),
320            "a failed external signal must record its reason",
321        ));
322    }
323    Ok(ExternalSignalResult {
324        outcome,
325        reason,
326        message: optional_string(event, "message"),
327        target_workflow_id: request.target_workflow_id.clone(),
328        target_run_id: optional_string(event, "target_workflow_run_id"),
329        signal_name: request.signal_name.clone(),
330        request_id,
331        target_command_id: optional_string(event, "target_command_id"),
332        target_signal_id: optional_string(event, "target_signal_id"),
333        retained: event.payload.get("retained").and_then(Value::as_bool) == Some(true),
334    })
335}
336
337/// The Server's signal-name rule (server#1251): not blank, no control
338/// character (a byte below 0x20 or 0x7f), at most 191 characters and 255
339/// bytes. Checked in workflow code so a bad name never reaches the Server,
340/// which would refuse the whole completion.
341fn validate_signal_name(signal_name: &str) -> Result<()> {
342    let refusal = if signal_name.trim().is_empty() {
343        Some("must not be empty or blank")
344    } else if signal_name.bytes().any(|byte| byte < 0x20 || byte == 0x7f) {
345        Some("must not contain control characters")
346    } else if signal_name.len() > MAX_SIGNAL_NAME_BYTES {
347        Some("must be at most 255 bytes")
348    } else if signal_name.chars().count() > MAX_SIGNAL_NAME_CHARS {
349        Some("must be at most 191 characters")
350    } else {
351        None
352    };
353    match refusal {
354        Some(refusal) => Err(Error::InvalidExternalSignal(format!(
355            "signal_name {refusal}"
356        ))),
357        None => Ok(()),
358    }
359}
360
361fn validate(workflow_id: &str, signal_name: &str, run_id: Option<&str>) -> Result<()> {
362    if workflow_id.is_empty() || workflow_id.chars().count() > MAX_WORKFLOW_ID_CHARS {
363        return Err(Error::InvalidExternalSignal(format!(
364            "workflow_id must be 1 to {MAX_WORKFLOW_ID_CHARS} characters"
365        )));
366    }
367    validate_signal_name(signal_name)?;
368    if run_id.is_some_and(str::is_empty) {
369        return Err(Error::InvalidExternalSignal(
370            "run_id must not be empty; omit it to signal the current run".to_string(),
371        ));
372    }
373    Ok(())
374}
375
376impl WorkflowContext {
377    /// Signal another workflow in this namespace as a durable workflow
378    /// command, and await the recorded outcome.
379    ///
380    /// The signal is recorded once in this workflow's history and delivered
381    /// by the Server in the same transaction; replay reads the recorded
382    /// outcome and never sends it again. Without
383    /// [`run_id`](ExternalSignalCall::run_id) the signal goes to the target
384    /// instance's current run. `args` are encoded like child-workflow
385    /// arguments (a value that is not an array is sent as one argument).
386    ///
387    /// A delivery that fails (missing target, closed target, rejected
388    /// signal) resolves to `Ok` with that [`ExternalSignalOutcome`] and its
389    /// reason, so workflow code decides what to do. Errors are reserved for
390    /// invalid input ([`Error::InvalidExternalSignal`]), a Server that does
391    /// not advertise the command ([`Error::SignalExternalWorkflowUnavailable`],
392    /// returned before anything is submitted), and replay mismatches. A
393    /// different target, name or arguments at a recorded sequence is a
394    /// nondeterministic replay.
395    ///
396    /// ```no_run
397    /// # use durable_workflow::{json, Client, ExternalSignalOutcome, Worker};
398    /// # fn configure(client: Client) {
399    /// let mut worker = Worker::new(client, "orders");
400    /// worker.register_workflow("approver", |ctx, _input| async move {
401    ///     let sent = ctx
402    ///         .signal_external_workflow("order-42", "approve", json!(["manager"]))
403    ///         .await?;
404    ///     Ok(json!({
405    ///         "outcome": sent.outcome.as_str(),
406    ///         "reason": sent.reason,
407    ///         "delivered": sent.outcome == ExternalSignalOutcome::Delivered,
408    ///     }))
409    /// });
410    /// # }
411    /// ```
412    pub fn signal_external_workflow<T: Serialize>(
413        &self,
414        workflow_id: impl Into<String>,
415        signal_name: impl Into<String>,
416        args: T,
417    ) -> ExternalSignalCall {
418        ExternalSignalCall {
419            ctx: self.clone(),
420            workflow_id: workflow_id.into(),
421            signal_name: signal_name.into(),
422            run_id: None,
423            args: Some(AvroValue::from_serialize(&args)),
424            submitted: false,
425            matched_pending: false,
426        }
427    }
428}
429
430/// Future returned by [`WorkflowContext::signal_external_workflow`].
431pub struct ExternalSignalCall {
432    ctx: WorkflowContext,
433    workflow_id: String,
434    signal_name: String,
435    run_id: Option<String>,
436    args: Option<Result<AvroValue>>,
437    submitted: bool,
438    matched_pending: bool,
439}
440
441impl ExternalSignalCall {
442    /// Signal only this run of the target instance. A run the instance has
443    /// since replaced resolves to [`ExternalSignalOutcome::TargetClosed`]
444    /// with reason `historical_run`.
445    pub fn run_id(mut self, run_id: impl Into<String>) -> Self {
446        self.run_id = Some(run_id.into());
447        self
448    }
449
450    fn mismatch(
451        &self,
452        sequence: u64,
453        field: &str,
454        recorded: String,
455        current: String,
456    ) -> Poll<Result<ExternalSignalResult>> {
457        Poll::Ready(Err(Error::NonDeterministicReplay(ReplayFailure::new(
458            "recorded_command_detail_mismatch",
459            Some(sequence),
460            Some(format!("external signal {field}:{recorded}")),
461            Some(format!("external signal {field}:{current}")),
462            format!("recorded external signal {field} differs from the current workflow command"),
463        ))))
464    }
465}
466
467impl Future for ExternalSignalCall {
468    type Output = Result<ExternalSignalResult>;
469
470    fn poll(mut self: Pin<&mut Self>, _cx: &mut TaskContext<'_>) -> Poll<Self::Output> {
471        if self.matched_pending || self.submitted {
472            return Poll::Pending;
473        }
474        let args = match self.args.take() {
475            Some(Ok(args)) => normalize_avro_arguments(args),
476            Some(Err(error)) => return Poll::Ready(Err(error)),
477            None => AvroValue::Array(Vec::new()),
478        };
479        let ctx = self.ctx.clone();
480        let mut state = match ctx.state.lock() {
481            Ok(state) => state,
482            Err(_) => return Poll::Ready(Err(Error::WorkflowStatePoisoned)),
483        };
484
485        if let Some(recorded) = state.recorded_commands.get(state.command_cursor).cloned() {
486            let RecordedCommand::ExternalSignal {
487                sequence,
488                request,
489                outcome,
490            } = recorded
491            else {
492                return Poll::Ready(Err(command_mismatch(
493                    &recorded,
494                    format!("external signal:{}", self.signal_name),
495                )));
496            };
497            if request.target_workflow_id != self.workflow_id {
498                return self.mismatch(
499                    sequence,
500                    "target",
501                    request.target_workflow_id,
502                    self.workflow_id.clone(),
503                );
504            }
505            if request.target_run_id != self.run_id {
506                return self.mismatch(
507                    sequence,
508                    "run",
509                    request.target_run_id.unwrap_or_default(),
510                    self.run_id.clone().unwrap_or_default(),
511                );
512            }
513            if request.signal_name != self.signal_name {
514                return self.mismatch(
515                    sequence,
516                    "name",
517                    request.signal_name,
518                    self.signal_name.clone(),
519                );
520            }
521            if let Some(recorded_args) = request.arguments {
522                if recorded_args != args {
523                    return self.mismatch(
524                        sequence,
525                        "arguments",
526                        format!("{recorded_args:?}"),
527                        format!("{args:?}"),
528                    );
529                }
530            }
531            state.command_cursor += 1;
532            state.replay_clock.unavailable();
533            if let Some(outcome) = outcome {
534                return Poll::Ready(Ok(outcome));
535            }
536            // The outcome is recorded in the request's own transaction, so a
537            // request without one is only seen on a partial history page.
538            state.matched_recorded_pending = true;
539            state.observation_pending = true;
540            self.matched_pending = true;
541            return Poll::Pending;
542        }
543
544        if let Err(error) = validate(&self.workflow_id, &self.signal_name, self.run_id.as_deref()) {
545            return Poll::Ready(Err(error));
546        }
547        if !state.signal_external_workflow_supported {
548            return Poll::Ready(Err(Error::SignalExternalWorkflowUnavailable));
549        }
550        let arguments = match encode_typed_envelope(&args, &state.payload_codec) {
551            Ok(arguments) => arguments,
552            Err(error) => return Poll::Ready(Err(error)),
553        };
554        state.replay_clock.unavailable();
555        state.commands.push(serde_json::json!({
556            "type": COMMAND,
557            "workflow_id": self.workflow_id,
558            "run_id": self.run_id,
559            "signal_name": self.signal_name,
560            "arguments": arguments,
561        }));
562        drop(state);
563        self.submitted = true;
564        Poll::Pending
565    }
566}