temporalio 0.0.1 → 0.0.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (232) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +175 -4
  3. data/bridge/Cargo.lock +44 -21
  4. data/bridge/Cargo.toml +1 -0
  5. data/bridge/sdk-core/Cargo.toml +1 -1
  6. data/bridge/sdk-core/README.md +1 -4
  7. data/bridge/sdk-core/client/Cargo.toml +1 -1
  8. data/bridge/sdk-core/client/src/lib.rs +12 -20
  9. data/bridge/sdk-core/client/src/raw.rs +9 -8
  10. data/bridge/sdk-core/client/src/retry.rs +100 -23
  11. data/bridge/sdk-core/core/Cargo.toml +7 -7
  12. data/bridge/sdk-core/core/benches/workflow_replay.rs +13 -10
  13. data/bridge/sdk-core/core/src/abstractions.rs +22 -22
  14. data/bridge/sdk-core/core/src/core_tests/activity_tasks.rs +146 -43
  15. data/bridge/sdk-core/core/src/core_tests/local_activities.rs +419 -9
  16. data/bridge/sdk-core/core/src/core_tests/queries.rs +247 -89
  17. data/bridge/sdk-core/core/src/core_tests/workers.rs +2 -2
  18. data/bridge/sdk-core/core/src/core_tests/workflow_cancels.rs +1 -1
  19. data/bridge/sdk-core/core/src/core_tests/workflow_tasks.rs +47 -27
  20. data/bridge/sdk-core/core/src/lib.rs +139 -32
  21. data/bridge/sdk-core/core/src/protosext/mod.rs +1 -1
  22. data/bridge/sdk-core/core/src/replay/mod.rs +185 -41
  23. data/bridge/sdk-core/core/src/telemetry/log_export.rs +190 -0
  24. data/bridge/sdk-core/core/src/telemetry/metrics.rs +184 -139
  25. data/bridge/sdk-core/core/src/telemetry/mod.rs +310 -315
  26. data/bridge/sdk-core/core/src/telemetry/prometheus_server.rs +4 -3
  27. data/bridge/sdk-core/core/src/test_help/mod.rs +23 -9
  28. data/bridge/sdk-core/core/src/worker/activities/local_activities.rs +12 -6
  29. data/bridge/sdk-core/core/src/worker/activities.rs +40 -23
  30. data/bridge/sdk-core/core/src/worker/client/mocks.rs +1 -1
  31. data/bridge/sdk-core/core/src/worker/client.rs +30 -4
  32. data/bridge/sdk-core/core/src/worker/mod.rs +23 -19
  33. data/bridge/sdk-core/core/src/worker/workflow/driven_workflow.rs +10 -19
  34. data/bridge/sdk-core/core/src/worker/workflow/history_update.rs +99 -25
  35. data/bridge/sdk-core/core/src/worker/workflow/machines/activity_state_machine.rs +1 -5
  36. data/bridge/sdk-core/core/src/worker/workflow/machines/cancel_external_state_machine.rs +1 -5
  37. data/bridge/sdk-core/core/src/worker/workflow/machines/cancel_workflow_state_machine.rs +1 -5
  38. data/bridge/sdk-core/core/src/worker/workflow/machines/child_workflow_state_machine.rs +3 -5
  39. data/bridge/sdk-core/core/src/worker/workflow/machines/complete_workflow_state_machine.rs +1 -5
  40. data/bridge/sdk-core/core/src/worker/workflow/machines/continue_as_new_workflow_state_machine.rs +2 -6
  41. data/bridge/sdk-core/core/src/worker/workflow/machines/fail_workflow_state_machine.rs +1 -5
  42. data/bridge/sdk-core/core/src/worker/workflow/machines/local_activity_state_machine.rs +24 -22
  43. data/bridge/sdk-core/core/src/worker/workflow/machines/mod.rs +12 -38
  44. data/bridge/sdk-core/core/src/worker/workflow/machines/modify_workflow_properties_state_machine.rs +178 -0
  45. data/bridge/sdk-core/core/src/worker/workflow/machines/patch_state_machine.rs +1 -5
  46. data/bridge/sdk-core/core/src/worker/workflow/machines/signal_external_state_machine.rs +1 -5
  47. data/bridge/sdk-core/core/src/worker/workflow/machines/timer_state_machine.rs +1 -5
  48. data/bridge/sdk-core/core/src/worker/workflow/machines/transition_coverage.rs +8 -2
  49. data/bridge/sdk-core/core/src/worker/workflow/machines/upsert_search_attributes_state_machine.rs +1 -5
  50. data/bridge/sdk-core/core/src/worker/workflow/machines/workflow_machines/local_acts.rs +1 -1
  51. data/bridge/sdk-core/core/src/worker/workflow/machines/workflow_machines.rs +233 -217
  52. data/bridge/sdk-core/core/src/worker/workflow/machines/workflow_task_state_machine.rs +1 -6
  53. data/bridge/sdk-core/core/src/worker/workflow/managed_run/managed_wf_test.rs +4 -4
  54. data/bridge/sdk-core/core/src/worker/workflow/managed_run.rs +13 -5
  55. data/bridge/sdk-core/core/src/worker/workflow/mod.rs +86 -29
  56. data/bridge/sdk-core/core/src/worker/workflow/wft_poller.rs +2 -2
  57. data/bridge/sdk-core/core/src/worker/workflow/workflow_stream.rs +56 -11
  58. data/bridge/sdk-core/core-api/Cargo.toml +4 -3
  59. data/bridge/sdk-core/core-api/src/lib.rs +1 -43
  60. data/bridge/sdk-core/core-api/src/telemetry.rs +147 -0
  61. data/bridge/sdk-core/core-api/src/worker.rs +13 -0
  62. data/bridge/sdk-core/etc/deps.svg +115 -140
  63. data/bridge/sdk-core/etc/regen-depgraph.sh +5 -0
  64. data/bridge/sdk-core/fsm/rustfsm_procmacro/tests/trybuild/no_handle_conversions_require_into_fail.stderr +1 -1
  65. data/bridge/sdk-core/histories/evict_while_la_running_no_interference-23_history.bin +0 -0
  66. data/bridge/sdk-core/histories/evict_while_la_running_no_interference-85_history.bin +0 -0
  67. data/bridge/sdk-core/protos/api_upstream/buf.yaml +0 -3
  68. data/bridge/sdk-core/protos/api_upstream/build/go.mod +7 -0
  69. data/bridge/sdk-core/protos/api_upstream/build/go.sum +5 -0
  70. data/bridge/sdk-core/protos/api_upstream/{temporal/api/update/v1/message.proto → build/tools.go} +6 -23
  71. data/bridge/sdk-core/protos/api_upstream/go.mod +6 -0
  72. data/bridge/sdk-core/protos/api_upstream/temporal/api/batch/v1/message.proto +12 -9
  73. data/bridge/sdk-core/protos/api_upstream/temporal/api/command/v1/message.proto +20 -19
  74. data/bridge/sdk-core/protos/api_upstream/temporal/api/common/v1/message.proto +2 -2
  75. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/batch_operation.proto +3 -2
  76. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/command_type.proto +4 -4
  77. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/common.proto +3 -2
  78. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/event_type.proto +5 -3
  79. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/failed_cause.proto +23 -2
  80. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/{cluster.proto → interaction_type.proto} +10 -11
  81. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/namespace.proto +2 -2
  82. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/query.proto +2 -2
  83. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/reset.proto +2 -2
  84. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/schedule.proto +2 -2
  85. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/task_queue.proto +2 -2
  86. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/update.proto +2 -13
  87. data/bridge/sdk-core/protos/api_upstream/temporal/api/enums/v1/workflow.proto +2 -2
  88. data/bridge/sdk-core/protos/api_upstream/temporal/api/errordetails/v1/message.proto +2 -2
  89. data/bridge/sdk-core/protos/api_upstream/temporal/api/failure/v1/message.proto +2 -2
  90. data/bridge/sdk-core/protos/api_upstream/temporal/api/filter/v1/message.proto +2 -2
  91. data/bridge/sdk-core/protos/api_upstream/temporal/api/history/v1/message.proto +26 -19
  92. data/bridge/sdk-core/protos/api_upstream/temporal/api/interaction/v1/message.proto +87 -0
  93. data/bridge/sdk-core/protos/api_upstream/temporal/api/namespace/v1/message.proto +2 -2
  94. data/bridge/sdk-core/protos/api_upstream/temporal/api/operatorservice/v1/request_response.proto +21 -61
  95. data/bridge/sdk-core/protos/api_upstream/temporal/api/operatorservice/v1/service.proto +2 -21
  96. data/bridge/sdk-core/protos/api_upstream/temporal/api/query/v1/message.proto +2 -2
  97. data/bridge/sdk-core/protos/api_upstream/temporal/api/replication/v1/message.proto +2 -2
  98. data/bridge/sdk-core/protos/api_upstream/temporal/api/schedule/v1/message.proto +110 -31
  99. data/bridge/sdk-core/protos/api_upstream/temporal/api/taskqueue/v1/message.proto +4 -4
  100. data/bridge/sdk-core/protos/api_upstream/temporal/api/version/v1/message.proto +2 -2
  101. data/bridge/sdk-core/protos/api_upstream/temporal/api/workflow/v1/message.proto +3 -2
  102. data/bridge/sdk-core/protos/api_upstream/temporal/api/workflowservice/v1/request_response.proto +60 -16
  103. data/bridge/sdk-core/protos/api_upstream/temporal/api/workflowservice/v1/service.proto +17 -3
  104. data/bridge/sdk-core/protos/local/temporal/sdk/core/workflow_activation/workflow_activation.proto +2 -0
  105. data/bridge/sdk-core/protos/local/temporal/sdk/core/workflow_commands/workflow_commands.proto +8 -1
  106. data/bridge/sdk-core/protos/testsrv_upstream/temporal/api/testservice/v1/request_response.proto +2 -2
  107. data/bridge/sdk-core/protos/testsrv_upstream/temporal/api/testservice/v1/service.proto +2 -2
  108. data/bridge/sdk-core/sdk/Cargo.toml +2 -2
  109. data/bridge/sdk-core/sdk/src/interceptors.rs +36 -3
  110. data/bridge/sdk-core/sdk/src/lib.rs +7 -5
  111. data/bridge/sdk-core/sdk/src/workflow_context.rs +13 -2
  112. data/bridge/sdk-core/sdk/src/workflow_future.rs +3 -7
  113. data/bridge/sdk-core/sdk-core-protos/Cargo.toml +1 -1
  114. data/bridge/sdk-core/sdk-core-protos/build.rs +0 -1
  115. data/bridge/sdk-core/sdk-core-protos/src/history_builder.rs +65 -18
  116. data/bridge/sdk-core/sdk-core-protos/src/history_info.rs +22 -22
  117. data/bridge/sdk-core/sdk-core-protos/src/lib.rs +104 -44
  118. data/bridge/sdk-core/test-utils/Cargo.toml +2 -1
  119. data/bridge/sdk-core/test-utils/src/lib.rs +81 -29
  120. data/bridge/sdk-core/tests/integ_tests/heartbeat_tests.rs +5 -2
  121. data/bridge/sdk-core/tests/integ_tests/metrics_tests.rs +37 -0
  122. data/bridge/sdk-core/tests/integ_tests/polling_tests.rs +0 -13
  123. data/bridge/sdk-core/tests/integ_tests/workflow_tests/local_activities.rs +167 -13
  124. data/bridge/sdk-core/tests/integ_tests/workflow_tests/modify_wf_properties.rs +53 -0
  125. data/bridge/sdk-core/tests/integ_tests/workflow_tests/replay.rs +106 -20
  126. data/bridge/sdk-core/tests/integ_tests/workflow_tests.rs +18 -8
  127. data/bridge/sdk-core/tests/main.rs +6 -4
  128. data/bridge/src/connection.rs +81 -62
  129. data/bridge/src/lib.rs +92 -33
  130. data/bridge/src/runtime.rs +9 -2
  131. data/bridge/src/worker.rs +53 -2
  132. data/lib/bridge.so +0 -0
  133. data/lib/gen/temporal/api/batch/v1/message_pb.rb +8 -6
  134. data/lib/gen/temporal/api/command/v1/message_pb.rb +17 -9
  135. data/lib/gen/temporal/api/common/v1/message_pb.rb +1 -1
  136. data/lib/gen/temporal/api/enums/v1/batch_operation_pb.rb +2 -1
  137. data/lib/gen/temporal/api/enums/v1/command_type_pb.rb +3 -1
  138. data/lib/gen/temporal/api/enums/v1/common_pb.rb +2 -1
  139. data/lib/gen/temporal/api/enums/v1/event_type_pb.rb +3 -2
  140. data/lib/gen/temporal/api/enums/v1/failed_cause_pb.rb +7 -1
  141. data/lib/gen/temporal/api/enums/v1/interaction_type_pb.rb +25 -0
  142. data/lib/gen/temporal/api/enums/v1/namespace_pb.rb +1 -1
  143. data/lib/gen/temporal/api/enums/v1/query_pb.rb +1 -1
  144. data/lib/gen/temporal/api/enums/v1/reset_pb.rb +1 -1
  145. data/lib/gen/temporal/api/enums/v1/schedule_pb.rb +1 -1
  146. data/lib/gen/temporal/api/enums/v1/task_queue_pb.rb +1 -1
  147. data/lib/gen/temporal/api/enums/v1/update_pb.rb +1 -6
  148. data/lib/gen/temporal/api/enums/v1/workflow_pb.rb +1 -1
  149. data/lib/gen/temporal/api/errordetails/v1/message_pb.rb +1 -1
  150. data/lib/gen/temporal/api/failure/v1/message_pb.rb +1 -1
  151. data/lib/gen/temporal/api/filter/v1/message_pb.rb +1 -1
  152. data/lib/gen/temporal/api/history/v1/message_pb.rb +19 -18
  153. data/lib/gen/temporal/api/interaction/v1/message_pb.rb +49 -0
  154. data/lib/gen/temporal/api/namespace/v1/message_pb.rb +1 -1
  155. data/lib/gen/temporal/api/operatorservice/v1/request_response_pb.rb +11 -51
  156. data/lib/gen/temporal/api/operatorservice/v1/service_pb.rb +1 -1
  157. data/lib/gen/temporal/api/query/v1/message_pb.rb +1 -1
  158. data/lib/gen/temporal/api/replication/v1/message_pb.rb +1 -1
  159. data/lib/gen/temporal/api/schedule/v1/message_pb.rb +22 -1
  160. data/lib/gen/temporal/api/taskqueue/v1/message_pb.rb +2 -2
  161. data/lib/gen/temporal/api/version/v1/message_pb.rb +1 -1
  162. data/lib/gen/temporal/api/workflow/v1/message_pb.rb +2 -1
  163. data/lib/gen/temporal/api/workflowservice/v1/request_response_pb.rb +27 -10
  164. data/lib/gen/temporal/api/workflowservice/v1/service_pb.rb +1 -1
  165. data/lib/gen/temporal/sdk/core/workflow_activation/workflow_activation_pb.rb +1 -0
  166. data/lib/gen/temporal/sdk/core/workflow_commands/workflow_commands_pb.rb +5 -1
  167. data/lib/temporalio/activity/context.rb +97 -0
  168. data/lib/temporalio/activity/info.rb +67 -0
  169. data/lib/temporalio/activity.rb +85 -0
  170. data/lib/temporalio/bridge/error.rb +8 -0
  171. data/lib/temporalio/bridge.rb +14 -0
  172. data/lib/{temporal → temporalio}/client/implementation.rb +49 -48
  173. data/lib/{temporal → temporalio}/client/workflow_handle.rb +35 -35
  174. data/lib/{temporal → temporalio}/client.rb +19 -32
  175. data/lib/{temporal → temporalio}/connection.rb +238 -223
  176. data/lib/{temporal → temporalio}/data_converter.rb +76 -35
  177. data/lib/{temporal → temporalio}/error/failure.rb +6 -6
  178. data/lib/{temporal → temporalio}/error/workflow_failure.rb +4 -2
  179. data/lib/{temporal → temporalio}/errors.rb +19 -1
  180. data/lib/{temporal → temporalio}/failure_converter/base.rb +5 -5
  181. data/lib/{temporal → temporalio}/failure_converter/basic.rb +58 -52
  182. data/lib/temporalio/failure_converter.rb +7 -0
  183. data/lib/{temporal → temporalio}/interceptor/chain.rb +2 -1
  184. data/lib/{temporal → temporalio}/interceptor/client.rb +22 -1
  185. data/lib/{temporal → temporalio}/payload_codec/base.rb +5 -5
  186. data/lib/{temporal → temporalio}/payload_converter/base.rb +3 -3
  187. data/lib/{temporal → temporalio}/payload_converter/bytes.rb +4 -3
  188. data/lib/{temporal → temporalio}/payload_converter/composite.rb +7 -5
  189. data/lib/{temporal → temporalio}/payload_converter/encoding_base.rb +4 -4
  190. data/lib/{temporal → temporalio}/payload_converter/json.rb +4 -3
  191. data/lib/{temporal → temporalio}/payload_converter/nil.rb +4 -3
  192. data/lib/temporalio/payload_converter.rb +14 -0
  193. data/lib/{temporal → temporalio}/retry_policy.rb +4 -4
  194. data/lib/{temporal → temporalio}/retry_state.rb +1 -1
  195. data/lib/temporalio/runtime.rb +25 -0
  196. data/lib/{temporal → temporalio}/timeout_type.rb +2 -2
  197. data/lib/temporalio/version.rb +3 -0
  198. data/lib/temporalio/worker/activity_runner.rb +92 -0
  199. data/lib/temporalio/worker/activity_worker.rb +138 -0
  200. data/lib/temporalio/worker/reactor.rb +46 -0
  201. data/lib/temporalio/worker/runner.rb +63 -0
  202. data/lib/temporalio/worker/sync_worker.rb +88 -0
  203. data/lib/temporalio/worker/thread_pool_executor.rb +51 -0
  204. data/lib/temporalio/worker.rb +198 -0
  205. data/lib/{temporal → temporalio}/workflow/execution_info.rb +4 -4
  206. data/lib/{temporal → temporalio}/workflow/execution_status.rb +1 -1
  207. data/lib/{temporal → temporalio}/workflow/id_reuse_policy.rb +6 -6
  208. data/lib/{temporal → temporalio}/workflow/query_reject_condition.rb +5 -5
  209. data/lib/temporalio.rb +12 -3
  210. data/temporalio.gemspec +7 -3
  211. metadata +79 -56
  212. data/bridge/sdk-core/bridge-ffi/Cargo.toml +0 -24
  213. data/bridge/sdk-core/bridge-ffi/LICENSE.txt +0 -23
  214. data/bridge/sdk-core/bridge-ffi/build.rs +0 -25
  215. data/bridge/sdk-core/bridge-ffi/include/sdk-core-bridge.h +0 -249
  216. data/bridge/sdk-core/bridge-ffi/src/lib.rs +0 -825
  217. data/bridge/sdk-core/bridge-ffi/src/wrappers.rs +0 -211
  218. data/bridge/sdk-core/core/src/log_export.rs +0 -62
  219. data/bridge/sdk-core/core/src/worker/workflow/machines/mutable_side_effect_state_machine.rs +0 -127
  220. data/bridge/sdk-core/core/src/worker/workflow/machines/side_effect_state_machine.rs +0 -71
  221. data/bridge/sdk-core/protos/api_upstream/temporal/api/cluster/v1/message.proto +0 -83
  222. data/bridge/sdk-core/protos/local/temporal/sdk/core/bridge/bridge.proto +0 -210
  223. data/bridge/sdk-core/sdk/src/conversions.rs +0 -8
  224. data/lib/gen/temporal/api/cluster/v1/message_pb.rb +0 -67
  225. data/lib/gen/temporal/api/enums/v1/cluster_pb.rb +0 -26
  226. data/lib/gen/temporal/api/update/v1/message_pb.rb +0 -26
  227. data/lib/temporal/bridge.rb +0 -14
  228. data/lib/temporal/failure_converter.rb +0 -8
  229. data/lib/temporal/payload_converter.rb +0 -14
  230. data/lib/temporal/runtime.rb +0 -22
  231. data/lib/temporal/version.rb +0 -3
  232. data/lib/temporal.rb +0 -8
