@temporalio/core-bridge 0.17.2 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/Cargo.lock +339 -226
  2. package/Cargo.toml +7 -3
  3. package/common.js +50 -0
  4. package/index.d.ts +7 -0
  5. package/index.js +12 -0
  6. package/package.json +7 -4
  7. package/releases/aarch64-apple-darwin/index.node +0 -0
  8. package/releases/aarch64-unknown-linux-gnu/index.node +0 -0
  9. package/{index.node → releases/index.node} +0 -0
  10. package/releases/x86_64-apple-darwin/index.node +0 -0
  11. package/releases/x86_64-pc-windows-msvc/index.node +0 -0
  12. package/releases/x86_64-unknown-linux-gnu/index.node +0 -0
  13. package/scripts/build.js +10 -50
  14. package/sdk-core/.buildkite/docker/Dockerfile +1 -1
  15. package/sdk-core/.buildkite/docker/docker-compose.yaml +2 -2
  16. package/sdk-core/.buildkite/pipeline.yml +2 -0
  17. package/sdk-core/Cargo.toml +1 -88
  18. package/sdk-core/README.md +30 -6
  19. package/sdk-core/bridge-ffi/Cargo.toml +24 -0
  20. package/sdk-core/bridge-ffi/LICENSE.txt +23 -0
  21. package/sdk-core/bridge-ffi/build.rs +25 -0
  22. package/sdk-core/bridge-ffi/include/sdk-core-bridge.h +216 -0
  23. package/sdk-core/bridge-ffi/src/lib.rs +829 -0
  24. package/sdk-core/bridge-ffi/src/wrappers.rs +193 -0
  25. package/sdk-core/client/Cargo.toml +32 -0
  26. package/sdk-core/{src/pollers/gateway.rs → client/src/lib.rs} +101 -195
  27. package/sdk-core/client/src/metrics.rs +89 -0
  28. package/sdk-core/client/src/mocks.rs +167 -0
  29. package/sdk-core/{src/pollers → client/src}/retry.rs +172 -14
  30. package/sdk-core/core/Cargo.toml +96 -0
  31. package/sdk-core/{src → core/src}/core_tests/activity_tasks.rs +193 -37
  32. package/sdk-core/{src → core/src}/core_tests/child_workflows.rs +14 -14
  33. package/sdk-core/{src → core/src}/core_tests/determinism.rs +8 -8
  34. package/sdk-core/core/src/core_tests/local_activities.rs +328 -0
  35. package/sdk-core/{src → core/src}/core_tests/mod.rs +6 -9
  36. package/sdk-core/{src → core/src}/core_tests/queries.rs +45 -52
  37. package/sdk-core/{src → core/src}/core_tests/replay_flag.rs +8 -12
  38. package/sdk-core/{src → core/src}/core_tests/workers.rs +120 -33
  39. package/sdk-core/{src → core/src}/core_tests/workflow_cancels.rs +16 -26
  40. package/sdk-core/{src → core/src}/core_tests/workflow_tasks.rs +264 -286
  41. package/sdk-core/core/src/lib.rs +374 -0
  42. package/sdk-core/{src → core/src}/log_export.rs +3 -27
  43. package/sdk-core/core/src/pending_activations.rs +162 -0
  44. package/sdk-core/{src → core/src}/pollers/mod.rs +4 -22
  45. package/sdk-core/{src → core/src}/pollers/poll_buffer.rs +1 -1
  46. package/sdk-core/core/src/protosext/mod.rs +396 -0
  47. package/sdk-core/core/src/replay/mod.rs +210 -0
  48. package/sdk-core/core/src/retry_logic.rs +144 -0
  49. package/sdk-core/{src → core/src}/telemetry/metrics.rs +3 -58
  50. package/sdk-core/{src → core/src}/telemetry/mod.rs +8 -8
  51. package/sdk-core/{src → core/src}/telemetry/prometheus_server.rs +0 -0
  52. package/sdk-core/{src → core/src}/test_help/mod.rs +34 -73
  53. package/sdk-core/{src → core/src}/worker/activities/activity_heartbeat_manager.rs +95 -42
  54. package/sdk-core/core/src/worker/activities/local_activities.rs +973 -0
  55. package/sdk-core/{src → core/src}/worker/activities.rs +52 -33
  56. package/sdk-core/{src → core/src}/worker/dispatcher.rs +8 -6
  57. package/sdk-core/{src → core/src}/worker/mod.rs +305 -195
  58. package/sdk-core/core/src/worker/wft_delivery.rs +81 -0
  59. package/sdk-core/{src → core/src}/workflow/bridge.rs +5 -2
  60. package/sdk-core/{src → core/src}/workflow/driven_workflow.rs +17 -7
  61. package/sdk-core/{src → core/src}/workflow/history_update.rs +33 -7
  62. package/sdk-core/{src → core/src/workflow}/machines/activity_state_machine.rs +26 -26
  63. package/sdk-core/{src → core/src/workflow}/machines/cancel_external_state_machine.rs +8 -11
  64. package/sdk-core/{src → core/src/workflow}/machines/cancel_workflow_state_machine.rs +19 -21
  65. package/sdk-core/{src → core/src/workflow}/machines/child_workflow_state_machine.rs +19 -21
  66. package/sdk-core/{src → core/src/workflow}/machines/complete_workflow_state_machine.rs +3 -5
  67. package/sdk-core/{src → core/src/workflow}/machines/continue_as_new_workflow_state_machine.rs +18 -18
  68. package/sdk-core/{src → core/src/workflow}/machines/fail_workflow_state_machine.rs +5 -6
  69. package/sdk-core/core/src/workflow/machines/local_activity_state_machine.rs +1451 -0
  70. package/sdk-core/{src → core/src/workflow}/machines/mod.rs +54 -107
  71. package/sdk-core/{src → core/src/workflow}/machines/mutable_side_effect_state_machine.rs +0 -0
  72. package/sdk-core/{src → core/src/workflow}/machines/patch_state_machine.rs +29 -30
  73. package/sdk-core/{src → core/src/workflow}/machines/side_effect_state_machine.rs +0 -0
  74. package/sdk-core/{src → core/src/workflow}/machines/signal_external_state_machine.rs +17 -19
  75. package/sdk-core/{src → core/src/workflow}/machines/timer_state_machine.rs +20 -21
  76. package/sdk-core/{src → core/src/workflow}/machines/transition_coverage.rs +5 -2
  77. package/sdk-core/{src → core/src/workflow}/machines/upsert_search_attributes_state_machine.rs +0 -0
  78. package/sdk-core/core/src/workflow/machines/workflow_machines/local_acts.rs +96 -0
  79. package/sdk-core/{src → core/src/workflow}/machines/workflow_machines.rs +344 -160
  80. package/sdk-core/{src → core/src/workflow}/machines/workflow_task_state_machine.rs +1 -1
  81. package/sdk-core/{src → core/src}/workflow/mod.rs +200 -39
  82. package/sdk-core/{src → core/src}/workflow/workflow_tasks/cache_manager.rs +0 -0
  83. package/sdk-core/{src → core/src}/workflow/workflow_tasks/concurrency_manager.rs +38 -5
  84. package/sdk-core/{src → core/src}/workflow/workflow_tasks/mod.rs +297 -81
  85. package/sdk-core/{test_utils → core-api}/Cargo.toml +10 -7
  86. package/sdk-core/{src → core-api/src}/errors.rs +42 -90
  87. package/sdk-core/core-api/src/lib.rs +158 -0
  88. package/sdk-core/{src/worker/config.rs → core-api/src/worker.rs} +18 -23
  89. package/sdk-core/etc/deps.svg +156 -0
  90. package/sdk-core/fsm/rustfsm_procmacro/src/lib.rs +5 -5
  91. package/sdk-core/fsm/rustfsm_procmacro/tests/trybuild/no_handle_conversions_require_into_fail.stderr +3 -5
  92. package/sdk-core/fsm/rustfsm_trait/src/lib.rs +7 -1
  93. package/sdk-core/histories/fail_wf_task.bin +0 -0
  94. package/sdk-core/histories/timer_workflow_history.bin +0 -0
  95. package/sdk-core/protos/api_upstream/temporal/api/command/v1/message.proto +44 -13
  96. package/sdk-core/protos/api_upstream/temporal/api/common/v1/message.proto +19 -1
  97. package/sdk-core/protos/api_upstream/temporal/api/enums/v1/common.proto +1 -1
  98. package/sdk-core/protos/api_upstream/temporal/api/enums/v1/failed_cause.proto +9 -0
  99. package/sdk-core/protos/api_upstream/temporal/api/enums/v1/namespace.proto +1 -0
  100. package/sdk-core/protos/api_upstream/temporal/api/enums/v1/reset.proto +1 -0
  101. package/sdk-core/protos/api_upstream/temporal/api/enums/v1/task_queue.proto +13 -0
  102. package/sdk-core/protos/api_upstream/temporal/api/enums/v1/workflow.proto +14 -7
  103. package/sdk-core/protos/api_upstream/temporal/api/history/v1/message.proto +176 -18
  104. package/sdk-core/protos/api_upstream/temporal/api/namespace/v1/message.proto +6 -0
  105. package/sdk-core/protos/api_upstream/temporal/api/query/v1/message.proto +11 -0
  106. package/sdk-core/protos/api_upstream/temporal/api/taskqueue/v1/message.proto +3 -0
  107. package/sdk-core/protos/api_upstream/temporal/api/workflowservice/v1/request_response.proto +156 -7
  108. package/sdk-core/protos/api_upstream/temporal/api/workflowservice/v1/service.proto +135 -104
  109. package/sdk-core/protos/local/temporal/sdk/core/activity_result/activity_result.proto +78 -0
  110. package/sdk-core/protos/local/temporal/sdk/core/activity_task/activity_task.proto +78 -0
  111. package/sdk-core/protos/local/temporal/sdk/core/bridge/bridge.proto +205 -0
  112. package/sdk-core/protos/local/temporal/sdk/core/bridge/service.proto +61 -0
  113. package/sdk-core/protos/local/{child_workflow.proto → temporal/sdk/core/child_workflow/child_workflow.proto} +1 -1
  114. package/sdk-core/protos/local/{common.proto → temporal/sdk/core/common/common.proto} +5 -3
  115. package/sdk-core/protos/local/{core_interface.proto → temporal/sdk/core/core_interface.proto} +10 -10
  116. package/sdk-core/protos/local/temporal/sdk/core/external_data/external_data.proto +30 -0
  117. package/sdk-core/protos/local/{workflow_activation.proto → temporal/sdk/core/workflow_activation/workflow_activation.proto} +35 -11
  118. package/sdk-core/protos/local/{workflow_commands.proto → temporal/sdk/core/workflow_commands/workflow_commands.proto} +55 -4
  119. package/sdk-core/protos/local/{workflow_completion.proto → temporal/sdk/core/workflow_completion/workflow_completion.proto} +3 -3
  120. package/sdk-core/sdk/Cargo.toml +32 -0
  121. package/sdk-core/{src/prototype_rust_sdk → sdk/src}/conversions.rs +0 -0
  122. package/sdk-core/sdk/src/lib.rs +699 -0
  123. package/sdk-core/sdk/src/payload_converter.rs +11 -0
  124. package/sdk-core/sdk/src/workflow_context/options.rs +180 -0
  125. package/sdk-core/{src/prototype_rust_sdk → sdk/src}/workflow_context.rs +201 -124
  126. package/sdk-core/{src/prototype_rust_sdk → sdk/src}/workflow_future.rs +63 -30
  127. package/sdk-core/sdk-core-protos/Cargo.toml +10 -0
  128. package/sdk-core/sdk-core-protos/build.rs +28 -6
  129. package/sdk-core/sdk-core-protos/src/constants.rs +7 -0
  130. package/sdk-core/{src/test_help → sdk-core-protos/src}/history_builder.rs +134 -49
  131. package/sdk-core/sdk-core-protos/src/history_info.rs +216 -0
  132. package/sdk-core/sdk-core-protos/src/lib.rs +594 -168
  133. package/sdk-core/sdk-core-protos/src/task_token.rs +38 -0
  134. package/sdk-core/sdk-core-protos/src/utilities.rs +14 -0
  135. package/sdk-core/test-utils/Cargo.toml +32 -0
  136. package/sdk-core/{src/test_help → test-utils/src}/canned_histories.rs +59 -78
  137. package/sdk-core/test-utils/src/histfetch.rs +28 -0
  138. package/sdk-core/{test_utils → test-utils}/src/lib.rs +131 -68
  139. package/sdk-core/tests/integ_tests/client_tests.rs +1 -1
  140. package/sdk-core/tests/integ_tests/heartbeat_tests.rs +11 -7
  141. package/sdk-core/tests/integ_tests/polling_tests.rs +12 -11
  142. package/sdk-core/tests/integ_tests/queries_tests.rs +82 -78
  143. package/sdk-core/tests/integ_tests/workflow_tests/activities.rs +91 -71
  144. package/sdk-core/tests/integ_tests/workflow_tests/cancel_external.rs +3 -4
  145. package/sdk-core/tests/integ_tests/workflow_tests/cancel_wf.rs +2 -4
  146. package/sdk-core/tests/integ_tests/workflow_tests/child_workflows.rs +4 -6
  147. package/sdk-core/tests/integ_tests/workflow_tests/continue_as_new.rs +4 -6
  148. package/sdk-core/tests/integ_tests/workflow_tests/determinism.rs +3 -4
  149. package/sdk-core/tests/integ_tests/workflow_tests/local_activities.rs +496 -0
  150. package/sdk-core/tests/integ_tests/workflow_tests/patches.rs +5 -8
  151. package/sdk-core/tests/integ_tests/workflow_tests/replay.rs +125 -0
  152. package/sdk-core/tests/integ_tests/workflow_tests/signals.rs +7 -13
  153. package/sdk-core/tests/integ_tests/workflow_tests/stickyness.rs +33 -5
  154. package/sdk-core/tests/integ_tests/workflow_tests/timers.rs +12 -16
  155. package/sdk-core/tests/integ_tests/workflow_tests.rs +85 -82
  156. package/sdk-core/tests/load_tests.rs +6 -6
  157. package/sdk-core/tests/main.rs +2 -2
  158. package/src/conversions.rs +24 -21
  159. package/src/errors.rs +8 -0
  160. package/src/lib.rs +323 -211
  161. package/sdk-core/protos/local/activity_result.proto +0 -46
  162. package/sdk-core/protos/local/activity_task.proto +0 -66
  163. package/sdk-core/src/core_tests/retry.rs +0 -147
  164. package/sdk-core/src/lib.rs +0 -403
  165. package/sdk-core/src/machines/local_activity_state_machine.rs +0 -117
  166. package/sdk-core/src/pending_activations.rs +0 -249
  167. package/sdk-core/src/protosext/mod.rs +0 -160
  168. package/sdk-core/src/prototype_rust_sdk.rs +0 -412
  169. package/sdk-core/src/task_token.rs +0 -20
  170. package/sdk-core/src/test_help/history_info.rs +0 -158
