Ruby SDK for Temporal
A pure Ruby library for defining and running Temporal workflows and activities.
To find more about Temporal itself please visit .
Clone this repository:
git clone [email protected]:coinbase/temporal-ruby.gitInclude this gem to your Gemfile:
gem 'temporal-ruby', github: 'coinbase/temporal-ruby'Define an activity:
require 'temporal-ruby'
class HelloActivity .
There are plenty of [runnable examples](examples/) demonstrating various features of this library
available, make sure to check them out.
## Installing dependencies
Temporal service handles all the persistence, fault tolerance and coordination of your workflows and
activities. To set it up locally, download and boot the Docker Compose file from the official repo.
The Docker Compose file forwards all ports to your localhost so you can interact with
the containers easily from your shells.
Run:
```sh
curl -O https://raw.githubusercontent.com/temporalio/docker-compose/main/docker-compose.yml
docker-compose upIn many production deployments you will end up connecting to your Temporal Services via SSL. In this case you must read the public certificate of the CA that issued your Temporal server's SSL certificate and create an instance of gRPC Channel Credentials.
Configure your Temporal connection:
Temporal.configure do |config|
config.host = 'localhost'
config.port = 7233
config.namespace = 'ruby-samples'
config.task_queue = 'hello-world'
config.credentials = GRPC::Core::ChannelCredentials.new(root_cert, client_key, client_chain)
endUse gRPC Call Credentials to add OAuth2 token to gRPC calls:
Temporal.configure do |config|
config.host = 'localhost'
config.port = 7233
config.namespace = 'ruby-samples'
config.task_queue = 'hello-world'
config.credentials = GRPC::Core::CallCredentials.new(updater_proc)
endupdater_proc should be a method that returns proc. See an example of updater_proc in googleauth library.
To configure both SSL and OAuth2 token cedentials use compose method:
Temporal.configure do |config|
config.host = 'localhost'
config.port = 7233
config.namespace = 'ruby-samples'
config.task_queue = 'hello-world'
config.credentials = GRPC::Core::ChannelCredentials.new(root_cert, client_key, client_chain).compose(
GRPC::Core::CallCredentials.new(token.updater_proc)
)
endThis gem is optimised for the smoothest out-of-the-box experience, which is achieved using a global configuration:
Temporal.configure do |config|
config.host = '127.0.0.1' # sets global host
...
end
Temporal::Worker.new # uses global host
Temporal.start_workflow(...) # uses global hostThis will work just fine for simpler use-cases, however at some point you might need to setup multiple clients and workers within the same instance of your app (e.g. you have different Temporal hosts, need to use different codecs/converters for different parts of your app, etc). Should this be the case we recommend using explicit local configurations for each client/worker:
config_1 = Temporal::Configuration.new
config_1.host = 'temporal-01'
config_2 = Temporal::Configuration.new
config_2.host = 'temporal-01'
worker_1 = Temporal::Worker.new(config_1)
worker_2 = Temporal::Worker.new(config_2)
client_1 = Temporal::Client.new(config_1)
client_1.start_workflow(...)
client_2 = Temporal::Client.new(config_2)
client_2.start_workflow(...)
…
ruby
class RenewSubscriptionWorkflow e
CancelSubscriptionActivity.execute!(subscription[:id])
SendSubscriptionCancellationEmailActivity.execute!(user_id, subscription[:id])
end
endIn this simple workflow we are checking if a user has an active subscription and then attempt to charge their credit card to renew an expired subscription, notifying the user of the outcome. All the work is encapsulated in activities, while the workflow itself is responsible for calling the activities in the right order, passing values between them and handling failures.
There is a couple of ways to execute an activity from your workflow:
# Calls the activity by its class and blocks the execution until activity is
# finished. The return value of your activity will get assigned to the result
result = MyActivity.execute!(arg1, arg2)
# Here's a non-blocking version of the execute, returning back the future that
# will get fulfilled when activity completes. This approach allows modelling
# asynchronous workflows with activities executed in parallel
future = MyActivity.execute(arg1, arg2)
result = future.get
# Full versions of the calls from above, but has more flexibility (shown below)
result = workflow.execute_activity!(MyActivity, arg1, arg2)
future = workflow.execute_activity(MyActivity, arg1, arg2)
# In case your workflow code does not have access to activity classes (separate
# process, activities implemented in a different language, etc), you can
# simply reference them by their names
workflow.execute_activity('MyActivity', arg1, arg2, options: { namespace: 'my-namespace', task_queue: 'my-task-queue' })Besides calling activities workflows can:
An activity is a basic unit of work that performs the desired action (potentially causing side-effects). It can return a result or raise an error. It is defined like so:
class CloseUserAccountActivity < Temporal::Activity
class UserNotFound < Temporal::ActivityException; end
def execute(user_id)
user = User.find_by(id: user_id)
raise UserNotFound, 'User with specified ID does not exist' unless user
user.close_account
user.save
AccountClosureEmail.deliver(user)
return nil
end
end
…
ruby
class AsyncActivity < Temporal::Activity
def execute(user_id)
user = User.find_by(id: user_id)
# Pass the async_token to complete your activity later
ExternalSystem.verify_user(user, activity.async_token)
activity.async # prevents activity from completing immediately
end
endLater when a confirmation is received you'll need to complete your activity manually using the token provided:
Temporal.complete_activity(async_token, result)Similarly you can fail the activity by calling:
Temporal.fail_activity(async_token, MyError.new('Something went wrong'))
…
ruby
require 'temporal/worker'
worker = Temporal::Worker.new
worker.register_workflow(HelloWorldWorkflow)
worker.register_activity(SomeActivity)
worker.register_activity(SomeOtherActivity)
worker.startA call to worker.start will take over the current process and will keep it unning until a TERM
or INT signal is received. By only registering a subset of your workflows/activities with a given
worker you can split processing across as many workers as you need.
All communication is handled via Temporal service, so in order to start a workflow you need to send a message to Temporal:
Temporal.start_workflow(HelloWorldWorkflow)Optionally you can pass input and other options to the workflow:
Temporal.start_workflow(RenewSubscriptionWorkflow, user_id, options: { workflow_id: user_id })
…
ruby
Temporal.schedule_workflow(HealthCheckWorkflow, '*/5 * * * *')
…
class MyMiddleware
def call(metadata)
puts "Before execution"
yield
puts "After execution"
result
end
end
…
ruby
class MyWorkflow < Temporal::Workflow
def execute
ActivityOld1.execute!
workflow.sleep(10)
ActivityOld2.execute!
return nil
end
endwhich got updated to:
class MyWorkflow < Temporal::Workflow
def execute
Activity1.execute!
if workflow.has_release?(:fix_1)
ActivityNew1.execute!
end
workflow.sleep(10)
if workflow.has_release?(:fix_1)
ActivityNew2.execute!
else
ActivityOld.execute!
end
if workflow.has_release?(:fix_2)
ActivityNew3.execute!
end
return nil
end
end
…
ruby
require 'temporal/testing'This will allow you to execute workflows locally by running HelloWorldWorkflow.execute_locally.
Any arguments provided will forwarded to your #execute method.
In case of a higher level end-to-end integration specs, where you need to execute a Temporal workflow as part of your code, you can enable local testing:
Temporal::Testing.local!This will treat every Temporal.start_workflow call as local and perform your workflows inline. It
also works with a block, restoring the original mode back after the execution:
Temporal::Testing.local! do
Temporal.start_workflow(HelloWorldWorkflow)
endMake sure to check out example integration specs for more details. Instructions for running these integration specs can be found in examples/README.md.
There's plenty of work to be done, but most importanly we need:
Copyright 2020 Coinbase, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
No open issues yet, or sync has not completed.