1 # -*- encoding: binary -*-
4 # Raindrops middleware should be loaded at the top of Rack
5 # middleware stack before other middlewares for maximum accuracy.
7 class Middleware < ::Struct.new(:app, :stats, :path, :tcp, :unix)
10 Stats = Raindrops::Struct.new(:calling, :writing)
11 PATH_INFO = "PATH_INFO"
14 def initialize(app, opts = {})
15 super(app, opts[:stats] || Stats.new, opts[:path] || "/_raindrops")
16 tmp = opts[:listeners]
17 if tmp.nil? && defined?(Unicorn) && Unicorn.respond_to?(:listener_names)
18 tmp = Unicorn.listener_names
22 self.tcp = tmp.grep(/\A[^:]+:\d+\z/)
23 self.unix = tmp.grep(%r{\A/})
24 self.tcp = nil if tcp.empty?
25 self.unix = nil if unix.empty?
29 # standard Rack endpoint
31 env[PATH_INFO] == path ? stats_response : dup._call(env)
36 status, headers, self.app = app.call(env)
38 # the Rack server will start writing headers soon after this method
40 [ status, headers, self ]
45 # yield to the Rack server here for writing
50 # the Rack server should call this after #each (usually ensure-d)
53 app.close if app.respond_to?(:close)
57 body = "calling: #{stats.calling}\n" \
58 "writing: #{stats.writing}\n"
61 Linux.tcp_listener_stats(tcp).each do |addr,stats|
62 body << "#{addr} active: #{stats.active}\n" \
63 "#{addr} queued: #{stats.queued}\n"
65 Linux.unix_listener_stats(unix).each do |addr,stats|
66 body << "#{addr} active: #{stats.active}\n" \
67 "#{addr} queued: #{stats.queued}\n"
72 "Content-Type" => "text/plain",
73 "Content-Length" => body.size.to_s,
75 [ 200, headers, [ body ] ]