@@ -0,0 +1,1451 @@
1
+ use super::{
2
+ workflow_machines::MachineResponse, Cancellable, EventInfo, MachineKind, OnEventWrapper,
3
+ WFMachinesAdapter, WFMachinesError,
4
+ };
5
+ use crate::{
6
+ protosext::{CompleteLocalActivityData, HistoryEventExt, ValidScheduleLA},
7
+ worker::LocalActivityExecutionResult,
8
+ };
9
+ use rustfsm::{fsm, MachineError, StateMachine, TransitionResult};
10
+ use std::{
11
+ convert::TryFrom,
12
+ time::{Duration, SystemTime},
13
+ };
14
+ use temporal_sdk_core_protos::{
15
+ constants::LOCAL_ACTIVITY_MARKER_NAME,
16
+ coresdk::{
17
+ activity_result::{
18
+ ActivityResolution, Cancellation, DoBackoff, Failure as ActFail, Success,
19
+ },
20
+ common::build_local_activity_marker_details,
21
+ external_data::LocalActivityMarkerData,
22
+ workflow_activation::ResolveActivity,
23
+ workflow_commands::ActivityCancellationType,
24
+ },
25
+ temporal::api::{
26
+ command::v1::{Command, RecordMarkerCommandAttributes},
27
+ enums::v1::{CommandType, EventType},
28
+ failure::v1::failure::FailureInfo,
29
+ history::v1::HistoryEvent,
30
+ },
31
+ utilities::TryIntoOrNone,
32
+ };
33
+
34
+ fsm! {
35
+ pub(super) name LocalActivityMachine;
36
+ command LocalActivityCommand;
37
+ error WFMachinesError;
38
+ shared_state SharedState;
39
+
40
+ // Machine is created in either executing or replaying (referring to whether or not the workflow
41
+ // is replaying), and then immediately scheduled and transitions to either requesting that lang
42
+ // execute the activity, or waiting for the marker from history.
43
+ Executing --(Schedule, shared on_schedule) --> RequestSent;
44
+ Replaying --(Schedule, on_schedule) --> WaitingMarkerEvent;
45
+ ReplayingPreResolved --(Schedule, on_schedule) --> WaitingMarkerEventPreResolved;
46
+
47
+ // Execution path =============================================================================
48
+ RequestSent --(HandleResult(ResolveDat), on_handle_result) --> MarkerCommandCreated;
49
+ // We loop back on RequestSent here because the LA needs to report its result
50
+ RequestSent --(Cancel, on_cancel_requested) --> RequestSent;
51
+ // No wait cancels skip waiting for the LA to report the result, but do generate a command
52
+ // to record the cancel marker
53
+ RequestSent --(NoWaitCancel(ActivityCancellationType), shared on_no_wait_cancel)
54
+ --> MarkerCommandCreated;
55
+
56
+ MarkerCommandCreated --(CommandRecordMarker, on_command_record_marker) --> ResultNotified;
57
+
58
+ ResultNotified --(MarkerRecorded(CompleteLocalActivityData), shared on_marker_recorded)
59
+ --> MarkerCommandRecorded;
60
+
61
+ // Replay path ================================================================================
62
+ // LAs on the replay path should never have handle result explicitly called on them, but do need
63
+ // to eventually see the marker
64
+ WaitingMarkerEvent --(MarkerRecorded(CompleteLocalActivityData), shared on_marker_recorded)
65
+ --> MarkerCommandRecorded;
66
+ // If we are told to cancel while waiting for the marker, we still need to wait for the marker.
67
+ WaitingMarkerEvent --(Cancel, on_cancel_requested) --> WaitingMarkerEventCancelled;
68
+ WaitingMarkerEvent --(NoWaitCancel(ActivityCancellationType),
69
+ on_no_wait_cancel) --> WaitingMarkerEventCancelled;
70
+ WaitingMarkerEventCancelled --(HandleResult(ResolveDat), on_handle_result) --> WaitingMarkerEvent;
71
+
72
+ // It is entirely possible to have started the LA while replaying, only to find that we have
73
+ // reached a new WFT and there still was no marker. In such cases we need to execute the LA.
74
+ // This can easily happen if upon first execution, the worker does WFT heartbeating but then
75
+ // dies for some reason.
76
+ WaitingMarkerEvent --(StartedNonReplayWFT, shared on_started_non_replay_wft) --> RequestSent;
77
+
78
+ // If the activity is pre resolved we still expect to see marker recorded event at some point,
79
+ // even though we already resolved the activity.
80
+ WaitingMarkerEventPreResolved --(MarkerRecorded(CompleteLocalActivityData),
81
+ shared on_marker_recorded) --> MarkerCommandRecorded;
82
+
83
+ // Ignore cancellation in final state
84
+ MarkerCommandRecorded --(Cancel, on_cancel_requested) --> MarkerCommandRecorded;
85
+ MarkerCommandRecorded --(NoWaitCancel(ActivityCancellationType),
86
+ on_no_wait_cancel) --> MarkerCommandRecorded;
87
+
88
+ // LAs reporting status after they've handled their result can simply be ignored. We could
89
+ // optimize this away higher up but that feels very overkill.
90
+ MarkerCommandCreated --(HandleResult(ResolveDat)) --> MarkerCommandCreated;
91
+ ResultNotified --(HandleResult(ResolveDat)) --> ResultNotified;
92
+ MarkerCommandRecorded --(HandleResult(ResolveDat)) --> MarkerCommandRecorded;
93
+ }
94
+
95
+ #[derive(Debug, Clone)]
96
+ pub(super) struct ResolveDat {
97
+ pub(super) result: LocalActivityExecutionResult,
98
+ pub(super) complete_time: Option<SystemTime>,
99
+ pub(super) attempt: u32,
100
+ pub(super) backoff: Option<prost_types::Duration>,
101
+ pub(super) original_schedule_time: Option<SystemTime>,
102
+ }
103
+
104
+ impl From<CompleteLocalActivityData> for ResolveDat {
105
+ fn from(d: CompleteLocalActivityData) -> Self {
106
+ ResolveDat {
107
+ result: match d.result {
108
+ Ok(res) => LocalActivityExecutionResult::Completed(Success {
109
+ result: Some(res.into()),
110
+ }),
111
+ Err(fail) => {
112
+ if matches!(fail.failure_info, Some(FailureInfo::CanceledFailureInfo(_))) {
113
+ LocalActivityExecutionResult::Cancelled(Cancellation {
114
+ failure: Some(fail),
115
+ })
116
+ } else {
117
+ LocalActivityExecutionResult::Failed(ActFail {
118
+ failure: Some(fail),
119
+ })
120
+ }
121
+ }
122
+ },
123
+ complete_time: d.marker_dat.complete_time.try_into_or_none(),
124
+ attempt: d.marker_dat.attempt,
125
+ backoff: d.marker_dat.backoff,
126
+ original_schedule_time: d.marker_dat.original_schedule_time.try_into_or_none(),
127
+ }
128
+ }
129
+ }
130
+
131
+ /// Creates a new local activity state machine & immediately schedules the local activity for
132
+ /// execution. No command is produced immediately to be sent to the server, as the local activity
133
+ /// must resolve before we send a record marker command. A [MachineResponse] may be produced,
134
+ /// to queue the LA for execution if it needs to be.
135
+ pub(super) fn new_local_activity(
136
+ attrs: ValidScheduleLA,
137
+ replaying_when_invoked: bool,
138
+ maybe_pre_resolved: Option<ResolveDat>,
139
+ wf_time: Option<SystemTime>,
140
+ ) -> Result<(LocalActivityMachine, Vec<MachineResponse>), WFMachinesError> {
141
+ let initial_state = if replaying_when_invoked {
142
+ if let Some(dat) = maybe_pre_resolved {
143
+ ReplayingPreResolved { dat }.into()
144
+ } else {
145
+ Replaying {}.into()
146
+ }
147
+ } else {
148
+ if maybe_pre_resolved.is_some() {
149
+ return Err(WFMachinesError::Nondeterminism(
150
+ "Local activity cannot be created as pre-resolved while not replaying".to_string(),
151
+ ));
152
+ }
153
+ Executing {}.into()
154
+ };
155
+
156
+ let mut machine = LocalActivityMachine {
157
+ state: initial_state,
158
+ shared_state: SharedState {
159
+ attrs,
160
+ replaying_when_invoked,
161
+ wf_time_when_started: wf_time,
162
+ },
163
+ };
164
+
165
+ let mut res = OnEventWrapper::on_event_mut(&mut machine, LocalActivityMachineEvents::Schedule)
166
+ .expect("Scheduling local activities doesn't fail");
167
+ let mr = if let Some(res) = res.pop() {
168
+ machine
169
+ .adapt_response(res, None)
170
+ .expect("Adapting LA schedule response doesn't fail")
171
+ } else {
172
+ vec![]
173
+ };
174
+ Ok((machine, mr))
175
+ }
176
+
177
+ impl LocalActivityMachine {
178
+ /// Is called to check if, while handling the LA marker event, we should avoid doing normal
179
+ /// command-event processing - instead simply applying the event to this machine and then
180
+ /// skipping over the rest. If this machine is in the `ResultNotified` state, that means
181
+ /// command handling should proceed as normal (ie: The command needs to be matched and removed).
182
+ /// The other valid states to make this check in are the `WaitingMarkerEvent[PreResolved]`
183
+ /// states, which will return true.
184
+ ///
185
+ /// Attempting the check in any other state likely means a bug in the SDK.
186
+ pub(super) fn marker_should_get_special_handling(&self) -> Result<bool, WFMachinesError> {
187
+ match &self.state {
188
+ LocalActivityMachineState::ResultNotified(_) => Ok(false),
189
+ LocalActivityMachineState::WaitingMarkerEvent(_) => Ok(true),
190
+ LocalActivityMachineState::WaitingMarkerEventPreResolved(_) => Ok(true),
191
+ _ => Err(WFMachinesError::Fatal(format!(
192
+ "Attempted to check for LA marker handling in invalid state {}",
193
+ self.state
194
+ ))),
195
+ }
196
+ }
197
+
198
+ /// Must be called if the workflow encounters a non-replay workflow task
199
+ pub(super) fn encountered_non_replay_wft(
200
+ &mut self,
201
+ ) -> Result<Vec<MachineResponse>, WFMachinesError> {
202
+ // This only applies to the waiting-for-marker state. It can safely be ignored in the others
203
+ if !matches!(
204
+ self.state(),
205
+ LocalActivityMachineState::WaitingMarkerEvent(_)
206
+ ) {
207
+ return Ok(vec![]);
208
+ }
209
+
210
+ let mut res =
211
+ OnEventWrapper::on_event_mut(self, LocalActivityMachineEvents::StartedNonReplayWFT)
212
+ .map_err(|e| match e {
213
+ MachineError::InvalidTransition => WFMachinesError::Fatal(format!(
214
+ "Invalid transition while notifying local activity (seq {})\
215
+ of non-replay-wft-started in {}",
216
+ self.shared_state.attrs.seq,
217
+ self.state(),
218
+ )),
219
+ MachineError::Underlying(e) => e,
220
+ })?;
221
+ let res = res.pop().expect("Always produces one response");
222
+ Ok(self
223
+ .adapt_response(res, None)
224
+ .expect("Adapting LA wft-non-replay response doesn't fail"))
225
+ }
226
+
227
+ /// Attempt to resolve the local activity with a result from execution (not from history)
228
+ pub(super) fn try_resolve(
229
+ &mut self,
230
+ result: LocalActivityExecutionResult,
231
+ runtime: Duration,
232
+ attempt: u32,
233
+ backoff: Option<prost_types::Duration>,
234
+ original_schedule_time: Option<SystemTime>,
235
+ ) -> Result<Vec<MachineResponse>, WFMachinesError> {
236
+ self.try_resolve_with_dat(ResolveDat {
237
+ result,
238
+ complete_time: self.shared_state.wf_time_when_started.map(|t| t + runtime),
239
+ attempt,
240
+ backoff,
241
+ original_schedule_time,
242
+ })
243
+ }
244
+ /// Attempt to resolve the local activity with already known data, ex pre-resolved data
245
+ pub(super) fn try_resolve_with_dat(
246
+ &mut self,
247
+ dat: ResolveDat,
248
+ ) -> Result<Vec<MachineResponse>, WFMachinesError> {
249
+ let res = OnEventWrapper::on_event_mut(self, LocalActivityMachineEvents::HandleResult(dat))
250
+ .map_err(|e| match e {
251
+ MachineError::InvalidTransition => WFMachinesError::Fatal(format!(
252
+ "Invalid transition resolving local activity (seq {}) in {}",
253
+ self.shared_state.attrs.seq,
254
+ self.state(),
255
+ )),
256
+ MachineError::Underlying(e) => e,
257
+ })?;
258
+
259
+ Ok(res
260
+ .into_iter()
261
+ .flat_map(|res| {
262
+ self.adapt_response(res, None)
263
+ .expect("Adapting LA resolve response doesn't fail")
264
+ })
265
+ .collect())
266
+ }
267
+ }
268
+
269
+ #[derive(Clone)]
270
+ pub(super) struct SharedState {
271
+ attrs: ValidScheduleLA,
272
+ replaying_when_invoked: bool,
273
+ wf_time_when_started: Option<SystemTime>,
274
+ }
275
+
276
+ impl SharedState {
277
+ fn produce_no_wait_cancel_resolve_dat(&self) -> ResolveDat {
278
+ ResolveDat {
279
+ result: LocalActivityExecutionResult::empty_cancel(),
280
+ // Just don't provide a complete time, which means try-cancel/abandon cancels won't
281
+ // advance the clock. Seems like that's fine, since you can only cancel after awaiting
282
+ // some other command, which would have appropriately advanced the clock anyway.
283
+ complete_time: None,
284
+ attempt: self.attrs.attempt,
285
+ backoff: None,
286
+ original_schedule_time: self.attrs.original_schedule_time,
287
+ }
288
+ }
289
+ }
290
+
291
+ #[derive(Debug, derive_more::Display)]
292
+ pub(super) enum LocalActivityCommand {
293
+ RequestActivityExecution(ValidScheduleLA),
294
+ #[display(fmt = "Resolved")]
295
+ Resolved(ResolveDat),
296
+ /// The fake marker is used to avoid special casing marker recorded event handling.
297
+ /// If we didn't have the fake marker, there would be no "outgoing command" to match
298
+ /// against the event. This way there is, but the command never will be issued to
299
+ /// server because it is understood to be meaningless.
300
+ #[display(fmt = "FakeMarker")]
301
+ FakeMarker,
302
+ /// Indicate we want to cancel an LA that is currently executing, or look up if we have
303
+ /// processed a marker with resolution data since the machine was constructed.
304
+ #[display(fmt = "Cancel")]
305
+ RequestCancel,
306
+ }
307
+
308
+ #[derive(Default, Clone)]
309
+ pub(super) struct Executing {}
310
+
311
+ impl Executing {
312
+ pub(super) fn on_schedule(
313
+ self,
314
+ dat: SharedState,
315
+ ) -> LocalActivityMachineTransition<RequestSent> {
316
+ TransitionResult::commands([LocalActivityCommand::RequestActivityExecution(dat.attrs)])
317
+ }
318
+ }
319
+
320
+ #[derive(Clone, Copy, PartialEq, Eq)]
321
+ enum ResultType {
322
+ Completed,
323
+ Cancelled,
324
+ Failed,
325
+ }
326
+ #[derive(Clone)]
327
+ pub(super) struct MarkerCommandCreated {
328
+ result_type: ResultType,
329
+ }
330
+ impl From<MarkerCommandCreated> for ResultNotified {
331
+ fn from(mc: MarkerCommandCreated) -> Self {
332
+ Self {
333
+ result_type: mc.result_type,
334
+ }
335
+ }
336
+ }
337
+
338
+ impl MarkerCommandCreated {
339
+ pub(super) fn on_command_record_marker(self) -> LocalActivityMachineTransition<ResultNotified> {
340
+ TransitionResult::from(self)
341
+ }
342
+ }
343
+
344
+ #[derive(Default, Clone)]
345
+ pub(super) struct MarkerCommandRecorded {}
346
+ impl MarkerCommandRecorded {
347
+ fn on_cancel_requested(self) -> LocalActivityMachineTransition<MarkerCommandRecorded> {
348
+ // We still must issue a cancel request even if this command is resolved, because if it
349
+ // failed and we are backing off locally, we must tell the LA dispatcher to quit retrying.
350
+ TransitionResult::ok([LocalActivityCommand::RequestCancel], self)
351
+ }
352
+
353
+ fn on_no_wait_cancel(
354
+ self,
355
+ cancel_type: ActivityCancellationType,
356
+ ) -> LocalActivityMachineTransition<MarkerCommandRecorded> {
357
+ if matches!(cancel_type, ActivityCancellationType::TryCancel) {
358
+ // We still must issue a cancel request even if this command is resolved, because if it
359
+ // failed and we are backing off locally, we must tell the LA dispatcher to quit
360
+ // retrying.
361
+ TransitionResult::ok(
362
+ [LocalActivityCommand::RequestCancel],
363
+ MarkerCommandRecorded::default(),
364
+ )
365
+ } else {
366
+ TransitionResult::default()
367
+ }
368
+ }
369
+ }
370
+
371
+ #[derive(Default, Clone)]
372
+ pub(super) struct Replaying {}
373
+ impl Replaying {
374
+ pub(super) fn on_schedule(self) -> LocalActivityMachineTransition<WaitingMarkerEvent> {
375
+ TransitionResult::ok(
376
+ [],
377
+ WaitingMarkerEvent {
378
+ already_resolved: false,
379
+ },
380
+ )
381
+ }
382
+ }
383
+
384
+ #[derive(Clone)]
385
+ pub(super) struct ReplayingPreResolved {
386
+ dat: ResolveDat,
387
+ }
388
+ impl ReplayingPreResolved {
389
+ pub(super) fn on_schedule(
390
+ self,
391
+ ) -> LocalActivityMachineTransition<WaitingMarkerEventPreResolved> {
392
+ TransitionResult::ok(
393
+ [
394
+ LocalActivityCommand::FakeMarker,
395
+ LocalActivityCommand::Resolved(self.dat),
396
+ ],
397
+ WaitingMarkerEventPreResolved {},
398
+ )
399
+ }
400
+ }
401
+
402
+ #[derive(Default, Clone)]
403
+ pub(super) struct RequestSent {}
404
+
405
+ impl RequestSent {
406
+ fn on_handle_result(
407
+ self,
408
+ dat: ResolveDat,
409
+ ) -> LocalActivityMachineTransition<MarkerCommandCreated> {
410
+ let result_type = match &dat.result {
411
+ LocalActivityExecutionResult::Completed(_) => ResultType::Completed,
412
+ LocalActivityExecutionResult::Failed(_) => ResultType::Failed,
413
+ LocalActivityExecutionResult::TimedOut(_) => ResultType::Failed,
414
+ LocalActivityExecutionResult::Cancelled { .. } => ResultType::Cancelled,
415
+ };
416
+ let new_state = MarkerCommandCreated { result_type };
417
+ TransitionResult::ok([LocalActivityCommand::Resolved(dat)], new_state)
418
+ }
419
+
420
+ fn on_cancel_requested(self) -> LocalActivityMachineTransition<RequestSent> {
421
+ TransitionResult::ok([LocalActivityCommand::RequestCancel], self)
422
+ }
423
+
424
+ fn on_no_wait_cancel(
425
+ self,
426
+ shared: SharedState,
427
+ cancel_type: ActivityCancellationType,
428
+ ) -> LocalActivityMachineTransition<MarkerCommandCreated> {
429
+ let mut cmds = vec![];
430
+ if matches!(cancel_type, ActivityCancellationType::TryCancel) {
431
+ // For try-cancels also request the cancel
432
+ cmds.push(LocalActivityCommand::RequestCancel);
433
+ }
434
+ // Immediately resolve
435
+ cmds.push(LocalActivityCommand::Resolved(
436
+ shared.produce_no_wait_cancel_resolve_dat(),
437
+ ));
438
+ TransitionResult::ok(
439
+ cmds,
440
+ MarkerCommandCreated {
441
+ result_type: ResultType::Cancelled,
442
+ },
443
+ )
444
+ }
445
+ }
446
+
447
+ macro_rules! verify_marker_dat {
448
+ ($shared:expr, $dat:expr, $ok_expr:expr) => {
449
+ if let Err(err) = verify_marker_data_matches($shared, $dat) {
450
+ TransitionResult::Err(err)
451
+ } else {
452
+ $ok_expr
453
+ }
454
+ };
455
+ }
456
+
457
+ #[derive(Clone)]
458
+ pub(super) struct ResultNotified {
459
+ result_type: ResultType,
460
+ }
461
+
462
+ impl ResultNotified {
463
+ pub(super) fn on_marker_recorded(
464
+ self,
465
+ shared: SharedState,
466
+ dat: CompleteLocalActivityData,
467
+ ) -> LocalActivityMachineTransition<MarkerCommandRecorded> {
468
+ if self.result_type == ResultType::Completed && dat.result.is_err() {
469
+ return TransitionResult::Err(WFMachinesError::Nondeterminism(format!(
470
+ "Local activity (seq {}) completed successfully locally, but history said \
471
+ it failed!",
472
+ shared.attrs.seq
473
+ )));
474
+ } else if self.result_type == ResultType::Failed && dat.result.is_ok() {
475
+ return TransitionResult::Err(WFMachinesError::Nondeterminism(format!(
476
+ "Local activity (seq {}) failed locally, but history said it completed!",
477
+ shared.attrs.seq
478
+ )));
479
+ }
480
+ verify_marker_dat!(&shared, &dat, TransitionResult::default())
481
+ }
482
+ }
483
+
484
+ #[derive(Default, Clone)]
485
+ pub(super) struct WaitingMarkerEvent {
486
+ already_resolved: bool,
487
+ }
488
+
489
+ impl WaitingMarkerEvent {
490
+ pub(super) fn on_marker_recorded(
491
+ self,
492
+ shared: SharedState,
493
+ dat: CompleteLocalActivityData,
494
+ ) -> LocalActivityMachineTransition<MarkerCommandRecorded> {
495
+ verify_marker_dat!(
496
+ &shared,
497
+ &dat,
498
+ TransitionResult::commands(if self.already_resolved {
499
+ vec![]
500
+ } else {
501
+ vec![LocalActivityCommand::Resolved(dat.into())]
502
+ })
503
+ )
504
+ }
505
+ pub(super) fn on_started_non_replay_wft(
506
+ self,
507
+ mut dat: SharedState,
508
+ ) -> LocalActivityMachineTransition<RequestSent> {
509
+ // We aren't really "replaying" anymore for our purposes, and want to record the marker.
510
+ dat.replaying_when_invoked = false;
511
+ TransitionResult::ok_shared(
512
+ [LocalActivityCommand::RequestActivityExecution(
513
+ dat.attrs.clone(),
514
+ )],
515
+ RequestSent::default(),
516
+ dat,
517
+ )
518
+ }
519
+
520
+ fn on_cancel_requested(self) -> LocalActivityMachineTransition<WaitingMarkerEventCancelled> {
521
+ // We still "request a cancel" even though we know the local activity should not be running
522
+ // because the data might be in the pre-resolved list.
523
+ TransitionResult::ok(
524
+ [LocalActivityCommand::RequestCancel],
525
+ WaitingMarkerEventCancelled {},
526
+ )
527
+ }
528
+
529
+ fn on_no_wait_cancel(
530
+ self,
531
+ _: ActivityCancellationType,
532
+ ) -> LocalActivityMachineTransition<WaitingMarkerEventCancelled> {
533
+ // Markers are always recorded when cancelling, so this is the same as a normal cancel on
534
+ // the replay path
535
+ self.on_cancel_requested()
536
+ }
537
+ }
538
+
539
+ #[derive(Default, Clone)]
540
+ pub(super) struct WaitingMarkerEventCancelled {}
541
+ impl WaitingMarkerEventCancelled {
542
+ fn on_handle_result(
543
+ self,
544
+ dat: ResolveDat,
545
+ ) -> LocalActivityMachineTransition<WaitingMarkerEvent> {
546
+ TransitionResult::ok(
547
+ [LocalActivityCommand::Resolved(dat)],
548
+ WaitingMarkerEvent {
549
+ already_resolved: true,
550
+ },
551
+ )
552
+ }
553
+ }
554
+
555
+ #[derive(Default, Clone)]
556
+ pub(super) struct WaitingMarkerEventPreResolved {}
557
+ impl WaitingMarkerEventPreResolved {
558
+ pub(super) fn on_marker_recorded(
559
+ self,
560
+ shared: SharedState,
561
+ dat: CompleteLocalActivityData,
562
+ ) -> LocalActivityMachineTransition<MarkerCommandRecorded> {
563
+ verify_marker_dat!(&shared, &dat, TransitionResult::default())
564
+ }
565
+ }
566
+
567
+ impl Cancellable for LocalActivityMachine {
568
+ fn cancel(&mut self) -> Result<Vec<MachineResponse>, MachineError<Self::Error>> {
569
+ let event = match self.shared_state.attrs.cancellation_type {
570
+ ct @ ActivityCancellationType::TryCancel | ct @ ActivityCancellationType::Abandon => {
571
+ LocalActivityMachineEvents::NoWaitCancel(ct)
572
+ }
573
+ _ => LocalActivityMachineEvents::Cancel,
574
+ };
575
+ let cmds = OnEventWrapper::on_event_mut(self, event)?;
576
+ let mach_resps = cmds
577
+ .into_iter()
578
+ .map(|mc| self.adapt_response(mc, None))
579
+ .collect::<Result<Vec<_>, _>>()?
580
+ .into_iter()
581
+ .flatten()
582
+ .collect();
583
+ Ok(mach_resps)
584
+ }
585
+
586
+ fn was_cancelled_before_sent_to_server(&self) -> bool {
587
+ // This needs to always be false because for the situation where we cancel in the same WFT,
588
+ // no command of any kind is created and no LA request is queued. Otherwise, the command we
589
+ // create to record a cancel marker *needs* to be sent to the server still, which returning
590
+ // true here would prevent.
591
+ false
592
+ }
593
+ }
594
+
595
+ #[derive(Default, Clone)]
596
+ pub(super) struct Abandoned {}
597
+
598
+ impl WFMachinesAdapter for LocalActivityMachine {
599
+ fn adapt_response(
600
+ &self,
601
+ my_command: Self::Command,
602
+ _event_info: Option<EventInfo>,
603
+ ) -> Result<Vec<MachineResponse>, WFMachinesError> {
604
+ match my_command {
605
+ LocalActivityCommand::RequestActivityExecution(act) => {
606
+ Ok(vec![MachineResponse::QueueLocalActivity(act)])
607
+ }
608
+ LocalActivityCommand::Resolved(ResolveDat {
609
+ result,
610
+ complete_time,
611
+ attempt,
612
+ backoff,
613
+ original_schedule_time,
614
+ }) => {
615
+ let mut maybe_ok_result = None;
616
+ let mut maybe_failure = None;
617
+ // Only issue record marker commands if we weren't replaying
618
+ let record_marker = !self.shared_state.replaying_when_invoked;
619
+ let mut will_not_run_again = false;
620
+ match result.clone() {
621
+ LocalActivityExecutionResult::Completed(suc) => {
622
+ maybe_ok_result = suc.result;
623
+ }
624
+ LocalActivityExecutionResult::Failed(fail) => {
625
+ maybe_failure = fail.failure;
626
+ }
627
+ LocalActivityExecutionResult::Cancelled(Cancellation { failure })
628
+ | LocalActivityExecutionResult::TimedOut(ActFail { failure }) => {
629
+ will_not_run_again = true;
630
+ maybe_failure = failure;
631
+ }
632
+ };
633
+ let resolution = if let Some(b) = backoff.as_ref() {
634
+ ActivityResolution {
635
+ status: Some(
636
+ DoBackoff {
637
+ attempt: attempt + 1,
638
+ backoff_duration: Some(b.clone()),
639
+ original_schedule_time: original_schedule_time.map(Into::into),
640
+ }
641
+ .into(),
642
+ ),
643
+ }
644
+ } else {
645
+ result.into()
646
+ };
647
+ let mut responses = vec![
648
+ MachineResponse::PushWFJob(
649
+ ResolveActivity {
650
+ seq: self.shared_state.attrs.seq,
651
+ result: Some(resolution),
652
+ }
653
+ .into(),
654
+ ),
655
+ MachineResponse::UpdateWFTime(complete_time),
656
+ ];
657
+
658
+ // Cancel-resolves of abandoned activities must be explicitly dropped from tracking
659
+ // to avoid unnecessary WFT heartbeating.
660
+ if will_not_run_again
661
+ && matches!(
662
+ self.shared_state.attrs.cancellation_type,
663
+ ActivityCancellationType::Abandon
664
+ )
665
+ {
666
+ responses.push(MachineResponse::AbandonLocalActivity(
667
+ self.shared_state.attrs.seq,
668
+ ));
669
+ }
670
+
671
+ if record_marker {
672
+ let marker_data = RecordMarkerCommandAttributes {
673
+ marker_name: LOCAL_ACTIVITY_MARKER_NAME.to_string(),
674
+ details: build_local_activity_marker_details(
675
+ LocalActivityMarkerData {
676
+ seq: self.shared_state.attrs.seq,
677
+ attempt,
678
+ activity_id: self.shared_state.attrs.activity_id.clone(),
679
+ activity_type: self.shared_state.attrs.activity_type.clone(),
680
+ complete_time: complete_time.map(Into::into),
681
+ backoff,
682
+ original_schedule_time: original_schedule_time.map(Into::into),
683
+ },
684
+ maybe_ok_result,
685
+ ),
686
+ header: None,
687
+ failure: maybe_failure,
688
+ };
689
+ responses.push(MachineResponse::IssueNewCommand(Command {
690
+ command_type: CommandType::RecordMarker as i32,
691
+ attributes: Some(marker_data.into()),
692
+ }));
693
+ }
694
+ Ok(responses)
695
+ }
696
+ LocalActivityCommand::FakeMarker => {
697
+ // See docs for `FakeMarker` for more
698
+ Ok(vec![MachineResponse::IssueFakeLocalActivityMarker(
699
+ self.shared_state.attrs.seq,
700
+ )])
701
+ }
702
+ LocalActivityCommand::RequestCancel => {
703
+ Ok(vec![MachineResponse::RequestCancelLocalActivity(
704
+ self.shared_state.attrs.seq,
705
+ )])
706
+ }
707
+ }
708
+ }
709
+
710
+ fn matches_event(&self, event: &HistoryEvent) -> bool {
711
+ event.is_local_activity_marker()
712
+ }
713
+
714
+ fn kind(&self) -> MachineKind {
715
+ MachineKind::LocalActivity
716
+ }
717
+ }
718
+
719
+ impl TryFrom<CommandType> for LocalActivityMachineEvents {
720
+ type Error = ();
721
+
722
+ fn try_from(c: CommandType) -> Result<Self, Self::Error> {
723
+ Ok(match c {
724
+ CommandType::RecordMarker => Self::CommandRecordMarker,
725
+ _ => return Err(()),
726
+ })
727
+ }
728
+ }
729
+
730
+ impl TryFrom<HistoryEvent> for LocalActivityMachineEvents {
731
+ type Error = WFMachinesError;
732
+
733
+ fn try_from(e: HistoryEvent) -> Result<Self, Self::Error> {
734
+ if e.event_type() != EventType::MarkerRecorded {
735
+ return Err(WFMachinesError::Nondeterminism(format!(
736
+ "Local activity machine cannot handle this event: {}",
737
+ e
738
+ )));
739
+ }
740
+
741
+ match e.into_local_activity_marker_details() {
742
+ Some(marker_dat) => Ok(LocalActivityMachineEvents::MarkerRecorded(marker_dat)),
743
+ _ => Err(WFMachinesError::Nondeterminism(
744
+ "Local activity machine encountered an unparsable marker".to_string(),
745
+ )),
746
+ }
747
+ }
748
+ }
749
+
750
+ fn verify_marker_data_matches(
751
+ shared: &SharedState,
752
+ dat: &CompleteLocalActivityData,
753
+ ) -> Result<(), WFMachinesError> {
754
+ if shared.attrs.seq != dat.marker_dat.seq {
755
+ return Err(WFMachinesError::Nondeterminism(format!(
756
+ "Local activity marker data has sequence number {} but matched against LA \
757
+ command with sequence number {}",
758
+ dat.marker_dat.seq, shared.attrs.seq
759
+ )));
760
+ }
761
+
762
+ Ok(())
763
+ }
764
+
765
+ impl From<LocalActivityExecutionResult> for ActivityResolution {
766
+ fn from(lar: LocalActivityExecutionResult) -> Self {
767
+ match lar {
768
+ LocalActivityExecutionResult::Completed(c) => ActivityResolution {
769
+ status: Some(c.into()),
770
+ },
771
+ LocalActivityExecutionResult::Failed(f) | LocalActivityExecutionResult::TimedOut(f) => {
772
+ ActivityResolution {
773
+ status: Some(f.into()),
774
+ }
775
+ }
776
+ LocalActivityExecutionResult::Cancelled(cancel) => ActivityResolution {
777
+ status: Some(cancel.into()),
778
+ },
779
+ }
780
+ }
781
+ }
782
+
783
+ #[cfg(test)]
784
+ mod tests {
785
+ use super::*;
786
+ use crate::{
787
+ replay::TestHistoryBuilder, test_help::canned_histories,
788
+ workflow::managed_wf::ManagedWFFunc,
789
+ };
790
+ use rstest::rstest;
791
+ use std::time::Duration;
792
+ use temporal_sdk::{
793
+ CancellableFuture, LocalActivityOptions, WfContext, WorkflowFunction, WorkflowResult,
794
+ };
795
+ use temporal_sdk_core_protos::{
796
+ coresdk::{
797
+ activity_result::ActivityExecutionResult,
798
+ workflow_activation::{workflow_activation_job, WorkflowActivationJob},
799
+ workflow_commands::ActivityCancellationType::WaitCancellationCompleted,
800
+ },
801
+ temporal::api::{
802
+ command::v1::command, enums::v1::WorkflowTaskFailedCause, failure::v1::Failure,
803
+ },
804
+ };
805
+
806
+ async fn la_wf(ctx: WfContext) -> WorkflowResult<()> {
807
+ ctx.local_activity(LocalActivityOptions::default()).await;
808
+ Ok(().into())
809
+ }
810
+
811
+ #[rstest]
812
+ #[case::incremental(false, true)]
813
+ #[case::replay(true, true)]
814
+ #[case::incremental_fail(false, false)]
815
+ #[case::replay_fail(true, false)]
816
+ #[tokio::test]
817
+ async fn one_la_success(#[case] replay: bool, #[case] completes_ok: bool) {
818
+ let func = WorkflowFunction::new(la_wf);
819
+ let activity_id = "1";
820
+ let mut t = TestHistoryBuilder::default();
821
+ t.add_by_type(EventType::WorkflowExecutionStarted);
822
+ t.add_full_wf_task();
823
+ if completes_ok {
824
+ t.add_local_activity_result_marker(1, activity_id, b"hi".into());
825
+ } else {
826
+ t.add_local_activity_fail_marker(
827
+ 1,
828
+ activity_id,
829
+ Failure::application_failure("I failed".to_string(), false),
830
+ );
831
+ }
832
+ t.add_workflow_execution_completed();
833
+
834
+ let histinfo = if replay {
835
+ t.get_full_history_info().unwrap().into()
836
+ } else {
837
+ t.get_history_info(1).unwrap().into()
838
+ };
839
+ let mut wfm = ManagedWFFunc::new_from_update(histinfo, func, vec![]);
840
+
841
+ // First activation will have no server commands. Activity will be put into the activity
842
+ // queue locally
843
+ wfm.get_next_activation().await.unwrap();
844
+ let commands = wfm.get_server_commands().commands;
845
+ assert_eq!(commands.len(), 0);
846
+
847
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
848
+ if !replay {
849
+ assert_eq!(ready_to_execute_las.len(), 1);
850
+ } else {
851
+ assert_eq!(ready_to_execute_las.len(), 0);
852
+ }
853
+
854
+ if !replay {
855
+ if completes_ok {
856
+ wfm.complete_local_activity(1, ActivityExecutionResult::ok(b"hi".into()))
857
+ .unwrap();
858
+ } else {
859
+ wfm.complete_local_activity(
860
+ 1,
861
+ ActivityExecutionResult::fail(Failure {
862
+ message: "I failed".to_string(),
863
+ ..Default::default()
864
+ }),
865
+ )
866
+ .unwrap();
867
+ }
868
+ }
869
+
870
+ // Now the next activation will unblock the local activity
871
+ wfm.get_next_activation().await.unwrap();
872
+ let commands = wfm.get_server_commands().commands;
873
+ if replay {
874
+ assert_eq!(commands.len(), 1);
875
+ assert_eq!(
876
+ commands[0].command_type,
877
+ CommandType::CompleteWorkflowExecution as i32
878
+ );
879
+ } else {
880
+ assert_eq!(commands.len(), 2);
881
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
882
+ if completes_ok {
883
+ assert_matches!(
884
+ commands[0].attributes.as_ref().unwrap(),
885
+ command::Attributes::RecordMarkerCommandAttributes(
886
+ RecordMarkerCommandAttributes { failure: None, .. }
887
+ )
888
+ );
889
+ } else {
890
+ assert_matches!(
891
+ commands[0].attributes.as_ref().unwrap(),
892
+ command::Attributes::RecordMarkerCommandAttributes(
893
+ RecordMarkerCommandAttributes {
894
+ failure: Some(_),
895
+ ..
896
+ }
897
+ )
898
+ );
899
+ }
900
+ assert_eq!(
901
+ commands[1].command_type,
902
+ CommandType::CompleteWorkflowExecution as i32
903
+ );
904
+ }
905
+
906
+ if !replay {
907
+ wfm.new_history(t.get_full_history_info().unwrap().into())
908
+ .await
909
+ .unwrap();
910
+ }
911
+ assert_eq!(wfm.drain_queued_local_activities().len(), 0);
912
+ assert_eq!(wfm.get_next_activation().await.unwrap().jobs.len(), 0);
913
+ let commands = wfm.get_server_commands().commands;
914
+ assert_eq!(commands.len(), 0);
915
+
916
+ wfm.shutdown().await.unwrap();
917
+ }
918
+
919
+ async fn two_la_wf(ctx: WfContext) -> WorkflowResult<()> {
920
+ ctx.local_activity(LocalActivityOptions::default()).await;
921
+ ctx.local_activity(LocalActivityOptions::default()).await;
922
+ Ok(().into())
923
+ }
924
+
925
+ #[rstest]
926
+ #[case::incremental(false)]
927
+ #[case::replay(true)]
928
+ #[tokio::test]
929
+ async fn two_sequential_las(#[case] replay: bool) {
930
+ let func = WorkflowFunction::new(two_la_wf);
931
+ let t = canned_histories::two_local_activities_one_wft(false);
932
+ let histinfo = if replay {
933
+ t.get_full_history_info().unwrap().into()
934
+ } else {
935
+ t.get_history_info(1).unwrap().into()
936
+ };
937
+ let mut wfm = ManagedWFFunc::new_from_update(histinfo, func, vec![]);
938
+
939
+ // First activation will have no server commands. Activity will be put into the activity
940
+ // queue locally
941
+ let act = wfm.get_next_activation().await.unwrap();
942
+ let first_act_ts = act.timestamp.unwrap();
943
+ let commands = wfm.get_server_commands().commands;
944
+ assert_eq!(commands.len(), 0);
945
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
946
+ let num_queued = if !replay { 1 } else { 0 };
947
+ assert_eq!(ready_to_execute_las.len(), num_queued);
948
+
949
+ if !replay {
950
+ wfm.complete_local_activity(1, ActivityExecutionResult::ok(b"Resolved".into()))
951
+ .unwrap();
952
+ }
953
+
954
+ let act = wfm.get_next_activation().await.unwrap();
955
+ // Verify LAs advance time (they take 1s in this test)
956
+ assert_eq!(act.timestamp.unwrap().seconds, first_act_ts.seconds + 1);
957
+ assert_matches!(
958
+ act.jobs.as_slice(),
959
+ [WorkflowActivationJob {
960
+ variant: Some(workflow_activation_job::Variant::ResolveActivity(ra))
961
+ }] => assert_eq!(ra.seq, 1)
962
+ );
963
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
964
+ if !replay {
965
+ assert_eq!(ready_to_execute_las.len(), 1);
966
+ } else {
967
+ assert_eq!(ready_to_execute_las.len(), 0);
968
+ }
969
+
970
+ if !replay {
971
+ wfm.complete_local_activity(2, ActivityExecutionResult::ok(b"Resolved".into()))
972
+ .unwrap();
973
+ }
974
+
975
+ let act = wfm.get_next_activation().await.unwrap();
976
+ assert_eq!(act.timestamp.unwrap().seconds, first_act_ts.seconds + 2);
977
+ assert_matches!(
978
+ act.jobs.as_slice(),
979
+ [WorkflowActivationJob {
980
+ variant: Some(workflow_activation_job::Variant::ResolveActivity(ra))
981
+ }] => assert_eq!(ra.seq, 2)
982
+ );
983
+ let commands = wfm.get_server_commands().commands;
984
+ if replay {
985
+ assert_eq!(commands.len(), 1);
986
+ assert_eq!(
987
+ commands[0].command_type,
988
+ CommandType::CompleteWorkflowExecution as i32
989
+ );
990
+ } else {
991
+ assert_eq!(commands.len(), 3);
992
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
993
+ assert_eq!(commands[1].command_type, CommandType::RecordMarker as i32);
994
+ assert_eq!(
995
+ commands[2].command_type,
996
+ CommandType::CompleteWorkflowExecution as i32
997
+ );
998
+ }
999
+
1000
+ if !replay {
1001
+ wfm.new_history(t.get_full_history_info().unwrap().into())
1002
+ .await
1003
+ .unwrap();
1004
+ }
1005
+ assert_eq!(wfm.get_next_activation().await.unwrap().jobs.len(), 0);
1006
+ let commands = wfm.get_server_commands().commands;
1007
+ assert_eq!(commands.len(), 0);
1008
+
1009
+ wfm.shutdown().await.unwrap();
1010
+ }
1011
+
1012
+ async fn two_la_wf_parallel(ctx: WfContext) -> WorkflowResult<()> {
1013
+ tokio::join!(
1014
+ ctx.local_activity(LocalActivityOptions::default()),
1015
+ ctx.local_activity(LocalActivityOptions::default())
1016
+ );
1017
+ Ok(().into())
1018
+ }
1019
+
1020
+ #[rstest]
1021
+ #[case::incremental(false)]
1022
+ #[case::replay(true)]
1023
+ #[tokio::test]
1024
+ async fn two_parallel_las(#[case] replay: bool) {
1025
+ let func = WorkflowFunction::new(two_la_wf_parallel);
1026
+ let t = canned_histories::two_local_activities_one_wft(true);
1027
+ let histinfo = if replay {
1028
+ t.get_full_history_info().unwrap().into()
1029
+ } else {
1030
+ t.get_history_info(1).unwrap().into()
1031
+ };
1032
+ let mut wfm = ManagedWFFunc::new_from_update(histinfo, func, vec![]);
1033
+
1034
+ // First activation will have no server commands. Activity(ies) will be put into the queue
1035
+ // for execution
1036
+ let act = wfm.get_next_activation().await.unwrap();
1037
+ let first_act_ts = act.timestamp.unwrap();
1038
+ let commands = wfm.get_server_commands().commands;
1039
+ assert_eq!(commands.len(), 0);
1040
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1041
+ let num_queued = if !replay { 2 } else { 0 };
1042
+ assert_eq!(ready_to_execute_las.len(), num_queued);
1043
+
1044
+ if !replay {
1045
+ wfm.complete_local_activity(1, ActivityExecutionResult::ok(b"Resolved".into()))
1046
+ .unwrap();
1047
+ wfm.complete_local_activity(2, ActivityExecutionResult::ok(b"Resolved".into()))
1048
+ .unwrap();
1049
+ }
1050
+
1051
+ let act = wfm.get_next_activation().await.unwrap();
1052
+ assert_eq!(act.timestamp.unwrap().seconds, first_act_ts.seconds + 1);
1053
+ assert_matches!(
1054
+ act.jobs.as_slice(),
1055
+ [WorkflowActivationJob {
1056
+ variant: Some(workflow_activation_job::Variant::ResolveActivity(ra))
1057
+ },
1058
+ WorkflowActivationJob {
1059
+ variant: Some(workflow_activation_job::Variant::ResolveActivity(ra2))
1060
+ }] => {assert_eq!(ra.seq, 1); assert_eq!(ra2.seq, 2)}
1061
+ );
1062
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1063
+ assert_eq!(ready_to_execute_las.len(), 0);
1064
+
1065
+ let commands = wfm.get_server_commands().commands;
1066
+ if replay {
1067
+ assert_eq!(commands.len(), 1);
1068
+ assert_eq!(
1069
+ commands[0].command_type,
1070
+ CommandType::CompleteWorkflowExecution as i32
1071
+ );
1072
+ } else {
1073
+ assert_eq!(commands.len(), 3);
1074
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
1075
+ assert_eq!(commands[1].command_type, CommandType::RecordMarker as i32);
1076
+ assert_eq!(
1077
+ commands[2].command_type,
1078
+ CommandType::CompleteWorkflowExecution as i32
1079
+ );
1080
+ }
1081
+
1082
+ if !replay {
1083
+ wfm.new_history(t.get_full_history_info().unwrap().into())
1084
+ .await
1085
+ .unwrap();
1086
+ }
1087
+ let act = wfm.get_next_activation().await.unwrap();
1088
+ // Still only 1s ahead b/c parallel
1089
+ assert_eq!(act.timestamp.unwrap().seconds, first_act_ts.seconds + 1);
1090
+ assert_eq!(act.jobs.len(), 0);
1091
+ let commands = wfm.get_server_commands().commands;
1092
+ assert_eq!(commands.len(), 0);
1093
+
1094
+ wfm.shutdown().await.unwrap();
1095
+ }
1096
+
1097
+ async fn la_timer_la(ctx: WfContext) -> WorkflowResult<()> {
1098
+ ctx.local_activity(LocalActivityOptions::default()).await;
1099
+ ctx.timer(Duration::from_secs(5)).await;
1100
+ ctx.local_activity(LocalActivityOptions::default()).await;
1101
+ Ok(().into())
1102
+ }
1103
+
1104
+ #[rstest]
1105
+ #[case::incremental(false)]
1106
+ #[case::replay(true)]
1107
+ #[tokio::test]
1108
+ async fn las_separated_by_timer(#[case] replay: bool) {
1109
+ let func = WorkflowFunction::new(la_timer_la);
1110
+ let t = canned_histories::two_local_activities_separated_by_timer();
1111
+ let histinfo = if replay {
1112
+ t.get_full_history_info().unwrap().into()
1113
+ } else {
1114
+ t.get_history_info(1).unwrap().into()
1115
+ };
1116
+ let mut wfm = ManagedWFFunc::new_from_update(histinfo, func, vec![]);
1117
+
1118
+ wfm.get_next_activation().await.unwrap();
1119
+ let commands = wfm.get_server_commands().commands;
1120
+ assert_eq!(commands.len(), 0);
1121
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1122
+ let num_queued = if !replay { 1 } else { 0 };
1123
+ assert_eq!(ready_to_execute_las.len(), num_queued);
1124
+
1125
+ if !replay {
1126
+ wfm.complete_local_activity(1, ActivityExecutionResult::ok(b"Resolved".into()))
1127
+ .unwrap();
1128
+ }
1129
+
1130
+ let act = wfm.get_next_activation().await.unwrap();
1131
+ assert_matches!(
1132
+ act.jobs.as_slice(),
1133
+ [WorkflowActivationJob {
1134
+ variant: Some(workflow_activation_job::Variant::ResolveActivity(ra))
1135
+ }] => assert_eq!(ra.seq, 1)
1136
+ );
1137
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1138
+ assert_eq!(ready_to_execute_las.len(), 0);
1139
+
1140
+ let commands = wfm.get_server_commands().commands;
1141
+ if replay {
1142
+ assert_eq!(commands.len(), 1);
1143
+ assert_eq!(commands[0].command_type, CommandType::StartTimer as i32);
1144
+ } else {
1145
+ assert_eq!(commands.len(), 2);
1146
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
1147
+ assert_eq!(commands[1].command_type, CommandType::StartTimer as i32);
1148
+ }
1149
+
1150
+ let act = if !replay {
1151
+ wfm.new_history(t.get_history_info(2).unwrap().into())
1152
+ .await
1153
+ .unwrap()
1154
+ } else {
1155
+ wfm.get_next_activation().await.unwrap()
1156
+ };
1157
+ assert_matches!(
1158
+ act.jobs.as_slice(),
1159
+ [WorkflowActivationJob {
1160
+ variant: Some(workflow_activation_job::Variant::FireTimer(_))
1161
+ }]
1162
+ );
1163
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1164
+ let num_queued = if !replay { 1 } else { 0 };
1165
+ assert_eq!(ready_to_execute_las.len(), num_queued);
1166
+ if !replay {
1167
+ wfm.complete_local_activity(2, ActivityExecutionResult::ok(b"Resolved".into()))
1168
+ .unwrap();
1169
+ }
1170
+
1171
+ let act = wfm.get_next_activation().await.unwrap();
1172
+ assert_matches!(
1173
+ act.jobs.as_slice(),
1174
+ [WorkflowActivationJob {
1175
+ variant: Some(workflow_activation_job::Variant::ResolveActivity(ra))
1176
+ }] => assert_eq!(ra.seq, 2)
1177
+ );
1178
+
1179
+ let commands = wfm.get_server_commands().commands;
1180
+ if replay {
1181
+ assert_eq!(commands.len(), 1);
1182
+ assert_eq!(
1183
+ commands[0].command_type,
1184
+ CommandType::CompleteWorkflowExecution as i32
1185
+ );
1186
+ } else {
1187
+ assert_eq!(commands.len(), 2);
1188
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
1189
+ assert_eq!(
1190
+ commands[1].command_type,
1191
+ CommandType::CompleteWorkflowExecution as i32
1192
+ );
1193
+ }
1194
+
1195
+ wfm.shutdown().await.unwrap();
1196
+ }
1197
+
1198
+ #[tokio::test]
1199
+ async fn one_la_heartbeating_wft_failure_still_executes() {
1200
+ let func = WorkflowFunction::new(la_wf);
1201
+ let mut t = TestHistoryBuilder::default();
1202
+ t.add_by_type(EventType::WorkflowExecutionStarted);
1203
+ // Heartbeats
1204
+ t.add_full_wf_task();
1205
+ // fails a wft for some reason
1206
+ t.add_workflow_task_scheduled_and_started();
1207
+ t.add_workflow_task_failed_with_failure(
1208
+ WorkflowTaskFailedCause::NonDeterministicError,
1209
+ Default::default(),
1210
+ );
1211
+ t.add_workflow_task_scheduled_and_started();
1212
+
1213
+ let histinfo = t.get_full_history_info().unwrap().into();
1214
+ let mut wfm = ManagedWFFunc::new_from_update(histinfo, func, vec![]);
1215
+
1216
+ // First activation will request to run the LA, but it will *not* be queued for execution
1217
+ // yet as we're still replaying.
1218
+ wfm.get_next_activation().await.unwrap();
1219
+ let commands = wfm.get_server_commands().commands;
1220
+ assert_eq!(commands.len(), 0);
1221
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1222
+ assert_eq!(ready_to_execute_las.len(), 0);
1223
+
1224
+ // On the *next* activation, we are no longer replaying and the activity should be queued
1225
+ wfm.get_next_activation().await.unwrap();
1226
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1227
+ assert_eq!(ready_to_execute_las.len(), 1);
1228
+ // We can happily complete it now
1229
+ wfm.complete_local_activity(1, ActivityExecutionResult::ok(b"hi".into()))
1230
+ .unwrap();
1231
+
1232
+ wfm.shutdown().await.unwrap();
1233
+ }
1234
+
1235
+ /// This test verifies something that technically shouldn't really be possible but is worth
1236
+ /// checking anyway. What happens if in memory we think an LA passed but then the next history
1237
+ /// chunk comes back with it failing? We should fail with a mismatch.
1238
+ #[tokio::test]
1239
+ async fn exec_passes_but_history_has_fail() {
1240
+ let func = WorkflowFunction::new(la_wf);
1241
+ let mut t = TestHistoryBuilder::default();
1242
+ t.add_by_type(EventType::WorkflowExecutionStarted);
1243
+ t.add_full_wf_task();
1244
+ t.add_local_activity_fail_marker(
1245
+ 1,
1246
+ "1",
1247
+ Failure::application_failure("I failed".to_string(), false),
1248
+ );
1249
+ t.add_workflow_execution_completed();
1250
+
1251
+ let histinfo = t.get_history_info(1).unwrap().into();
1252
+ let mut wfm = ManagedWFFunc::new_from_update(histinfo, func, vec![]);
1253
+
1254
+ wfm.get_next_activation().await.unwrap();
1255
+ let commands = wfm.get_server_commands().commands;
1256
+ assert_eq!(commands.len(), 0);
1257
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1258
+ assert_eq!(ready_to_execute_las.len(), 1);
1259
+ // Completes OK
1260
+ wfm.complete_local_activity(1, ActivityExecutionResult::ok(b"hi".into()))
1261
+ .unwrap();
1262
+
1263
+ // next activation unblocks LA
1264
+ wfm.get_next_activation().await.unwrap();
1265
+ let commands = wfm.get_server_commands().commands;
1266
+ assert_eq!(commands.len(), 2);
1267
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
1268
+ assert_eq!(
1269
+ commands[1].command_type,
1270
+ CommandType::CompleteWorkflowExecution as i32
1271
+ );
1272
+
1273
+ let err = wfm
1274
+ .new_history(t.get_full_history_info().unwrap().into())
1275
+ .await
1276
+ .unwrap_err();
1277
+ assert!(err.to_string().contains("Nondeterminism"));
1278
+ wfm.shutdown().await.unwrap();
1279
+ }
1280
+
1281
+ #[rstest]
1282
+ #[tokio::test]
1283
+ async fn immediate_cancel(
1284
+ #[values(
1285
+ ActivityCancellationType::WaitCancellationCompleted,
1286
+ ActivityCancellationType::TryCancel,
1287
+ ActivityCancellationType::Abandon
1288
+ )]
1289
+ cancel_type: ActivityCancellationType,
1290
+ ) {
1291
+ let func = WorkflowFunction::new(move |ctx| async move {
1292
+ let la = ctx.local_activity(LocalActivityOptions {
1293
+ cancel_type,
1294
+ ..Default::default()
1295
+ });
1296
+ la.cancel(&ctx);
1297
+ la.await;
1298
+ Ok(().into())
1299
+ });
1300
+ let mut t = TestHistoryBuilder::default();
1301
+ t.add_by_type(EventType::WorkflowExecutionStarted);
1302
+ t.add_full_wf_task();
1303
+ t.add_workflow_execution_completed();
1304
+
1305
+ let histinfo = t.get_history_info(1).unwrap().into();
1306
+ let mut wfm = ManagedWFFunc::new_from_update(histinfo, func, vec![]);
1307
+
1308
+ wfm.get_next_activation().await.unwrap();
1309
+ let commands = wfm.get_server_commands().commands;
1310
+ assert_eq!(commands.len(), 1);
1311
+ // We record the cancel marker
1312
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
1313
+ // Importantly, the activity shouldn't get executed since it was insta-cancelled
1314
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1315
+ assert_eq!(ready_to_execute_las.len(), 0);
1316
+
1317
+ // next activation unblocks LA, which is cancelled now.
1318
+ wfm.get_next_activation().await.unwrap();
1319
+ let commands = wfm.get_server_commands().commands;
1320
+ assert_eq!(commands.len(), 2);
1321
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
1322
+ assert_eq!(
1323
+ commands[1].command_type,
1324
+ CommandType::CompleteWorkflowExecution as i32
1325
+ );
1326
+
1327
+ wfm.shutdown().await.unwrap();
1328
+ }
1329
+
1330
+ #[rstest]
1331
+ #[case::incremental(false)]
1332
+ #[case::replay(true)]
1333
+ #[tokio::test]
1334
+ async fn cancel_after_act_starts(
1335
+ #[case] replay: bool,
1336
+ #[values(
1337
+ ActivityCancellationType::WaitCancellationCompleted,
1338
+ ActivityCancellationType::TryCancel,
1339
+ ActivityCancellationType::Abandon
1340
+ )]
1341
+ cancel_type: ActivityCancellationType,
1342
+ ) {
1343
+ let func = WorkflowFunction::new(move |ctx| async move {
1344
+ let la = ctx.local_activity(LocalActivityOptions {
1345
+ cancel_type,
1346
+ ..Default::default()
1347
+ });
1348
+ ctx.timer(Duration::from_secs(1)).await;
1349
+ la.cancel(&ctx);
1350
+ // This extra timer is here to ensure the presence of another WF task doesn't mess up
1351
+ // resolving the LA with cancel on replay
1352
+ ctx.timer(Duration::from_secs(1)).await;
1353
+ let resolution = la.await;
1354
+ assert!(resolution.cancelled());
1355
+ Ok(().into())
1356
+ });
1357
+
1358
+ let mut t = TestHistoryBuilder::default();
1359
+ t.add_by_type(EventType::WorkflowExecutionStarted);
1360
+ t.add_full_wf_task();
1361
+ let timer_started_event_id = t.add_get_event_id(EventType::TimerStarted, None);
1362
+ t.add_timer_fired(timer_started_event_id, "1".to_string());
1363
+ t.add_full_wf_task();
1364
+ if cancel_type != ActivityCancellationType::WaitCancellationCompleted {
1365
+ // With non-wait cancels, the cancel is immediate
1366
+ t.add_local_activity_cancel_marker(1, "1");
1367
+ }
1368
+ let timer_started_event_id = t.add_get_event_id(EventType::TimerStarted, None);
1369
+ if cancel_type == ActivityCancellationType::WaitCancellationCompleted {
1370
+ // With wait cancels, the cancel marker is not recorded until activity reports.
1371
+ t.add_local_activity_cancel_marker(1, "1");
1372
+ }
1373
+ t.add_timer_fired(timer_started_event_id, "2".to_string());
1374
+ t.add_full_wf_task();
1375
+ t.add_workflow_execution_completed();
1376
+
1377
+ let histinfo = if replay {
1378
+ t.get_full_history_info().unwrap().into()
1379
+ } else {
1380
+ t.get_history_info(1).unwrap().into()
1381
+ };
1382
+ let mut wfm = ManagedWFFunc::new_from_update(histinfo, func, vec![]);
1383
+
1384
+ wfm.get_next_activation().await.unwrap();
1385
+ let commands = wfm.get_server_commands().commands;
1386
+ assert_eq!(commands.len(), 1);
1387
+ assert_eq!(commands[0].command_type, CommandType::StartTimer as i32);
1388
+ let ready_to_execute_las = wfm.drain_queued_local_activities();
1389
+ let num_queued = if !replay { 1 } else { 0 };
1390
+ assert_eq!(ready_to_execute_las.len(), num_queued);
1391
+
1392
+ // Next activation timer fires and activity cancel will be requested
1393
+ if replay {
1394
+ wfm.get_next_activation().await.unwrap()
1395
+ } else {
1396
+ wfm.new_history(t.get_history_info(2).unwrap().into())
1397
+ .await
1398
+ .unwrap()
1399
+ };
1400
+
1401
+ let commands = wfm.get_server_commands().commands;
1402
+ if cancel_type == ActivityCancellationType::WaitCancellationCompleted || replay {
1403
+ assert_eq!(commands.len(), 1);
1404
+ assert_eq!(commands[0].command_type, CommandType::StartTimer as i32);
1405
+ } else {
1406
+ // Try-cancel/abandon will immediately record marker (when not replaying)
1407
+ assert_eq!(commands.len(), 2);
1408
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
1409
+ assert_eq!(commands[1].command_type, CommandType::StartTimer as i32);
1410
+ }
1411
+
1412
+ if replay {
1413
+ wfm.get_next_activation().await.unwrap()
1414
+ } else {
1415
+ // On non replay, there's an additional activation, because completing with the cancel
1416
+ // wants to wake up the workflow to see if resolving the LA as cancelled did anything.
1417
+ // In this case, it doesn't really, because we just hit the next timer which is also
1418
+ // what would have happened if we woke up with new history -- but it does mean we
1419
+ // generate the commands at this point. This matters b/c we want to make sure the record
1420
+ // marker command is sent as soon as cancel happens.
1421
+ if cancel_type == WaitCancellationCompleted {
1422
+ wfm.complete_local_activity(1, ActivityExecutionResult::cancel_from_details(None))
1423
+ .unwrap();
1424
+ }
1425
+ wfm.get_next_activation().await.unwrap();
1426
+ let commands = wfm.get_server_commands().commands;
1427
+ assert_eq!(commands.len(), 2);
1428
+ if cancel_type == ActivityCancellationType::WaitCancellationCompleted {
1429
+ assert_eq!(commands[0].command_type, CommandType::StartTimer as i32);
1430
+ assert_eq!(commands[1].command_type, CommandType::RecordMarker as i32);
1431
+ } else {
1432
+ assert_eq!(commands[0].command_type, CommandType::RecordMarker as i32);
1433
+ assert_eq!(commands[1].command_type, CommandType::StartTimer as i32);
1434
+ }
1435
+
1436
+ wfm.new_history(t.get_history_info(3).unwrap().into())
1437
+ .await
1438
+ .unwrap()
1439
+ };
1440
+
1441
+ wfm.get_next_activation().await.unwrap();
1442
+ let commands = wfm.get_server_commands().commands;
1443
+ assert_eq!(commands.len(), 1);
1444
+ assert_eq!(
1445
+ commands[0].command_type,
1446
+ CommandType::CompleteWorkflowExecution as i32
1447
+ );
1448
+
1449
+ wfm.shutdown().await.unwrap();
1450
+ }
1451
+ }