Project

webhukhs

0.01
The project is in a healthy, maintained state
Webhukhs is a Rails engine for processing webhooks from various services. Engine saves webhook in database first and later processes in async job.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies
 Project Readme

Webhukhs

Webhukhs is a Rails engine for processing webhooks from various services. Engine saves webhook in database first and later processes webhook in async process.

This is a fork of cheddar-me/munster. Original project became unmaintained, so I continued it.

Installation

Install the gem and add to the application's Gemfile by executing:

$ bundle add webhukhs

If bundler is not being used to manage dependencies, install the gem by executing:

$ gem install webhukhs

Usage

Generate migrations and initializer file.

bin/rails g webhukhs:install

Mount webhukhs engine in config/routes.rb file (simple approach, with only one dynamic route showing up in rails routes)

mount Webhukhs::Engine, at: "/webhooks"

Advanced mounting approach (all webhooks paths will be shown in rails routes)

Webhukhs.configuration.active_handlers.each_key do |service_id|
  post "/webhooks/#{service_id}",
    to: "webhukhs/receive_webhooks#create",
    defaults: { service_id: service_id },
    as: :"#{service_id.tr('-', '_')}_webhook"
end

Define a class for your first handler (let's call it ExampleHandler) and inherit it from Webhukhs::BaseHandler. We recommend app/webhooks, but any place known to autoloading will do.

# app/webhooks/example_handler.rb
class ExampleHandler < Webhukhs::BaseHandler
  # Called asynchronously to process a stored webhook.
  def process(received_webhook)
    payload = JSON.parse(received_webhook.body, symbolize_names: true)
    # handle payload...
  end

  # Optional: verify the request signature before processing.
  # Return false to mark the webhook as failed_validation.
  def valid?(action_dispatch_request)
    action_dispatch_request.headers["X-Secret-Token"] == ENV["EXAMPLE_WEBHOOK_SECRET"]
  end

  # Optional: use a sender-supplied ID for deduplication.
  def extract_event_id_from_request(action_dispatch_request)
    action_dispatch_request.headers["X-Event-Id"] || SecureRandom.uuid
  end
end

Add the handler to your webhukhs.rb config file:

Webhukhs.configure do |config|
  config.active_handlers = {
    "example" => "ExampleHandler"
  }
end

Now you will be able to accept webhooks on /webhooks/example path.

Keeping an existing webhook URL

If you are moving a webhook you already receive onto Webhukhs, the senders have your current URL configured already - and it's likely to be a pain to tweak it everywhere.

Route the path you already have to the webhukhs controller, and set the service_id as a default param:

# config/routes.rb
# Was: post "/github-hook", to: "github_hook#post"
post "/github-hook", to: "webhukhs/receive_webhooks#create", defaults: {service_id: "github"}

service_id is a path segment when you mount the engine, but the controller only ever reads it out of params - so a route default does the job just as well, and the senders never learn that anything changed. The handler is configured as usual:

config.active_handlers = {"github" => "GithubHandler"}

Admin

Webhukhs comes with a read-only admin for looking at the webhooks you have received: a sortable, filterable list, and a page per webhook with its body (pretty-printed when it is JSON) and the request headers it arrived with.

Webhukhs admin listing with compact UUIDs, status filters, and received and updated timestamps

It is not reachable until you mount it:

# config/routes.rb
Rails.application.routes.draw do
  mount Webhukhs::Admin::Engine, at: "/admin/webhooks"
end

The list lives at the mount point itself (/admin/webhooks above), with each webhook at /admin/webhooks/:id.

The admin does no authentication of its own, and webhook bodies tend to carry personal data and secrets - so mount it behind whatever guards the rest of your admin. For example, with Devise:

authenticate :user, ->(user) { user.admin? } do
  mount Webhukhs::Admin::Engine, at: "/admin/webhooks"
end

or with HTTP basic auth:

webhukhs_admin = Rack::Builder.new do
  use Rack::Auth::Basic do |username, password|
    ActiveSupport::SecurityUtils.secure_compare(username, ENV.fetch("ADMIN_USER")) &
      ActiveSupport::SecurityUtils.secure_compare(password, ENV.fetch("ADMIN_PASSWORD"))
  end
  run Webhukhs::Admin::Engine
end
mount webhukhs_admin, at: "/admin/webhooks"

The admin brings its own CSS and JS, served by Assiette from inside the engine - it does not touch your asset pipeline (Propshaft, Sprockets or anything else) and needs no build step.

To try it out, run bin/dev from a checkout of this repository. It starts the app in example with some webhooks seeded, and the admin at http://localhost:3000/admin/webhukhs.

The list sorts only by ID, descending by default, using the existing primary-key index; no extra migration is needed. Click ID to switch between ascending and descending order. Other columns are not sortable, avoiding expensive sorts on large webhook tables. Handler and status filters are still available.

Retrying a webhook

A webhook that did not get processed can be put back in line, from its own page or from the listing:

The admin listing with a Retry button in every row, disabled for the webhooks that have been processed

Pressed in the listing, the button replaces that one row with what it became - the status, the timestamp and the button itself come back changed and the page stays where it is. On the webhook's own page it reloads the page. Without JavaScript the same form submits normally and lands on the webhook, so nothing here depends on the browser being able to run anything.

Retrying takes the webhook back to received and enqueues it exactly as a fresh delivery would be, so it goes through the same handler validation and processing as the first attempt. That makes the button worth having mostly for the delivery your side refused: a signature secret that had not been configured yet, a handler that raised on something it has since learned to cope with.

The button is enabled for the three states a webhook comes to rest in without having been processed

  • error, failed_validation and skipped - and disabled for processed, as well as for received and processing, which are already on their way. Webhukhs::ReceivedWebhook#retryable? answers the same question in code, and #retry! does it:
webhook = Webhukhs::ReceivedWebhook.find(id)
webhook.retry! if webhook.retryable?

#retry! raises StateMachineEnum::InvalidTransition for a webhook that cannot be retried, rather than quietly enqueueing a second run of something that already succeeded.

UUIDs are abbreviated in the list, for example 01a1..6e51; hover over the ID to see the full value. Detail pages and copied IDs retain the full UUID.

We strongly recommend against UUIDv4 primary keys. Use UUIDv7 or auto-incrementing integer IDs instead. UUIDv4 IDs are random, so sorting by ID does not reflect creation time, and inserts have poorer index locality. Webhukhs generates UUIDv7 when Ruby supports it, but falls back to UUIDv4 otherwise; use a Ruby with UUIDv7 support if you need UUID primary keys.

More Examples

  • example folder contains a demo app with the engine and the admin fully configured - run it with bin/dev.
  • We provide a number of webhook handlers which demonstrate certain features of Webhukhs. You will find them in handler-examples.

Requirements

  • Ruby >= 3.1
  • Rails >= 7.2

Error reporter

This gem uses Rails common error reporter to report any possible error to services like Honeybadger, Appsignal, Sentry and etc. Most of those services already support this common interface, if not - it's not that hard to add this support on your own.

It's possible to provide additional context for every error. e.g.

Webhukhs.configure do |config|
  config.error_context = { appsignal: { namespace: "webhooks" } }
end

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake test to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

Coverage tooling requires Ruby 3.3 or newer. CI checks 100% line and branch coverage, both overall and per file. To generate the same report locally, including which tests exercise each line:

SIMPLECOV=1 bundle exec rake test
bundle exec simplecov open
bundle exec simplecov tests lib/webhukhs/jobs/processing_job.rb

Run mutation testing with bundle exec mutant run --fail-fast. Mutant 0.17+ uses the recorded test map to select and rank tests for each subject; without a usable recording, it falls back to the suite's cover declarations. Regenerate the recording with the full coverage-enabled suite above after changing source or tests. SimpleCov is disabled during mutation runs so they do not overwrite the recording. Mutation CI records coverage first and requires map-based selection with --selection context_map.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and the created tag, and push the .gem file to rubygems.org.

The admin also has a click-through test in a real (headless) Chrome, which rake test leaves out. Run it with bundle exec rake test:browser - it needs Chrome or Chromium installed, and finds it by itself or through BROWSER_PATH.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/skatkov/webhukhs.

License

The gem is available as open source under the terms of the MIT License.