temporalio_common_wasm/activity_definition.rs
1//! Contains types for activity definitions, used by the code generated by the macros for defining
2//! activities, or directly by users targeting activities in other languages.
3
4use crate::{
5 data_converters::{RawValue, TemporalDeserializable, TemporalSerializable},
6 error::{ApplicationFailure, FailurePayloads},
7};
8
9/// Implement on a marker struct to define an activity.
10///
11/// Typically, you will want to use the `#[activity]` attribute within an `#[activities]` macro to
12/// define activities. However, this trait may be implemented manually if desired.
13pub trait ActivityDefinition {
14 /// Type of the input argument to the workflow
15 type Input: TemporalDeserializable + TemporalSerializable + 'static;
16 /// Type of the output of the workflow
17 type Output: TemporalDeserializable + TemporalSerializable + 'static;
18
19 /// The name that will be used for the activity type.
20 fn name(&self) -> &str;
21}
22
23/// Marker type for starting activities by activity type name. Uses [`RawValue`] for both input and
24/// output.
25pub struct UntypedActivity {
26 name: String,
27}
28
29impl UntypedActivity {
30 /// Create a new `UntypedActivity` with the given activity type name.
31 pub fn new(name: impl Into<String>) -> Self {
32 Self { name: name.into() }
33 }
34}
35
36impl ActivityDefinition for UntypedActivity {
37 type Input = RawValue;
38 type Output = RawValue;
39
40 fn name(&self) -> &str {
41 &self.name
42 }
43}
44
45/// Returned as errors from activity functions.
46#[derive(Debug)]
47#[non_exhaustive]
48pub enum ActivityError {
49 /// Return this error to attach application-failure metadata to an activity failure.
50 Application(Box<ApplicationFailure>),
51 /// Return this error to indicate your activity is cancelling
52 Cancelled {
53 /// Optional cancellation details.
54 details: Option<FailurePayloads>,
55 },
56 /// Return this error to indicate that the activity will be completed outside of this activity
57 /// definition, by an external client.
58 WillCompleteAsync,
59}
60
61impl ActivityError {
62 /// Construct a cancelled error without details
63 pub fn cancelled() -> Self {
64 Self::Cancelled { details: None }
65 }
66
67 /// Construct a cancelled error with details that will be converted using the active data
68 /// converter.
69 pub fn cancelled_with_details<T>(details: T) -> Self
70 where
71 T: Into<FailurePayloads>,
72 {
73 Self::Cancelled {
74 details: Some(details.into()),
75 }
76 }
77
78 /// Construct an application activity error.
79 pub fn application(err: ApplicationFailure) -> Self {
80 Self::Application(err.into())
81 }
82}
83
84impl<E> From<E> for ActivityError
85where
86 E: Into<anyhow::Error>,
87{
88 fn from(source: E) -> Self {
89 match source.into().downcast::<ApplicationFailure>() {
90 Ok(application_failure) => Self::Application(Box::new(application_failure)),
91 Err(err) => Self::Application(ApplicationFailure::new(err).into()),
92 }
93 }
94}