@@ -13,12 +13,11 @@ extern crate core;
13
13
 
14
14
  mod abstractions;
15
15
  pub mod ephemeral_server;
16
- mod log_export;
17
16
  mod pollers;
18
17
  mod protosext;
19
18
  pub mod replay;
20
19
  pub(crate) mod retry_logic;
21
- pub(crate) mod telemetry;
20
+ pub mod telemetry;
22
21
  mod worker;
23
22
 
24
23
  #[cfg(test)]
@@ -33,10 +32,6 @@ pub use pollers::{
33
32
  Client, ClientOptions, ClientOptionsBuilder, ClientTlsConfig, RetryClient, RetryConfig,
34
33
  TlsConfig, WorkflowClientTrait,
35
34
  };
36
- pub use telemetry::{
37
- fetch_global_buffered_logs, telemetry_init, Logger, MetricTemporality, MetricsExporter,
38
- OtelCollectorOptions, TelemetryOptions, TelemetryOptionsBuilder, TraceExporter,
39
- };
40
35
  pub use temporal_sdk_core_api as api;
41
36
  pub use temporal_sdk_core_protos as protos;
42
37
  pub use temporal_sdk_core_protos::TaskToken;
@@ -44,33 +39,39 @@ pub use url::Url;
44
39
  pub use worker::{Worker, WorkerConfig, WorkerConfigBuilder};
45
40
 
46
41
  use crate::{
47
- replay::mock_client_from_history,
48
- telemetry::metrics::{MetricsContext, METRIC_METER},
42
+ replay::{mock_client_from_histories, Historator, HistoryForReplay},
43
+ telemetry::{
44
+ metrics::MetricsContext, remove_trace_subscriber_for_current_thread,
45
+ set_trace_subscriber_for_current_thread, telemetry_init, TelemetryInstance,
46
+ },
49
47
  worker::client::WorkerClientBag,
50
48
  };
49
+ use futures::Stream;
51
50
  use std::sync::Arc;
52
51
  use temporal_client::{ConfiguredClient, TemporalServiceClientWithMetrics};
53
52
  use temporal_sdk_core_api::{
54
53
  errors::{CompleteActivityError, PollActivityError, PollWfError},
55
- CoreLog, Worker as WorkerTrait,
54
+ telemetry::{CoreTelemetry, TelemetryOptions},
55
+ Worker as WorkerTrait,
56
56
  };
57
- use temporal_sdk_core_protos::{coresdk::ActivityHeartbeat, temporal::api::history::v1::History};
58
-
59
- lazy_static::lazy_static! {
60
- /// A process-wide unique string, which will be different on every startup
61
- static ref PROCCESS_UNIQ_ID: String = {
62
- uuid::Uuid::new_v4().simple().to_string()
63
- };
64
- }
57
+ use temporal_sdk_core_protos::coresdk::ActivityHeartbeat;
65
58
 
