Skip to content

Instantly share code, notes, and snippets.

@mvastola
Created June 9, 2022 18:44
Show Gist options
  • Save mvastola/964fc632799a40f032beea0db1f265d5 to your computer and use it in GitHub Desktop.
Save mvastola/964fc632799a40f032beea0db1f265d5 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment