summaryrefslogtreecommitdiff
path: root/lib/rack/lock.rb
blob: 4bae3a9034e83b50d3dfbf2fad13722df25fd0a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# frozen_string_literal: true

require 'thread'

module Rack
  # Rack::Lock locks every request inside a mutex, so that every request
  # will effectively be executed synchronously.
  class Lock
    def initialize(app, mutex = Mutex.new)
      @app, @mutex = app, mutex
    end

    def call(env)
      @mutex.lock
      @env = env
      @old_rack_multithread = env[RACK_MULTITHREAD]
      begin
        response = @app.call(env.merge!(RACK_MULTITHREAD => false))
        returned = response << BodyProxy.new(response.pop) { unlock }
      ensure
        unlock unless returned
      end
    end

    private

    def unlock
      @mutex.unlock
      @env[RACK_MULTITHREAD] = @old_rack_multithread
    end
  end
end