66
59
  /// Initialize a worker bound to a task queue.
67
60
  ///
61
+ /// You will need to have already initialized a [CoreRuntime] which will be used for this worker.
62
+ /// After the worker is initialized, you should use [CoreRuntime::tokio_handle] to run the worker's
63
+ /// async functions.
64
+ ///
68
65
  /// Lang implementations may pass in a [temporal_client::ConfiguredClient] directly (or a
69
66
  /// [RetryClient] wrapping one, or a handful of other variants of the same idea). When they do so,
70
67
  /// this function will always overwrite the client retry configuration, force the client to use the
71
68
  /// namespace defined in the worker config, and set the client identity appropriately. IE: Use
72
69
  /// [ClientOptions::connect_no_namespace], not [ClientOptions::connect].
73
- pub fn init_worker<CT>(worker_config: WorkerConfig, client: CT) -> Worker
70
+ pub fn init_worker<CT>(
71
+ runtime: &CoreRuntime,
72
+ worker_config: WorkerConfig,
73
+ client: CT,
74
+ ) -> Result<Worker, anyhow::Error>
74
75
  where
75
76
  CT: Into<sealed::AnyClient>,
76
77
  {
@@ -96,18 +97,24 @@ where
96
97
  worker_config.use_worker_versioning,
97
98
  ));
