项目作者: mattes

项目描述 :
Rails on Google Cloud Run
高级语言: Ruby
项目地址: git://github.com/mattes/google_cloud_run.git
创建时间: 2021-02-12T07:08:21Z
项目社区:https://github.com/mattes/google_cloud_run

开源协议:MIT License

下载


Rails on Google Cloud Run

  • Logging
  • Error Reporting
  • Active Job Adapter via Cloud Tasks
  • Minor patches for better compatibility
  • Works with Ruby 3 and Rails 6

Usage

  1. logger.info "Hello World"
  2. logger.info do
  3. "Expensive logging operation, only run when logged"
  4. end
  5. logger.info "Labels work, too!", my_label: "works", another_one: "great"

All Google Cloud Logging Severities are supported:

  1. logger.default (or logger.unknown) - The log entry has no assigned severity level.
  2. logger.debug - Debug or trace information.
  3. logger.info - Routine information, such as ongoing status or performance.
  4. logger.notice - Normal but significant events, such as start up, shut down, or a configuration change.
  5. logger.warning (or logger.warn) - Warning events might cause problems.
  6. logger.error - Error events are likely to cause problems.
  7. logger.critical (or logger.fatal) - Critical events cause more severe problems or outages.
  8. logger.alert - A person must take an action immediately.
  9. logger.emergency - One or more systems are unusable.

Installation

Add the gem to your Gemfile and run bundle install.

  1. # Gemfile
  2. group :production do
  3. gem 'google_cloud_run'
  4. end

In your production config:

  1. # config/environments/production.rb
  2. config.log_level = :g_notice
  3. config.logger = GoogleCloudRun::Logger.new
  4. config.active_job.queue_adapter = :google_cloudrun_tasks
  5. config.google_cloudrun.job_queue_default_region = "us-central1"
  6. config.google_cloudrun.job_callback_url = "https://your-domain.com/rails/google_cloudrun/job_callback"

Set the default queue:

  1. # app/jobs/application_job.rb
  2. queue_as "my-queue"
  3. # or if `config.google_cloudrun.job_queue_default_region` isn't set:
  4. queue_as "us-central1/my-queue"
  1. # config/environments/production.rb
  2. config.action_mailer.deliver_later_queue_name = "my-queue" # or "us-central1/my-queue"

In the default production config, the logger is wrapped around
a ENV["RAILS_LOG_TO_STDOUT"].present? block. I usually just
remove this block so I don’t have to actually set this ENV var.

You can also remove config.log_formatter and config.log_tags as we don’t need it anymore.

I recommend logging :g_notice and higher. Rails logs a lot of noise when logging
:info and higher.

Configuration

You can change more settings in config/environments/production.rb. See below
for the default configuration.

  1. # Enable Google Cloud Logging
  2. config.google_cloudrun.logger = true
  3. # Set output (STDERR or STDOUT)
  4. config.google_cloudrun.out = STDERR
  5. # Add source location (file, line number, method) to each log
  6. config.google_cloudrun.logger_source_location = true
  7. # Run Proc to assign current user as label to each log
  8. config.google_cloudrun.logger_user = nil
  9. # Enable Error Reporting
  10. config.google_cloudrun.error_reporting = true
  11. # Assign a default severity level to exceptions
  12. config.google_cloudrun.error_reporting_exception_severity = :critical
  13. # Run Proc to assign current user to Error Report
  14. config.google_cloudrun.error_reporting_user = nil
  15. # Turn logs into error reports for this severity and higher.
  16. # Set to nil to disable.
  17. config.google_cloudrun.error_reporting_level = :error
  18. # When log is turned into error report, discard the original
  19. # log and only report the error.
  20. # Set to false to log and report the error at the same time.
  21. config.google_cloudrun.error_reporting_discard_log = true
  22. # Don't log or error report the following exceptions,
  23. # because Cloud Run will create access logs for us already.
  24. config.google_cloudrun.silence_exceptions = [
  25. ActionController::RoutingError,
  26. ActionController::MethodNotAllowed,
  27. ActionController::UnknownHttpMethod,
  28. ActionController::NotImplemented,
  29. ActionController::UnknownFormat,
  30. ActionController::BadRequest,
  31. ActionController::ParameterMissing,
  32. ]
  33. # Set Rails' request id to the trace id from X-Cloud-Trace-Context header
  34. # as set by Cloud Run.
  35. config.google_cloudrun.patch_request_id = true
  36. # Enable Jobs via Cloud Tasks
  37. config.google_cloudrun.jobs = true
  38. # Set the default Google Cloud Task region, i.e. us-central1
  39. config.google_cloudrun.job_queue_default_region = nil
  40. # Google Cloud Tasks will call this url to execute the job
  41. config.google_cloudrun.job_callback_url = nil # required, see above
  42. # The default route for the callback url.
  43. config.google_cloudrun.job_callback_path = "/rails/google_cloudrun/job_callback"
  44. # Time for a job to run in seconds, default is 30min.
  45. # Use `timeout_after 5.minutes` to configure a job individually.
  46. config.google_cloudrun.job_timeout_sec = 1800 # (min 15s, max 30m)

Both error_reporting_user and logger_user expect a Proc like this:

  1. config.google_cloudrun.logger_user = Proc.new do |request|
  2. # extract and return user id from request, example:
  3. request.try { cookie_jar.encrypted[:user_id] }
  4. end

An example job:

  1. class MyJob < ApplicationJob
  2. queue_as "us-central1/urgent"
  3. timeout_after 1.minute # min 15s, max 30m, overrides config.google_cloudrun.job_timeout_sec
  4. def perform(*args)
  5. # Do something
  6. end
  7. end

Cloud Task considerations

  • Cloud Tasks are a better fit than Google Pub/Sub.
    Read more
  • I’d recommend to create two different Cloud Run services.
    One for HTTP requests (aka Heroku Dynos) and another service
    for jobs (aka Heroku Workers). Set the Request Timeout for
    the request-bound service to something like 15s, and for workers
    to 1800s or match config.google_cloudrun.job_timeout_sec.
  • Cloud Task execution calls are authenticated with a Google-issued
    OIDC token. So even though /rails/google_cloudrun/job_callback is publicly
    available, without a valid token, no job will be executed.
  • Cloud Task job processing is async. It supports multiple queues. Delayed jobs
    are natively supported through Cloud Task. Priority jobs are not supported, use
    different queues for that, i.e. “urgent”, or “low-priority”. Timeouts can be set
    globally or per job-basis (min 15s, max 30m).
    Retries are natively supported by Cloud Tasks.