@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,973 @@
1
+ use crate::{protosext::ValidScheduleLA, retry_logic::RetryPolicyExt, TaskToken};
2
+ use parking_lot::Mutex;
3
+ use std::{
4
+ collections::HashMap,
5
+ fmt::{Debug, Formatter},
6
+ time::{Duration, Instant, SystemTime},
7
+ };
8
+ use temporal_sdk_core_protos::{
9
+ coresdk::{
10
+ activity_result::{Cancellation, Failure as ActFail, Success},
11
+ activity_task::{activity_task, ActivityCancelReason, ActivityTask, Cancel, Start},
12
+ common::WorkflowExecution,
13
+ },
14
+ temporal::api::enums::v1::TimeoutType,
15
+ };
16
+ use tokio::{
17
+ sync::{
18
+ mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender},
19
+ Notify, Semaphore,
20
+ },
21
+ task::JoinHandle,
22
+ time::sleep,
23
+ };
24
+ use tokio_util::sync::CancellationToken;
25
+
26
+ #[allow(clippy::large_enum_variant)] // Timeouts are relatively rare
27
+ #[derive(Debug)]
28
+ pub(crate) enum DispatchOrTimeoutLA {
29
+ /// Send the activity task to lang
30
+ Dispatch(ActivityTask),
31
+ /// Notify the machines (and maybe lang) that this LA has timed out
32
+ Timeout {
33
+ run_id: String,
34
+ resolution: LocalActivityResolution,
35
+ task: Option<ActivityTask>,
36
+ },
37
+ }
38
+
39
+ #[derive(Debug)]
40
+ pub(crate) struct LocalInFlightActInfo {
41
+ pub la_info: NewLocalAct,
42
+ pub dispatch_time: Instant,
43
+ pub attempt: u32,
44
+ }
45
+
46
+ #[derive(Debug, Clone)]
47
+ pub(crate) enum LocalActivityExecutionResult {
48
+ Completed(Success),
49
+ Failed(ActFail),
50
+ TimedOut(ActFail),
51
+ Cancelled(Cancellation),
52
+ }
53
+ impl LocalActivityExecutionResult {
54
+ pub(crate) fn empty_cancel() -> Self {
55
+ Self::Cancelled(Cancellation::from_details(None))
56
+ }
57
+ pub(crate) fn timeout(tt: TimeoutType) -> Self {
58
+ Self::TimedOut(ActFail::timeout(tt))
59
+ }
60
+ }
61
+
62
+ #[derive(Debug, Clone)]
63
+ pub(crate) struct LocalActivityResolution {
64
+ pub seq: u32,
65
+ pub result: LocalActivityExecutionResult,
66
+ pub runtime: Duration,
67
+ pub attempt: u32,
68
+ pub backoff: Option<prost_types::Duration>,
69
+ pub original_schedule_time: Option<SystemTime>,
70
+ }
71
+
72
+ #[derive(Clone)]
73
+ pub(crate) struct NewLocalAct {
74
+ pub schedule_cmd: ValidScheduleLA,
75
+ pub workflow_type: String,
76
+ pub workflow_exec_info: WorkflowExecution,
77
+ pub schedule_time: SystemTime,
78
+ }
79
+ impl Debug for NewLocalAct {
80
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
81
+ write!(
82
+ f,
83
+ "LocalActivity({}, {})",
84
+ self.schedule_cmd.seq, self.schedule_cmd.activity_type
85
+ )
86
+ }
87
+ }
88
+
89
+ #[derive(Debug, derive_more::From)]
90
+ #[allow(clippy::large_enum_variant)]
91
+ pub(crate) enum LocalActRequest {
92
+ New(NewLocalAct),
93
+ Cancel(ExecutingLAId),
94
+ }
95
+
96
+ #[derive(Debug, Clone, Eq, PartialEq, Hash)]
97
+ pub(crate) struct ExecutingLAId {
98
+ pub run_id: String,
99
+ pub seq_num: u32,
100
+ }
101
+
102
+ pub(crate) struct LocalActivityManager {
103
+ /// Just so we can provide activity tasks the same namespace as the worker
104
+ namespace: String,
105
+ /// Constrains number of currently executing local activities
106
+ semaphore: Semaphore,
107
+ /// Sink for new activity execution requests
108
+ act_req_tx: UnboundedSender<NewOrRetry>,
109
+ /// Cancels need a different queue since they should be taken first, and don't take a permit
110
+ cancels_req_tx: UnboundedSender<CancelOrTimeout>,
111
+ /// Wakes every time a complete is processed
112
+ complete_notify: Notify,
113
+
114
+ rcvs: tokio::sync::Mutex<RcvChans>,
115
+ shutdown_complete_tok: CancellationToken,
116
+ dat: Mutex<LAMData>,
117
+ }
118
+
119
+ struct LAMData {
120
+ /// Activities that have been issued to lang but not yet completed
121
+ outstanding_activity_tasks: HashMap<TaskToken, LocalInFlightActInfo>,
122
+ id_to_tt: HashMap<ExecutingLAId, TaskToken>,
123
+ /// Tasks for activities which are currently backing off. May be used to cancel retrying them.
124
+ backing_off_tasks: HashMap<ExecutingLAId, JoinHandle<()>>,
125
+ /// Tasks for timing out activities which are currently in the queue or dispatched.
126
+ timeout_tasks: HashMap<ExecutingLAId, TimeoutBag>,
127
+ next_tt_num: u32,
128
+ }
129
+
130
+ impl LAMData {
131
+ fn gen_next_token(&mut self) -> TaskToken {
132
+ self.next_tt_num += 1;
133
+ TaskToken::new_local_activity_token(self.next_tt_num.to_le_bytes())
134
+ }
135
+ }
136
+
137
+ impl LocalActivityManager {
138
+ pub(crate) fn new(max_concurrent: usize, namespace: String) -> Self {
139
+ let (act_req_tx, act_req_rx) = unbounded_channel();
140
+ let (cancels_req_tx, cancels_req_rx) = unbounded_channel();
141
+ let shutdown_complete_tok = CancellationToken::new();
142
+ Self {
143
+ namespace,
144
+ semaphore: Semaphore::new(max_concurrent),
145
+ act_req_tx,
146
+ cancels_req_tx,
147
+ complete_notify: Notify::new(),
148
+ rcvs: tokio::sync::Mutex::new(RcvChans {
149
+ act_req_rx,
150
+ cancels_req_rx,
151
+ shutdown: shutdown_complete_tok.clone(),
152
+ }),
153
+ shutdown_complete_tok,
154
+ dat: Mutex::new(LAMData {
155
+ outstanding_activity_tasks: Default::default(),
156
+ id_to_tt: Default::default(),
157
+ backing_off_tasks: Default::default(),
158
+ timeout_tasks: Default::default(),
159
+ next_tt_num: 0,
160
+ }),
161
+ }
162
+ }
163
+
164
+ pub(crate) fn num_outstanding(&self) -> usize {
165
+ self.dat.lock().outstanding_activity_tasks.len()
166
+ }
167
+
168
+ #[cfg(test)]
169
+ fn num_in_backoff(&self) -> usize {
170
+ self.dat.lock().backing_off_tasks.len()
171
+ }
172
+
173
+ pub(crate) fn enqueue(
174
+ &self,
175
+ reqs: impl IntoIterator<Item = LocalActRequest> + Debug,
176
+ ) -> Vec<LocalActivityResolution> {
177
+ debug!("Queuing local activities: {:?}", &reqs);
178
+ let mut immediate_resolutions = vec![];
179
+ for req in reqs {
180
+ match req {
181
+ LocalActRequest::New(act) => {
182
+ let id = ExecutingLAId {
183
+ run_id: act.workflow_exec_info.run_id.clone(),
184
+ seq_num: act.schedule_cmd.seq,
185
+ };
186
+ let mut dlock = self.dat.lock();
187
+ if dlock.id_to_tt.contains_key(&id) {
188
+ // Do not queue local activities which are in fact already executing.
189
+ // This can happen during evictions.
190
+ debug!("Tried to queue already-executing local activity {:?}", &id);
191
+ continue;
192
+ }
193
+ // Pre-generate and insert the task token now, before we may or may not dispatch
194
+ // the activity, so we can enforce idempotency. Prevents two identical LAs
195
+ // ending up in the queue at once.
196
+ let tt = dlock.gen_next_token();
197
+ dlock.id_to_tt.insert(id.clone(), tt);
198
+
199
+ // Set up timeouts for the new activity
200
+ match TimeoutBag::new(&act, self.cancels_req_tx.clone()) {
201
+ Ok(tb) => {
202
+ dlock.timeout_tasks.insert(id, tb);
203
+
204
+ self.act_req_tx
205
+ .send(NewOrRetry::New(act))
206
+ .expect("Receive half of LA request channel cannot be dropped");
207
+ }
208
+ Err(res) => immediate_resolutions.push(res),
209
+ }
210
+ }
211
+ LocalActRequest::Cancel(id) => {
212
+ let mut dlock = self.dat.lock();
213
+
214
+ // First check if this ID is currently backing off, if so abort the backoff
215
+ // task
216
+ if let Some(t) = dlock.backing_off_tasks.remove(&id) {
217
+ t.abort();
218
+ immediate_resolutions.push(LocalActivityResolution {
219
+ seq: id.seq_num,
220
+ result: LocalActivityExecutionResult::Cancelled(
221
+ Cancellation::from_details(None),
222
+ ),
223
+ runtime: Duration::from_secs(0),
224
+ attempt: 0,
225
+ backoff: None,
226
+ original_schedule_time: None,
227
+ });
228
+ continue;
229
+ }
230
+
231
+ if let Some(tt) = dlock.id_to_tt.get(&id) {
232
+ self.cancels_req_tx
233
+ .send(CancelOrTimeout::Cancel(ActivityTask {
234
+ task_token: tt.0.clone(),
235
+ variant: Some(activity_task::Variant::Cancel(Cancel {
236
+ reason: ActivityCancelReason::Cancelled as i32,
237
+ })),
238
+ }))
239
+ .expect("Receive half of LA cancel channel cannot be dropped");
240
+ }
241
+ }
242
+ }
243
+ }
244
+ immediate_resolutions
245
+ }
246
+
247
+ /// Returns the next pending local-activity related action, or None if shutdown has initiated
248
+ /// and there are no more remaining actions to take.
249
+ pub(crate) async fn next_pending(&self) -> Option<DispatchOrTimeoutLA> {
250
+ let new_or_retry = match self.rcvs.lock().await.next(&self.semaphore).await? {
251
+ NewOrCancel::Cancel(c) => {
252
+ return match c {
253
+ CancelOrTimeout::Cancel(c) => Some(DispatchOrTimeoutLA::Dispatch(c)),
254
+ CancelOrTimeout::Timeout {
255
+ run_id,
256
+ resolution,
257
+ dispatch_cancel,
258
+ } => {
259
+ let task = if dispatch_cancel {
260
+ let tt = self
261
+ .dat
262
+ .lock()
263
+ .id_to_tt
264
+ .get(&ExecutingLAId {
265
+ run_id: run_id.clone(),
266
+ seq_num: resolution.seq,
267
+ })
268
+ .map(Clone::clone);
269
+ if let Some(task_token) = tt {
270
+ self.complete(&task_token, &resolution.result);
271
+ Some(ActivityTask {
272
+ task_token: task_token.0,
273
+ variant: Some(activity_task::Variant::Cancel(Cancel {
274
+ reason: ActivityCancelReason::TimedOut as i32,
275
+ })),
276
+ })
277
+ } else {
278
+ None
279
+ }
280
+ } else {
281
+ None
282
+ };
283
+ Some(DispatchOrTimeoutLA::Timeout {
284
+ run_id,
285
+ resolution,
286
+ task,
287
+ })
288
+ }
289
+ };
290
+ }
291
+ NewOrCancel::New(n) => n,
292
+ };
293
+
294
+ // It is important that there are no await points after receiving from the channel, as
295
+ // it would mean dropping this future would cause us to drop the activity request.
296
+ let (new_la, attempt) = match new_or_retry {
297
+ NewOrRetry::New(n) => {
298
+ let explicit_attempt_num_or_1 = n.schedule_cmd.attempt.max(1);
299
+ (n, explicit_attempt_num_or_1)
300
+ }
301
+ NewOrRetry::Retry { in_flight, attempt } => (in_flight, attempt),
302
+ };
303
+ let orig = new_la.clone();
304
+ let id = ExecutingLAId {
305
+ run_id: new_la.workflow_exec_info.run_id.clone(),
306
+ seq_num: new_la.schedule_cmd.seq,
307
+ };
308
+ let sa = new_la.schedule_cmd;
309
+
310
+ let mut dat = self.dat.lock();
311
+ // If this request originated from a local backoff task, clear the entry for it. We
312
+ // don't await the handle because we know it must already be done, and there's no
313
+ // meaningful value.
314
+ dat.backing_off_tasks.remove(&id);
315
+
316
+ // If this task sat in the queue for too long, return a timeout for it instead
317
+ if let Some(s2s) = sa.schedule_to_start_timeout.as_ref() {
318
+ let sat_for = new_la.schedule_time.elapsed().unwrap_or_default();
319
+ if sat_for > *s2s {
320
+ return Some(DispatchOrTimeoutLA::Timeout {
321
+ run_id: new_la.workflow_exec_info.run_id,
322
+ resolution: LocalActivityResolution {
323
+ seq: sa.seq,
324
+ result: LocalActivityExecutionResult::timeout(TimeoutType::ScheduleToStart),
325
+ runtime: sat_for,
326
+ attempt,
327
+ backoff: None,
328
+ original_schedule_time: Some(new_la.schedule_time),
329
+ },
330
+ task: None,
331
+ });
332
+ }
333
+ }
334
+
335
+ let tt = dat
336
+ .id_to_tt
337
+ .get(&id)
338
+ .expect("Task token must exist")
339
+ .clone();
340
+ dat.outstanding_activity_tasks.insert(
341
+ tt.clone(),
342
+ LocalInFlightActInfo {
343
+ la_info: orig,
344
+ dispatch_time: Instant::now(),
345
+ attempt,
346
+ },
347
+ );
348
+ if let Some(to) = dat.timeout_tasks.get_mut(&id) {
349
+ to.mark_started();
350
+ }
351
+
352
+ let (schedule_to_close, start_to_close) = sa.close_timeouts.into_sched_and_start();
353
+ Some(DispatchOrTimeoutLA::Dispatch(ActivityTask {
354
+ task_token: tt.0,
355
+ variant: Some(activity_task::Variant::Start(Start {
356
+ workflow_namespace: self.namespace.clone(),
357
+ workflow_type: new_la.workflow_type,
358
+ workflow_execution: Some(new_la.workflow_exec_info),
359
+ activity_id: sa.activity_id,
360
+ activity_type: sa.activity_type,
361
+ header_fields: sa.header_fields,
362
+ input: sa.arguments,
363
+ heartbeat_details: vec![],
364
+ scheduled_time: Some(new_la.schedule_time.into()),
365
+ current_attempt_scheduled_time: Some(new_la.schedule_time.into()),
366
+ started_time: Some(SystemTime::now().into()),
367
+ attempt,
368
+ schedule_to_close_timeout: schedule_to_close.map(Into::into),
369
+ start_to_close_timeout: start_to_close.map(Into::into),
370
+ heartbeat_timeout: None,
371
+ retry_policy: Some(sa.retry_policy),
372
+ is_local: true,
373
+ })),
374
+ }))
375
+ }
376
+
377
+ /// Mark a local activity as having completed (pass, fail, or cancelled)
378
+ pub(crate) fn complete(
379
+ &self,
380
+ task_token: &TaskToken,
381
+ status: &LocalActivityExecutionResult,
382
+ ) -> LACompleteAction {
383
+ let mut dlock = self.dat.lock();
384
+ if let Some(info) = dlock.outstanding_activity_tasks.remove(task_token) {
385
+ let exec_id = ExecutingLAId {
386
+ run_id: info.la_info.workflow_exec_info.run_id.clone(),
387
+ seq_num: info.la_info.schedule_cmd.seq,
388
+ };
389
+ dlock.id_to_tt.remove(&exec_id);
390
+ self.semaphore.add_permits(1);
391
+
392
+ match status {
393
+ LocalActivityExecutionResult::Completed(_)
394
+ | LocalActivityExecutionResult::TimedOut(_)
395
+ | LocalActivityExecutionResult::Cancelled { .. } => {
396
+ // Timeouts are included in this branch since they are not retried
397
+ self.complete_notify.notify_one();
398
+ LACompleteAction::Report(info)
399
+ }
400
+ LocalActivityExecutionResult::Failed(f) => {
401
+ if let Some(backoff_dur) = info.la_info.schedule_cmd.retry_policy.should_retry(
402
+ info.attempt as usize,
403
+ &f.failure
404
+ .as_ref()
405
+ .map(|f| format!("{:?}", f))
406
+ .unwrap_or_else(|| "".to_string()),
407
+ ) {
408
+ let will_use_timer =
409
+ backoff_dur > info.la_info.schedule_cmd.local_retry_threshold;
410
+ debug!(run_id = %info.la_info.workflow_exec_info.run_id,
411
+ seq_num = %info.la_info.schedule_cmd.seq,
412
+ attempt = %info.attempt,
413
+ will_use_timer,
414
+ "Local activity failed, will retry after backing off for {:?}",
415
+ backoff_dur
416
+ );
417
+ if will_use_timer {
418
+ // We want this to be reported, as the workflow will mark this
419
+ // failure down, then start a timer for backoff.
420
+ return LACompleteAction::LangDoesTimerBackoff(
421
+ backoff_dur.into(),
422
+ info,
423
+ );
424
+ }
425
+ // Immediately create a new task token for the to-be-retried LA
426
+ let tt = dlock.gen_next_token();
427
+ dlock.id_to_tt.insert(exec_id.clone(), tt);
428
+
429
+ // Send the retry request after waiting the backoff duration
430
+ let send_chan = self.act_req_tx.clone();
431
+ let jh = tokio::spawn(async move {
432
+ tokio::time::sleep(backoff_dur).await;
433
+
434
+ send_chan
435
+ .send(NewOrRetry::Retry {
436
+ in_flight: info.la_info,
437
+ attempt: info.attempt + 1,
438
+ })
439
+ .expect("Receive half of LA request channel cannot be dropped");
440
+ });
441
+ dlock.backing_off_tasks.insert(exec_id, jh);
442
+
443
+ LACompleteAction::WillBeRetried
444
+ } else {
445
+ LACompleteAction::Report(info)
446
+ }
447
+ }
448
+ }
449
+ } else {
450
+ LACompleteAction::Untracked
451
+ }
452
+ }
453
+
454
+ pub(crate) async fn shutdown_and_wait_all_finished(&self) {
455
+ while !self.dat.lock().outstanding_activity_tasks.is_empty() {
456
+ self.complete_notify.notified().await;
457
+ }
458
+ self.shutdown_complete_tok.cancel();
459
+ }
460
+ }
461
+
462
+ #[derive(Debug)]
463
+ #[allow(clippy::large_enum_variant)] // Most will be reported
464
+ pub(crate) enum LACompleteAction {
465
+ /// Caller should report the status to the workflow
466
+ Report(LocalInFlightActInfo),
467
+ /// Lang needs to be told to do the schedule-a-timer-then-rerun hack
468
+ LangDoesTimerBackoff(prost_types::Duration, LocalInFlightActInfo),
469
+ /// The activity will be re-enqueued for another attempt (and so status should not be reported
470
+ /// to the workflow)
471
+ WillBeRetried,
472
+ /// The activity was unknown
473
+ Untracked,
474
+ }
475
+
476
+ #[derive(Debug)]
477
+ enum NewOrRetry {
478
+ New(NewLocalAct),
479
+ Retry {
480
+ in_flight: NewLocalAct,
481
+ attempt: u32,
482
+ },
483
+ }
484
+
485
+ #[allow(clippy::large_enum_variant)]
486
+ #[derive(Debug, Clone)]
487
+ enum CancelOrTimeout {
488
+ Cancel(ActivityTask),
489
+ Timeout {
490
+ run_id: String,
491
+ resolution: LocalActivityResolution,
492
+ dispatch_cancel: bool,
493
+ },
494
+ }
495
+
496
+ enum NewOrCancel {
497
+ New(NewOrRetry),
498
+ Cancel(CancelOrTimeout),
499
+ }
500
+
501
+ struct RcvChans {
502
+ /// Activities that need to be executed by lang
503
+ act_req_rx: UnboundedReceiver<NewOrRetry>,
504
+ /// Cancels to send to lang or apply internally
505
+ cancels_req_rx: UnboundedReceiver<CancelOrTimeout>,
506
+ shutdown: CancellationToken,
507
+ }
508
+
509
+ impl RcvChans {
510
+ async fn next(&mut self, new_sem: &Semaphore) -> Option<NewOrCancel> {
511
+ tokio::select! {
512
+ cancel = async { self.cancels_req_rx.recv().await } => {
513
+ Some(NewOrCancel::Cancel(cancel.expect("Send halves of LA manager are not dropped")))
514
+ }
515
+ maybe_new_or_retry = async {
516
+ // Wait for a permit to take a task and forget it. Permits are removed until a
517
+ // completion.
518
+ new_sem.acquire().await.expect("is never closed").forget();
519
+ self.act_req_rx.recv().await
520
+ } => Some(NewOrCancel::New(
521
+ maybe_new_or_retry.expect("Send halves of LA manager are not dropped")
522
+ )),
523
+ _ = self.shutdown.cancelled() => None
524
+ }
525
+ }
526
+ }
527
+
528
+ struct TimeoutBag {
529
+ sched_to_close_handle: JoinHandle<()>,
530
+ start_to_close_dur_and_dat: Option<(Duration, CancelOrTimeout)>,
531
+ start_to_close_handle: Option<JoinHandle<()>>,
532
+ cancel_chan: UnboundedSender<CancelOrTimeout>,
533
+ }
534
+
535
+ impl TimeoutBag {
536
+ /// Create new timeout tasks for the provided local activity. This must be called as soon
537
+ /// as request to schedule it arrives.
538
+ ///
539
+ /// Returns error in the event the activity is *already* timed out
540
+ fn new(
541
+ new_la: &NewLocalAct,
542
+ cancel_chan: UnboundedSender<CancelOrTimeout>,
543
+ ) -> Result<TimeoutBag, LocalActivityResolution> {
544
+ let (schedule_to_close, start_to_close) =
545
+ new_la.schedule_cmd.close_timeouts.into_sched_and_start();
546
+
547
+ let resolution = LocalActivityResolution {
548
+ seq: new_la.schedule_cmd.seq,
549
+ result: LocalActivityExecutionResult::timeout(TimeoutType::ScheduleToClose),
550
+ runtime: Default::default(),
551
+ attempt: new_la.schedule_cmd.attempt,
552
+ backoff: None,
553
+ original_schedule_time: Some(new_la.schedule_time),
554
+ };
555
+ // Remove any time already elapsed since the scheduling time
556
+ let schedule_to_close = schedule_to_close
557
+ .map(|s2c| s2c.saturating_sub(new_la.schedule_time.elapsed().unwrap_or_default()));
558
+ if let Some(ref s2c) = schedule_to_close {
559
+ if s2c.is_zero() {
560
+ return Err(resolution);
561
+ }
562
+ }
563
+ let timeout_dat = CancelOrTimeout::Timeout {
564
+ run_id: new_la.workflow_exec_info.run_id.clone(),
565
+ resolution,
566
+ dispatch_cancel: true,
567
+ };
568
+ let start_to_close_dur_and_dat = start_to_close.map(|d| (d, timeout_dat.clone()));
569
+ let fut_dat = schedule_to_close.map(|s2c| (s2c, timeout_dat));
570
+
571
+ let cancel_chan_clone = cancel_chan.clone();
572
+ let scheduling = tokio::spawn(async move {
573
+ if let Some((timeout, dat)) = fut_dat {
574
+ sleep(timeout).await;
575
+ cancel_chan_clone
576
+ .send(dat)
577
+ .expect("receive half not dropped");
578
+ }
579
+ });
580
+ Ok(TimeoutBag {
581
+ sched_to_close_handle: scheduling,
582
+ start_to_close_dur_and_dat,
583
+ start_to_close_handle: None,
584
+ cancel_chan,
585
+ })
586
+ }
587
+
588
+ /// Must be called once the associated local activity has been started / dispatched to lang.
589
+ fn mark_started(&mut self) {
590
+ if let Some((start_to_close, mut dat)) = self.start_to_close_dur_and_dat.take() {
591
+ let started_t = Instant::now();
592
+ let cchan = self.cancel_chan.clone();
593
+ self.start_to_close_handle = Some(tokio::spawn(async move {
594
+ sleep(start_to_close).await;
595
+ if let CancelOrTimeout::Timeout { resolution, .. } = &mut dat {
596
+ resolution.result =
597
+ LocalActivityExecutionResult::timeout(TimeoutType::StartToClose);
598
+ resolution.runtime = started_t.elapsed();
599
+ }
600
+
601
+ cchan.send(dat).expect("receive half not dropped");
602
+ }));
603
+ }
604
+ }
605
+ }
606
+
607
+ impl Drop for TimeoutBag {
608
+ fn drop(&mut self) {
609
+ self.sched_to_close_handle.abort();
610
+ if let Some(x) = self.start_to_close_handle.as_ref() {
611
+ x.abort()
612
+ }
613
+ }
614
+ }
615
+
616
+ #[cfg(test)]
617
+ mod tests {
618
+ use super::*;
619
+ use crate::protosext::LACloseTimeouts;
620
+ use temporal_sdk_core_protos::coresdk::common::RetryPolicy;
621
+ use tokio::{sync::mpsc::error::TryRecvError, task::yield_now};
622
+
623
+ impl DispatchOrTimeoutLA {
624
+ fn unwrap(self) -> ActivityTask {
625
+ match self {
626
+ DispatchOrTimeoutLA::Dispatch(t) => t,
627
+ DispatchOrTimeoutLA::Timeout { .. } => {
628
+ panic!("Timeout returned when expected a task")
629
+ }
630
+ }
631
+ }
632
+ }
633
+
634
+ #[tokio::test]
635
+ async fn max_concurrent_respected() {
636
+ let lam = LocalActivityManager::new(1, "whatever".to_string());
637
+ lam.enqueue((1..=50).map(|i| {
638
+ NewLocalAct {
639
+ schedule_cmd: ValidScheduleLA {
640
+ seq: i,
641
+ activity_id: i.to_string(),
642
+ ..Default::default()
643
+ },
644
+ workflow_type: "".to_string(),
645
+ workflow_exec_info: Default::default(),
646
+ schedule_time: SystemTime::now(),
647
+ }
648
+ .into()
649
+ }));
650
+ for i in 1..=50 {
651
+ let next = lam.next_pending().await.unwrap().unwrap();
652
+ assert_matches!(
653
+ next.variant.unwrap(),
654
+ activity_task::Variant::Start(Start {activity_id, ..})
655
+ if activity_id == i.to_string()
656
+ );
657
+ let next_tt = TaskToken(next.task_token);
658
+ let complete_branch = async {
659
+ lam.complete(
660
+ &next_tt,
661
+ &LocalActivityExecutionResult::Completed(Default::default()),
662
+ )
663
+ };
664
+ tokio::select! {
665
+ // Next call will not resolve until we complete the first
666
+ _ = lam.next_pending() => {
667
+ panic!("Branch must not be selected")
668
+ }
669
+ _ = complete_branch => {}
670
+ }
671
+ }
672
+ }
673
+
674
+ #[tokio::test]
675
+ async fn no_work_doesnt_deadlock_with_complete() {
676
+ let lam = LocalActivityManager::new(5, "whatever".to_string());
677
+ lam.enqueue([NewLocalAct {
678
+ schedule_cmd: ValidScheduleLA {
679
+ seq: 1,
680
+ activity_id: 1.to_string(),
681
+ ..Default::default()
682
+ },
683
+ workflow_type: "".to_string(),
684
+ workflow_exec_info: Default::default(),
685
+ schedule_time: SystemTime::now(),
686
+ }
687
+ .into()]);
688
+
689
+ let next = lam.next_pending().await.unwrap().unwrap();
690
+ let tt = TaskToken(next.task_token);
691
+ tokio::select! {
692
+ biased;
693
+
694
+ _ = lam.next_pending() => {
695
+ panic!("Complete branch must win")
696
+ }
697
+ _ = async {
698
+ // Spin until the receive lock has been grabbed by the call to pending, to ensure
699
+ // it's advanced enough
700
+ while lam.rcvs.try_lock().is_ok() { yield_now().await; }
701
+ lam.complete(&tt, &LocalActivityExecutionResult::Completed(Default::default()));
702
+ } => (),
703
+ };
704
+ }
705
+
706
+ #[tokio::test]
707
+ async fn can_cancel_in_flight() {
708
+ let lam = LocalActivityManager::new(5, "whatever".to_string());
709
+ lam.enqueue([NewLocalAct {
710
+ schedule_cmd: ValidScheduleLA {
711
+ seq: 1,
712
+ activity_id: 1.to_string(),
713
+ ..Default::default()
714
+ },
715
+ workflow_type: "".to_string(),
716
+ workflow_exec_info: WorkflowExecution {
717
+ workflow_id: "".to_string(),
718
+ run_id: "run_id".to_string(),
719
+ },
720
+ schedule_time: SystemTime::now(),
721
+ }
722
+ .into()]);
723
+ lam.next_pending().await.unwrap().unwrap();
724
+
725
+ lam.enqueue([LocalActRequest::Cancel(ExecutingLAId {
726
+ run_id: "run_id".to_string(),
727
+ seq_num: 1,
728
+ })]);
729
+ let next = lam.next_pending().await.unwrap().unwrap();
730
+ assert_matches!(next.variant.unwrap(), activity_task::Variant::Cancel(_));
731
+ }
732
+
733
+ #[tokio::test]
734
+ async fn respects_timer_backoff_threshold() {
735
+ let lam = LocalActivityManager::new(1, "whatever".to_string());
736
+ lam.enqueue([NewLocalAct {
737
+ schedule_cmd: ValidScheduleLA {
738
+ seq: 1,
739
+ activity_id: 1.to_string(),
740
+ attempt: 5,
741
+ retry_policy: RetryPolicy {
742
+ initial_interval: Some(Duration::from_secs(1).into()),
743
+ backoff_coefficient: 10.0,
744
+ maximum_interval: Some(Duration::from_secs(10).into()),
745
+ maximum_attempts: 10,
746
+ non_retryable_error_types: vec![],
747
+ },
748
+ local_retry_threshold: Duration::from_secs(5),
749
+ ..Default::default()
750
+ },
751
+ workflow_type: "".to_string(),
752
+ workflow_exec_info: Default::default(),
753
+ schedule_time: SystemTime::now(),
754
+ }
755
+ .into()]);
756
+
757
+ let next = lam.next_pending().await.unwrap().unwrap();
758
+ let tt = TaskToken(next.task_token);
759
+ let res = lam.complete(
760
+ &tt,
761
+ &LocalActivityExecutionResult::Failed(Default::default()),
762
+ );
763
+ assert_matches!(res, LACompleteAction::LangDoesTimerBackoff(dur, info)
764
+ if dur.seconds == 10 && info.attempt == 5
765
+ )
766
+ }
767
+
768
+ #[tokio::test]
769
+ async fn can_cancel_during_local_backoff() {
770
+ let lam = LocalActivityManager::new(1, "whatever".to_string());
771
+ lam.enqueue([NewLocalAct {
772
+ schedule_cmd: ValidScheduleLA {
773
+ seq: 1,
774
+ activity_id: 1.to_string(),
775
+ attempt: 5,
776
+ retry_policy: RetryPolicy {
777
+ initial_interval: Some(Duration::from_secs(10).into()),
778
+ backoff_coefficient: 1.0,
779
+ maximum_interval: Some(Duration::from_secs(10).into()),
780
+ maximum_attempts: 10,
781
+ non_retryable_error_types: vec![],
782
+ },
783
+ local_retry_threshold: Duration::from_secs(500),
784
+ ..Default::default()
785
+ },
786
+ workflow_type: "".to_string(),
787
+ workflow_exec_info: WorkflowExecution {
788
+ workflow_id: "".to_string(),
789
+ run_id: "run_id".to_string(),
790
+ },
791
+ schedule_time: SystemTime::now(),
792
+ }
793
+ .into()]);
794
+
795
+ let next = lam.next_pending().await.unwrap().unwrap();
796
+ let tt = TaskToken(next.task_token);
797
+ lam.complete(
798
+ &tt,
799
+ &LocalActivityExecutionResult::Failed(Default::default()),
800
+ );
801
+ // Cancel the activity, which is performing local backoff
802
+ let immediate_res = lam.enqueue([LocalActRequest::Cancel(ExecutingLAId {
803
+ run_id: "run_id".to_string(),
804
+ seq_num: 1,
805
+ })]);
806
+ // It should not be present in the backoff tasks
807
+ assert_eq!(lam.num_in_backoff(), 0);
808
+ assert_eq!(lam.num_outstanding(), 0);
809
+ // It should return a resolution to cancel
810
+ assert_eq!(immediate_res.len(), 1);
811
+ assert_matches!(
812
+ immediate_res[0].result,
813
+ LocalActivityExecutionResult::Cancelled { .. }
814
+ );
815
+ }
816
+
817
+ #[tokio::test]
818
+ async fn local_backoff_clears_handle_map_when_started() {
819
+ let lam = LocalActivityManager::new(1, "whatever".to_string());
820
+ lam.enqueue([NewLocalAct {
821
+ schedule_cmd: ValidScheduleLA {
822
+ seq: 1,
823
+ activity_id: 1.to_string(),
824
+ attempt: 5,
825
+ retry_policy: RetryPolicy {
826
+ initial_interval: Some(Duration::from_millis(10).into()),
827
+ backoff_coefficient: 1.0,
828
+ ..Default::default()
829
+ },
830
+ local_retry_threshold: Duration::from_secs(500),
831
+ ..Default::default()
832
+ },
833
+ workflow_type: "".to_string(),
834
+ workflow_exec_info: WorkflowExecution {
835
+ workflow_id: "".to_string(),
836
+ run_id: "run_id".to_string(),
837
+ },
838
+ schedule_time: SystemTime::now(),
839
+ }
840
+ .into()]);
841
+
842
+ let next = lam.next_pending().await.unwrap().unwrap();
843
+ let tt = TaskToken(next.task_token);
844
+ lam.complete(
845
+ &tt,
846
+ &LocalActivityExecutionResult::Failed(Default::default()),
847
+ );
848
+ lam.next_pending().await.unwrap().unwrap();
849
+ assert_eq!(lam.num_in_backoff(), 0);
850
+ assert_eq!(lam.num_outstanding(), 1);
851
+ }
852
+
853
+ #[tokio::test]
854
+ async fn sched_to_start_timeout() {
855
+ let lam = LocalActivityManager::new(1, "whatever".to_string());
856
+ let timeout = Duration::from_millis(100);
857
+ lam.enqueue([NewLocalAct {
858
+ schedule_cmd: ValidScheduleLA {
859
+ seq: 1,
860
+ activity_id: 1.to_string(),
861
+ attempt: 5,
862
+ retry_policy: RetryPolicy {
863
+ initial_interval: Some(Duration::from_millis(10).into()),
864
+ backoff_coefficient: 1.0,
865
+ ..Default::default()
866
+ },
867
+ local_retry_threshold: Duration::from_secs(500),
868
+ schedule_to_start_timeout: Some(timeout),
869
+ ..Default::default()
870
+ },
871
+ workflow_type: "".to_string(),
872
+ workflow_exec_info: WorkflowExecution {
873
+ workflow_id: "".to_string(),
874
+ run_id: "run_id".to_string(),
875
+ },
876
+ schedule_time: SystemTime::now(),
877
+ }
878
+ .into()]);
879
+
880
+ // Wait more than the timeout before grabbing the task
881
+ sleep(timeout + Duration::from_millis(10)).await;
882
+
883
+ assert_matches!(
884
+ lam.next_pending().await.unwrap(),
885
+ DispatchOrTimeoutLA::Timeout { .. }
886
+ );
887
+ assert_eq!(lam.num_in_backoff(), 0);
888
+ assert_eq!(lam.num_outstanding(), 0);
889
+ }
890
+
891
+ #[rstest::rstest]
892
+ #[case::schedule(true)]
893
+ #[case::start(false)]
894
+ #[tokio::test]
895
+ async fn local_x_to_close_timeout(#[case] is_schedule: bool) {
896
+ let lam = LocalActivityManager::new(1, "whatever".to_string());
897
+ let timeout = Duration::from_millis(100);
898
+ let close_timeouts = if is_schedule {
899
+ LACloseTimeouts::ScheduleOnly(timeout)
900
+ } else {
901
+ LACloseTimeouts::StartOnly(timeout)
902
+ };
903
+ lam.enqueue([NewLocalAct {
904
+ schedule_cmd: ValidScheduleLA {
905
+ seq: 1,
906
+ activity_id: 1.to_string(),
907
+ attempt: 5,
908
+ retry_policy: RetryPolicy {
909
+ initial_interval: Some(Duration::from_millis(10).into()),
910
+ backoff_coefficient: 1.0,
911
+ ..Default::default()
912
+ },
913
+ local_retry_threshold: Duration::from_secs(500),
914
+ close_timeouts,
915
+ ..Default::default()
916
+ },
917
+ workflow_type: "".to_string(),
918
+ workflow_exec_info: WorkflowExecution {
919
+ workflow_id: "".to_string(),
920
+ run_id: "run_id".to_string(),
921
+ },
922
+ schedule_time: SystemTime::now(),
923
+ }
924
+ .into()]);
925
+
926
+ lam.next_pending().await.unwrap().unwrap();
927
+ assert_eq!(lam.num_in_backoff(), 0);
928
+ assert_eq!(lam.num_outstanding(), 1);
929
+
930
+ sleep(timeout + Duration::from_millis(10)).await;
931
+ assert_matches!(
932
+ lam.next_pending().await.unwrap(),
933
+ DispatchOrTimeoutLA::Timeout { .. }
934
+ );
935
+ assert_eq!(lam.num_outstanding(), 0);
936
+ }
937
+
938
+ #[tokio::test]
939
+ async fn idempotency_enforced() {
940
+ let lam = LocalActivityManager::new(10, "whatever".to_string());
941
+ let new_la = NewLocalAct {
942
+ schedule_cmd: ValidScheduleLA {
943
+ seq: 1,
944
+ activity_id: 1.to_string(),
945
+ ..Default::default()
946
+ },
947
+ workflow_type: "".to_string(),
948
+ workflow_exec_info: WorkflowExecution {
949
+ workflow_id: "".to_string(),
950
+ run_id: "run_id".to_string(),
951
+ },
952
+ schedule_time: SystemTime::now(),
953
+ };
954
+ // Verify only one will get queued
955
+ lam.enqueue([new_la.clone().into(), new_la.clone().into()]);
956
+ lam.next_pending().await.unwrap().unwrap();
957
+ assert_eq!(lam.num_outstanding(), 1);
958
+ // There should be nothing else in the queue
959
+ assert_eq!(
960
+ lam.rcvs.lock().await.act_req_rx.try_recv().unwrap_err(),
961
+ TryRecvError::Empty
962
+ );
963
+
964
+ // Verify that if we now enqueue the same act again, after the task is outstanding, we still
965
+ // don't add it.
966
+ lam.enqueue([new_la.into()]);
967
+ assert_eq!(lam.num_outstanding(), 1);
968
+ assert_eq!(
969
+ lam.rcvs.lock().await.act_req_rx.try_recv().unwrap_err(),
970
+ TryRecvError::Empty
971
+ );
972
+ }
973
+ }