98
99
 
99
- let metrics = MetricsContext::top_level(worker_config.namespace.clone())
100
+ let metrics = MetricsContext::top_level(worker_config.namespace.clone(), &runtime.telemetry)
100
101
  .with_task_q(worker_config.task_queue.clone());
101
- Worker::new(worker_config, sticky_q, client_bag, metrics)
102
+ Ok(Worker::new(worker_config, sticky_q, client_bag, metrics))
102
103
  }
103
104
 
104
105
  /// Create a worker for replaying a specific history. It will auto-shutdown as soon as the history
105
- /// has finished being replayed. The provided client should be a mock, and this should only be used
106
- /// for workflow testing purposes.
107
- pub fn init_replay_worker(
106
+ /// has finished being replayed.
107
+ ///
108
+ /// You do not necessarily need a [CoreRuntime] for replay workers, but it's advisable to create
109
+ /// one and use it to run the replay worker's async functions the same way you would for a normal
110
+ /// worker.
111
+ pub fn init_replay_worker<I>(
108
112
  mut config: WorkerConfig,
109
- history: &History,
110
- ) -> Result<Worker, anyhow::Error> {
113
+ histories: I,
114
+ ) -> Result<Worker, anyhow::Error>
115
+ where
116
+ I: Stream<Item = HistoryForReplay> + Send + 'static,
117
+ {
111
118
  info!(
112
119
  task_queue = config.task_queue.as_str(),
113
120
  "Registering replay worker"
@@ -115,15 +122,18 @@ pub fn init_replay_worker(
115
122
  config.max_cached_workflows = 1;
116
123
  config.max_concurrent_wft_polls = 1;
117
124
  config.no_remote_activities = true;
118
- // Could possibly just use mocked pollers here?
119
- let client = mock_client_from_history(history, config.task_queue.clone());
120
- let run_id = history.extract_run_id_from_start()?.to_string();
121
- let last_event = history.last_event_id();
122
- let mut worker = Worker::new(config, None, Arc::new(client), MetricsContext::default());
123
- worker.set_shutdown_on_run_reaches_event(run_id, last_event);
125
+ let historator = Historator::new(histories);
126
+ let post_activate = historator.get_post_activate_hook();
127
+ let shutdown_tok = historator.get_shutdown_setter();
128
+ let client = mock_client_from_histories(historator);
129
+ let mut worker = Worker::new(config, None, Arc::new(client), MetricsContext::no_op());
130
+ worker.set_post_activate_hook(post_activate);
131
+ shutdown_tok(worker.shutdown_token());
124
132
  Ok(worker)
125
133
  }
126
134
 
135
+ /// Creates a unique sticky queue name for a worker, iff the config allows for 1 or more cached
136
+ /// workflows.
127
137
  pub(crate) fn sticky_q_name_for_worker(
128
138
  process_identity: &str,
129
139
  config: &WorkerConfig,
@@ -131,7 +141,9 @@ pub(crate) fn sticky_q_name_for_worker(
131
141
  if config.max_cached_workflows > 0 {
132
142
  Some(format!(
133
143
  "{}-{}-{}",
134
- &process_identity, &config.task_queue, *PROCCESS_UNIQ_ID
144
+ &process_identity,
145
+ &config.task_queue,
146
+ uuid::Uuid::new_v4().simple()
135
147
  ))
136
148
  } else {
137
149
  None
@@ -173,3 +185,98 @@ mod sealed {
173
185
  }
174
186
  }
175
187
  }
188
+
189
+ /// Holds shared state/components needed to back instances of workers and clients. More than one
190
+ /// may be instantiated, but typically only one is needed. More than one runtime instance may be
191
+ /// useful if multiple different telemetry settings are required.
192
+ pub struct CoreRuntime {
193
+ telemetry: TelemetryInstance,
194
+ runtime: Option<tokio::runtime::Runtime>,
195
+ runtime_handle: tokio::runtime::Handle,
196
+ }
197
+
198
+ impl CoreRuntime {
199
+ /// Create a new core runtime with the provided telemetry options and tokio runtime builder.
200
+ /// Also initialize telemetry for the thread this is being called on.
201
+ ///
202
+ /// Note that this function will call the [tokio::runtime::Builder::enable_all] builder option
203
+ /// on the Tokio runtime builder, and will call [tokio::runtime::Builder::on_thread_start] to
204
+ /// ensure telemetry subscribers are set on every tokio thread.
205
+ ///
206
+ /// **Important**: You need to call this *before* calling any async functions on workers or
207
+ /// clients, otherwise the tracing subscribers will not be properly attached.
208
+ ///
209
+ /// # Panics
210
+ /// If a tokio runtime has already been initialized. To re-use an existing runtime, call
211
+ /// [CoreRuntime::new_assume_tokio].
212
+ pub fn new(
213
+ telemetry_options: TelemetryOptions,
214
+ mut tokio_builder: tokio::runtime::Builder,
215
+ ) -> Result<Self, anyhow::Error> {
216
+ let telemetry = telemetry_init(telemetry_options)?;
217
+ let subscriber = telemetry.trace_subscriber();
218
+ let runtime = tokio_builder
219
+ .enable_all()
220
+ .on_thread_start(move || {
221
+ set_trace_subscriber_for_current_thread(subscriber.clone());
222
+ })
223
+ .build()?;
224
+ let _rg = runtime.enter();
225
+ let mut me = Self::new_assume_tokio_initialized_telem(telemetry);
226
+ me.runtime = Some(runtime);
227
+ Ok(me)
228
+ }
229
+
230
+ /// Initialize telemetry for the thread this is being called on, assuming a tokio runtime is
231
+ /// already active and this call exists in its context. See [Self::new] for more.
232
+ ///
233
+ /// # Panics
234
+ /// If there is no currently active Tokio runtime
235
+ pub fn new_assume_tokio(telemetry_options: TelemetryOptions) -> Result<Self, anyhow::Error> {
236
+ let telemetry = telemetry_init(telemetry_options)?;
237
+ Ok(Self::new_assume_tokio_initialized_telem(telemetry))
238
+ }
239
+
240
+ /// Construct a runtime from an already-initialized telemetry instance, assuming a tokio runtime
241
+ /// is already active and this call exists in its context. See [Self::new] for more.
242
+ ///
243
+ /// # Panics
244
+ /// If there is no currently active Tokio runtime
245
+ pub fn new_assume_tokio_initialized_telem(telemetry: TelemetryInstance) -> Self {
246
+ let runtime_handle = tokio::runtime::Handle::current();
247
+ set_trace_subscriber_for_current_thread(telemetry.trace_subscriber());
248
+ Self {
249
+ telemetry,
250
+ runtime: None,
251
+ runtime_handle,
252
+ }
253
+ }
254
+
255
+ /// Get a handle to the tokio runtime used by this Core runtime.
256
+ pub fn tokio_handle(&self) -> tokio::runtime::Handle {
257
+ self.runtime_handle.clone()
258
+ }
259
+
260
+ /// Returns the metric meter used for recording metrics, if they were enabled.
261
+ pub fn metric_meter(&self) -> Option<&opentelemetry::metrics::Meter> {
262
+ self.telemetry.get_metric_meter()
263
+ }
264
+
265
+ /// Return the trace subscriber associated with the telemetry options/instance. Can be used
266
+ /// to manually set the default for a thread or globally using the `tracing` crate, or with
267
+ /// [set_trace_subscriber_for_current_thread]
268
+ pub fn trace_subscriber(&self) -> Arc<dyn tracing::Subscriber + Send + Sync> {
269
+ self.telemetry.trace_subscriber()
270
+ }
271
+
272
+ /// Return a reference to the owned [TelemetryInstance]
273
+ pub fn telemetry(&self) -> &TelemetryInstance {
274
+ &self.telemetry
275
+ }
276
+ }
277
+
278
+ impl Drop for CoreRuntime {
279
+ fn drop(&mut self) {
280
+ remove_trace_subscriber_for_current_thread();
281
+ }
282
+ }
@@ -274,7 +274,7 @@ impl TryFrom<activity_execution_result::Status> for LocalActivityExecutionResult
274
274
  Status::Failed(f)
275
275
  if f.failure
276
276
  .as_ref()
277
- .map(|fail| fail.is_timeout())
277
+ .map(|fail| fail.is_timeout().is_some())
278
278
  .unwrap_or_default() =>
279
279
  {
280
280
  Ok(LocalActivityExecutionResult::TimedOut(f))
@@ -2,70 +2,214 @@
2
2
  //! to replay canned histories. It should be used by Lang SDKs to provide replay capabilities to
3
3
  //! users during testing.
4
4
 
5
- use crate::worker::client::{mocks::mock_manual_workflow_client, WorkerClient};
6
- use futures::FutureExt;
5
+ use crate::{
6
+ worker::client::{mocks::mock_manual_workflow_client, WorkerClient},
7
+ Worker,
8
+ };
9
+ use futures::{FutureExt, Stream, StreamExt};
10
+ use once_cell::sync::OnceCell;
11
+ use parking_lot::Mutex;
7
12
  use std::{
8
- sync::{
9
- atomic::{AtomicBool, Ordering},
10
- Arc,
11
- },
12
- time::Duration,
13
+ collections::HashMap,
14
+ pin::Pin,
15
+ sync::Arc,
16
+ task::{Context, Poll},
13
17
  };
14
- use temporal_sdk_core_protos::temporal::api::{
15
- common::v1::WorkflowExecution,
16
- history::v1::History,
17
- workflowservice::v1::{
18
- RespondWorkflowTaskCompletedResponse, RespondWorkflowTaskFailedResponse,
18
+ use temporal_sdk_core_protos::{
19
+ coresdk::workflow_activation::remove_from_cache::EvictionReason,
20
+ temporal::api::{
21
+ common::v1::WorkflowExecution,
22
+ history::v1::History,
23
+ workflowservice::v1::{
24
+ RespondWorkflowTaskCompletedResponse, RespondWorkflowTaskFailedResponse,
25
+ },
19
26
  },
20
27
  };
21
28
  pub use temporal_sdk_core_protos::{
22
29
  default_wes_attribs, HistoryInfo, TestHistoryBuilder, DEFAULT_WORKFLOW_TYPE,
23
30
  };
31
+ use tokio::sync::{mpsc, mpsc::UnboundedSender, Mutex as TokioMutex};
32
+ use tokio_stream::wrappers::UnboundedReceiverStream;
33
+ use tokio_util::sync::CancellationToken;
34
+
35
+ /// A history which will be used during replay verification. Since histories do not include the
36
+ /// workflow id, it must be manually attached.
37
+ #[derive(Debug, Clone, derive_more::Constructor)]
38
+ pub struct HistoryForReplay {
39
+ hist: History,
40
+ workflow_id: String,
41
+ }
42
+
43
+ /// Allows lang to feed histories into the replayer one at a time. Simply drop the feeder to signal
44
+ /// to the worker that you're done and it should initiate shutdown.
45
+ pub struct HistoryFeeder {
46
+ tx: mpsc::Sender<HistoryForReplay>,
47
+ }
48
+ /// The stream half of a [HistoryFeeder]
49
+ pub struct HistoryFeederStream {
50
+ rcvr: mpsc::Receiver<HistoryForReplay>,
51
+ }
52
+
53
+ impl HistoryFeeder {
54
+ /// Make a new history feeder, which will store at most `buffer_size` histories before `feed`
55
+ /// blocks.
56
+ ///
57
+ /// Returns a feeder which will be used to feed in histories, and a stream you can pass to
58
+ /// one of the replay worker init functions.
59
+ pub fn new(buffer_size: usize) -> (Self, HistoryFeederStream) {
60
+ let (tx, rcvr) = mpsc::channel(buffer_size);
61
+ (Self { tx }, HistoryFeederStream { rcvr })
62
+ }
63
+ /// Feed a new history into the replayer, blocking if there is not room to accept another
64
+ /// history.
65
+ pub async fn feed(&self, history: HistoryForReplay) -> anyhow::Result<()> {
66
+ self.tx.send(history).await?;
67
+ Ok(())
68
+ }
69
+ }
70
+
71
+ impl Stream for HistoryFeederStream {
72
+ type Item = HistoryForReplay;
73
+
74
+ fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
75
+ self.rcvr.poll_recv(cx)
76
+ }
77
+ }
24
78
 
25
- /// Create a mock client which can be used by a replay worker to serve up canned history.
26
- /// It will return the entire history in one workflow task, after that it will return default
27
- /// responses (with a 10s wait). If a workflow task failure is sent to the mock, it will send
28
- /// the complete response again.
29
- pub(crate) fn mock_client_from_history(
30
- history: &History,
31
- task_queue: impl Into<String>,
32
- ) -> impl WorkerClient {
79
+ /// Create a mock client which can be used by a replay worker to serve up canned histories. It will
80
+ /// return the entire history in one workflow task. If a workflow task failure is sent to the mock,
81
+ /// it will send the complete response again.
82
+ ///
83
+ /// Once it runs out of histories to return, it will serve up default responses after a 10s delay
84
+ pub(crate) fn mock_client_from_histories(historator: Historator) -> impl WorkerClient {
33
85
  let mut mg = mock_manual_workflow_client();
34
86
 
35
- let hist_info = HistoryInfo::new_from_history(history, None).unwrap();
36
- let wf = WorkflowExecution {
37
- workflow_id: "fake_wf_id".to_string(),
38
- run_id: hist_info.orig_run_id().to_string(),
39
- };
87
+ let hist_allow_tx = historator.replay_done_tx.clone();
88
+ let historator = Arc::new(TokioMutex::new(historator));
40
89
 
41
- let did_send = Arc::new(AtomicBool::new(false));
42
- let did_send_clone = did_send.clone();
43
- let tq = task_queue.into();
44
90
  mg.expect_poll_workflow_task().returning(move |_, _| {
45
- let hist_info = hist_info.clone();
46
- let wf = wf.clone();
47
- let did_send_clone = did_send_clone.clone();
48
- let tq = tq.clone();
91
+ let historator = historator.clone();
49
92
  async move {
50
- if !did_send_clone.swap(true, Ordering::AcqRel) {
51
- let mut resp = hist_info.as_poll_wft_response(tq);
52
- resp.workflow_execution = Some(wf.clone());
93
+ let mut hlock = historator.lock().await;
94
+ // Always wait for permission before dispatching the next task
95
+ let _ = hlock.allow_stream.next().await;
96
+
97
+ if let Some(history) = hlock.next().await {
98
+ let hist_info = HistoryInfo::new_from_history(&history.hist, None).unwrap();
99
+ let mut resp = hist_info.as_poll_wft_response();
100
+ resp.workflow_execution = Some(WorkflowExecution {
101
+ workflow_id: history.workflow_id,
102
+ run_id: hist_info.orig_run_id().to_string(),
103
+ });
53
104
  Ok(resp)
54
105
  } else {
55
- tokio::time::sleep(Duration::from_secs(10)).await;
106
+ if let Some(wc) = hlock.worker_closer.get() {
107
+ wc.cancel();
108
+ }
56
109
  Ok(Default::default())
57
110
  }
58
111
  }
59
112
  .boxed()
60
113
  });
61
114
 
62
- mg.expect_complete_workflow_task()
63
- .returning(|_| async move { Ok(RespondWorkflowTaskCompletedResponse::default()) }.boxed());
115
+ mg.expect_complete_workflow_task().returning(move |_| {
116
+ async move { Ok(RespondWorkflowTaskCompletedResponse::default()) }.boxed()
117
+ });
64
118
  mg.expect_fail_workflow_task().returning(move |_, _, _| {
65
- // We'll need to re-send the history if WFT fails
66
- did_send.store(false, Ordering::Release);
67
- async move { Ok(RespondWorkflowTaskFailedResponse {}) }.boxed()
119
+ hist_allow_tx.send("Failed".to_string()).unwrap();
120
+ async move { Ok(RespondWorkflowTaskFailedResponse::default()) }.boxed()
68
121
  });
69
122
 
70
123
  mg
71
124
  }
125
+
126
+ pub(crate) struct Historator {
127
+ iter: Pin<Box<dyn Stream<Item = HistoryForReplay> + Send>>,
128
+ allow_stream: UnboundedReceiverStream<String>,
129
+ worker_closer: Arc<OnceCell<CancellationToken>>,
130
+ dat: Arc<Mutex<HistoratorDat>>,
131
+ replay_done_tx: UnboundedSender<String>,
132
+ }
133
+ impl Historator {
134
+ pub(crate) fn new(histories: impl Stream<Item = HistoryForReplay> + Send + 'static) -> Self {
135
+ let dat = Arc::new(Mutex::new(HistoratorDat::default()));
136
+ let (replay_done_tx, replay_done_rx) = mpsc::unbounded_channel();
137
+ // Need to allow the first history item
138
+ replay_done_tx.send("fake".to_string()).unwrap();
139
+ Self {
140
+ iter: Box::pin(histories.fuse()),
141
+ allow_stream: UnboundedReceiverStream::new(replay_done_rx),
142
+ worker_closer: Arc::new(OnceCell::new()),
143
+ dat,
144
+ replay_done_tx,
145
+ }
146
+ }
147
+
148
+ /// Returns a callback that can be used as the post-activation hook for a worker to indicate
149
+ /// we're ready to replay the next history, or whatever else.
150
+ pub(crate) fn get_post_activate_hook(&self) -> impl Fn(&Worker, &str, usize) + Send + Sync {
151
+ let dat = self.dat.clone();
152
+ let done_tx = self.replay_done_tx.clone();
153
+ move |worker, activated_run_id, last_processed_event| {
154
+ // We can't hold the lock while evaluating the hook, or we'd deadlock.
155
+ let last_event_in_hist = dat
156
+ .lock()
157
+ .run_id_to_last_event_num
158
+ .get(activated_run_id)
159
+ .cloned();
160
+ if let Some(le) = last_event_in_hist {
161
+ if last_processed_event >= le {
162
+ worker.request_wf_eviction(
163
+ activated_run_id,
164
+ "Always evict workflows after replay",
165
+ EvictionReason::LangRequested,
166
+ );
167
+ done_tx.send(activated_run_id.to_string()).unwrap();
168
+ }
169
+ }
170
+ }
171
+ }
172
+
173
+ pub(crate) fn get_shutdown_setter(&self) -> impl FnOnce(CancellationToken) + 'static {
174
+ let wc = self.worker_closer.clone();
175
+ move |ct| {
176
+ wc.set(ct).expect("Shutdown token must only be set once");
177
+ }
178
+ }
179
+ }
180
+
181
+ impl Stream for Historator {
182
+ type Item = HistoryForReplay;
183
+
184
+ fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
185
+ match self.iter.poll_next_unpin(cx) {
186
+ Poll::Ready(Some(history)) => {
187
+ let run_id = history
188
+ .hist
189
+ .extract_run_id_from_start()
190
+ .expect(
191
+ "Histories provided for replay must contain run ids in their workflow \
192
+ execution started events",
193
+ )
194
+ .to_string();
195
+ let last_event = history.hist.last_event_id();
196
+ self.dat
197
+ .lock()
198
+ .run_id_to_last_event_num
199
+ .insert(run_id, last_event as usize);
200
+ Poll::Ready(Some(history))
201
+ }
202
+ Poll::Ready(None) => {
203
+ self.dat.lock().all_dispatched = true;
204
+ Poll::Ready(None)
205
+ }
206
+ o => o,
207
+ }
208
+ }
209
+ }
210
+
211
+ #[derive(Default)]
212
+ struct HistoratorDat {
213
+ run_id_to_last_event_num: HashMap<String, usize>,
214
+ all_dispatched: bool,
215
+ }