Skip to content

Instantly share code, notes, and snippets.

@mvastola
Created June 9, 2022 18:44
Show Gist options
  • Save mvastola/43f7b27f0345deab0d3875a95809e40c to your computer and use it in GitHub Desktop.
Save mvastola/43f7b27f0345deab0d3875a95809e40c to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'thin'
gem 'rack'
gem 'rack-timeout'
end
$logger = Logger.new(STDERR)
class TimeoutCatcherMiddleware
def initialize(app)
@app = app
end
def call(env)
$logger.info "Starting #{self.class.name}.."
$logger.info "Invoking next middleware in stack"
status, headers, body = @app.call(env)
$logger.info "Retrieved response. Sending now."
[status, headers, body]
rescue StandardError => e
$logger.error "Timeout exceeded. Showing error"
$logger.error e.inspect
['500', {'Content-Type' => 'text/plain'}, [e.inspect]]
end
end
app = Proc.new do |env|
$logger.info "In app. Sleeping for 5 seconds."
sleep 5
['200', {'Content-Type' => 'text/plain'}, ['Request Succeeded (slowly)']]
end
Thin::Server.start('127.0.0.1', 3000) do
use Rack::CommonLogger, logger: $loggger
#use Rack::ShowExceptions
use TimeoutCatcherMiddleware
use Rack::Timeout, service_timeout: 2
use Rack::Lock # ensure requests are serial
map '/' do
run app
end
end
# class TestApp < Rails::Application
# secrets.secret_token = 'secret_token'
# secrets.secret_key_base = 'secret_key_base'
#
# config.logger = Logger.new($stdout)
# Rails.logger = config.logger
#
# routes.draw do
# root to: 'main#index'
# end
# end
#
# Rails.application.config.middleware.insert_before Rack::Runtime, Rack::Timeout, service_timeout: 5
#
# class MainController < ActionController::Base
# include Rails.application.routes.url_helpers
#
# def index
# sleep 10
# render inline: 'Done!'
# end
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment