clara-temporalio 0.4.3

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 (192) hide show
  1. checksums.yaml +7 -0
  2. data/.yardopts +2 -0
  3. data/Cargo.lock +4429 -0
  4. data/Cargo.toml +31 -0
  5. data/Gemfile +27 -0
  6. data/LICENSE +21 -0
  7. data/README.md +1311 -0
  8. data/Rakefile +101 -0
  9. data/ext/Cargo.toml +27 -0
  10. data/lib/temporalio/activity/cancellation_details.rb +58 -0
  11. data/lib/temporalio/activity/complete_async_error.rb +11 -0
  12. data/lib/temporalio/activity/context.rb +131 -0
  13. data/lib/temporalio/activity/definition.rb +197 -0
  14. data/lib/temporalio/activity/info.rb +70 -0
  15. data/lib/temporalio/activity.rb +14 -0
  16. data/lib/temporalio/api/activity/v1/message.rb +25 -0
  17. data/lib/temporalio/api/batch/v1/message.rb +38 -0
  18. data/lib/temporalio/api/cloud/account/v1/message.rb +28 -0
  19. data/lib/temporalio/api/cloud/cloudservice/v1/request_response.rb +135 -0
  20. data/lib/temporalio/api/cloud/cloudservice/v1/service.rb +25 -0
  21. data/lib/temporalio/api/cloud/cloudservice.rb +3 -0
  22. data/lib/temporalio/api/cloud/identity/v1/message.rb +46 -0
  23. data/lib/temporalio/api/cloud/namespace/v1/message.rb +46 -0
  24. data/lib/temporalio/api/cloud/nexus/v1/message.rb +32 -0
  25. data/lib/temporalio/api/cloud/operation/v1/message.rb +28 -0
  26. data/lib/temporalio/api/cloud/region/v1/message.rb +24 -0
  27. data/lib/temporalio/api/cloud/resource/v1/message.rb +23 -0
  28. data/lib/temporalio/api/cloud/sink/v1/message.rb +24 -0
  29. data/lib/temporalio/api/cloud/usage/v1/message.rb +31 -0
  30. data/lib/temporalio/api/command/v1/message.rb +46 -0
  31. data/lib/temporalio/api/common/v1/grpc_status.rb +23 -0
  32. data/lib/temporalio/api/common/v1/message.rb +49 -0
  33. data/lib/temporalio/api/deployment/v1/message.rb +39 -0
  34. data/lib/temporalio/api/enums/v1/batch_operation.rb +22 -0
  35. data/lib/temporalio/api/enums/v1/command_type.rb +21 -0
  36. data/lib/temporalio/api/enums/v1/common.rb +28 -0
  37. data/lib/temporalio/api/enums/v1/deployment.rb +23 -0
  38. data/lib/temporalio/api/enums/v1/event_type.rb +21 -0
  39. data/lib/temporalio/api/enums/v1/failed_cause.rb +26 -0
  40. data/lib/temporalio/api/enums/v1/namespace.rb +23 -0
  41. data/lib/temporalio/api/enums/v1/nexus.rb +21 -0
  42. data/lib/temporalio/api/enums/v1/query.rb +22 -0
  43. data/lib/temporalio/api/enums/v1/reset.rb +23 -0
  44. data/lib/temporalio/api/enums/v1/schedule.rb +21 -0
  45. data/lib/temporalio/api/enums/v1/task_queue.rb +25 -0
  46. data/lib/temporalio/api/enums/v1/update.rb +22 -0
  47. data/lib/temporalio/api/enums/v1/workflow.rb +31 -0
  48. data/lib/temporalio/api/errordetails/v1/message.rb +44 -0
  49. data/lib/temporalio/api/export/v1/message.rb +24 -0
  50. data/lib/temporalio/api/failure/v1/message.rb +38 -0
  51. data/lib/temporalio/api/filter/v1/message.rb +27 -0
  52. data/lib/temporalio/api/history/v1/message.rb +94 -0
  53. data/lib/temporalio/api/namespace/v1/message.rb +31 -0
  54. data/lib/temporalio/api/nexus/v1/message.rb +41 -0
  55. data/lib/temporalio/api/operatorservice/v1/request_response.rb +49 -0
  56. data/lib/temporalio/api/operatorservice/v1/service.rb +23 -0
  57. data/lib/temporalio/api/operatorservice.rb +3 -0
  58. data/lib/temporalio/api/payload_visitor.rb +1668 -0
  59. data/lib/temporalio/api/protocol/v1/message.rb +23 -0
  60. data/lib/temporalio/api/query/v1/message.rb +28 -0
  61. data/lib/temporalio/api/replication/v1/message.rb +26 -0
  62. data/lib/temporalio/api/rules/v1/message.rb +27 -0
  63. data/lib/temporalio/api/schedule/v1/message.rb +43 -0
  64. data/lib/temporalio/api/sdk/v1/enhanced_stack_trace.rb +25 -0
  65. data/lib/temporalio/api/sdk/v1/task_complete_metadata.rb +21 -0
  66. data/lib/temporalio/api/sdk/v1/user_metadata.rb +23 -0
  67. data/lib/temporalio/api/sdk/v1/workflow_metadata.rb +23 -0
  68. data/lib/temporalio/api/taskqueue/v1/message.rb +48 -0
  69. data/lib/temporalio/api/testservice/v1/request_response.rb +31 -0
  70. data/lib/temporalio/api/testservice/v1/service.rb +23 -0
  71. data/lib/temporalio/api/update/v1/message.rb +33 -0
  72. data/lib/temporalio/api/version/v1/message.rb +26 -0
  73. data/lib/temporalio/api/workflow/v1/message.rb +63 -0
  74. data/lib/temporalio/api/workflowservice/v1/request_response.rb +244 -0
  75. data/lib/temporalio/api/workflowservice/v1/service.rb +23 -0
  76. data/lib/temporalio/api/workflowservice.rb +3 -0
  77. data/lib/temporalio/api.rb +15 -0
  78. data/lib/temporalio/cancellation.rb +170 -0
  79. data/lib/temporalio/client/activity_id_reference.rb +32 -0
  80. data/lib/temporalio/client/async_activity_handle.rb +85 -0
  81. data/lib/temporalio/client/connection/cloud_service.rb +786 -0
  82. data/lib/temporalio/client/connection/operator_service.rb +201 -0
  83. data/lib/temporalio/client/connection/service.rb +42 -0
  84. data/lib/temporalio/client/connection/test_service.rb +111 -0
  85. data/lib/temporalio/client/connection/workflow_service.rb +1326 -0
  86. data/lib/temporalio/client/connection.rb +316 -0
  87. data/lib/temporalio/client/interceptor.rb +457 -0
  88. data/lib/temporalio/client/schedule.rb +991 -0
  89. data/lib/temporalio/client/schedule_handle.rb +126 -0
  90. data/lib/temporalio/client/with_start_workflow_operation.rb +115 -0
  91. data/lib/temporalio/client/workflow_execution.rb +119 -0
  92. data/lib/temporalio/client/workflow_execution_count.rb +36 -0
  93. data/lib/temporalio/client/workflow_execution_status.rb +18 -0
  94. data/lib/temporalio/client/workflow_handle.rb +389 -0
  95. data/lib/temporalio/client/workflow_query_reject_condition.rb +14 -0
  96. data/lib/temporalio/client/workflow_update_handle.rb +65 -0
  97. data/lib/temporalio/client/workflow_update_wait_stage.rb +17 -0
  98. data/lib/temporalio/client.rb +625 -0
  99. data/lib/temporalio/common_enums.rb +55 -0
  100. data/lib/temporalio/contrib/open_telemetry.rb +469 -0
  101. data/lib/temporalio/converters/data_converter.rb +99 -0
  102. data/lib/temporalio/converters/failure_converter.rb +205 -0
  103. data/lib/temporalio/converters/payload_codec.rb +26 -0
  104. data/lib/temporalio/converters/payload_converter/binary_null.rb +34 -0
  105. data/lib/temporalio/converters/payload_converter/binary_plain.rb +35 -0
  106. data/lib/temporalio/converters/payload_converter/binary_protobuf.rb +42 -0
  107. data/lib/temporalio/converters/payload_converter/composite.rb +66 -0
  108. data/lib/temporalio/converters/payload_converter/encoding.rb +35 -0
  109. data/lib/temporalio/converters/payload_converter/json_plain.rb +44 -0
  110. data/lib/temporalio/converters/payload_converter/json_protobuf.rb +41 -0
  111. data/lib/temporalio/converters/payload_converter.rb +71 -0
  112. data/lib/temporalio/converters/raw_value.rb +20 -0
  113. data/lib/temporalio/converters.rb +9 -0
  114. data/lib/temporalio/error/failure.rb +237 -0
  115. data/lib/temporalio/error.rb +156 -0
  116. data/lib/temporalio/internal/bridge/api/activity_result/activity_result.rb +34 -0
  117. data/lib/temporalio/internal/bridge/api/activity_task/activity_task.rb +32 -0
  118. data/lib/temporalio/internal/bridge/api/child_workflow/child_workflow.rb +33 -0
  119. data/lib/temporalio/internal/bridge/api/common/common.rb +27 -0
  120. data/lib/temporalio/internal/bridge/api/core_interface.rb +40 -0
  121. data/lib/temporalio/internal/bridge/api/external_data/external_data.rb +27 -0
  122. data/lib/temporalio/internal/bridge/api/nexus/nexus.rb +34 -0
  123. data/lib/temporalio/internal/bridge/api/workflow_activation/workflow_activation.rb +56 -0
  124. data/lib/temporalio/internal/bridge/api/workflow_commands/workflow_commands.rb +58 -0
  125. data/lib/temporalio/internal/bridge/api/workflow_completion/workflow_completion.rb +31 -0
  126. data/lib/temporalio/internal/bridge/api.rb +3 -0
  127. data/lib/temporalio/internal/bridge/client.rb +95 -0
  128. data/lib/temporalio/internal/bridge/runtime.rb +56 -0
  129. data/lib/temporalio/internal/bridge/testing.rb +69 -0
  130. data/lib/temporalio/internal/bridge/worker.rb +109 -0
  131. data/lib/temporalio/internal/bridge.rb +36 -0
  132. data/lib/temporalio/internal/client/implementation.rb +926 -0
  133. data/lib/temporalio/internal/metric.rb +122 -0
  134. data/lib/temporalio/internal/proto_utils.rb +165 -0
  135. data/lib/temporalio/internal/worker/activity_worker.rb +448 -0
  136. data/lib/temporalio/internal/worker/multi_runner.rb +213 -0
  137. data/lib/temporalio/internal/worker/workflow_instance/child_workflow_handle.rb +54 -0
  138. data/lib/temporalio/internal/worker/workflow_instance/context.rb +391 -0
  139. data/lib/temporalio/internal/worker/workflow_instance/details.rb +49 -0
  140. data/lib/temporalio/internal/worker/workflow_instance/external_workflow_handle.rb +32 -0
  141. data/lib/temporalio/internal/worker/workflow_instance/externally_immutable_hash.rb +22 -0
  142. data/lib/temporalio/internal/worker/workflow_instance/handler_execution.rb +25 -0
  143. data/lib/temporalio/internal/worker/workflow_instance/handler_hash.rb +41 -0
  144. data/lib/temporalio/internal/worker/workflow_instance/illegal_call_tracer.rb +97 -0
  145. data/lib/temporalio/internal/worker/workflow_instance/inbound_implementation.rb +62 -0
  146. data/lib/temporalio/internal/worker/workflow_instance/outbound_implementation.rb +404 -0
  147. data/lib/temporalio/internal/worker/workflow_instance/replay_safe_logger.rb +37 -0
  148. data/lib/temporalio/internal/worker/workflow_instance/replay_safe_metric.rb +40 -0
  149. data/lib/temporalio/internal/worker/workflow_instance/scheduler.rb +183 -0
  150. data/lib/temporalio/internal/worker/workflow_instance.rb +800 -0
  151. data/lib/temporalio/internal/worker/workflow_worker.rb +249 -0
  152. data/lib/temporalio/internal.rb +7 -0
  153. data/lib/temporalio/metric.rb +109 -0
  154. data/lib/temporalio/priority.rb +59 -0
  155. data/lib/temporalio/retry_policy.rb +74 -0
  156. data/lib/temporalio/runtime/metric_buffer.rb +94 -0
  157. data/lib/temporalio/runtime.rb +352 -0
  158. data/lib/temporalio/scoped_logger.rb +96 -0
  159. data/lib/temporalio/search_attributes.rb +356 -0
  160. data/lib/temporalio/testing/activity_environment.rb +175 -0
  161. data/lib/temporalio/testing/workflow_environment.rb +406 -0
  162. data/lib/temporalio/testing.rb +10 -0
  163. data/lib/temporalio/version.rb +5 -0
  164. data/lib/temporalio/versioning_override.rb +55 -0
  165. data/lib/temporalio/worker/activity_executor/fiber.rb +49 -0
  166. data/lib/temporalio/worker/activity_executor/thread_pool.rb +46 -0
  167. data/lib/temporalio/worker/activity_executor.rb +55 -0
  168. data/lib/temporalio/worker/deployment_options.rb +45 -0
  169. data/lib/temporalio/worker/interceptor.rb +367 -0
  170. data/lib/temporalio/worker/poller_behavior.rb +61 -0
  171. data/lib/temporalio/worker/thread_pool.rb +237 -0
  172. data/lib/temporalio/worker/tuner.rb +189 -0
  173. data/lib/temporalio/worker/workflow_executor/thread_pool.rb +236 -0
  174. data/lib/temporalio/worker/workflow_executor.rb +26 -0
  175. data/lib/temporalio/worker/workflow_replayer.rb +349 -0
  176. data/lib/temporalio/worker.rb +633 -0
  177. data/lib/temporalio/worker_deployment_version.rb +67 -0
  178. data/lib/temporalio/workflow/activity_cancellation_type.rb +20 -0
  179. data/lib/temporalio/workflow/child_workflow_cancellation_type.rb +21 -0
  180. data/lib/temporalio/workflow/child_workflow_handle.rb +43 -0
  181. data/lib/temporalio/workflow/definition.rb +680 -0
  182. data/lib/temporalio/workflow/external_workflow_handle.rb +41 -0
  183. data/lib/temporalio/workflow/future.rb +151 -0
  184. data/lib/temporalio/workflow/handler_unfinished_policy.rb +13 -0
  185. data/lib/temporalio/workflow/info.rb +107 -0
  186. data/lib/temporalio/workflow/parent_close_policy.rb +19 -0
  187. data/lib/temporalio/workflow/update_info.rb +20 -0
  188. data/lib/temporalio/workflow.rb +594 -0
  189. data/lib/temporalio/workflow_history.rb +47 -0
  190. data/lib/temporalio.rb +12 -0
  191. data/temporalio.gemspec +31 -0
  192. metadata +263 -0
data/README.md ADDED
@@ -0,0 +1,1311 @@
1
+ <div style="overflow: hidden"><img src="https://raw.githubusercontent.com/temporalio/assets/main/files/w/ruby.png" alt="Temporal Ruby SDK" /></div>
2
+
3
+ ![Ruby 3.2 | 3.3 | 3.4](https://img.shields.io/badge/ruby-3.2%20|%203.3%20|%203.4-blue.svg?style=for-the-badge)
4
+ [![MIT](https://img.shields.io/github/license/temporalio/sdk-ruby.svg?style=for-the-badge)](LICENSE)
5
+ [![Gem](https://img.shields.io/gem/v/temporalio?style=for-the-badge)](https://rubygems.org/gems/temporalio)
6
+
7
+ [Temporal](https://temporal.io/) is a distributed, scalable, durable, and highly available orchestration engine used to
8
+ execute asynchronous, long-running business logic in a scalable and resilient way.
9
+
10
+ **Temporal Ruby SDK** is the framework for authoring workflows and activities using the Ruby programming language.
11
+
12
+ Also see:
13
+
14
+ * [Ruby SDK](https://github.com/temporalio/sdk-ruby)
15
+ * [Ruby Samples](https://github.com/temporalio/samples-ruby)
16
+ * [API Documentation](https://ruby.temporal.io)
17
+
18
+ **NOTE: This README is for the current branch and not necessarily what's released on RubyGems.**
19
+
20
+ ⚠️ UNDER ACTIVE DEVELOPMENT
21
+
22
+ This SDK is under active development and has not released a stable version yet. APIs may change in incompatible ways
23
+ until the SDK is marked stable.
24
+
25
+ During this time, we are requesting any/all feedback from early adopters. We welcome all forms of suggestions or
26
+ opinions. Please communicate with us on [Slack](https://t.mp/slack) in the `#ruby-sdk` channel or via email at
27
+ `sdk@temporal.io`.
28
+
29
+ ---
30
+
31
+ <!-- START doctoc generated TOC please keep comment here to allow auto update -->
32
+ <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
33
+ **Contents**
34
+
35
+ - [Quick Start](#quick-start)
36
+ - [Installation](#installation)
37
+ - [Implementing a Workflow and Activity](#implementing-a-workflow-and-activity)
38
+ - [Running a Worker](#running-a-worker)
39
+ - [Executing a Workflow](#executing-a-workflow)
40
+ - [Usage](#usage)
41
+ - [Client](#client)
42
+ - [Cloud Client Using mTLS](#cloud-client-using-mtls)
43
+ - [Cloud Client Using API Key](#cloud-client-using-api-key)
44
+ - [Data Conversion](#data-conversion)
45
+ - [ActiveModel](#activemodel)
46
+ - [Workers](#workers)
47
+ - [Workflows](#workflows)
48
+ - [Workflow Definition](#workflow-definition)
49
+ - [Running Workflows](#running-workflows)
50
+ - [Invoking Activities](#invoking-activities)
51
+ - [Invoking Child Workflows](#invoking-child-workflows)
52
+ - [Timers and Conditions](#timers-and-conditions)
53
+ - [Workflow Fiber Scheduling and Cancellation](#workflow-fiber-scheduling-and-cancellation)
54
+ - [Workflow Futures](#workflow-futures)
55
+ - [Workflow Utilities](#workflow-utilities)
56
+ - [Workflow Exceptions](#workflow-exceptions)
57
+ - [Workflow Logic Constraints](#workflow-logic-constraints)
58
+ - [Workflow Testing](#workflow-testing)
59
+ - [Automatic Time Skipping](#automatic-time-skipping)
60
+ - [Manual Time Skipping](#manual-time-skipping)
61
+ - [Mocking Activities](#mocking-activities)
62
+ - [Workflow Replay](#workflow-replay)
63
+ - [Activities](#activities)
64
+ - [Activity Definition](#activity-definition)
65
+ - [Activity Context](#activity-context)
66
+ - [Activity Heartbeating and Cancellation](#activity-heartbeating-and-cancellation)
67
+ - [Activity Worker Shutdown](#activity-worker-shutdown)
68
+ - [Activity Concurrency and Executors](#activity-concurrency-and-executors)
69
+ - [Activity Testing](#activity-testing)
70
+ - [Telemetry](#telemetry)
71
+ - [Metrics](#metrics)
72
+ - [OpenTelemetry Tracing](#opentelemetry-tracing)
73
+ - [OpenTelemetry Tracing in Workflows](#opentelemetry-tracing-in-workflows)
74
+ - [Rails](#rails)
75
+ - [ActiveRecord](#activerecord)
76
+ - [Lazy/Eager Loading](#lazyeager-loading)
77
+ - [Ractors](#ractors)
78
+ - [Platform Support](#platform-support)
79
+ - [Development](#development)
80
+ - [Build](#build)
81
+ - [Build Platform-specific Gem](#build-platform-specific-gem)
82
+ - [Testing](#testing)
83
+ - [Code Formatting and Type Checking](#code-formatting-and-type-checking)
84
+ - [Proto Generation](#proto-generation)
85
+
86
+ <!-- END doctoc generated TOC please keep comment here to allow auto update -->
87
+
88
+ ## Quick Start
89
+
90
+ ### Installation
91
+
92
+ The Ruby SDK works with Ruby 3.2, 3.3, and 3.4.
93
+
94
+ Can require in a Gemfile like:
95
+
96
+ ```
97
+ gem 'temporalio'
98
+ ```
99
+
100
+ Or via `gem install` like:
101
+
102
+ ```
103
+ gem install temporalio
104
+ ```
105
+
106
+ **NOTE**: Only macOS ARM/x64 and Linux ARM/x64 are supported, and the platform-specific gem chosen is based on when the
107
+ gem/bundle install is performed. A source gem is published but cannot be used directly and will fail to build if tried.
108
+ MinGW-based Windows is not currently supported. There are caveats with the Google Protobuf dependency on musl-based
109
+ Linux. See the [Platform Support](#platform-support) section for more information.
110
+
111
+ **NOTE**: Due to [an issue](https://github.com/temporalio/sdk-ruby/issues/162), fibers (and `async` gem) are only
112
+ supported on Ruby versions 3.3 and newer.
113
+
114
+ ### Implementing a Workflow and Activity
115
+
116
+ Activities are classes. Here is an example of a simple activity that can be put in `say_hello_activity.rb`:
117
+
118
+
119
+ ```ruby
120
+ require 'temporalio/activity'
121
+
122
+ # Implementation of a simple activity
123
+ class SayHelloActivity < Temporalio::Activity::Definition
124
+ def execute(name)
125
+ "Hello, #{name}!"
126
+ end
127
+ end
128
+ ```
129
+
130
+ Workflows are also classes. To create the workflow, put the following in `say_hello_workflow.rb`:
131
+
132
+ ```ruby
133
+ require 'temporalio/workflow'
134
+ require_relative 'say_hello_activity'
135
+
136
+ class SayHelloWorkflow < Temporalio::Workflow::Definition
137
+ def execute(name)
138
+ Temporalio::Workflow.execute_activity(
139
+ SayHelloActivity,
140
+ name,
141
+ schedule_to_close_timeout: 300
142
+ )
143
+ end
144
+ end
145
+ ```
146
+
147
+ This is a simple workflow that executes the `SayHelloActivity` activity.
148
+
149
+ ### Running a Worker
150
+
151
+ To run this in a worker, put the following in `worker.rb`:
152
+
153
+ ```ruby
154
+ require 'temporalio/client'
155
+ require 'temporalio/worker'
156
+ require_relative 'say_hello_activity'
157
+ require_relative 'say_hello_workflow'
158
+
159
+ # Create a client
160
+ client = Temporalio::Client.connect('localhost:7233', 'my-namespace')
161
+
162
+ # Create a worker with the client, activities, and workflows
163
+ worker = Temporalio::Worker.new(
164
+ client:,
165
+ task_queue: 'my-task-queue',
166
+ workflows: [SayHelloWorkflow],
167
+ # There are various forms an activity can take, see "Activities" section for details
168
+ activities: [SayHelloActivity]
169
+ )
170
+
171
+ # Run the worker until SIGINT. This can be done in many ways, see "Workers" section for details.
172
+ worker.run(shutdown_signals: ['SIGINT'])
173
+ ```
174
+
175
+ Running that will run the worker until Ctrl+C is pressed.
176
+
177
+ ### Executing a Workflow
178
+
179
+ To start and wait on the workflow result, with the worker program running elsewhere, put the following in
180
+ `execute_workflow.rb`:
181
+
182
+ ```ruby
183
+ require 'temporalio/client'
184
+ require_relative 'say_hello_workflow'
185
+
186
+ # Create a client
187
+ client = Temporalio::Client.connect('localhost:7233', 'my-namespace')
188
+
189
+ # Run workflow
190
+ result = client.execute_workflow(
191
+ SayHelloWorkflow,
192
+ 'Temporal', # This is the input to the workflow
193
+ id: 'my-workflow-id',
194
+ task_queue: 'my-task-queue'
195
+ )
196
+ puts "Result: #{result}"
197
+ ```
198
+
199
+ This will output:
200
+
201
+ ```
202
+ Result: Hello, Temporal!
203
+ ```
204
+
205
+ ## Usage
206
+
207
+ ### Client
208
+
209
+ A client can be created and used to start a workflow or otherwise interact with Temporal. For example:
210
+
211
+ ```ruby
212
+ require 'temporalio/client'
213
+
214
+ # Create a client
215
+ client = Temporalio::Client.connect('localhost:7233', 'my-namespace')
216
+
217
+ # Start a workflow
218
+ handle = client.start_workflow(
219
+ MyWorkflow,
220
+ 'arg1', 'arg2',
221
+ id: 'my-workflow-id',
222
+ task_queue: 'my-task-queue'
223
+ )
224
+
225
+ # Wait for result
226
+ result = handle.result
227
+ puts "Result: #{result}"
228
+ ```
229
+
230
+ Notes about the above code:
231
+
232
+ * Temporal clients are not explicitly closed.
233
+ * To enable TLS, the `tls` option can be set to `true` or a `Temporalio::Client::Connection::TLSOptions` instance.
234
+ * Instead of `start_workflow` + `result` above, `execute_workflow` shortcut can be used if the handle is not needed.
235
+ * Both `start_workflow` and `execute_workflow` accept either the workflow class or the string/symbol name of the
236
+ workflow.
237
+ * The `handle` above is a `Temporalio::Client::WorkflowHandle` which has several other operations that can be performed
238
+ on a workflow. To get a handle to an existing workflow, use `workflow_handle` on the client.
239
+ * Clients are thread safe and are fiber-compatible (but fiber compatibility only supported for Ruby 3.3+ at this time).
240
+
241
+ #### Cloud Client Using mTLS
242
+
243
+ Assuming a client certificate is present at `my-cert.pem` and a client key is present at `my-key.pem`, this is how to
244
+ connect to Temporal Cloud:
245
+
246
+ ```ruby
247
+ require 'temporalio/client'
248
+
249
+ # Create a client
250
+ client = Temporalio::Client.connect(
251
+ 'my-namespace.a1b2c.tmprl.cloud:7233',
252
+ 'my-namespace.a1b2c',
253
+ tls: Temporalio::Client::Connection::TLSOptions.new(
254
+ client_cert: File.read('my-cert.pem'),
255
+ client_private_key: File.read('my-key.pem')
256
+ ))
257
+ ```
258
+
259
+ #### Cloud Client Using API Key
260
+
261
+ Assuming the API key is 'my-api-key', this is how to connect to Temporal cloud:
262
+
263
+ ```ruby
264
+ require 'temporalio/client'
265
+
266
+ # Create a client
267
+ client = Temporalio::Client.connect(
268
+ 'my-namespace.a1b2c.tmprl.cloud:7233',
269
+ 'my-namespace.a1b2c',
270
+ api_key: 'my-api-key'
271
+ tls: true
272
+ )
273
+ ```
274
+
275
+ #### Data Conversion
276
+
277
+ Data converters are used to convert raw Temporal payloads to/from actual Ruby types. A custom data converter can be set
278
+ via the `data_converter` keyword argument when creating a client. Data converters are a combination of payload
279
+ converters, payload codecs, and failure converters. Payload converters convert Ruby values to/from serialized bytes.
280
+ Payload codecs convert bytes to bytes (e.g. for compression or encryption). Failure converters convert exceptions
281
+ to/from serialized failures.
282
+
283
+ Data converters are in the `Temporalio::Converters` module. The default data converter uses a default payload converter,
284
+ which supports the following types:
285
+
286
+ * `nil`
287
+ * "bytes" (i.e. `String` with `Encoding::ASCII_8BIT` encoding)
288
+ * `Google::Protobuf::MessageExts` instances
289
+ * [JSON module](https://docs.ruby-lang.org/en/master/JSON.html) for everything else
290
+
291
+ This means that normal Ruby objects will use `JSON.generate` when serializing and `JSON.parse` when deserializing (with
292
+ `create_additions: true` set by default). So a Ruby object will often appear as a hash when deserialized. Also, hashes
293
+ that are passed in with symbol keys end up with string keys when deserialized. While "JSON Additions" are supported, it
294
+ is not cross-SDK-language compatible since this is a Ruby-specific construct.
295
+
296
+ The default payload converter is a collection of "encoding payload converters". On serialize, each encoding converter
297
+ will be tried in order until one accepts (default falls through to the JSON one). The encoding converter sets an
298
+ `encoding` metadata value which is used to know which converter to use on deserialize. Custom encoding converters can be
299
+ created, or even the entire payload converter can be replaced with a different implementation.
300
+
301
+ **NOTE:** For ActiveRecord, or other general/ORM models that are used for a different purpose, it is not recommended to
302
+ try to reuse them as Temporal models. Eventually model purposes diverge and models for a Temporal workflows/activities
303
+ should be specific to their use for clarity and compatibility reasons. Also many Ruby ORMs do many lazy things and
304
+ therefore provide unclear serialization semantics. Instead, consider having models specific for workflows/activities and
305
+ translate to/from existing models as needed. See the next section on how to do this with ActiveModel objects.
306
+
307
+ ##### ActiveModel
308
+
309
+ By default, ActiveModel objects do not natively support the `JSON` module. A mixin can be created to add this support
310
+ for ActiveRecord, for example:
311
+
312
+ ```ruby
313
+ module ActiveModelJSONSupport
314
+ extend ActiveSupport::Concern
315
+ include ActiveModel::Serializers::JSON
316
+
317
+ included do
318
+ def as_json(*)
319
+ super.merge(::JSON.create_id => self.class.name)
320
+ end
321
+
322
+ def to_json(*args)
323
+ as_json.to_json(*args)
324
+ end
325
+
326
+ def self.json_create(object)
327
+ object = object.dup
328
+ object.delete(::JSON.create_id)
329
+ new(**object.symbolize_keys)
330
+ end
331
+ end
332
+ end
333
+ ```
334
+
335
+ Now if `include ActiveModelJSONSupport` is present on any ActiveModel class, on serialization `to_json` will be used
336
+ which will use `as_json` which calls the super `as_json` but also includes the fully qualified class name as the JSON
337
+ `create_id` key. On deserialization, Ruby JSON then uses this key to know what class to call `json_create` on.
338
+
339
+ ### Workers
340
+
341
+ Workers host workflows and/or activities. Here's how to run a worker:
342
+
343
+ ```ruby
344
+ require 'temporalio/client'
345
+ require 'temporalio/worker'
346
+ require 'my_module'
347
+
348
+ # Create a client
349
+ client = Temporalio::Client.connect('localhost:7233', 'my-namespace')
350
+
351
+ # Create a worker with the client, activities, and workflows
352
+ worker = Temporalio::Worker.new(
353
+ client:,
354
+ task_queue: 'my-task-queue',
355
+ workflows: [MyModule::MyWorkflow],
356
+ # There are various forms an activity can take, see "Activities" section for details
357
+ activities: [MyModule::MyActivity]
358
+ )
359
+
360
+ # Run the worker until block complete
361
+ worker.run do
362
+ something_that_waits_for_completion
363
+ end
364
+ ```
365
+
366
+ Notes about the above code:
367
+
368
+ * A worker uses the same client that is used for other Temporal things.
369
+ * This just shows providing an activity class, but there are other forms, see the "Activities" section for details.
370
+ * The worker `run` method accepts an optional `Temporalio::Cancellation` object that can be used to cancel instead or in
371
+ addition to providing a block that waits for completion.
372
+ * The worker `run` method accepts a `shutdown_signals` array which will trap the signal and start shutdown when
373
+ received.
374
+ * Workers work with threads or fibers (but fiber compatibility only supported for Ruby 3.3+ at this time). Fiber-based
375
+ activities (see "Activities" section) only work if the worker is created within a fiber.
376
+ * The `run` method does not return until the worker is shut down. This means even if shutdown is triggered (e.g. via
377
+ `Cancellation` or block completion), it may not return immediately. Activities not completing may hang worker
378
+ shutdown, see the "Activities" section.
379
+ * Workers can have many more options not shown here (e.g. tuners and interceptors).
380
+ * The `Temporalio::Worker.run_all` class method is available for running multiple workers concurrently.
381
+
382
+ ### Workflows
383
+
384
+ #### Workflow Definition
385
+
386
+ Workflows are defined as classes that extend `Temporalio::Workflow::Definition`. The entry point for a workflow is
387
+ `execute` and must be defined. Methods for handling signals, queries, and updates are marked with `workflow_signal`,
388
+ `workflow_query`, and `workflow_update` just before the method is defined. Here is an example of a workflow definition:
389
+
390
+ ```ruby
391
+ require 'temporalio/workflow'
392
+
393
+ class GreetingWorkflow < Temporalio::Workflow::Definition
394
+ workflow_query_attr_reader :current_greeting
395
+
396
+ def execute(params)
397
+ loop do
398
+ # Call activity called CreateGreeting to create greeting and store as attribute
399
+ @current_greeting = Temporalio::Workflow.execute_activity(
400
+ CreateGreeting,
401
+ params,
402
+ schedule_to_close_timeout: 300
403
+ )
404
+ Temporalio::Workflow.logger.debug("Greeting set to #{@current_greeting}")
405
+
406
+ # Wait for param update or complete signal. Note, cancellation can occur by default
407
+ # on wait_condition calls, so Cancellation object doesn't need to be passed
408
+ # explicitly.
409
+ Temporalio::Workflow.wait_condition { @greeting_params_update || @complete }
410
+
411
+ # If there was an update, exchange and rerun. If it's _only_ a complete, finish
412
+ # workflow with the greeting.
413
+ if @greeting_params_update
414
+ params, @greeting_params_update = @greeting_params_update, nil
415
+ else
416
+ return @current_greeting
417
+ end
418
+ end
419
+ end
420
+
421
+ workflow_update
422
+ def update_greeting_params(greeting_params_update)
423
+ @greeting_params_update = greeting_params_update
424
+ end
425
+
426
+ workflow_signal
427
+ def complete_with_greeting
428
+ @complete = true
429
+ end
430
+ end
431
+ ```
432
+
433
+ Notes about the above code:
434
+
435
+ * `execute` is the primary entrypoint and its result/exception represents the workflow result/failure.
436
+ * `workflow_signal`, `workflow_query` (and the shortcut seen above, `workflow_query_attr_reader`), and `workflow_update`
437
+ implicitly create class methods usable by callers/clients. A workflow definition with no methods actually implemented
438
+ can even be created for use by clients if the workflow is implemented elsewhere and/or in another language.
439
+ * Workflow code must be deterministic. See the "Workflow Logic Constraints" section below.
440
+ * `execute_activity` accepts either the activity class or the string/symbol for the name.
441
+
442
+ The following protected class methods are available on `Temporalio::Workflow::Definition` to customize the overall
443
+ workflow definition/behavior:
444
+
445
+ * `workflow_name` - Accepts a string or symbol to change the name. Otherwise the name is defaulted to the unqualified
446
+ class name.
447
+ * `workflow_dynamic` - Marks a workflow as dynamic. Dynamic workflows do not have names and handle any workflow that is
448
+ not otherwise registered. A worker can only have one dynamic workflow. It is often useful to use `workflow_raw_args`
449
+ with this.
450
+ * `workflow_raw_args` - Have workflow arguments delivered to `execute` (and `initialize` if `workflow_init` in use) as
451
+ `Temporalio::Converters::RawValue`s. These are wrappers for the raw payloads that have not been decoded. They can be
452
+ decoded with `Temporalio::Workflow.payload_converter`. Using this with `*args` splat can be helpful in dynamic
453
+ situations.
454
+ * `workflow_failure_exception_type` - Accepts one or more exception classes that will be considered workflow failure
455
+ instead of task failure. See the "Exceptions" section later on what this means. This can be called multiple times.
456
+ * `workflow_query_attr_reader` - Is a helper that accepts one or more symbols for attributes to expose as `attr_reader`
457
+ _and_ `workflow_query`. This means it is a superset of `attr_reader` and will not work if also using `attr_reader` or
458
+ `attr_accessor`. If a writer is needed alongside this, use `attr_writer`.
459
+
460
+ The following protected class methods can be called just before defining instance methods to customize the
461
+ definition/behavior of the method:
462
+
463
+ * `workflow_init` - Mark an `initialize` method as needing the workflow start arguments. Otherwise, `initialize` must
464
+ accept no required arguments. This must be placed above the `initialize` method or it will fail.
465
+ * `workflow_signal` - Mark the next method as a workflow signal. The signal name is defaulted to the method name but can
466
+ be customized by the `name` kwarg. See the API documentation for more kwargs that can be set. Return values for
467
+ signals are discarded and exceptions raised in signal handlers are treated as if they occurred in the primary workflow
468
+ method. This also defines a class method of the same name to return the definition for use by clients.
469
+ * `workflow_query` - Mark the next method as a workflow query. The query name is defaulted to the method name but can
470
+ be customized by the `name` kwarg. See the API documentation for more kwargs that can be set. The result of the method
471
+ is the result of the query. Queries must never have any side effects, meaning they should never mutate state or try to
472
+ wait on anything. This also defines a class method of the same name to return the definition for use by clients.
473
+ * `workflow_update` - Mark the next method as a workflow update. The update name is defaulted to the method name but can
474
+ be customized by the `name` kwarg. See the API documentation for more kwargs that can be set. The result of the method
475
+ is the result of the update. This also defines a class method of the same name to return the definition for use by
476
+ clients.
477
+ * `workflow_update_validator` - Mark the next method as a validator to an update. This accepts a symbol for the
478
+ `workflow_update` method it validates. Validators are used to do early rejection of updates and must never have any
479
+ side effects, meaning they should never mutate state or try to wait on anything.
480
+
481
+ Workflows can be inherited, but subclass workflow-level decorators override superclass ones, and the same method can't
482
+ be decorated with different handler types/names in the hierarchy. Workflow handlers (execute or any marked method)
483
+ cannot accept keyword arguments.
484
+
485
+ #### Running Workflows
486
+
487
+ To start a workflow from a client, you can `start_workflow` and use the resulting handle:
488
+
489
+ ```ruby
490
+ # Start the workflow
491
+ handle = my_client.start_workflow(
492
+ GreetingWorkflow,
493
+ { salutation: 'Hello', name: 'Temporal' },
494
+ id: 'my-workflow-id',
495
+ task_queue: 'my-task-queue'
496
+ )
497
+
498
+ # Check current greeting via query
499
+ puts "Current greeting: #{handle.query(GreetingWorkflow.current_greeting)}"
500
+
501
+ # Change the params via update
502
+ handle.execute_update(
503
+ GreetingWorkflow.update_greeting_params,
504
+ { salutation: 'Aloha', name: 'John' }
505
+ )
506
+
507
+ # Tell it to complete via signal
508
+ handle.signal(GreetingWorkflow.complete_with_greeting)
509
+
510
+ # Wait for workflow result
511
+ puts "Final greeting: #{handle.result}"
512
+ ```
513
+
514
+ Some things to note about the above code:
515
+
516
+ * This uses the `GreetingWorkflow` workflow from the previous section.
517
+ * The output of this code is "Current greeting: Hello, Temporal!" and "Final greeting: Aloha, John!".
518
+ * ID and task queue are required for starting a workflow.
519
+ * Signal, query, and update calls here use the class methods created on the definition for safety. So if the
520
+ `update_greeting_params` method didn't exist or wasn't marked as an update, the code will fail client side before even
521
+ attempting the call. Static typing tooling may also take advantage of this for param/result type checking.
522
+ * A helper `execute_workflow` method is available on the client that is just `start_workflow` + handle `result`.
523
+
524
+ #### Invoking Activities
525
+
526
+ * Activities are executed with `Temporalio::Workflow.execute_activity`, which accepts the activity class or a
527
+ string/symbol activity name.
528
+ * Activity options are kwargs on the `execute_activity` method. Either `schedule_to_close_timeout` or
529
+ `start_to_close_timeout` must be set.
530
+ * Other options like `retry_policy`, `cancellation_type`, etc can also be set.
531
+ * The `cancellation` can be set to a `Cancellation` to send a cancel request to the activity. By default, the
532
+ `cancellation` is the overall `Temporalio::Workflow.cancellation` which is the overarching workflow cancellation.
533
+ * Activity failures are raised from the call as `Temporalio::Error::ActivityError`.
534
+ * `execute_local_activity` exists with mostly the same options for local activities.
535
+
536
+ #### Invoking Child Workflows
537
+
538
+ * Child workflows are started with `Temporalio::Workflow.start_child_workflow`, which accepts the workflow class or
539
+ string/symbol name, arguments, and other options.
540
+ * Result for `start_child_workflow` is a `Temporalio::Workflow::ChildWorkflowHandle` which has the `id`, the ability to
541
+ wait on the `result`, and the ability to `signal` the child.
542
+ * The `start_child_workflow` call does not complete until the start has been accepted by the server.
543
+ * A helper `execute_child_workflow` method is available that is just `start_child_workflow` + handle `result`.
544
+
545
+ #### Timers and Conditions
546
+
547
+ * A timer is represented by `Temporalio::Workflow.sleep`.
548
+ * Timers are also started on `Temporalio::Workflow.timeout`.
549
+ * _Technically_ `Kernel.sleep` and `Timeout.timeout` also delegate to the above calls, but the more explicit workflow
550
+ forms are encouraged because they accept more options and are not subject to Ruby standard library implementation
551
+ changes.
552
+ * Each timer accepts a `Cancellation`, but if none is given, it defaults to `Temporalio::Workflow.cancellation`.
553
+ * `Temporalio::Workflow.wait_condition` accepts a block that waits until the evaluated block result is truthy, then
554
+ returns the value.
555
+ * This function is invoked on each iteration of the internal event loop. This means it cannot have any side effects.
556
+ * This is commonly used for checking if a variable is changed from some other part of a workflow (e.g. a signal
557
+ handler).
558
+ * Each wait conditions accepts a `Cancellation`, but if none is given, it defaults to
559
+ `Temporalio::Workflow.cancellation`.
560
+
561
+ #### Workflow Fiber Scheduling and Cancellation
562
+
563
+ Workflows are backed by a custom, deterministic `Fiber::Scheduler`. All fiber calls inside a workflow use this scheduler
564
+ to ensure coroutines run deterministically.
565
+
566
+ Every workflow contains a `Temporalio::Cancellation` at `Temporalio::Workflow.cancellation`. This is canceled when the
567
+ workflow is canceled. For all workflow calls that accept a cancellation token, this is the default. So if a workflow is
568
+ waiting on `execute_activity` and the workflow is canceled, that cancellation will propagate to the waiting activity.
569
+
570
+ `Cancellation`s may be created to perform cancellation more specifically. A `Cancellation` token derived from the
571
+ workflow one can be created via `my_cancel, my_cancel_proc = Cancellation.new(Temporalio::Workflow.cancellation)`. Then
572
+ `my_cancel` can be passed as `cancellation` to cancel something more specifically when `my_cancel_proc.call` is invoked.
573
+
574
+ `Cancellation`s don't have to be derived from the workflow one, they can just be created standalone or "detached". This
575
+ is useful for executing, say, a cleanup activity in an `ensure` block that needs to run even on cancel. If the cleanup
576
+ activity had instead used the workflow cancellation or one derived from it, then on cancellation it would be cancelled
577
+ before it even started.
578
+
579
+ #### Workflow Futures
580
+
581
+ `Temporalio::Workflow::Future` can be used for running things in the background or concurrently. This is basically a
582
+ safe wrapper around `Fiber.schedule` for starting and `Workflow.wait_condition` for waiting.
583
+
584
+ Nothing uses futures by default, but they work with all workflow code/constructs. For instance, to run 3 activities and
585
+ wait for them all to complete, something like this can be written:
586
+
587
+ ```ruby
588
+ # Start 3 activities in background
589
+ fut1 = Temporalio::Workflow::Future.new do
590
+ Temporalio::Workflow.execute_activity(MyActivity1, schedule_to_close_timeout: 300)
591
+ end
592
+ fut2 = Temporalio::Workflow::Future.new do
593
+ Temporalio::Workflow.execute_activity(MyActivity2, schedule_to_close_timeout: 300)
594
+ end
595
+ fut3 = Temporalio::Workflow::Future.new do
596
+ Temporalio::Workflow.execute_activity(MyActivity3, schedule_to_close_timeout: 300)
597
+ end
598
+
599
+ # Wait for them all to complete
600
+ Temporalio::Workflow::Future.all_of(fut1, fut2, fut3).wait
601
+
602
+ Temporalio::Workflow.logger.debug("Got: #{fut1.result}, #{fut2.result}, #{fut3.result}")
603
+ ```
604
+
605
+ Or, say, to wait on the first of 5 activities or a timeout to complete:
606
+
607
+ ```ruby
608
+ # Start 5 activities
609
+ act_futs = 5.times.map do |i|
610
+ Temporalio::Workflow::Future.new do
611
+ Temporalio::Workflow.execute_activity(MyActivity, "my-arg-#{i}", schedule_to_close_timeout: 300)
612
+ end
613
+ end
614
+ # Start a timer
615
+ sleep_fut = Temporalio::Workflow::Future.new { Temporalio::Workflow.sleep(30) }
616
+
617
+ # Wait for first act result or sleep fut
618
+ act_result = Temporalio::Workflow::Future.any_of(sleep_fut, *act_futs).wait
619
+ # Fail if timer done first
620
+ raise Temporalio::Error::ApplicationError, 'Timer expired' if sleep_fut.done?
621
+ # Print act result otherwise
622
+ puts "Act result: #{act_result}"
623
+ ```
624
+
625
+ There are several other details not covered here about futures, such as how exceptions are handled, how to use a setter
626
+ proc instead of a block, etc. See the API documentation for details.
627
+
628
+ #### Workflow Utilities
629
+
630
+ In addition to the pieces documented above, additional methods are available on `Temporalio::Workflow` that can be used
631
+ from workflows including:
632
+
633
+ * `in_workflow?` - Returns `true` if in the workflow or `false` otherwise. This is the only method on the class that can
634
+ be called outside of a workflow without raising an exception.
635
+ * `info` - Immutable workflow information.
636
+ * `logger` - A Ruby logger that adds contextual information and takes care not to log on replay.
637
+ * `metric_meter` - A metric meter for making custom metrics that adds contextual information and takes care not to
638
+ record on replay.
639
+ * `random` - A deterministic `Random` instance.
640
+ * `memo` - A read-only hash of the memo (updated via `upsert_memo`).
641
+ * `search_attributes` - A read-only `SearchAttributes` collection (updated via `upsert_search_attributes`).
642
+ * `now` - Current, deterministic UTC time for the workflow.
643
+ * `all_handlers_finished?` - Returns true when all signal and update handlers are done. Useful as
644
+ `Temporalio::Workflow.wait_condition { Temporalio::Workflow.all_handlers_finished? }` for making sure not to return
645
+ from the primary workflow method until all handlers are done.
646
+ * `patched` and `deprecate_patch` - Support for patch-based versioning inside the workflow.
647
+ * `continue_as_new_suggested` - Returns true when the server recommends performing a continue as new.
648
+ * `current_update_info` - Returns `Temporalio::Workflow::UpdateInfo` if the current code is inside an update, or nil
649
+ otherwise.
650
+ * `external_workflow_handle` - Obtain an handle to an external workflow for signalling or cancelling.
651
+ * `payload_converter` - Payload converter if needed for converting raw args.
652
+ * `signal_handlers`, `query_handlers`, and `update_handlers` - Hashes for the current set of handlers keyed by name (or
653
+ nil key for dynamic). `[]=` or `store` can be called on these to update the handlers, though defined handlers are
654
+ encouraged over runtime-set ones.
655
+
656
+ `Temporalio::Workflow::ContinueAsNewError` can be raised to continue-as-new the workflow. It accepts positional args and
657
+ defaults the workflow to the same as the current, though it can be changed with the `workflow` kwarg. See API
658
+ documentation for other details.
659
+
660
+ #### Workflow Exceptions
661
+
662
+ * Workflows can raise exceptions to fail the workflow/update or the "workflow task" (i.e. suspend the workflow, retrying
663
+ until code update allows it to continue).
664
+ * By default, exceptions that are instances of `Temporalio::Error::Failure` (or `Timeout::Error`) will fail the
665
+ workflow/update with that exception.
666
+ * For failing the workflow/update explicitly with a user exception, explicitly raise
667
+ `Temporalio::Error::ApplicationError`. This can be marked non-retryable or include details as needed.
668
+ * Other exceptions that come from activity execution, child execution, cancellation, etc are already instances of
669
+ `Temporalio::Error::Failure` and will fail the workflow/update if uncaught.
670
+ * By default, all other exceptions fail the "workflow task" which means the workflow/update will continually retry until
671
+ the code is fixed. This is helpful for bad code or other non-predictable exceptions. To actually fail the
672
+ workflow/update, use `Temporalio::Error::ApplicationError` as mentioned above.
673
+ * By default, all non-deterministic exceptions that are detected internally fail the "workflow task".
674
+
675
+ The default behavior can be customized at the worker level for all workflows via the
676
+ `workflow_failure_exception_types` worker option or per workflow via the `workflow_failure_exception_type` definition
677
+ method on the workflow itself. When a workflow encounters a "workflow task" fail (i.e. suspend), it will first check
678
+ either of these collections to see if the exception is an instance of any of the types and if so, will turn into a
679
+ workflow/update failure. As a special case, when a non-deterministic exception occurs and
680
+ `Temporalio::Workflow::NondeterminismError` is assignable to any of the types in the collection, that too
681
+ will turn into a workflow/update failure. However unlike other exceptions, non-deterministic exceptions that match
682
+ during update handlers become workflow failures not update failures because a non-deterministic exception is an
683
+ entire-workflow-failure situation.
684
+
685
+ #### Workflow Logic Constraints
686
+
687
+ Temporal Workflows [must be deterministic](https://docs.temporal.io/workflows#deterministic-constraints), which includes
688
+ Ruby workflows. This means there are several things workflows cannot do such as:
689
+
690
+ * Perform IO (network, disk, stdio, etc)
691
+ * Access/alter external mutable state
692
+ * Do any threading
693
+ * Do anything using the system clock (e.g. `Time.Now`)
694
+ * Make any random calls
695
+ * Make any not-guaranteed-deterministic calls
696
+
697
+ #### Workflow Testing
698
+
699
+ Workflow testing can be done in an integration-test fashion against a real server. However, it is hard to simulate
700
+ timeouts and other long time-based code. Using the time-skipping workflow test environment can help there.
701
+
702
+ A non-time-skipping `Temporalio::Testing::WorkflowEnvironment` can be started via `start_local` which supports all
703
+ standard Temporal features. It is actually a real Temporal server lazily downloaded on first use and run as a
704
+ subprocess in the background.
705
+
706
+ A time-skipping `Temporalio::Testing::WorkflowEnvironment` can be started via `start_time_skipping` which is a
707
+ reimplementation of the Temporal server with special time skipping capabilities. This too lazily downloads the process
708
+ to run when first called. Note, this class is not thread safe nor safe for use with independent tests. It can be reused,
709
+ but only for one test at a time because time skipping is locked/unlocked at the environment level. Note, the
710
+ time-skipping test server does not work on ARM-based processors at this time, though macOS ARM users can use it via the
711
+ built-in x64 translation in macOS.
712
+
713
+ ##### Automatic Time Skipping
714
+
715
+ Anytime a workflow result is waited on, the time-skipping server automatically advances to the next event it can. To
716
+ manually advance time before waiting on the result of the workflow, the `WorkflowEnvironment.sleep` method can be used
717
+ on the environment itself. If an activity is running, time-skipping is disabled.
718
+
719
+ Here's a simple example of a workflow that sleeps for 24 hours:
720
+
721
+ ```ruby
722
+ require 'temporalio/workflow'
723
+
724
+ class WaitADayWorkflow < Temporalio::Workflow::Definition
725
+ def execute
726
+ Temporalio::Workflow.sleep(1 * 24 * 60 * 60)
727
+ 'all done'
728
+ end
729
+ end
730
+ ```
731
+
732
+ A regular integration test of this workflow on a normal server would be way too slow. However, the time-skipping server
733
+ automatically skips to the next event when we wait on the result. Here's a minitest for that workflow:
734
+
735
+ ```ruby
736
+ class MyTest < Minitest::Test
737
+ def test_wait_a_day
738
+ Temporalio::Testing::WorkflowEnvironment.start_time_skipping do |env|
739
+ worker = Temporalio::Worker.new(
740
+ client: env.client,
741
+ task_queue: "tq-#{SecureRandom.uuid}",
742
+ workflows: [WaitADayWorkflow],
743
+ workflow_executor: Temporalio::Worker::WorkflowExecutor::ThreadPool.default
744
+ )
745
+ worker.run do
746
+ result = env.client.execute_workflow(
747
+ WaitADayWorkflow,
748
+ id: "wf-#{SecureRandom.uuid}",
749
+ task_queue: worker.task_queue
750
+ )
751
+ assert_equal 'all done', result
752
+ end
753
+ end
754
+ end
755
+ end
756
+ ```
757
+
758
+ This test will run almost instantly. This is because by calling `execute_workflow` on our client, we are actually
759
+ calling `start_workflow` + handle `result`, and `result` automatically skips time as much as it can (basically until the
760
+ end of the workflow or until an activity is run).
761
+
762
+ To disable automatic time-skipping while waiting for a workflow result, run code inside a block passed to
763
+ `auto_time_skipping_disabled`.
764
+
765
+ ##### Manual Time Skipping
766
+
767
+ Until a workflow is waited on, all time skipping in the time-skipping environment is done manually via
768
+ `WorkflowEnvironment.sleep`.
769
+
770
+ Here's a workflow that waits for a signal or times out:
771
+
772
+ ```ruby
773
+ require 'temporalio/workflow'
774
+
775
+ class SignalWorkflow < Temporalio::Workflow::Definition
776
+ def execute
777
+ Temporalio::Workflow.timeout(45) do
778
+ Temporalio::Workflow.wait_condition { @signal_received }
779
+ 'got signal'
780
+ rescue Timeout::Error
781
+ 'got timeout'
782
+ end
783
+ end
784
+
785
+ workflow_signal
786
+ def some_signal
787
+ @signal_received = true
788
+ end
789
+ end
790
+ ```
791
+
792
+ To test a normal signal, you might:
793
+
794
+ ```ruby
795
+ class MyTest < Minitest::Test
796
+ def test_signal_workflow_success
797
+ Temporalio::Testing::WorkflowEnvironment.start_time_skipping do |env|
798
+ worker = Temporalio::Worker.new(
799
+ client: env.client,
800
+ task_queue: "tq-#{SecureRandom.uuid}",
801
+ workflows: [SignalWorkflow],
802
+ workflow_executor: Temporalio::Worker::WorkflowExecutor::ThreadPool.default
803
+ )
804
+ worker.run do
805
+ handle = env.client.start_workflow(
806
+ SignalWorkflow,
807
+ id: "wf-#{SecureRandom.uuid}",
808
+ task_queue: worker.task_queue
809
+ )
810
+ handle.signal(SignalWorkflow.some_signal)
811
+ assert_equal 'got signal', handle.result
812
+ end
813
+ end
814
+ end
815
+ end
816
+ ```
817
+
818
+ But how would you test the timeout part? Like so:
819
+
820
+ ```ruby
821
+ class MyTest < Minitest::Test
822
+ def test_signal_workflow_timeout
823
+ Temporalio::Testing::WorkflowEnvironment.start_time_skipping do |env|
824
+ worker = Temporalio::Worker.new(
825
+ client: env.client,
826
+ task_queue: "tq-#{SecureRandom.uuid}",
827
+ workflows: [SignalWorkflow],
828
+ workflow_executor: Temporalio::Worker::WorkflowExecutor::ThreadPool.default
829
+ )
830
+ worker.run do
831
+ handle = env.client.start_workflow(
832
+ SignalWorkflow,
833
+ id: "wf-#{SecureRandom.uuid}",
834
+ task_queue: worker.task_queue
835
+ )
836
+ env.sleep(50)
837
+ assert_equal 'got timeout', handle.result
838
+ end
839
+ end
840
+ end
841
+ end
842
+ ```
843
+
844
+ This test will run almost instantly. The `env.sleep(50)` manually skips 50 seconds of time, allowing the timeout to be
845
+ triggered without actually waiting the full 45 seconds to time out.
846
+
847
+ ##### Mocking Activities
848
+
849
+ When testing workflows, often you don't want to actually run the activities. Activities are just classes that extend
850
+ `Temporalio::Activity::Definition`. Simply write different/empty/fake/asserting ones and pass those to the worker to
851
+ have different activities called during the test. You may need to use `activity_name :MyRealActivityClassName` inside
852
+ the mock activity class to make it appear as the real name.
853
+
854
+ #### Workflow Replay
855
+
856
+ Given a workflow's history, it can be replayed locally to check for things like non-determinism errors. For example,
857
+ assuming the `history_json` parameter below is given a JSON string of history exported from the CLI or web UI, the
858
+ following function will replay it:
859
+
860
+ ```ruby
861
+ def replay_from_json(history_json)
862
+ replayer = Temporalio::Worker::WorkflowReplayer.new(workflows: [MyWorkflow])
863
+ replayer.replay_workflow(Temporalio::WorkflowHistory.from_history_json(history_json))
864
+ end
865
+ ```
866
+
867
+ If there is a non-determinism, this will raise an exception by default.
868
+
869
+ Workflow history can be loaded from more than just JSON. It can be fetched individually from a workflow handle, or even
870
+ in a list. For example, the following code will check that all workflow histories for a certain workflow type (i.e.
871
+ workflow class) are safe with the current workflow code.
872
+
873
+ ```ruby
874
+ def check_past_histories(client)
875
+ replayer = Temporalio::Worker::WorkflowReplayer.new(workflows: [MyWorkflow])
876
+ results = replayer.replay_workflows(client.list_workflows("WorkflowType = 'MyWorkflow'").map do |desc|
877
+ client.workflow_handle(desc.id, run_id: desc.run_id).fetch_history
878
+ end)
879
+ results.each { |res| raise res.replay_failure if res.replay_failure }
880
+ end
881
+ ```
882
+
883
+ But this only raises at the end because by default `replay_workflows` does not raise on failure like `replay_workflow`
884
+ does. The `raise_on_replay_failure: true` parameter could be set, or the replay worker can be used to process each one
885
+ like so:
886
+
887
+ ```ruby
888
+ def check_past_histories(client)
889
+ Temporalio::Worker::WorkflowReplayer.new(workflows: [MyWorkflow]) do |worker|
890
+ client.list_workflows("WorkflowType = 'MyWorkflow'").each do |desc|
891
+ worker.replay_workflow(client.workflow_handle(desc.id, run_id: desc.run_id).fetch_history)
892
+ end
893
+ end
894
+ end
895
+ ```
896
+
897
+ See the `WorkflowReplayer` API documentation for more details.
898
+
899
+ ### Activities
900
+
901
+ #### Activity Definition
902
+
903
+ Activities can be defined in a few different ways. They are usually classes, but manual definitions are supported too.
904
+
905
+ Here is a common activity definition:
906
+
907
+ ```ruby
908
+ class FindUserActivity < Temporalio::Activity::Definition
909
+ def execute(user_id)
910
+ User.find(user_id)
911
+ end
912
+ end
913
+ ```
914
+
915
+ Activities are defined as classes that extend `Temporalio::Activity::Definition` and provide an `execute` method. When
916
+ this activity is provided to the worker as a _class_ (e.g. `activities: [FindUserActivity]`), it will be instantiated
917
+ for _every attempt_. Many users may prefer using the same instance across activities, for example:
918
+
919
+ ```ruby
920
+ class FindUserActivity < Temporalio::Activity
921
+ def initialize(db)
922
+ @db = db
923
+ end
924
+
925
+ def execute(user_id)
926
+ @db[:users].first(id: user_id)
927
+ end
928
+ end
929
+ ```
930
+
931
+ When this is provided to a worker as an instance of the activity (e.g. `activities: [FindUserActivity.new(my_db)]`) then
932
+ the same instance is reused for each activity.
933
+
934
+ Some notes about activity definition:
935
+
936
+ * Temporal activities are identified by their name (or sometimes referred to as "activity type"). This defaults to the
937
+ unqualified class name of the activity, but can be customized by calling the `activity_name` class method.
938
+ * Long running activities should heartbeat regularly, see "Activity Heartbeating and Cancellation" later.
939
+ * By default every activity attempt is executed in a thread on a thread pool, but fibers are also supported. See
940
+ "Activity Concurrency and Executors" section later for more details.
941
+ * Technically an activity definition can be created manually via `Temporalio::Activity::Definition::Info.new` that
942
+ accepts a proc or a block, but the class form is recommended.
943
+ * `activity_dynamic` can be used to mark an activity dynamic. Dynamic activities do not have names and handle any
944
+ activity that is not otherwise registered. A worker can only have one dynamic activity.
945
+ * `workflow_raw_args` can be used to have activity arguments delivered to `execute` as
946
+ `Temporalio::Converters::RawValue`s. These are wrappers for the raw payloads that have not been converted to types
947
+ (but they have been decoded by the codec if present). They can be converted with `payload_converter` on the context.
948
+ * Activities cannot accept keyword arguments.
949
+
950
+ #### Activity Context
951
+
952
+ When running in an activity, the `Temporalio::Activity::Context` is available via
953
+ `Temporalio::Activity::Context.current` which is backed by a thread/fiber local. In addition to other more advanced
954
+ things, this context provides:
955
+
956
+ * `info` - Information about the running activity.
957
+ * `heartbeat` - Method to call to issue an activity heartbeat (see "Activity Heartbeating and Cancellation" later).
958
+ * `cancellation` - Instance of `Temporalio::Cancellation` canceled when an activity is canceled (see
959
+ "Activity Heartbeating and Cancellation" later).
960
+ * `worker_shutdown_cancellation` - Instance of `Temporalio::Cancellation` canceled when worker is shutting down (see
961
+ "Activity Worker Shutdown" later).
962
+ * `logger` - Logger that automatically appends a hash with some activity info to every message.
963
+
964
+ #### Activity Heartbeating and Cancellation
965
+
966
+ In order for a non-local activity to be notified of server-side cancellation requests, it must regularly invoke
967
+ `heartbeat` on the `Temporalio::Activity::Context` instance (available via `Temporalio::Activity::Context.current`). It
968
+ is strongly recommended that all but the fastest executing activities call this function regularly.
969
+
970
+ In addition to obtaining cancellation information, heartbeats also support detail data that is persisted on the server
971
+ for retrieval during activity retry. If an activity calls `heartbeat(123)` and then fails and is retried,
972
+ `Temporalio::Activity::Context.current.info.heartbeat_details.first` will be `123`.
973
+
974
+ An activity can be canceled for multiple reasons, some server-side and some worker side. Server side cancellation
975
+ reasons include workflow canceling the activity, workflow completing, or activity timing out. On the worker side, the
976
+ activity can be canceled on worker shutdown (see next section). By default cancellation is relayed two ways - by marking
977
+ the `cancellation` on `Temporalio::Activity::Context` as canceled, and by issuing a `Thread.raise` or `Fiber.raise` with
978
+ the `Temporalio::Error::CanceledError`.
979
+
980
+ The `raise`-by-default approach was chosen because it is dangerous to the health of the system and the continued use of
981
+ worker slots to require activities opt-in to checking for cancellation by default. But if this behavior is not wanted,
982
+ `activity_cancel_raise false` class method can be called at the top of the activity which will disable the `raise`
983
+ behavior and just set the `cancellation` as canceled.
984
+
985
+ If needing to shield work from being canceled, the `shield` call on the `Temporalio::Cancellation` object can be used
986
+ with a block for the code to be shielded. The cancellation will not take effect on the cancellation object nor the raise
987
+ call while the work is shielded (regardless of nested depth). Once the shielding is complete, the cancellation will take
988
+ effect, including `Thread.raise`/`Fiber.raise` if that remains enabled.
989
+
990
+ #### Activity Worker Shutdown
991
+
992
+ An activity can react to a worker shutdown specifically and also a normal cancellation will be sent. A worker will not
993
+ complete its shutdown while an activity is in progress.
994
+
995
+ Upon worker shutdown, the `worker_shutdown_cancellation` cancellation on `Temporalio::Activity::Context` will be
996
+ canceled. Then the worker will wait a for a grace period set by the `graceful_shutdown_period` worker option (default 0)
997
+ before issuing actual cancellation to all still-running activities.
998
+
999
+ Worker shutdown will then wait on all activities to complete. If a long-running activity does not respect cancellation,
1000
+ the shutdown may never complete.
1001
+
1002
+ #### Activity Concurrency and Executors
1003
+
1004
+ By default, activities run in the "thread pool executor" (i.e. `Temporalio::Worker::ActivityExecutor::ThreadPool`). This
1005
+ default is shared across all workers and is a naive thread pool that continually makes threads as needed when none are
1006
+ idle/available to handle incoming work. If a thread sits idle long enough, it will be killed.
1007
+
1008
+ The maximum number of concurrent activities a worker will run at a time is configured via its `tuner` option. The
1009
+ default is `Temporalio::Worker::Tuner.create_fixed` which defaults to 100 activities at a time for that worker. When
1010
+ this value is reached, the worker will stop asking for work from the server until there are slots available again.
1011
+
1012
+ In addition to the thread pool executor, there is also a fiber executor in the default executor set. To use fibers, call
1013
+ `activity_executor :fiber` class method at the top of the activity class (the default of this value is `:default` which
1014
+ is the thread pool executor). Activities can only choose the fiber executor if the worker has been created and run in a
1015
+ fiber, but thread pool executor is always available. Currently due to
1016
+ [an issue](https://github.com/temporalio/sdk-ruby/issues/162), workers can only run in a fiber on Ruby versions 3.3 and
1017
+ newer.
1018
+
1019
+ Technically the executor can be customized. The `activity_executors` worker option accepts a hash with the key as the
1020
+ symbol and the value as a `Temporalio::Worker::ActivityExecutor` implementation. Users should usually not need to
1021
+ customize this. If general code is needed to run around activities, users should use interceptors instead.
1022
+
1023
+ #### Activity Testing
1024
+
1025
+ Unit testing an activity can be done via the `Temporalio::Testing::ActivityEnvironment` class. Simply instantiate the
1026
+ class, then invoke `run` with the activity to test and the arguments to give. The result will be the activity result or
1027
+ it will raise the error raised in the activity.
1028
+
1029
+ The constructor of the environment has multiple keyword arguments that can be set to affect the activity context for the
1030
+ activity.
1031
+
1032
+ ### Telemetry
1033
+
1034
+ #### Metrics
1035
+
1036
+ Metrics can be configured on a `Temporalio::Runtime`. Only one runtime is expected to be created for the entire
1037
+ application and it should be created before any clients are created. For example, this configures Prometheus to export
1038
+ metrics at `http://127.0.0.1:9000/metrics`:
1039
+
1040
+ ```ruby
1041
+ require 'temporalio/runtime'
1042
+
1043
+ Temporalio::Runtime.default = Temporalio::Runtime.new(
1044
+ telemetry: Temporalio::Runtime::TelemetryOptions.new(
1045
+ metrics: Temporalio::Runtime::MetricsOptions.new(
1046
+ prometheus: Temporalio::Runtime::PrometheusMetricsOptions.new(
1047
+ bind_address: '127.0.0.1:9000'
1048
+ )
1049
+ )
1050
+ )
1051
+ )
1052
+ ```
1053
+
1054
+ Now every client created will use this runtime. Setting the default will fail if a runtime has already been requested or
1055
+ a default already set. Technically a runtime can be created without setting the default and be set on each client via
1056
+ the `runtime` parameter, but this is discouraged because a runtime represents a heavy internal engine not meant to be
1057
+ created multiple times.
1058
+
1059
+ OpenTelemetry metrics can be configured instead by passing `Temporalio::Runtime::OpenTelemetryMetricsOptions` as the
1060
+ `opentelemetry` parameter to the metrics options. See API documentation for details.
1061
+
1062
+ #### OpenTelemetry Tracing
1063
+
1064
+ OpenTelemetry tracing for clients, activities, and workflows can be enabled using the
1065
+ `Temporalio::Contrib::OpenTelemetry::TracingInterceptor`. Specifically, when creating a client, set the interceptor like
1066
+ so:
1067
+
1068
+ ```ruby
1069
+ require 'opentelemetry/api'
1070
+ require 'opentelemetry/sdk'
1071
+ require 'temporalio/client'
1072
+ require 'temporalio/contrib/open_telemetry'
1073
+
1074
+ # ... assumes my_otel_tracer_provider is a tracer provider created by the user
1075
+ my_tracer = my_otel_tracer_provider.tracer('my-otel-tracer')
1076
+
1077
+ my_client = Temporalio::Client.connect(
1078
+ 'localhost:7233', 'my-namespace',
1079
+ interceptors: [Temporalio::Contrib::OpenTelemetry::TracingInterceptor.new(my_tracer)]
1080
+ )
1081
+ ```
1082
+
1083
+ Now many high-level client calls and activities/workflows on workers using this client will have spans created on that
1084
+ OpenTelemetry tracer.
1085
+
1086
+ ##### OpenTelemetry Tracing in Workflows
1087
+
1088
+ OpenTelemetry works by creating spans as necessary and in some cases serializing them to Temporal headers to be
1089
+ deserialized by workflows/activities to be set on the context. However, OpenTelemetry requires spans to be finished
1090
+ where they start, so spans cannot be resumed. This is fine for client calls and activity attempts, but Temporal
1091
+ workflows are resumable functions that may start on a different machine than they complete. Due to this, spans created
1092
+ by workflows are immediately closed since there is no way for the span to actually span machines. They are also not
1093
+ created during replay. The spans still become the proper parents of other spans if they are created.
1094
+
1095
+ Custom spans can be created inside of workflows using class methods on the
1096
+ `Temporalio::Contrib::OpenTelemetry::Workflow` module. For example:
1097
+
1098
+ ```ruby
1099
+ class MyWorkflow < Temporalio::Workflow::Definition
1100
+ def execute
1101
+ # Sleep for a bit
1102
+ Temporalio::Workflow.sleep(10)
1103
+ # Run activity in span
1104
+ Temporalio::Contrib::OpenTelemetry::Workflow.with_completed_span(
1105
+ 'my-span',
1106
+ attributes: { 'my-attr' => 'some val' }
1107
+ ) do
1108
+ # Execute an activity
1109
+ Temporalio::Workflow.execute_activity(MyActivity, start_to_close_timeout: 10)
1110
+ end
1111
+ end
1112
+ end
1113
+ ```
1114
+
1115
+ If this all executes on one worker (because Temporal has a concept of stickiness that caches instances), the span tree
1116
+ may look like:
1117
+
1118
+ ```
1119
+ StartWorkflow:MyWorkflow <-- created by client outbound
1120
+ RunWorkflow:MyWorkflow <-- created inside workflow on first task
1121
+ my-span <-- created inside workflow by code
1122
+ StartActivity:MyActivity <-- created inside workflow when first called
1123
+ RunActivity:MyActivity <-- created inside activity attempt 1
1124
+ CompleteWorkflow:MyWorkflow <-- created inside workflow on last task
1125
+ ```
1126
+
1127
+ However if, say, the worker crashed during the 10s sleep and the workflow was resumed (i.e. replayed) on another worker,
1128
+ the span tree may look like:
1129
+
1130
+ ```
1131
+ StartWorkflow:MyWorkflow <-- created by client outbound
1132
+ RunWorkflow:MyWorkflow <-- created by workflow inbound on first task
1133
+ my-span <-- created inside the workflow
1134
+ StartActivity:MyActivity <-- created by workflow outbound
1135
+ RunActivity:MyActivity <-- created by activity attempt 1 inbound
1136
+ CompleteWorkflow:MyWorkflow <-- created by workflow inbound on last task
1137
+ ```
1138
+
1139
+ Notice how the spans are no longer under `RunWorkflow`. This is because spans inside the workflow are not created on
1140
+ replay, so there is no parent on replay. But there are no orphans because we still have the overarching parent of
1141
+ `StartWorkflow` that was created by the client and is serialized into Temporal headers so it can always be the parent.
1142
+
1143
+ And reminder that `StartWorkflow` and `RunActivity` spans do last the length of their calls (so time to start the
1144
+ workflow and time to run the activity attempt respectively), but the other spans have no measurable time because they
1145
+ are created in workflows and closed immediately since long-lived spans cannot work for durable software that may resume
1146
+ on other machines.
1147
+
1148
+ ### Rails
1149
+
1150
+ Temporal Ruby SDK is a generic Ruby library that can work in any Ruby environment. However, there are some common
1151
+ conventions for Rails users to be aware of.
1152
+
1153
+ See the [rails_app](https://github.com/temporalio/samples-ruby/tree/main/rails_app) sample for an example of using
1154
+ Temporal from Rails.
1155
+
1156
+ #### ActiveRecord
1157
+
1158
+ For ActiveRecord, or other general/ORM models that are used for a different purpose, it is not recommended to
1159
+ try to reuse them as Temporal models. Eventually model purposes diverge and models for a Temporal workflows/activities
1160
+ should be specific to their use for clarity and compatibility reasons. Also many Ruby ORMs do many lazy things and
1161
+ therefore provide unclear serialization semantics. Instead, consider having models specific for workflows/activities and
1162
+ translate to/from existing models as needed. See the [ActiveModel](#activemodel) section on how to do this with
1163
+ ActiveModel objects.
1164
+
1165
+ #### Lazy/Eager Loading
1166
+
1167
+ By default, Rails
1168
+ [eagerly loads](https://guides.rubyonrails.org/v7.2/autoloading_and_reloading_constants.html#eager-loading) all
1169
+ application code on application start in production, but lazily loads it in non-production environments. Temporal
1170
+ workflows by default disallow use of IO during the workflow run. With lazy loading enabled in dev/test environments,
1171
+ when an activity class is referenced in a workflow before it has been explicitly `require`d, it can give an error like:
1172
+
1173
+ > Cannot access File path from inside a workflow. If this is known to be safe, the code can be run in a
1174
+ > Temporalio::Workflow::Unsafe.illegal_call_tracing_disabled block.
1175
+
1176
+ This comes from `bootsnap` via `zeitwork` because it is lazily loading a class/module at workflow runtime. It is not
1177
+ good to lazily load code durnig a workflow run because it can be side effecting. Workflows and the classes they
1178
+ reference should not be eagerly loaded.
1179
+
1180
+ To resolve this, either always eagerly load (e.g. `config.eager_load = true`) or explicitly `require` what is used by a
1181
+ workflow at the top of the file.
1182
+
1183
+ Note, this only affects non-production environments.
1184
+
1185
+ ### Ractors
1186
+
1187
+ It was an original goal to have workflows actually be Ractors for deterministic state isolation and have the library
1188
+ support Ractors in general. However, due to the SDK's heavy use of the Google Protobuf library which
1189
+ [is not Ractor-safe](https://github.com/protocolbuffers/protobuf/issues/19321), the Temporal Ruby SDK does not currently
1190
+ work with Ractors.
1191
+
1192
+ ### Platform Support
1193
+
1194
+ This SDK is backed by a Ruby C extension written in Rust leveraging the
1195
+ [Temporal Rust Core](https://github.com/temporalio/sdk-core). Gems are currently published for the following platforms:
1196
+
1197
+ * `aarch64-linux`
1198
+ * `aarch64-linux-musl`
1199
+ * `x86_64-linux`
1200
+ * `x86_64-linux-musl`
1201
+ * `arm64-darwin`
1202
+ * `x86_64-darwin`
1203
+
1204
+ This means Linux and macOS for ARM and x64 have published gems.
1205
+
1206
+ Due to [an issue](https://github.com/temporalio/sdk-ruby/issues/172) with Windows and multi-threaded Rust, MinGW-based
1207
+ Windows (i.e. `x64-mingw-ucrt`) is not supported. But WSL is supported using the normal Linux gem.
1208
+
1209
+ Due to [an issue](https://github.com/protocolbuffers/protobuf/issues/16853) with Google Protobuf, latest Linux versions
1210
+ of Google Protobuf gems will not work in musl-based environments. Instead use the pure "ruby" platform which will build
1211
+ the Google Protobuf gem on install (e.g.
1212
+ `gem 'google-protobuf', force_ruby_platform: RUBY_PLATFORM.include?('linux-musl')` in the `Gemfile`).
1213
+
1214
+ At this time a pure source gem is published for documentation reasons, but it cannot be built and will fail if tried.
1215
+ Building from source requires many files across submodules and requires Rust to be installed. See the [Build](#build)
1216
+ section for how to build a the repository.
1217
+
1218
+ The SDK works on Ruby 3.2+, but due to [an issue](https://github.com/temporalio/sdk-ruby/issues/162), fibers (and
1219
+ `async` gem) are only supported on Ruby versions 3.3 and newer.
1220
+
1221
+ ## Development
1222
+
1223
+ ### Build
1224
+
1225
+ Prerequisites:
1226
+
1227
+ * [Ruby](https://www.ruby-lang.org/) >= 3.2 (i.e. `ruby` and `bundle` on the `PATH`)
1228
+ * [Rust](https://www.rust-lang.org/) latest stable (i.e. `cargo` on the `PATH`)
1229
+ * This repository, cloned recursively
1230
+ * Change to the `temporalio/` directory
1231
+
1232
+ First, install dependencies:
1233
+
1234
+ # Optional: Change bundler install path to be local
1235
+ bundle config --local path $(pwd)/.bundle
1236
+ bundle instal
1237
+
1238
+ To build shared library for development use (ensure you have cloned submodules :
1239
+
1240
+ bundle exec rake compile
1241
+
1242
+ **NOTE**: This will make the current directory usable for the current Ruby version by putting the shared library
1243
+ `lib/temporalio/internal/bridge/temporalio_bridge.<ext>` in the proper place. But this development shared library may
1244
+ not work for other Ruby versions or other OS/arch combinations. For that, see "Build Platform-specific Gem" below.
1245
+
1246
+ **NOTE**: This is not `compile:dev` because debug-mode in Rust has
1247
+ [an issue](https://github.com/rust-lang/rust/issues/34283) that causes runtime stack size problems.
1248
+
1249
+ To lint, build, and test:
1250
+
1251
+ bundle exec rake
1252
+
1253
+ #### Build Platform-specific Gem
1254
+
1255
+ The standard `bundle exec rake build` will produce a gem in the `pkg` directory, but that gem will not be usable because
1256
+ the shared library is not present (neither the Rust code nor the compiled form). To create a platform-specific gem that
1257
+ can be used, `rb-sys-dock` must be run. See the
1258
+ [Cross-Compilation documentation](https://oxidize-rb.github.io/rb-sys/tutorial/publishing/cross-compilation.html) in the
1259
+ `rb-sys` repository. For example, running:
1260
+
1261
+ bundle exec rb-sys-dock --platform x86_64-linux --ruby-versions 3.2,3.3 --build
1262
+
1263
+ Will create a `pkg/temporalio-<version>-x86_64-linux.gem` file that can be used in x64 Linux environments on both Ruby
1264
+ 3.2 and Ruby 3.3 because it contains the shared libraries. For this specific example, the shared libraries are inside
1265
+ the gem at `lib/temporalio/internal/bridge/3.2/temporalio_bridge.so` and
1266
+ `lib/temporalio/internal/bridge/3.3/temporalio_bridge.so`.
1267
+
1268
+ ### Testing
1269
+
1270
+ Note you can set `TEMPORAL_TEST_CLIENT_TARGET_HOST` and `TEMPORAL_TEST_CLIENT_TARGET_NAMESPACE`
1271
+ (optional, defaults to 'default') environment variables to use an existing server.
1272
+
1273
+ This project uses `minitest`. To test:
1274
+
1275
+ bundle exec rake test
1276
+
1277
+ Can add options via `TESTOPTS`. E.g. single test:
1278
+
1279
+ bundle exec rake test TESTOPTS="--name=test_some_method"
1280
+
1281
+ E.g. all starting with prefix:
1282
+
1283
+ bundle exec rake test TESTOPTS="--name=/^test_some_method_prefix/"
1284
+
1285
+ E.g. all for a class:
1286
+
1287
+ bundle exec rake test TESTOPTS="--name=/SomeClassName/"
1288
+
1289
+ E.g. show all test names while executing:
1290
+
1291
+ bundle exec rake test TESTOPTS="--verbose"
1292
+
1293
+ ### Code Formatting and Type Checking
1294
+
1295
+ This project uses `rubocop`:
1296
+
1297
+ bundle exec rake rubocop:autocorrect
1298
+
1299
+ This project uses `steep`. First may need the RBS collection:
1300
+
1301
+ bundle exec rake rbs:install_collection
1302
+
1303
+ Now can run `steep`:
1304
+
1305
+ bundle exec rake steep
1306
+
1307
+ ### Proto Generation
1308
+
1309
+ Run:
1310
+
1311
+ bundle exec rake proto:generate