{"id":18728801,"url":"https://github.com/rubyonworld/cadence-ruby","last_synced_at":"2025-11-12T05:30:20.414Z","repository":{"id":174007883,"uuid":"542153372","full_name":"RubyOnWorld/cadence-ruby","owner":"RubyOnWorld","description":"A pure Ruby library for defining and running Cadence workflows and activities.","archived":false,"fork":false,"pushed_at":"2022-09-27T16:43:51.000Z","size":9397,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-12-28T14:26:41.042Z","etag":null,"topics":["active","codence","define","library","pure","ruby","workfloow"],"latest_commit_sha":null,"homepage":"","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/RubyOnWorld.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}},"created_at":"2022-09-27T15:19:34.000Z","updated_at":"2022-09-27T18:14:01.000Z","dependencies_parsed_at":null,"dependency_job_id":"a57df4b5-a6bd-47dd-8663-f1904806689c","html_url":"https://github.com/RubyOnWorld/cadence-ruby","commit_stats":null,"previous_names":["rubyonworld/cadence-ruby"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RubyOnWorld%2Fcadence-ruby","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RubyOnWorld%2Fcadence-ruby/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RubyOnWorld%2Fcadence-ruby/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RubyOnWorld%2Fcadence-ruby/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RubyOnWorld","download_url":"https://codeload.github.com/RubyOnWorld/cadence-ruby/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239599040,"owners_count":19665911,"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":["active","codence","define","library","pure","ruby","workfloow"],"created_at":"2024-11-07T14:24:24.858Z","updated_at":"2025-11-12T05:30:20.382Z","avatar_url":"https://github.com/RubyOnWorld.png","language":"Ruby","readme":"# Ruby worker for Cadence\n\n[![Coverage Status](https://coveralls.io/repos/github/coinbase/cadence-ruby/badge.svg?branch=master)](https://coveralls.io/github/coinbase/cadence-ruby?branch=master)\n\n\u003cimg src=\"./assets/cadence_logo_2.png\" width=\"250\" align=\"right\" alt=\"Cadence\" /\u003e\n\nA pure Ruby library for defining and running Cadence workflows and activities.\n\nTo find more about Cadence please visit \u003chttps://cadenceworkflow.io/\u003e.\n\n\n## Getting Started\n\n*NOTE: Make sure you have both Cadence and TChannel Proxy up and running. Head over to\n[this section](#installing-dependencies) for installation instructions.*\n\nClone this repository:\n\n```sh\n\u003e git clone git@github.com:coinbase/cadence-ruby.git\n```\n\nInclude this gem to your `Gemfile`:\n\n```ruby\ngem 'cadence-ruby', path: 'path/to/a/cloned/cadence-ruby/'\n```\n\nDefine an activity:\n\n```ruby\nclass HelloActivity \u003c Cadence::Activity\n  def execute(name)\n    puts \"Hello #{name}!\"\n\n    return\n  end\nend\n```\n\nDefine a workflow:\n\n```ruby\nrequire 'path/to/hello_activity'\n\nclass HelloWorldWorkflow \u003c Cadence::Workflow\n  def execute\n    HelloActivity.execute!('World')\n\n    return\n  end\nend\n```\n\nConfigure your Cadence connection:\n\n```ruby\nCadence.configure do |config|\n  config.host = 'localhost'\n  config.port = 6666 # this should point to the tchannel proxy\n  config.domain = 'ruby-samples'\n  config.task_list = 'hello-world'\nend\n```\n\nRegister domain with the Cadence service:\n\n```ruby\nCadence.register_domain('ruby-samples', 'A safe space for playing with Cadence Ruby')\n```\n\nConfigure and start your worker process:\n\n```ruby\nrequire 'cadence/worker'\n\nworker = Cadence::Worker.new\nworker.register_workflow(HelloWorldWorkflow)\nworker.register_activity(HelloActivity)\nworker.start\n```\n\nAnd finally start your workflow:\n\n```ruby\nrequire 'path/to/hello_world_workflow'\n\nCadence.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/domain/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\nIn order to run your Ruby workers you need to have the Cadence service and the TChannel Proxy\nrunning. Below are the instructions on setting these up:\n\n### Cadence\n\nCadence 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:\n\n```sh\n\u003e curl -O https://raw.githubusercontent.com/uber/cadence/master/docker/docker-compose.yml\n\n\u003e docker-compose up\n```\n\n### TChannel Proxy\n\nRight now the Cadence service only communicates with the workers using Thrift over TChannel.\nUnfortunately there isn't a working TChannel protocol implementation for Ruby, so in order to\nconnect to the Cadence service a simple proxy was created. You can run it using:\n\n```sh\n\u003e cd proxy\n\n\u003e bin/proxy\n```\n\nThe code and detailed instructions can be found [here](proxy/).\n\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 Cadence::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: { domain: 'my-domain', task_list: 'my-task-list' })\n```\n\nBesides calling activities workflows can:\n\n- Use timers\n- Receive signals\n- Execute other (child) workflows\n- Respond to queries [not yet implemented]\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 Cadence::Activity\n  class UserNotFound \u003c Cadence::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\n  end\nend\n```\n\nIt is important to make your activities **idempotent**, because they can get retried by Cadence (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 Cadence::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\nCadence.complete_activity(async_token, result)\n```\n\nSimilarly you can fail the activity by calling:\n\n```ruby\nCadence.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 Cadence server and manages Workflow and Activity\nexecution. To start a worker:\n\n```ruby\nrequire 'cadence/worker'\n\nworker = Cadence::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 Cadence service, so in order to start a workflow you need to send a\nmessage to Cadence:\n\n```ruby\nCadence.start_workflow(HelloWorldWorkflow)\n```\n\nOptionally you can pass input and other options to the workflow:\n\n```ruby\nCadence.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`CadenceThrift::WorkflowExecutionAlreadyStartedError`. 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(domain, task_list, 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. `domain 'my-domain'`)\n3. Globally, when configuring your Cadence library via `Cadence.configure`\n\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 Cadence::Workflow\n  def execute\n    ActivityOld1.execute!\n\n    workflow.sleep(10)\n\n    ActivityOld2.execute!\n\n    return\n  end\nend\n```\n\nwhich got updated to:\n\n```ruby\nclass MyWorkflow \u003c Cadence::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\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 `cadence-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 'cadence/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 Cadence workflow\nas part of your code, you can enable local testing:\n\n```ruby\nCadence::Testing.local!\n```\n\nThis will treat every `Cadence.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\nCadence::Testing.local! do\n  Cadence.start_workflow(HelloWorldWorkflow)\nend\n```\n\nMake sure to check out [example integration specs](examples/spec/integration) for more details.\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","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubyonworld%2Fcadence-ruby","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frubyonworld%2Fcadence-ruby","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frubyonworld%2Fcadence-ruby/lists"}