Background jobs for Ruby using Google Cloud Tasks
Background jobs for Ruby using Google Cloud Tasks
Background jobs for Ruby using Google Cloud Tasks.
Cloudtasker provides an easy to manage interface to Google Cloud Tasks for background job processing. Workers can be defined programmatically using the Cloudtasker DSL and enqueued for processing using a simple to use API.
Cloudtasker is particularly suited for serverless applications only responding to HTTP requests and where running a dedicated job processing server is not an option (e.g. deploy via Cloud Run). All jobs enqueued in Cloud Tasks via Cloudtasker eventually get processed by your application via HTTP requests.
Cloudtasker also provides optional modules for running cron jobs, batch jobs, unique jobs and storable jobs.
A local processing server is also available for development. This local server processes jobs in lieu of Cloud Tasks and allows you to work offline.
Add this line to your application's Gemfile:
gem 'cloudtasker'And then execute:
$ bundleOr install it yourself with:
$ gem install cloudtaskerCloudtasker is pre-integrated with Rails. Follow the steps below to get started.
Install redis on your machine (this is required by the Cloudtasker local processing server)
# E.g. using brew
brew install redisAdd the following initializer
# config/initializers/cloudtasker.rb
Cloudtasker.configure do |config|
#
# Adapt the server port to be the one used by your Rails web process
#
config.processor_host = 'http://localhost:3000'
#
# If you do not have any Rails secret_key_base defined, uncomment the following
# This secret is used to authenticate jobs sent to the processing endpoint
# of your application.
#
# config.secret = 'some-long-token'
endDefine your first worker:
# app/workers/dummy_worker.rb
class DummyWorker
include Cloudtasker::Worker
def perform(some_arg)
logger.info("Job run with #{some_arg}. This is working!")
end
endLaunch Rails and the local Cloudtasker processing server (or add cloudtasker to your foreman config as a worker process)
# In one terminal
> rails s -p 3000
# In another terminal
> cloudtaskerOpen a Rails console and enqueue some jobs
# Process job as soon as possible
DummyWorker.perform_async('foo')
# Process job in 60 seconds
DummyWorker.perform_in(60, 'foo')
# Process job immediately, inline
# Supported since: v0.15.0
DummyWorker.perform_now('foo')Your Rails logs should display the following:
…That's it! Your job was picked up by the Cloudtasker local server and sent for processing to your Rails web process.
Now jump to the next section to configure your app to use Google Cloud Tasks as a backend.
Note: ActiveJob is supported since 0.11.0
Note: Cloudtasker extensions (cron, batch, unique jobs and storable) are not available when using cloudtasker via ActiveJob.
Cloudtasker is pre-integrated with ActiveJob. Follow the steps below to get started.
Install redis on your machine (this is required by the Cloudtasker local processing server)
# E.g. using brew
brew install redisAdd the following initializer
# config/initializers/cloudtasker.rb
Cloudtasker.configure do |config|
#
# Adapt the server port to be the one used by your Rails web process
#
config.processor_host = 'http://localhost:3000'
#
# If you do not have any Rails secret_key_base defined, uncomment the following
# This secret is used to authenticate jobs sent to the processing endpoint
# of your application.
#
# config.secret = 'some-long-token'
endConfigure ActiveJob to use Cloudtasker. You can also configure ActiveJob per environment via the config/environments/:env.rb files
# config/application.rb
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module Dummy
class Application rails s -p 3000
# In another terminal
> cloudtaskerOpen a Rails console and enqueue some jobs
# Process job as soon as possible
ExampleJob.perform_later('foo')
# Process job in 60 seconds
ExampleJob.set(wait: 60).perform_later('foo')The Google Cloud library authenticates via the Google Cloud SDK by default. If you do not have it setup then we recommend you install it.
Other options are available such as using a service account. You can see all authentication options in the Google Cloud Authentication guide.
In order to function properly Cloudtasker requires the authenticated account to have the following IAM permissions:
cloudtasks.tasks.getcloudtasks.tasks.createcloudtasks.tasks.deleteTo get started quickly you can add the roles/cloudtasks.admin role to your account via the IAM Console. This is not required if your account is a project admin account.
The GCP project ID and region values are not loaded automatically by the Google Cloud library, and must be explicitly defined in the initializer when using Google Cloud Tasks.
The gem can be configured through an initializer. See below all the available configuration options.
…If the default queue -default does not exist in Cloud Tasks you should create it using the gcloud sdk.
Alternatively with Rails you can simply run the following rake task if you have queue admin permissions (cloudtasks.queues.get and cloudtasks.queues.create).
bundle exec rake cloudtasker:setup_queueCloudtasker provides multiple ways of enqueuing jobs.
…Cloudtasker also provides a helper for re-enqueuing jobs. Re-enqueued jobs keep the same job id. Some middlewares may rely on this to track the fact that that a job didn't actually complete (e.g. Cloustasker batch). This is optional and you can always fallback to using exception management (raise an error) to retry/re-enqueue jobs.
E.g.
# app/workers/fetch_resource_worker.rb
class FetchResourceWorker
include Cloudtasker::Worker
def perform(id)
# ...do some logic...
if some_condition
# Stop and re-enqueue the job to be run again in 10 seconds.
# Also see the section on Cloudtasker::RetryWorkerError for a different
# approach on reenqueuing.
return reenqueue(10)
else
# ...keep going...
end
end
endCloudtasker allows you to manage several queues and distribute workers across them based on job priority. By default jobs are pushed to the default queue, which is -default in Cloud Tasks.
More queues can be created using the gcloud sdk or the cloudtasker:setup_queue rake task.
E.g. Create a critical queue with a concurrency of 5 via the gcloud SDK
gcloud tasks queues create -critical --max-concurrent-dispatches=5E.g. Create a real-time queue with a concurrency of 15 via the rake task (Rails only)
rake cloudtasker:setup_queue name=real-time concurrency=15When running the Cloudtasker local processing server, you can specify the concurrency for each queue using:
cloudtasker -q critical,5 -q important,4 -q default,3Queues can be assigned to workers via the cloudtasker_options directive on the worker class:
# app/workers/critical_worker.rb
class CriticalWorker
include Cloudtasker::Worker
cloudtasker_options queue: :critical
def perform(some_arg)
logger.info("This is a critical job run with arg=#{some_arg}.")
end
endQueues can also be assigned at runtime when scheduling a job:
CriticalWorker.schedule(args: [1], queue: :important)Supported since: v0.15.0
You can specify propagate_queue: true via the cloudtasker_options to make workers enqueued inside a job use the runtime queue instead of the default (class-configured or default) queue:
# app/workers/child_worker.rb
class ChildWorker
include Cloudtasker::Worker
cloudtasker_options queue: :level2
def perform(some_arg)
logger.info("This is a child job, which is set to run on the level2 queue by default.")
end
end…Note: Extensions are not available when using cloudtasker via ActiveJob.
Cloudtasker comes with three optional features:
Cloudtasker pushes jobs to Google Cloud Tasks, which in turn sends jobs for processing to your application via HTTP POST requests to the /cloudtasker/run endpoint of the publicly accessible domain of your application.
When working locally on your application it is usually not possible to have a public domain. So what are the options?
The Cloudtasker local server is a ruby daemon that looks for jobs pushed to Redis and sends them to your application via HTTP POST requests. The server mimics the way Google Cloud Tasks works, but locally!
You can configure your application to use the Cloudtasker local server using the following initializer:
# config/initializers/cloudtasker.rb
Cloudtasker.configure do |config|
# ... other options
# Push jobs to redis and let the Cloudtasker local server collect them
# This is the default mode unless CLOUDTASKER_ENV or RAILS_ENV or RACK_ENV is set
# to a non-development environment
config.mode = :development
endThe Cloudtasker server can then be started using:
bundle exec cloudtaskerYou can as well define a Procfile to manage the cloudtasker process via foreman. Then
No open issues yet, or sync has not completed.