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)]
47pub enum ActivityError {
48 /// Return this error to attach application-failure metadata to an activity failure.
49 Application(Box<ApplicationFailure>),
50 /// Return this error to indicate your activity is cancelling
51 Cancelled {
52 /// Optional cancellation details.
53 details: Option<FailurePayloads>,
54 },
55 /// Return this error to indicate that the activity will be completed outside of this activity
56 /// definition, by an external client.
57 WillCompleteAsync,
58}
59
60impl ActivityError {
61 /// Construct a cancelled error without details
62 pub fn cancelled() -> Self {
63 Self::Cancelled { details: None }
64 }
65
66 /// Construct a cancelled error with details that will be converted using the active data
67 /// converter.
68 pub fn cancelled_with_details<T>(details: T) -> Self
69 where
70 T: Into<FailurePayloads>,
71 {
72 Self::Cancelled {
73 details: Some(details.into()),
74 }
75 }
76
77 /// Construct an application activity error.
78 pub fn application(err: ApplicationFailure) -> Self {
79 Self::Application(err.into())
80 }
81}
82
83impl<E> From<E> for ActivityError
84where
85 E: Into<anyhow::Error>,
86{
87 fn from(source: E) -> Self {
88 match source.into().downcast::<ApplicationFailure>() {
89 Ok(application_failure) => Self::Application(Box::new(application_failure)),
90 Err(err) => Self::Application(ApplicationFailure::new(err).into()),
91 }
92 }
93}