Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for asynchonous request handling #2

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ gemspec

group :test do
gem 'shoulda'
gem 'rack-test'
end
32 changes: 29 additions & 3 deletions lib/rack/cors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,38 @@ def call(env)
cors_headers = process_cors(env)
end
end
status, headers, body = @app.call env
headers = headers.merge(cors_headers) if cors_headers
[status, headers, body]
process_request(env, cors_headers)
end

protected
def process_request(env, cors_headers)
# The thin web server allows apps to signal async request processing by
# throwing the symbol :async, then signalling completion later by
# invoking env['async.callback'].
#
# Here we ensure compatibility with that protocol: if @app.call throws
# :async, we catch it, wrap async.callback to insert the appropriate
# CORS response headers, then rethrow :async up to thin. If @app.call
# completes without throwing, we just add our headers immediately in
# the normal synchronous fashion.

catch :async do
status, headers, body = @app.call(env)
# if we got this far, then @app.call completed without throwing.
headers = headers.merge(cors_headers) if cors_headers
return [status, headers, body]
end

# if we ended up here, must have caught :async (skipping the 'return')
original_callback = env['async.callback']
env['async.callback'] = proc do |response|
status, headers, body = response
headers = headers.merge(cors_headers) if cors_headers
original_callback.call([status, headers, body])
end
throw :async
end

def debug(env, message = nil, &block)
logger = @logger || env['rack.logger'] || begin
@logger = ::Logger.new(STDOUT).tap {|logger| logger.level = ::Logger::Severity::INFO}
Expand Down