{"id":13704936,"url":"https://github.com/coinbase/temporal-ruby","last_synced_at":"2025-05-15T02:07:41.176Z","repository":{"id":38039941,"uuid":"269181561","full_name":"coinbase/temporal-ruby","owner":"coinbase","description":"Ruby SDK for Temporal","archived":false,"fork":false,"pushed_at":"2025-03-26T18:02:32.000Z","size":10301,"stargazers_count":258,"open_issues_count":61,"forks_count":100,"subscribers_count":12,"default_branch":"master","last_synced_at":"2025-05-14T18:54:38.532Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/coinbase.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2020-06-03T19:55:40.000Z","updated_at":"2025-05-13T16:02:39.000Z","dependencies_parsed_at":"2023-10-11T17:31:10.015Z","dependency_job_id":"5cf53624-d775-463c-b6db-84c8aa0668e8","html_url":"https://github.com/coinbase/temporal-ruby","commit_stats":{"total_commits":307,"total_committers":39,"mean_commits":7.871794871794871,"dds":0.745928338762215,"last_synced_commit":"b5efd2cef802be2fa97d5bab04839413726ac06e"},"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coinbase%2Ftemporal-ruby","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coinbase%2Ftemporal-ruby/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coinbase%2Ftemporal-ruby/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coinbase%2Ftemporal-ruby/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/coinbase","download_url":"https://codeload.github.com/coinbase/temporal-ruby/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254259383,"owners_count":22040820,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T22:00:27.169Z","updated_at":"2025-05-15T02:07:41.148Z","avatar_url":"https://github.com/coinbase.png","language":"Ruby","funding_links":[],"categories":["Ruby","Temporal"],"sub_categories":[],"readme":"# Ruby SDK for Temporal\n\n[![Coverage Status](https://coveralls.io/repos/github/coinbase/temporal-ruby/badge.svg?branch=master)](https://coveralls.io/github/coinbase/temporal-ruby?branch=master)\n\n\u003cimg src=\"./assets/temporal_logo.png\" width=\"250\" align=\"right\" alt=\"Temporal\" /\u003e\n\nA pure Ruby library for defining and running Temporal workflows and activities.\n\nTo find more about Temporal itself please visit \u003chttps://temporal.io/\u003e.\n\n\n## Getting Started\n\nClone this repository:\n\n```sh\ngit clone git@github.com:coinbase/temporal-ruby.git\n```\n\nInclude this gem to your `Gemfile`:\n\n```ruby\ngem 'temporal-ruby', github: 'coinbase/temporal-ruby'\n```\n\nDefine an activity:\n\n```ruby\nrequire 'temporal-ruby'\nclass HelloActivity \u003c Temporal::Activity\n  def execute(name)\n    puts \"Hello #{name}!\"\n\n    return nil\n  end\nend\n```\n\nDefine a workflow:\n\n```ruby\nrequire 'path/to/hello_activity'\n\nclass HelloWorldWorkflow \u003c Temporal::Workflow\n  def execute\n    HelloActivity.execute!('World')\n\n    return nil\n  end\nend\n```\n\nConfigure your Temporal connection and register the namespace with the Temporal service:\n\n```ruby\nrequire 'temporal-ruby'\nTemporal.configure do |config|\n  config.host = 'localhost'\n  config.port = 7233\n  config.namespace = 'ruby-samples'\n  config.task_queue = 'hello-world'\n  config.credentials = :this_channel_is_insecure\nend\n\nbegin\n  Temporal.register_namespace('ruby-samples', 'A safe space for playing with Temporal Ruby')\nrescue Temporal::NamespaceAlreadyExistsFailure\n  nil # service was already registered\nend\n```\n\n\nConfigure and start your worker process in a terminal shell:\n\n```ruby\nrequire 'path/to/configuration'\nrequire 'temporal/worker'\n\nworker = Temporal::Worker.new\nworker.register_workflow(HelloWorldWorkflow)\nworker.register_activity(HelloActivity)\nworker.start # runs forever\n```\n\nYou can add several options when initializing worker (here defaults are provided as values):\n\n```ruby\nTemporal::Worker.new(\n  activity_thread_pool_size: 20, # how many threads poll for activities\n  workflow_thread_pool_size: 10, # how many threads poll for workflows\n  binary_checksum: nil, # identifies the version of workflow worker code\n  activity_poll_retry_seconds: 0, # how many seconds to wait after unsuccessful poll for activities\n  workflow_poll_retry_seconds: 0, # how many seconds to wait after unsuccessful poll for workflows\n  activity_max_tasks_per_second: 0 # rate-limit for starting activity tasks (new activities + retries) on the task queue\n)\n```\n\nAnd finally start your workflow in another terminal shell:\n\n```ruby\nrequire 'path/to/configuration'\nrequire 'path/to/hello_world_workflow'\n\nTemporal.start_workflow(HelloWorldWorkflow)\n```\n\nCongratulation you've just created and executed a distributed workflow!\n\nTo view more details about your execution, point your browser to\n\u003chttp://localhost:8088/namespace/ruby-samples/workflows?range=last-3-hours\u0026status=CLOSED\u003e.\n\nThere are plenty of [runnable examples](examples/) demonstrating various features of this library\navailable, make sure to check them out.\n\n\n## Installing dependencies\n\nTemporal service handles all the persistence, fault tolerance and coordination of your workflows and\nactivities. To set it up locally, download and boot the Docker Compose file from the official repo.\nThe Docker Compose file forwards all ports to your localhost so you can interact with\nthe containers easily from your shells.\n\nRun:\n\n```sh\ncurl -O https://raw.githubusercontent.com/temporalio/docker-compose/main/docker-compose.yml\n\ndocker-compose up\n```\n\n## Using Credentials\n\n### SSL\n\nIn many production deployments you will end up connecting to your Temporal Services via SSL. In this\ncase you must read the public certificate of the CA that issued your Temporal server's SSL certificate and create\nan instance of [gRPC Channel Credentials](https://grpc.io/docs/guides/auth/#with-server-authentication-ssltls-1).\n\nConfigure your Temporal connection:\n\n```ruby\nTemporal.configure do |config|\n    config.host = 'localhost'\n    config.port = 7233\n    config.namespace = 'ruby-samples'\n    config.task_queue = 'hello-world'\n    config.credentials = GRPC::Core::ChannelCredentials.new(root_cert, client_key, client_chain)\nend\n```\n\n### OAuth2 Token\n\nUse gRPC Call Credentials to add OAuth2 token to gRPC calls:\n\n```ruby\nTemporal.configure do |config|\n    config.host = 'localhost'\n    config.port = 7233\n    config.namespace = 'ruby-samples'\n    config.task_queue = 'hello-world'\n    config.credentials = GRPC::Core::CallCredentials.new(updater_proc)\nend\n```\n`updater_proc` should be a method that returns `proc`. See an example of `updater_proc` in [googleauth](https://www.rubydoc.info/gems/googleauth/0.1.0/Signet/OAuth2/Client) library.\n\n### Combining Credentials\n\nTo configure both SSL and OAuth2 token cedentials use `compose` method:\n\n```ruby\nTemporal.configure do |config|\n    config.host = 'localhost'\n    config.port = 7233\n    config.namespace = 'ruby-samples'\n    config.task_queue = 'hello-world'\n    config.credentials = GRPC::Core::ChannelCredentials.new(root_cert, client_key, client_chain).compose(\n        GRPC::Core::CallCredentials.new(token.updater_proc)\n    )\nend\n```\n\n## Configuration\n\nThis gem is optimised for the smoothest out-of-the-box experience, which is achieved using a global\nconfiguration:\n\n```ruby\nTemporal.configure do |config|\n  config.host = '127.0.0.1' # sets global host\n  ...\nend\n\nTemporal::Worker.new # uses global host\nTemporal.start_workflow(...) # uses global host\n```\n\nThis will work just fine for simpler use-cases, however at some point you might need to setup\nmultiple clients and workers within the same instance of your app (e.g. you have different Temporal\nhosts, need to use different codecs/converters for different parts of your app, etc). Should this be\nthe case we recommend using explicit local configurations for each client/worker:\n\n```ruby\nconfig_1 = Temporal::Configuration.new\nconfig_1.host = 'temporal-01'\n\nconfig_2 = Temporal::Configuration.new\nconfig_2.host = 'temporal-01'\n\nworker_1 = Temporal::Worker.new(config_1)\nworker_2 = Temporal::Worker.new(config_2)\n\nclient_1 = Temporal::Client.new(config_1)\nclient_1.start_workflow(...)\n\nclient_2 = Temporal::Client.new(config_2)\nclient_2.start_workflow(...)\n```\n\n*NOTE: Almost all the methods on the `Temporal` module are delegated to the default client that's\ninitialized using global configuration. The same methods can be used directly on your own client\ninstances.*\n\n## Workflows\n\nA workflow is defined using pure Ruby code, however it should contain only a high-level\ndeterministic outline of the steps (their composition) that need to be executed to complete a\nworkflow. The actual work should be defined in your activities.\n\n*NOTE: Keep in mind that your workflow code can get run multiple times (replayed) during the same\nexecution, which is why it must NOT contain any non-deterministic code (network requests, DB\nqueries, etc) as it can break your workflows.*\n\nHere's an example workflow:\n\n```ruby\nclass RenewSubscriptionWorkflow \u003c Temporal::Workflow\n  def execute(user_id)\n    subscription = FetchUserSubscriptionActivity.execute!(user_id)\n    subscription ||= CreateUserSubscriptionActivity.execute!(user_id)\n\n    return if subscription[:active]\n\n    ChargeCreditCardActivity.execute!(subscription[:price], subscription[:card_token])\n\n    RenewedSubscriptionActivity.execute!(subscription[:id])\n    SendSubscriptionRenewalEmailActivity.execute!(user_id, subscription[:id])\n  rescue CreditCardNotChargedError =\u003e e\n    CancelSubscriptionActivity.execute!(subscription[:id])\n    SendSubscriptionCancellationEmailActivity.execute!(user_id, subscription[:id])\n  end\nend\n```\n\nIn this simple workflow we are checking if a user has an active subscription and then attempt to\ncharge their credit card to renew an expired subscription, notifying the user of the outcome. All\nthe work is encapsulated in activities, while the workflow itself is responsible for calling the\nactivities in the right order, passing values between them and handling failures.\n\nThere is a couple of ways to execute an activity from your workflow:\n\n```ruby\n# Calls the activity by its class and blocks the execution until activity is\n# finished. The return value of your activity will get assigned to the result\nresult = MyActivity.execute!(arg1, arg2)\n\n# Here's a non-blocking version of the execute, returning back the future that\n# will get fulfilled when activity completes. This approach allows modelling\n# asynchronous workflows with activities executed in parallel\nfuture = MyActivity.execute(arg1, arg2)\nresult = future.get\n\n# Full versions of the calls from above, but has more flexibility (shown below)\nresult = workflow.execute_activity!(MyActivity, arg1, arg2)\nfuture = workflow.execute_activity(MyActivity, arg1, arg2)\n\n# In case your workflow code does not have access to activity classes (separate\n# process, activities implemented in a different language, etc), you can\n# simply reference them by their names\nworkflow.execute_activity('MyActivity', arg1, arg2, options: { namespace: 'my-namespace', task_queue: 'my-task-queue' })\n```\n\nBesides calling activities workflows can:\n\n- Use timers\n- Receive signals\n- Execute other (child) workflows\n- Respond to queries\n\n\n## Activities\n\nAn activity is a basic unit of work that performs the desired action (potentially causing\nside-effects). It can return a result or raise an error. It is defined like so:\n\n```ruby\nclass CloseUserAccountActivity \u003c Temporal::Activity\n  class UserNotFound \u003c Temporal::ActivityException; end\n\n  def execute(user_id)\n    user = User.find_by(id: user_id)\n\n    raise UserNotFound, 'User with specified ID does not exist' unless user\n\n    user.close_account\n    user.save\n\n    AccountClosureEmail.deliver(user)\n\n    return nil\n  end\nend\n```\n\nIt is important to make your activities **idempotent**, because they can get retried by Temporal (in\ncase a timeout is reached or your activity has thrown an error). You normally want to avoid\ngenerating additional side effects during subsequent activity execution.\n\nTo achieve this there are two methods (returning a UUID token) available from your activity class:\n\n- `activity.run_idem` — unique within for the current workflow execution (scoped to run_id)\n- `activity.workflow_idem` — unique across all execution of the workflow (scoped to workflow_id)\n\nBoth tokens will remain the same across multiple retry attempts of the activity.\n\n### Asynchronous completion\n\nWhen dealing with asynchronous business logic in your activities, you might need to wait for an\nexternal event to complete your activity (e.g. a callback or a webhook). This can be achieved by\nmanually completing your activity using a provided `async_token` from activity's context:\n\n```ruby\nclass AsyncActivity \u003c Temporal::Activity\n  def execute(user_id)\n    user = User.find_by(id: user_id)\n\n    # Pass the async_token to complete your activity later\n    ExternalSystem.verify_user(user, activity.async_token)\n\n    activity.async # prevents activity from completing immediately\n  end\nend\n```\n\nLater when a confirmation is received you'll need to complete your activity manually using the token\nprovided:\n\n```ruby\nTemporal.complete_activity(async_token, result)\n```\n\nSimilarly you can fail the activity by calling:\n\n```ruby\nTemporal.fail_activity(async_token, MyError.new('Something went wrong'))\n```\n\nThis doesn't change the behaviour from the workflow's perspective — as any other activity the result\nwill be returned or an error raised.\n\n*NOTE: Make sure to configure your timeouts accordingly and not to set heartbeat timeout (off by\ndefault) since you won't be able to emit heartbeats and your async activities will keep timing out.*\n\nSimilar behaviour can also be achieved in other ways (one which might be more preferable in your\nspecific use-case), e.g.:\n\n- by polling for a result within your activity (long-running activities with heartbeat)\n- using retry policy to keep retrying activity until a result is available\n- completing your activity after the initial call is made, but then waiting on a completion signal\nfrom your workflow\n\n\n## Worker\n\nWorker is a process that communicates with the Temporal server and manages Workflow and Activity\nexecution. To start a worker:\n\n```ruby\nrequire 'temporal/worker'\n\nworker = Temporal::Worker.new\nworker.register_workflow(HelloWorldWorkflow)\nworker.register_activity(SomeActivity)\nworker.register_activity(SomeOtherActivity)\nworker.start\n```\n\nA call to `worker.start` will take over the current process and will keep it unning until a `TERM`\nor `INT` signal is received. By only registering a subset of your workflows/activities with a given\nworker you can split processing across as many workers as you need.\n\n\n## Starting a workflow\n\nAll communication is handled via Temporal service, so in order to start a workflow you need to send\na message to Temporal:\n\n```ruby\nTemporal.start_workflow(HelloWorldWorkflow)\n```\n\nOptionally you can pass input and other options to the workflow:\n\n```ruby\nTemporal.start_workflow(RenewSubscriptionWorkflow, user_id, options: { workflow_id: user_id })\n```\n\nPassing in a `workflow_id` allows you to prevent concurrent execution of a workflow — a subsequent\ncall with the same `workflow_id` will always get rejected while it is still running, raising\n`Temporal::WorkflowExecutionAlreadyStartedFailure`. You can adjust the behaviour for finished\nworkflows by supplying the `workflow_id_reuse_policy:` argument with one of these options:\n\n- `:allow_failed` will allow re-running workflows that have failed (terminated, cancelled, timed out or failed)\n- `:allow` will allow re-running any finished workflows both failed and completed\n- `:reject` will reject any subsequent attempt to run a workflow\n\n\n## Execution Options\n\nThere are lots of ways in which you can configure your Workflows and Activities. The common ones\n(namespace, task_queue, timeouts and retry policy) can be defined in one of these places (in the order\nof precedence):\n\n1. Inline when starting or registering a workflow/activity (use `options:` argument)\n2. In your workflow/activity class definitions by calling a class method (e.g. `namespace 'my-namespace'`)\n3. Globally, when configuring your Temporal library via `Temporal.configure`\n\n\n## Periodic workflow execution\n\nIn certain cases you might need a workflow that runs periodically using a cron schedule. This can be\nachieved using the `Temporal.schedule_workflow` API that take a periodic cron schedule as a second\nargument:\n\n```ruby\nTemporal.schedule_workflow(HealthCheckWorkflow, '*/5 * * * *')\n```\n\nThis will instruct Temporal to run a HealthCheckWorkflow every 5 minutes. All the rest of the\narguments are identical to the `Temporal.start_workflow` API.\n\n*NOTE: Your execution timeout will be measured across all the workflow invocations, so make sure to\nset it to allow as many invocations as you need. You can also set it to `nil`, which will use a\ndefault value of 10 years.*\n\n## Middleware\nMiddleware sits between the execution of your workflows/activities and the Temporal SDK, allowing you to insert custom code before or after the execution.\n\n### Activity Middleware Stack\nMiddleware added to the activity middleware stack will be executed around each activity method. This is useful when you want to perform a certain task before and/or after each activity execution, such as logging, error handling, or measuring execution time.\n\n### Workflow Middleware Stack\nThere are actually two types of workflow middleware in Temporal Ruby SDK:\n\n*Workflow Middleware*: This middleware is executed around each entire workflow. This is similar to activity middleware, but for workflows.\n\n*Workflow Task Middleware*: This middleware is executed around each workflow task, of which there will be many for each workflow.\n\n### Example\nTo add a middleware, you need to define a class that responds to the call method. Within the call method, you should call yield to allow the next middleware in the stack (or the workflow/activity method itself if there are no more middlewares) to execute. Here's an example:\n\n```\nclass MyMiddleware\n  def call(metadata)\n    puts \"Before execution\"\n    yield\n    puts \"After execution\"\n    result\n  end\nend\n```\n\nYou can add this middleware to the stack like so `worker.add_activity_middleware(MyMiddleware)`\n\nPlease note that the order of middleware in the stack matters. The middleware that is added last will be the first one to execute. In the example above, MyMiddleware will execute before any other middleware in the stack.\n\n## Breaking Changes\n\nSince the workflow execution has to be deterministic, breaking changes can not be simply added and\ndeployed — this will undermine the consistency of running workflows and might lead to unexpected\nbehaviour. However, breaking changes are often needed and these include:\n\n- Adding new activities, timers, child workflows, etc.\n- Remove existing activities, timers, child workflows, etc.\n- Rearranging existing activities, timers, child workflows, etc.\n- Adding/removing signal handlers\n\nIn order to add a breaking change you can use `workflow.has_release?(release_name)` method in your\nworkflows, which is guaranteed to return a consistent result whether or not it was called prior to\nshipping the new release. It is also consistent for all the subsequent calls with the same\n`release_name` — all of them will return the original result. Consider the following example:\n\n```ruby\nclass MyWorkflow \u003c Temporal::Workflow\n  def execute\n    ActivityOld1.execute!\n\n    workflow.sleep(10)\n\n    ActivityOld2.execute!\n\n    return nil\n  end\nend\n```\n\nwhich got updated to:\n\n```ruby\nclass MyWorkflow \u003c Temporal::Workflow\n  def execute\n    Activity1.execute!\n\n    if workflow.has_release?(:fix_1)\n      ActivityNew1.execute!\n    end\n\n    workflow.sleep(10)\n\n    if workflow.has_release?(:fix_1)\n      ActivityNew2.execute!\n    else\n      ActivityOld.execute!\n    end\n\n    if workflow.has_release?(:fix_2)\n      ActivityNew3.execute!\n    end\n\n    return nil\n  end\nend\n```\n\nIf the release got deployed while the original workflow was waiting on a timer, `ActivityNew1` and\n`ActivityNew2` won't get executed, because they are part of the same change (same release_name),\nhowever `ActivityNew3` will get executed, since the release wasn't yet checked at the time. And for\nevery new execution of the workflow — all new activities will get executed, while `ActivityOld` will\nnot.\n\nLater on you can clean it up and drop all the checks if you don't have any older workflows running\nor expect them to ever be executed (e.g. reset).\n\n*NOTE: Releases with different names do not depend on each other in any way.*\n\n## Testing\n\nIt is crucial to properly test your workflows and activities before running them in production. The\nprovided testing framework is still limited in functionality, but will allow you to test basic\nuse-cases.\n\nThe testing framework is not required automatically when you require `temporal-ruby`, so you have to\ndo this yourself (it is strongly recommended to only include this in your test environment,\n`spec_helper.rb` or similar):\n\n```ruby\nrequire 'temporal/testing'\n```\n\nThis will allow you to execute workflows locally by running `HelloWorldWorkflow.execute_locally`.\nAny arguments provided will forwarded to your `#execute` method.\n\nIn case of a higher level end-to-end integration specs, where you need to execute a Temporal workflow\nas part of your code, you can enable local testing:\n\n```ruby\nTemporal::Testing.local!\n```\n\nThis will treat every `Temporal.start_workflow` call as local and perform your workflows inline. It\nalso works with a block, restoring the original mode back after the execution:\n\n```ruby\nTemporal::Testing.local! do\n  Temporal.start_workflow(HelloWorldWorkflow)\nend\n```\n\nMake sure to check out [example integration specs](examples/spec/integration) for more details. Instructions\nfor running these integration specs can be found in [examples/README.md](examples/README.md).\n\n\n## TODO\n\nThere's plenty of work to be done, but most importanly we need:\n\n- Write specs for everything\n- Implement support for missing features\n\n\n## LICENSE\n\nCopyright 2020 Coinbase, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoinbase%2Ftemporal-ruby","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcoinbase%2Ftemporal-ruby","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoinbase%2Ftemporal-ruby/lists"}