├── .gitattributes ├── .gitignore ├── .ruby-version ├── Gemfile ├── Gemfile.lock ├── README.md ├── Rakefile ├── app ├── controllers │ ├── application_controller.rb │ └── concerns │ │ └── .keep ├── jobs │ └── application_job.rb ├── mailers │ └── application_mailer.rb ├── models │ ├── application_record.rb │ ├── concerns │ │ └── .keep │ ├── webhook_endpoint.rb │ └── webhook_event.rb ├── services │ └── broadcast_webhook_service.rb ├── views │ └── layouts │ │ ├── mailer.html.erb │ │ └── mailer.text.erb └── workers │ └── webhook_worker.rb ├── bin ├── bundle ├── rails ├── rake ├── setup └── spring ├── config.ru ├── config ├── application.rb ├── boot.rb ├── credentials.yml.enc ├── database.yml ├── environment.rb ├── environments │ ├── development.rb │ ├── production.rb │ └── test.rb ├── initializers │ ├── application_controller_renderer.rb │ ├── backtrace_silencers.rb │ ├── cors.rb │ ├── filter_parameter_logging.rb │ ├── inflections.rb │ ├── mime_types.rb │ └── wrap_parameters.rb ├── locales │ └── en.yml ├── puma.rb ├── routes.rb └── spring.rb ├── db ├── migrate │ ├── 20210614145326_create_webhook_endpoints.rb │ ├── 20210614160959_create_webhook_events.rb │ ├── 20210614162001_add_enabled_to_webhook_endpoints.rb │ ├── 20210614165853_add_subscriptions_to_webhook_endpoints.rb │ └── 20210614170512_add_response_to_webhook_events.rb ├── schema.rb └── seeds.rb ├── lib └── tasks │ └── .keep ├── log └── .keep ├── public └── robots.txt ├── test ├── controllers │ └── .keep ├── fixtures │ └── files │ │ └── .keep ├── integration │ └── .keep ├── mailers │ └── .keep ├── models │ └── .keep └── test_helper.rb ├── tmp ├── .keep └── pids │ └── .keep └── vendor └── .keep /.gitattributes: -------------------------------------------------------------------------------- 1 | # See https://git-scm.com/docs/gitattributes for more about git attribute files. 2 | 3 | # Mark the database schema as having been generated. 4 | db/schema.rb linguist-generated 5 | 6 | 7 | # Mark any vendored files as having been vendored. 8 | vendor/* linguist-vendored 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files for more about ignoring files. 2 | # 3 | # If you find yourself ignoring temporary files generated by your text editor 4 | # or operating system, you probably want to add a global ignore instead: 5 | # git config --global core.excludesfile '~/.gitignore_global' 6 | 7 | # Ignore bundler config. 8 | /.bundle 9 | 10 | # Ignore all logfiles and tempfiles. 11 | /log/* 12 | /tmp/* 13 | !/log/.keep 14 | !/tmp/.keep 15 | 16 | # Ignore pidfiles, but keep the directory. 17 | /tmp/pids/* 18 | !/tmp/pids/ 19 | !/tmp/pids/.keep 20 | 21 | .byebug_history 22 | 23 | # Ignore master key for decrypting credentials and more. 24 | /config/master.key 25 | -------------------------------------------------------------------------------- /.ruby-version: -------------------------------------------------------------------------------- 1 | ruby-2.7.3 2 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | git_source(:github) { |repo| "https://github.com/#{repo}.git" } 3 | 4 | ruby '2.7.3' 5 | 6 | # Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main' 7 | gem 'rails', '~> 6.1.3', '>= 6.1.3.2' 8 | # Use postgresql as the database for Active Record 9 | gem 'pg', '~> 1.1' 10 | # Use Puma as the app server 11 | gem 'puma', '~> 5.0' 12 | # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder 13 | # gem 'jbuilder', '~> 2.7' 14 | # Use Active Model has_secure_password 15 | # gem 'bcrypt', '~> 3.1.7' 16 | 17 | gem 'sidekiq' 18 | gem 'redis' 19 | gem 'http' 20 | 21 | # Reduces boot times through caching; required in config/boot.rb 22 | gem 'bootsnap', '>= 1.4.4', require: false 23 | 24 | # Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible 25 | # gem 'rack-cors' 26 | 27 | group :development, :test do 28 | # Call 'byebug' anywhere in the code to stop execution and get a debugger console 29 | gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] 30 | end 31 | 32 | group :development do 33 | gem 'listen', '~> 3.3' 34 | # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring 35 | gem 'spring' 36 | end 37 | 38 | # Windows does not include zoneinfo files, so bundle the tzinfo-data gem 39 | gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] 40 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | actioncable (6.1.3.2) 5 | actionpack (= 6.1.3.2) 6 | activesupport (= 6.1.3.2) 7 | nio4r (~> 2.0) 8 | websocket-driver (>= 0.6.1) 9 | actionmailbox (6.1.3.2) 10 | actionpack (= 6.1.3.2) 11 | activejob (= 6.1.3.2) 12 | activerecord (= 6.1.3.2) 13 | activestorage (= 6.1.3.2) 14 | activesupport (= 6.1.3.2) 15 | mail (>= 2.7.1) 16 | actionmailer (6.1.3.2) 17 | actionpack (= 6.1.3.2) 18 | actionview (= 6.1.3.2) 19 | activejob (= 6.1.3.2) 20 | activesupport (= 6.1.3.2) 21 | mail (~> 2.5, >= 2.5.4) 22 | rails-dom-testing (~> 2.0) 23 | actionpack (6.1.3.2) 24 | actionview (= 6.1.3.2) 25 | activesupport (= 6.1.3.2) 26 | rack (~> 2.0, >= 2.0.9) 27 | rack-test (>= 0.6.3) 28 | rails-dom-testing (~> 2.0) 29 | rails-html-sanitizer (~> 1.0, >= 1.2.0) 30 | actiontext (6.1.3.2) 31 | actionpack (= 6.1.3.2) 32 | activerecord (= 6.1.3.2) 33 | activestorage (= 6.1.3.2) 34 | activesupport (= 6.1.3.2) 35 | nokogiri (>= 1.8.5) 36 | actionview (6.1.3.2) 37 | activesupport (= 6.1.3.2) 38 | builder (~> 3.1) 39 | erubi (~> 1.4) 40 | rails-dom-testing (~> 2.0) 41 | rails-html-sanitizer (~> 1.1, >= 1.2.0) 42 | activejob (6.1.3.2) 43 | activesupport (= 6.1.3.2) 44 | globalid (>= 0.3.6) 45 | activemodel (6.1.3.2) 46 | activesupport (= 6.1.3.2) 47 | activerecord (6.1.3.2) 48 | activemodel (= 6.1.3.2) 49 | activesupport (= 6.1.3.2) 50 | activestorage (6.1.3.2) 51 | actionpack (= 6.1.3.2) 52 | activejob (= 6.1.3.2) 53 | activerecord (= 6.1.3.2) 54 | activesupport (= 6.1.3.2) 55 | marcel (~> 1.0.0) 56 | mini_mime (~> 1.0.2) 57 | activesupport (6.1.3.2) 58 | concurrent-ruby (~> 1.0, >= 1.0.2) 59 | i18n (>= 1.6, < 2) 60 | minitest (>= 5.1) 61 | tzinfo (~> 2.0) 62 | zeitwerk (~> 2.3) 63 | addressable (2.7.0) 64 | public_suffix (>= 2.0.2, < 5.0) 65 | bootsnap (1.7.5) 66 | msgpack (~> 1.0) 67 | builder (3.2.4) 68 | byebug (11.1.3) 69 | concurrent-ruby (1.1.9) 70 | connection_pool (2.2.5) 71 | crass (1.0.6) 72 | domain_name (0.5.20190701) 73 | unf (>= 0.0.5, < 1.0.0) 74 | erubi (1.10.0) 75 | ffi (1.15.1) 76 | ffi-compiler (1.0.1) 77 | ffi (>= 1.0.0) 78 | rake 79 | globalid (0.4.2) 80 | activesupport (>= 4.2.0) 81 | http (5.0.0) 82 | addressable (~> 2.3) 83 | http-cookie (~> 1.0) 84 | http-form_data (~> 2.2) 85 | llhttp-ffi (~> 0.0.1) 86 | http-cookie (1.0.4) 87 | domain_name (~> 0.5) 88 | http-form_data (2.3.0) 89 | i18n (1.8.10) 90 | concurrent-ruby (~> 1.0) 91 | listen (3.5.1) 92 | rb-fsevent (~> 0.10, >= 0.10.3) 93 | rb-inotify (~> 0.9, >= 0.9.10) 94 | llhttp-ffi (0.0.1) 95 | ffi-compiler (~> 1.0) 96 | rake (~> 13.0) 97 | loofah (2.10.0) 98 | crass (~> 1.0.2) 99 | nokogiri (>= 1.5.9) 100 | mail (2.7.1) 101 | mini_mime (>= 0.1.1) 102 | marcel (1.0.1) 103 | method_source (1.0.0) 104 | mini_mime (1.0.3) 105 | mini_portile2 (2.5.3) 106 | minitest (5.14.4) 107 | msgpack (1.4.2) 108 | nio4r (2.5.7) 109 | nokogiri (1.11.7) 110 | mini_portile2 (~> 2.5.0) 111 | racc (~> 1.4) 112 | pg (1.2.3) 113 | public_suffix (4.0.6) 114 | puma (5.3.2) 115 | nio4r (~> 2.0) 116 | racc (1.5.2) 117 | rack (2.2.3) 118 | rack-test (1.1.0) 119 | rack (>= 1.0, < 3) 120 | rails (6.1.3.2) 121 | actioncable (= 6.1.3.2) 122 | actionmailbox (= 6.1.3.2) 123 | actionmailer (= 6.1.3.2) 124 | actionpack (= 6.1.3.2) 125 | actiontext (= 6.1.3.2) 126 | actionview (= 6.1.3.2) 127 | activejob (= 6.1.3.2) 128 | activemodel (= 6.1.3.2) 129 | activerecord (= 6.1.3.2) 130 | activestorage (= 6.1.3.2) 131 | activesupport (= 6.1.3.2) 132 | bundler (>= 1.15.0) 133 | railties (= 6.1.3.2) 134 | sprockets-rails (>= 2.0.0) 135 | rails-dom-testing (2.0.3) 136 | activesupport (>= 4.2.0) 137 | nokogiri (>= 1.6) 138 | rails-html-sanitizer (1.3.0) 139 | loofah (~> 2.3) 140 | railties (6.1.3.2) 141 | actionpack (= 6.1.3.2) 142 | activesupport (= 6.1.3.2) 143 | method_source 144 | rake (>= 0.8.7) 145 | thor (~> 1.0) 146 | rake (13.0.3) 147 | rb-fsevent (0.11.0) 148 | rb-inotify (0.10.1) 149 | ffi (~> 1.0) 150 | redis (4.3.1) 151 | sidekiq (6.2.1) 152 | connection_pool (>= 2.2.2) 153 | rack (~> 2.0) 154 | redis (>= 4.2.0) 155 | spring (2.1.1) 156 | sprockets (4.0.2) 157 | concurrent-ruby (~> 1.0) 158 | rack (> 1, < 3) 159 | sprockets-rails (3.2.2) 160 | actionpack (>= 4.0) 161 | activesupport (>= 4.0) 162 | sprockets (>= 3.0.0) 163 | thor (1.1.0) 164 | tzinfo (2.0.4) 165 | concurrent-ruby (~> 1.0) 166 | unf (0.1.4) 167 | unf_ext 168 | unf_ext (0.0.7.7) 169 | websocket-driver (0.7.5) 170 | websocket-extensions (>= 0.1.0) 171 | websocket-extensions (0.1.5) 172 | zeitwerk (2.4.2) 173 | 174 | PLATFORMS 175 | ruby 176 | 177 | DEPENDENCIES 178 | bootsnap (>= 1.4.4) 179 | byebug 180 | http 181 | listen (~> 3.3) 182 | pg (~> 1.1) 183 | puma (~> 5.0) 184 | rails (~> 6.1.3, >= 6.1.3.2) 185 | redis 186 | sidekiq 187 | spring 188 | tzinfo-data 189 | 190 | RUBY VERSION 191 | ruby 2.7.3p183 192 | 193 | BUNDLED WITH 194 | 2.1.4 195 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Building a Webhook System with Rails and Sidekiq 2 | 3 | See: https://keygen.sh/blog/how-to-build-a-webhook-system-in-rails-using-sidekiq/ 4 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require_relative "config/application" 5 | 6 | Rails.application.load_tasks 7 | -------------------------------------------------------------------------------- /app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::API 2 | end 3 | -------------------------------------------------------------------------------- /app/controllers/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/app/controllers/concerns/.keep -------------------------------------------------------------------------------- /app/jobs/application_job.rb: -------------------------------------------------------------------------------- 1 | class ApplicationJob < ActiveJob::Base 2 | # Automatically retry jobs that encountered a deadlock 3 | # retry_on ActiveRecord::Deadlocked 4 | 5 | # Most jobs are safe to ignore if the underlying records are no longer available 6 | # discard_on ActiveJob::DeserializationError 7 | end 8 | -------------------------------------------------------------------------------- /app/mailers/application_mailer.rb: -------------------------------------------------------------------------------- 1 | class ApplicationMailer < ActionMailer::Base 2 | default from: 'from@example.com' 3 | layout 'mailer' 4 | end 5 | -------------------------------------------------------------------------------- /app/models/application_record.rb: -------------------------------------------------------------------------------- 1 | class ApplicationRecord < ActiveRecord::Base 2 | self.abstract_class = true 3 | end 4 | -------------------------------------------------------------------------------- /app/models/concerns/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/app/models/concerns/.keep -------------------------------------------------------------------------------- /app/models/webhook_endpoint.rb: -------------------------------------------------------------------------------- 1 | class WebhookEndpoint < ApplicationRecord 2 | has_many :webhook_events, inverse_of: :webhook_endpoint 3 | 4 | validates :subscriptions, length: { minimum: 1 }, presence: true 5 | validates :url, presence: true 6 | 7 | scope :enabled, -> { where(enabled: true) } 8 | 9 | def subscribed?(event) 10 | (subscriptions & ['*', event]).any? 11 | end 12 | 13 | def disable! 14 | update!(enabled: false) 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /app/models/webhook_event.rb: -------------------------------------------------------------------------------- 1 | class WebhookEvent < ApplicationRecord 2 | belongs_to :webhook_endpoint, inverse_of: :webhook_events 3 | 4 | validates :event, presence: true 5 | validates :payload, presence: true 6 | 7 | def deconstruct_keys(keys) 8 | { 9 | webhook_endpoint: { url: webhook_endpoint.url }, 10 | event: event, 11 | payload: payload, 12 | response: response.symbolize_keys, 13 | } 14 | end 15 | end 16 | -------------------------------------------------------------------------------- /app/services/broadcast_webhook_service.rb: -------------------------------------------------------------------------------- 1 | class BroadcastWebhookService 2 | def self.call(event:, payload:) 3 | new(event: event, payload: payload).call 4 | end 5 | 6 | def call 7 | WebhookEndpoint.enabled.find_each do |webhook_endpoint| 8 | next unless 9 | webhook_endpoint.subscribed?(event) 10 | 11 | webhook_event = WebhookEvent.create!( 12 | webhook_endpoint: webhook_endpoint, 13 | event: event, 14 | payload: payload, 15 | ) 16 | 17 | WebhookWorker.perform_async(webhook_event.id) 18 | end 19 | end 20 | 21 | private 22 | 23 | attr_reader :event, :payload 24 | 25 | def initialize(event:, payload:) 26 | @event = event 27 | @payload = payload 28 | end 29 | end 30 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | <%= yield %> 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/views/layouts/mailer.text.erb: -------------------------------------------------------------------------------- 1 | <%= yield %> 2 | -------------------------------------------------------------------------------- /app/workers/webhook_worker.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'http.rb' 4 | 5 | class WebhookWorker 6 | include Sidekiq::Worker 7 | 8 | sidekiq_options retry: 10, dead: false 9 | sidekiq_retry_in do |retry_count| 10 | # Exponential backoff, with a random 30-second to 10-minute "jitter" 11 | # added in to help spread out any webhook "bursts." 12 | jitter = rand(30.seconds..10.minutes).to_i 13 | 14 | (retry_count ** 5) + jitter 15 | end 16 | 17 | def perform(webhook_event_id) 18 | webhook_event = WebhookEvent.find_by(id: webhook_event_id) 19 | return if 20 | webhook_event.nil? 21 | 22 | webhook_endpoint = webhook_event.webhook_endpoint 23 | return if 24 | webhook_endpoint.nil? 25 | 26 | return unless 27 | webhook_endpoint.subscribed?(webhook_event.event) && 28 | webhook_endpoint.enabled? 29 | 30 | # Send the webhook request with a 30 second timeout. 31 | response = HTTP.timeout(30) 32 | .headers( 33 | 'User-Agent' => 'rails_webhook_system/1.0', 34 | 'Content-Type' => 'application/json', 35 | ) 36 | .post( 37 | webhook_endpoint.url, 38 | body: { 39 | event: webhook_event.event, 40 | payload: webhook_event.payload, 41 | }.to_json 42 | ) 43 | 44 | # Store the webhook response. 45 | webhook_event.update(response: { 46 | headers: response.headers.to_h, 47 | code: response.code.to_i, 48 | body: response.body.to_s, 49 | }) 50 | 51 | # Exit early if the webhook was successful. 52 | if response.status.success? 53 | logger.info "[webhook_worker] Delivered webhook event: type=#{webhook_event.event} event=#{webhook_event.id} endpoint=#{webhook_endpoint.id} url=#{webhook_endpoint.url} code=#{response.code}" 54 | 55 | return 56 | end 57 | 58 | # Handle response errors. 59 | case webhook_event 60 | in webhook_endpoint: { url: /\.ngrok\.io/ }, 61 | response: { code: 404, body: /tunnel .+?\.ngrok\.io not found/i } 62 | logger.warn "[webhook_worker] Deleting dead ngrok endpoint: type=#{webhook_event.event} event=#{webhook_event.id} endpoint=#{webhook_endpoint.id} url=#{webhook_endpoint.url} code=#{response.code}" 63 | 64 | # Automatically delete dead ngrok tunnel endpoints. This error likely 65 | # means that the developer forgot to remove their temporary ngrok 66 | # webhook endpoint, seeing as it no longer exists. 67 | webhook_endpoint.destroy! 68 | in webhook_endpoint: { url: /\.ngrok\.io/ }, 69 | response: { code: 502 } 70 | logger.warn "[webhook_worker] Retrying unresponsive ngrok endpoint: type=#{webhook_event.event} event=#{webhook_event.id} endpoint=#{webhook_endpoint.id} url=#{webhook_endpoint.url} code=#{response.code}" 71 | 72 | # The bad gateway error usually means that the tunnel is still open 73 | # but the local server is no longer responding for any number of 74 | # reasons. We're going to automatically retry. 75 | raise FailedRequestError 76 | in webhook_endpoint: { url: /\.ngrok\.io/ }, 77 | response: { code: 504 } 78 | logger.warn "[webhook_worker] Disabling bad ngrok endpoint: type=#{webhook_event.event} event=#{webhook_event.id} endpoint=#{webhook_endpoint.id} url=#{webhook_endpoint.url} code=#{response.code}" 79 | 80 | # Automatically disable these since the endpoint is likely an ngrok 81 | # "stable" URL, but it's not currently running. To save bandwidth, 82 | # we do not want to automatically retry. 83 | webhook_endpoint.disable! 84 | else 85 | logger.warn "[webhook_worker] Failed webhook event: type=#{webhook_event.event} event=#{webhook_event.id} endpoint=#{webhook_endpoint.id} url=#{webhook_endpoint.url} code=#{response.code}" 86 | 87 | # Raise a failed request error and let Sidekiq handle retrying. 88 | raise FailedRequestError 89 | end 90 | rescue OpenSSL::SSL::SSLError 91 | logger.warn "[webhook_worker] TLS error for webhook event: type=#{webhook_event.event} event=#{webhook_event.id} endpoint=#{webhook_endpoint.id} url=#{webhook_endpoint.url} code=TLS_ERROR" 92 | 93 | # Since TLS issues may be due to an expired cert, we'll continue retrying 94 | # since the issue may get resolved within the 3 day retry window. This 95 | # may be a good place to send an alert to the endpoint owner. 96 | webhook_event.update(response: { error: 'TLS_ERROR' }) 97 | 98 | # Signal the webhook for retry. 99 | raise FailedRequestError 100 | rescue HTTP::ConnectionError 101 | logger.warn "[webhook_worker] Connection error for webhook event: type=#{webhook_event.event} event=#{webhook_event.id} endpoint=#{webhook_endpoint.id} url=#{webhook_endpoint.url} code=CONNECTION_ERROR" 102 | 103 | # This error usually means DNS issues. To save us the bandwidth, 104 | # we're going to disable the endpoint. This would also be a good 105 | # location to send an alert to the endpoint owner. 106 | webhook_event.update(response: { error: 'CONNECTION_ERROR' }) 107 | 108 | # Disable the problem endpoint. 109 | webhook_endpoint.disable! 110 | rescue HTTP::TimeoutError 111 | logger.warn "[webhook_worker] Timeout for webhook event: type=#{webhook_event.event} event=#{webhook_event.id} endpoint=#{webhook_endpoint.id} url=#{webhook_endpoint.url} code=TIMEOUT_ERROR" 112 | 113 | # This error means the webhook endpoint timed out. We can either 114 | # raise a failed request error to trigger a retry, or leave it 115 | # as-is and consider timeouts terminal. We'll do the latter. 116 | webhook_event.update(response: { error: 'TIMEOUT_ERROR' }) 117 | end 118 | 119 | private 120 | 121 | def logger 122 | Sidekiq.logger 123 | end 124 | 125 | # General failed request error that we're going to use to signal 126 | # Sidekiq to retry our webhook worker. 127 | class FailedRequestError < StandardError; end 128 | end 129 | -------------------------------------------------------------------------------- /bin/bundle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | # 5 | # This file was generated by Bundler. 6 | # 7 | # The application 'bundle' is installed as part of a gem, and 8 | # this file is here to facilitate running it. 9 | # 10 | 11 | require "rubygems" 12 | 13 | m = Module.new do 14 | module_function 15 | 16 | def invoked_as_script? 17 | File.expand_path($0) == File.expand_path(__FILE__) 18 | end 19 | 20 | def env_var_version 21 | ENV["BUNDLER_VERSION"] 22 | end 23 | 24 | def cli_arg_version 25 | return unless invoked_as_script? # don't want to hijack other binstubs 26 | return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` 27 | bundler_version = nil 28 | update_index = nil 29 | ARGV.each_with_index do |a, i| 30 | if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN 31 | bundler_version = a 32 | end 33 | next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ 34 | bundler_version = $1 35 | update_index = i 36 | end 37 | bundler_version 38 | end 39 | 40 | def gemfile 41 | gemfile = ENV["BUNDLE_GEMFILE"] 42 | return gemfile if gemfile && !gemfile.empty? 43 | 44 | File.expand_path("../../Gemfile", __FILE__) 45 | end 46 | 47 | def lockfile 48 | lockfile = 49 | case File.basename(gemfile) 50 | when "gems.rb" then gemfile.sub(/\.rb$/, gemfile) 51 | else "#{gemfile}.lock" 52 | end 53 | File.expand_path(lockfile) 54 | end 55 | 56 | def lockfile_version 57 | return unless File.file?(lockfile) 58 | lockfile_contents = File.read(lockfile) 59 | return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ 60 | Regexp.last_match(1) 61 | end 62 | 63 | def bundler_version 64 | @bundler_version ||= 65 | env_var_version || cli_arg_version || 66 | lockfile_version 67 | end 68 | 69 | def bundler_requirement 70 | return "#{Gem::Requirement.default}.a" unless bundler_version 71 | 72 | bundler_gem_version = Gem::Version.new(bundler_version) 73 | 74 | requirement = bundler_gem_version.approximate_recommendation 75 | 76 | return requirement unless Gem::Version.new(Gem::VERSION) < Gem::Version.new("2.7.0") 77 | 78 | requirement += ".a" if bundler_gem_version.prerelease? 79 | 80 | requirement 81 | end 82 | 83 | def load_bundler! 84 | ENV["BUNDLE_GEMFILE"] ||= gemfile 85 | 86 | activate_bundler 87 | end 88 | 89 | def activate_bundler 90 | gem_error = activation_error_handling do 91 | gem "bundler", bundler_requirement 92 | end 93 | return if gem_error.nil? 94 | require_error = activation_error_handling do 95 | require "bundler/version" 96 | end 97 | return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) 98 | warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" 99 | exit 42 100 | end 101 | 102 | def activation_error_handling 103 | yield 104 | nil 105 | rescue StandardError, LoadError => e 106 | e 107 | end 108 | end 109 | 110 | m.load_bundler! 111 | 112 | if m.invoked_as_script? 113 | load Gem.bin_path("bundler", "bundle") 114 | end 115 | -------------------------------------------------------------------------------- /bin/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | load File.expand_path("spring", __dir__) 3 | APP_PATH = File.expand_path('../config/application', __dir__) 4 | require_relative "../config/boot" 5 | require "rails/commands" 6 | -------------------------------------------------------------------------------- /bin/rake: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | load File.expand_path("spring", __dir__) 3 | require_relative "../config/boot" 4 | require "rake" 5 | Rake.application.run 6 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | require "fileutils" 3 | 4 | # path to your application root. 5 | APP_ROOT = File.expand_path('..', __dir__) 6 | 7 | def system!(*args) 8 | system(*args) || abort("\n== Command #{args} failed ==") 9 | end 10 | 11 | FileUtils.chdir APP_ROOT do 12 | # This script is a way to set up or update your development environment automatically. 13 | # This script is idempotent, so that you can run it at any time and get an expectable outcome. 14 | # Add necessary setup steps to this file. 15 | 16 | puts '== Installing dependencies ==' 17 | system! 'gem install bundler --conservative' 18 | system('bundle check') || system!('bundle install') 19 | 20 | # puts "\n== Copying sample files ==" 21 | # unless File.exist?('config/database.yml') 22 | # FileUtils.cp 'config/database.yml.sample', 'config/database.yml' 23 | # end 24 | 25 | puts "\n== Preparing database ==" 26 | system! 'bin/rails db:prepare' 27 | 28 | puts "\n== Removing old logs and tempfiles ==" 29 | system! 'bin/rails log:clear tmp:clear' 30 | 31 | puts "\n== Restarting application server ==" 32 | system! 'bin/rails restart' 33 | end 34 | -------------------------------------------------------------------------------- /bin/spring: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | if !defined?(Spring) && [nil, "development", "test"].include?(ENV["RAILS_ENV"]) 3 | gem "bundler" 4 | require "bundler" 5 | 6 | # Load Spring without loading other gems in the Gemfile, for speed. 7 | Bundler.locked_gems&.specs&.find { |spec| spec.name == "spring" }&.tap do |spring| 8 | Gem.use_paths Gem.dir, Bundler.bundle_path.to_s, *Gem.path 9 | gem "spring", spring.version 10 | require "spring/binstub" 11 | rescue Gem::LoadError 12 | # Ignore when Spring is not installed. 13 | end 14 | end 15 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require_relative "config/environment" 4 | 5 | run Rails.application 6 | Rails.application.load_server 7 | -------------------------------------------------------------------------------- /config/application.rb: -------------------------------------------------------------------------------- 1 | require_relative "boot" 2 | 3 | require "rails" 4 | # Pick the frameworks you want: 5 | require "active_model/railtie" 6 | require "active_job/railtie" 7 | require "active_record/railtie" 8 | # require "active_storage/engine" 9 | require "action_controller/railtie" 10 | require "action_mailer/railtie" 11 | # require "action_mailbox/engine" 12 | # require "action_text/engine" 13 | require "action_view/railtie" 14 | # require "action_cable/engine" 15 | # require "sprockets/railtie" 16 | require "rails/test_unit/railtie" 17 | 18 | # Require the gems listed in Gemfile, including any gems 19 | # you've limited to :test, :development, or :production. 20 | Bundler.require(*Rails.groups) 21 | 22 | module Rails6WebhookSystem 23 | class Application < Rails::Application 24 | # Initialize configuration defaults for originally generated Rails version. 25 | config.load_defaults 6.1 26 | 27 | # Configuration for the application, engines, and railties goes here. 28 | # 29 | # These settings can be overridden in specific environments using the files 30 | # in config/environments, which are processed later. 31 | # 32 | # config.time_zone = "Central Time (US & Canada)" 33 | # config.eager_load_paths << Rails.root.join("extras") 34 | 35 | # Only loads a smaller set of middleware suitable for API only apps. 36 | # Middleware like session, flash, cookies can be added back manually. 37 | # Skip views, helpers and assets when generating a new resource. 38 | config.api_only = true 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /config/boot.rb: -------------------------------------------------------------------------------- 1 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) 2 | 3 | require "bundler/setup" # Set up gems listed in the Gemfile. 4 | require "bootsnap/setup" # Speed up boot time by caching expensive operations. 5 | -------------------------------------------------------------------------------- /config/credentials.yml.enc: -------------------------------------------------------------------------------- 1 | Rbnic/Cjl746ppD7nLymqTmCDFmB2TTRASBsdaiQL+zFs3Ftgxen4a196STiuP/4SclP5TJ1iVfu8X7MEtFmMbbbLlH50ZHptKsgqpsKyCxYs2RPOF+Jp61tdLTrt5utu6NUzVKrOx7E6aokUeyls96zzC/YOXzmY/Z7P3tOADU55dIwht7LW2YZmYjJQtl1LiyMtA1QFitg0X+qJlEUCPRJzKVOhQVMl3HgyfLjjQWfJVEdNP7pGapWEW53lX7oQPJwCYbHZY/E8Hrr9as3SDSYzJxNUos1wrcrREAkbpRilb4OnM1AVHfSmYQHjDSoKA3g0vh7hpXnHY8ro4/IoHAv3INXR6pIdePBCDYqzCv08227EzChOCcaQkwsot6P13FKcQU+76hsj0RgCEiPx6cjX0Ptxjx0dkm/--ftLmDeWIG7AQzDjY--WeOSalt2sE77bZVrEQiEpg== -------------------------------------------------------------------------------- /config/database.yml: -------------------------------------------------------------------------------- 1 | # PostgreSQL. Versions 9.3 and up are supported. 2 | # 3 | # Install the pg driver: 4 | # gem install pg 5 | # On macOS with Homebrew: 6 | # gem install pg -- --with-pg-config=/usr/local/bin/pg_config 7 | # On macOS with MacPorts: 8 | # gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config 9 | # On Windows: 10 | # gem install pg 11 | # Choose the win32 build. 12 | # Install PostgreSQL and put its /bin directory on your path. 13 | # 14 | # Configure Using Gemfile 15 | # gem 'pg' 16 | # 17 | default: &default 18 | adapter: postgresql 19 | encoding: unicode 20 | # For details on connection pooling, see Rails configuration guide 21 | # https://guides.rubyonrails.org/configuring.html#database-pooling 22 | pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> 23 | 24 | development: 25 | <<: *default 26 | database: rails_6_webhook_system_development 27 | 28 | # The specified database role being used to connect to postgres. 29 | # To create additional roles in postgres see `$ createuser --help`. 30 | # When left blank, postgres will use the default role. This is 31 | # the same name as the operating system user running Rails. 32 | #username: rails_6_webhook_system 33 | 34 | # The password associated with the postgres role (username). 35 | #password: 36 | 37 | # Connect on a TCP socket. Omitted by default since the client uses a 38 | # domain socket that doesn't need configuration. Windows does not have 39 | # domain sockets, so uncomment these lines. 40 | #host: localhost 41 | 42 | # The TCP port the server listens on. Defaults to 5432. 43 | # If your server runs on a different port number, change accordingly. 44 | #port: 5432 45 | 46 | # Schema search path. The server defaults to $user,public 47 | #schema_search_path: myapp,sharedapp,public 48 | 49 | # Minimum log levels, in increasing order: 50 | # debug5, debug4, debug3, debug2, debug1, 51 | # log, notice, warning, error, fatal, and panic 52 | # Defaults to warning. 53 | #min_messages: notice 54 | 55 | # Warning: The database defined as "test" will be erased and 56 | # re-generated from your development database when you run "rake". 57 | # Do not set this db to the same as development or production. 58 | test: 59 | <<: *default 60 | database: rails_6_webhook_system_test 61 | 62 | # As with config/credentials.yml, you never want to store sensitive information, 63 | # like your database password, in your source code. If your source code is 64 | # ever seen by anyone, they now have access to your database. 65 | # 66 | # Instead, provide the password or a full connection URL as an environment 67 | # variable when you boot the app. For example: 68 | # 69 | # DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" 70 | # 71 | # If the connection URL is provided in the special DATABASE_URL environment 72 | # variable, Rails will automatically merge its configuration values on top of 73 | # the values provided in this file. Alternatively, you can specify a connection 74 | # URL environment variable explicitly: 75 | # 76 | # production: 77 | # url: <%= ENV['MY_APP_DATABASE_URL'] %> 78 | # 79 | # Read https://guides.rubyonrails.org/configuring.html#configuring-a-database 80 | # for a full overview on how database connection configuration can be specified. 81 | # 82 | production: 83 | <<: *default 84 | database: rails_6_webhook_system_production 85 | username: rails_6_webhook_system 86 | password: <%= ENV['RAILS_6_WEBHOOK_SYSTEM_DATABASE_PASSWORD'] %> 87 | -------------------------------------------------------------------------------- /config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the Rails application. 2 | require_relative "application" 3 | 4 | # Initialize the Rails application. 5 | Rails.application.initialize! 6 | -------------------------------------------------------------------------------- /config/environments/development.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | config.hosts << '.ngrok.io' 6 | 7 | # In the development environment your application's code is reloaded any time 8 | # it changes. This slows down response time but is perfect for development 9 | # since you don't have to restart the web server when you make code changes. 10 | config.cache_classes = false 11 | 12 | # Do not eager load code on boot. 13 | config.eager_load = false 14 | 15 | # Show full error reports. 16 | config.consider_all_requests_local = true 17 | 18 | # Enable/disable caching. By default caching is disabled. 19 | # Run rails dev:cache to toggle caching. 20 | if Rails.root.join('tmp', 'caching-dev.txt').exist? 21 | config.cache_store = :memory_store 22 | config.public_file_server.headers = { 23 | 'Cache-Control' => "public, max-age=#{2.days.to_i}" 24 | } 25 | else 26 | config.action_controller.perform_caching = false 27 | 28 | config.cache_store = :null_store 29 | end 30 | 31 | # Don't care if the mailer can't send. 32 | config.action_mailer.raise_delivery_errors = false 33 | 34 | config.action_mailer.perform_caching = false 35 | 36 | # Print deprecation notices to the Rails logger. 37 | config.active_support.deprecation = :log 38 | 39 | # Raise exceptions for disallowed deprecations. 40 | config.active_support.disallowed_deprecation = :raise 41 | 42 | # Tell Active Support which deprecation messages to disallow. 43 | config.active_support.disallowed_deprecation_warnings = [] 44 | 45 | # Raise an error on page load if there are pending migrations. 46 | config.active_record.migration_error = :page_load 47 | 48 | # Highlight code that triggered database queries in logs. 49 | config.active_record.verbose_query_logs = true 50 | 51 | 52 | # Raises error for missing translations. 53 | # config.i18n.raise_on_missing_translations = true 54 | 55 | # Annotate rendered view with file names. 56 | # config.action_view.annotate_rendered_view_with_filenames = true 57 | 58 | # Use an evented file watcher to asynchronously detect changes in source code, 59 | # routes, locales, etc. This feature depends on the listen gem. 60 | config.file_watcher = ActiveSupport::EventedFileUpdateChecker 61 | 62 | # Uncomment if you wish to allow Action Cable access from any origin. 63 | # config.action_cable.disable_request_forgery_protection = true 64 | end 65 | -------------------------------------------------------------------------------- /config/environments/production.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | Rails.application.configure do 4 | # Settings specified here will take precedence over those in config/application.rb. 5 | 6 | # Code is not reloaded between requests. 7 | config.cache_classes = true 8 | 9 | # Eager load code on boot. This eager loads most of Rails and 10 | # your application in memory, allowing both threaded web servers 11 | # and those relying on copy on write to perform better. 12 | # Rake tasks automatically ignore this option for performance. 13 | config.eager_load = true 14 | 15 | # Full error reports are disabled and caching is turned on. 16 | config.consider_all_requests_local = false 17 | 18 | # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] 19 | # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). 20 | # config.require_master_key = true 21 | 22 | # Disable serving static files from the `/public` folder by default since 23 | # Apache or NGINX already handles this. 24 | config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? 25 | 26 | # Enable serving of images, stylesheets, and JavaScripts from an asset server. 27 | # config.asset_host = 'http://assets.example.com' 28 | 29 | # Specifies the header that your server uses for sending files. 30 | # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache 31 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX 32 | 33 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. 34 | # config.force_ssl = true 35 | 36 | # Include generic and useful information about system operation, but avoid logging too much 37 | # information to avoid inadvertent exposure of personally identifiable information (PII). 38 | config.log_level = :info 39 | 40 | # Prepend all log lines with the following tags. 41 | config.log_tags = [ :request_id ] 42 | 43 | # Use a different cache store in production. 44 | # config.cache_store = :mem_cache_store 45 | 46 | # Use a real queuing backend for Active Job (and separate queues per environment). 47 | # config.active_job.queue_adapter = :resque 48 | # config.active_job.queue_name_prefix = "rails_6_webhook_system_production" 49 | 50 | config.action_mailer.perform_caching = false 51 | 52 | # Ignore bad email addresses and do not raise email delivery errors. 53 | # Set this to true and configure the email server for immediate delivery to raise delivery errors. 54 | # config.action_mailer.raise_delivery_errors = false 55 | 56 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 57 | # the I18n.default_locale when a translation cannot be found). 58 | config.i18n.fallbacks = true 59 | 60 | # Send deprecation notices to registered listeners. 61 | config.active_support.deprecation = :notify 62 | 63 | # Log disallowed deprecations. 64 | config.active_support.disallowed_deprecation = :log 65 | 66 | # Tell Active Support which deprecation messages to disallow. 67 | config.active_support.disallowed_deprecation_warnings = [] 68 | 69 | # Use default logging formatter so that PID and timestamp are not suppressed. 70 | config.log_formatter = ::Logger::Formatter.new 71 | 72 | # Use a different logger for distributed setups. 73 | # require "syslog/logger" 74 | # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') 75 | 76 | if ENV["RAILS_LOG_TO_STDOUT"].present? 77 | logger = ActiveSupport::Logger.new(STDOUT) 78 | logger.formatter = config.log_formatter 79 | config.logger = ActiveSupport::TaggedLogging.new(logger) 80 | end 81 | 82 | # Do not dump schema after migrations. 83 | config.active_record.dump_schema_after_migration = false 84 | 85 | # Inserts middleware to perform automatic connection switching. 86 | # The `database_selector` hash is used to pass options to the DatabaseSelector 87 | # middleware. The `delay` is used to determine how long to wait after a write 88 | # to send a subsequent read to the primary. 89 | # 90 | # The `database_resolver` class is used by the middleware to determine which 91 | # database is appropriate to use based on the time delay. 92 | # 93 | # The `database_resolver_context` class is used by the middleware to set 94 | # timestamps for the last write to the primary. The resolver uses the context 95 | # class timestamps to determine how long to wait before reading from the 96 | # replica. 97 | # 98 | # By default Rails will store a last write timestamp in the session. The 99 | # DatabaseSelector middleware is designed as such you can define your own 100 | # strategy for connection switching and pass that into the middleware through 101 | # these configuration options. 102 | # config.active_record.database_selector = { delay: 2.seconds } 103 | # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver 104 | # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session 105 | end 106 | -------------------------------------------------------------------------------- /config/environments/test.rb: -------------------------------------------------------------------------------- 1 | require "active_support/core_ext/integer/time" 2 | 3 | # The test environment is used exclusively to run your application's 4 | # test suite. You never need to work with it otherwise. Remember that 5 | # your test database is "scratch space" for the test suite and is wiped 6 | # and recreated between test runs. Don't rely on the data there! 7 | 8 | Rails.application.configure do 9 | # Settings specified here will take precedence over those in config/application.rb. 10 | 11 | config.cache_classes = false 12 | config.action_view.cache_template_loading = true 13 | 14 | # Do not eager load code on boot. This avoids loading your whole application 15 | # just for the purpose of running a single test. If you are using a tool that 16 | # preloads Rails for running tests, you may have to set it to true. 17 | config.eager_load = false 18 | 19 | # Configure public file server for tests with Cache-Control for performance. 20 | config.public_file_server.enabled = true 21 | config.public_file_server.headers = { 22 | 'Cache-Control' => "public, max-age=#{1.hour.to_i}" 23 | } 24 | 25 | # Show full error reports and disable caching. 26 | config.consider_all_requests_local = true 27 | config.action_controller.perform_caching = false 28 | config.cache_store = :null_store 29 | 30 | # Raise exceptions instead of rendering exception templates. 31 | config.action_dispatch.show_exceptions = false 32 | 33 | # Disable request forgery protection in test environment. 34 | config.action_controller.allow_forgery_protection = false 35 | 36 | config.action_mailer.perform_caching = false 37 | 38 | # Tell Action Mailer not to deliver emails to the real world. 39 | # The :test delivery method accumulates sent emails in the 40 | # ActionMailer::Base.deliveries array. 41 | config.action_mailer.delivery_method = :test 42 | 43 | # Print deprecation notices to the stderr. 44 | config.active_support.deprecation = :stderr 45 | 46 | # Raise exceptions for disallowed deprecations. 47 | config.active_support.disallowed_deprecation = :raise 48 | 49 | # Tell Active Support which deprecation messages to disallow. 50 | config.active_support.disallowed_deprecation_warnings = [] 51 | 52 | # Raises error for missing translations. 53 | # config.i18n.raise_on_missing_translations = true 54 | 55 | # Annotate rendered view with file names. 56 | # config.action_view.annotate_rendered_view_with_filenames = true 57 | end 58 | -------------------------------------------------------------------------------- /config/initializers/application_controller_renderer.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # ActiveSupport::Reloader.to_prepare do 4 | # ApplicationController.renderer.defaults.merge!( 5 | # http_host: 'example.org', 6 | # https: false 7 | # ) 8 | # end 9 | -------------------------------------------------------------------------------- /config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code 7 | # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". 8 | Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"] 9 | -------------------------------------------------------------------------------- /config/initializers/cors.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Avoid CORS issues when API is called from the frontend app. 4 | # Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. 5 | 6 | # Read more: https://github.com/cyu/rack-cors 7 | 8 | # Rails.application.config.middleware.insert_before 0, Rack::Cors do 9 | # allow do 10 | # origins 'example.com' 11 | # 12 | # resource '*', 13 | # headers: :any, 14 | # methods: [:get, :post, :put, :patch, :delete, :options, :head] 15 | # end 16 | # end 17 | -------------------------------------------------------------------------------- /config/initializers/filter_parameter_logging.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Configure sensitive parameters which will be filtered from the log file. 4 | Rails.application.config.filter_parameters += [ 5 | :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn 6 | ] 7 | -------------------------------------------------------------------------------- /config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format. Inflections 4 | # are locale specific, and you may define rules for as many different 5 | # locales as you wish. All of these examples are active by default: 6 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 7 | # inflect.plural /^(ox)$/i, '\1en' 8 | # inflect.singular /^(ox)en/i, '\1' 9 | # inflect.irregular 'person', 'people' 10 | # inflect.uncountable %w( fish sheep ) 11 | # end 12 | 13 | # These inflection rules are supported but not enabled by default: 14 | # ActiveSupport::Inflector.inflections(:en) do |inflect| 15 | # inflect.acronym 'RESTful' 16 | # end 17 | -------------------------------------------------------------------------------- /config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | -------------------------------------------------------------------------------- /config/initializers/wrap_parameters.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # This file contains settings for ActionController::ParamsWrapper which 4 | # is enabled by default. 5 | 6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. 7 | ActiveSupport.on_load(:action_controller) do 8 | wrap_parameters format: [:json] 9 | end 10 | 11 | # To enable root element in JSON for ActiveRecord objects. 12 | # ActiveSupport.on_load(:active_record) do 13 | # self.include_root_in_json = true 14 | # end 15 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Files in the config/locales directory are used for internationalization 2 | # and are automatically loaded by Rails. If you want to use locales other 3 | # than English, add the necessary files in this directory. 4 | # 5 | # To use the locales, use `I18n.t`: 6 | # 7 | # I18n.t 'hello' 8 | # 9 | # In views, this is aliased to just `t`: 10 | # 11 | # <%= t('hello') %> 12 | # 13 | # To use a different locale, set it with `I18n.locale`: 14 | # 15 | # I18n.locale = :es 16 | # 17 | # This would use the information in config/locales/es.yml. 18 | # 19 | # The following keys must be escaped otherwise they will not be retrieved by 20 | # the default I18n backend: 21 | # 22 | # true, false, on, off, yes, no 23 | # 24 | # Instead, surround them with single quotes. 25 | # 26 | # en: 27 | # 'true': 'foo' 28 | # 29 | # To learn more, please read the Rails Internationalization guide 30 | # available at https://guides.rubyonrails.org/i18n.html. 31 | 32 | en: 33 | hello: "Hello world" 34 | -------------------------------------------------------------------------------- /config/puma.rb: -------------------------------------------------------------------------------- 1 | # Puma can serve each request in a thread from an internal thread pool. 2 | # The `threads` method setting takes two numbers: a minimum and maximum. 3 | # Any libraries that use thread pools should be configured to match 4 | # the maximum value specified for Puma. Default is set to 5 threads for minimum 5 | # and maximum; this matches the default thread size of Active Record. 6 | # 7 | max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } 8 | min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } 9 | threads min_threads_count, max_threads_count 10 | 11 | # Specifies the `worker_timeout` threshold that Puma will use to wait before 12 | # terminating a worker in development environments. 13 | # 14 | worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" 15 | 16 | # Specifies the `port` that Puma will listen on to receive requests; default is 3000. 17 | # 18 | port ENV.fetch("PORT") { 3000 } 19 | 20 | # Specifies the `environment` that Puma will run in. 21 | # 22 | environment ENV.fetch("RAILS_ENV") { "development" } 23 | 24 | # Specifies the `pidfile` that Puma will use. 25 | pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } 26 | 27 | # Specifies the number of `workers` to boot in clustered mode. 28 | # Workers are forked web server processes. If using threads and workers together 29 | # the concurrency of the application would be max `threads` * `workers`. 30 | # Workers do not work on JRuby or Windows (both of which do not support 31 | # processes). 32 | # 33 | # workers ENV.fetch("WEB_CONCURRENCY") { 2 } 34 | 35 | # Use the `preload_app!` method when specifying a `workers` number. 36 | # This directive tells Puma to first boot the application and load code 37 | # before forking the application. This takes advantage of Copy On Write 38 | # process behavior so workers use less memory. 39 | # 40 | # preload_app! 41 | 42 | # Allow puma to be restarted by `rails restart` command. 43 | plugin :tmp_restart 44 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | Rails.application.routes.draw do 2 | post '/webhooks', to: proc { [204, {}, []] } 3 | end 4 | -------------------------------------------------------------------------------- /config/spring.rb: -------------------------------------------------------------------------------- 1 | Spring.watch( 2 | ".ruby-version", 3 | ".rbenv-vars", 4 | "tmp/restart.txt", 5 | "tmp/caching-dev.txt" 6 | ) 7 | -------------------------------------------------------------------------------- /db/migrate/20210614145326_create_webhook_endpoints.rb: -------------------------------------------------------------------------------- 1 | class CreateWebhookEndpoints < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :webhook_endpoints do |t| 4 | t.string :url, null: false 5 | 6 | t.timestamps null: false 7 | end 8 | end 9 | end 10 | -------------------------------------------------------------------------------- /db/migrate/20210614160959_create_webhook_events.rb: -------------------------------------------------------------------------------- 1 | class CreateWebhookEvents < ActiveRecord::Migration[5.2] 2 | def change 3 | create_table :webhook_events do |t| 4 | t.integer :webhook_endpoint_id, null: false, index: true 5 | 6 | t.string :event, null: false 7 | t.jsonb :payload, null: false 8 | 9 | t.timestamps null: false 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /db/migrate/20210614162001_add_enabled_to_webhook_endpoints.rb: -------------------------------------------------------------------------------- 1 | class AddEnabledToWebhookEndpoints < ActiveRecord::Migration[5.2] 2 | def change 3 | add_column :webhook_endpoints, :enabled, :boolean, default: true, index: true 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20210614165853_add_subscriptions_to_webhook_endpoints.rb: -------------------------------------------------------------------------------- 1 | class AddSubscriptionsToWebhookEndpoints < ActiveRecord::Migration[5.2] 2 | def change 3 | add_column :webhook_endpoints, :subscriptions, :jsonb, default: ['*'] 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/migrate/20210614170512_add_response_to_webhook_events.rb: -------------------------------------------------------------------------------- 1 | class AddResponseToWebhookEvents < ActiveRecord::Migration[5.2] 2 | def change 3 | add_column :webhook_events, :response, :jsonb, default: {} 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # This file is the source Rails uses to define your schema when running `bin/rails 6 | # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to 7 | # be faster and is potentially less error prone than running all of your 8 | # migrations from scratch. Old migrations may fail to apply correctly if those 9 | # migrations use external dependencies or application code. 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 2021_06_14_170512) do 14 | 15 | # These are extensions that must be enabled in order to support this database 16 | enable_extension "plpgsql" 17 | 18 | create_table "webhook_endpoints", force: :cascade do |t| 19 | t.string "url", null: false 20 | t.datetime "created_at", null: false 21 | t.datetime "updated_at", null: false 22 | t.boolean "enabled", default: true 23 | t.jsonb "subscriptions", default: ["*"] 24 | end 25 | 26 | create_table "webhook_events", force: :cascade do |t| 27 | t.integer "webhook_endpoint_id", null: false 28 | t.string "event", null: false 29 | t.jsonb "payload", null: false 30 | t.datetime "created_at", null: false 31 | t.datetime "updated_at", null: false 32 | t.jsonb "response", default: {} 33 | t.index ["webhook_endpoint_id"], name: "index_webhook_events_on_webhook_endpoint_id" 34 | end 35 | 36 | end 37 | -------------------------------------------------------------------------------- /db/seeds.rb: -------------------------------------------------------------------------------- 1 | # This file should contain all the record creation needed to seed the database with its default values. 2 | # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). 3 | # 4 | # Examples: 5 | # 6 | # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) 7 | # Character.create(name: 'Luke', movie: movies.first) 8 | -------------------------------------------------------------------------------- /lib/tasks/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/lib/tasks/.keep -------------------------------------------------------------------------------- /log/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/log/.keep -------------------------------------------------------------------------------- /public/robots.txt: -------------------------------------------------------------------------------- 1 | # See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file 2 | -------------------------------------------------------------------------------- /test/controllers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/test/controllers/.keep -------------------------------------------------------------------------------- /test/fixtures/files/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/test/fixtures/files/.keep -------------------------------------------------------------------------------- /test/integration/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/test/integration/.keep -------------------------------------------------------------------------------- /test/mailers/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/test/mailers/.keep -------------------------------------------------------------------------------- /test/models/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/test/models/.keep -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | ENV['RAILS_ENV'] ||= 'test' 2 | require_relative "../config/environment" 3 | require "rails/test_help" 4 | 5 | class ActiveSupport::TestCase 6 | # Run tests in parallel with specified workers 7 | parallelize(workers: :number_of_processors) 8 | 9 | # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. 10 | fixtures :all 11 | 12 | # Add more helper methods to be used by all tests here... 13 | end 14 | -------------------------------------------------------------------------------- /tmp/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/tmp/.keep -------------------------------------------------------------------------------- /tmp/pids/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/tmp/pids/.keep -------------------------------------------------------------------------------- /vendor/.keep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezekg/example-rails-webhook-system/9555b3f23e7100d81435c04609a7a8d6979bac84/vendor/.keep --------------------------------------------------------------------------------