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 if tmp = opts[:listeners]
17 self.tcp = tmp.grep(/\A[^:]+:\d+\z/)
18 self.unix = tmp.grep(%r{\A/})
19 self.tcp = nil if tcp.empty?
20 self.unix = nil if unix.empty?
24 # standard Rack endpoing
26 env[PATH_INFO] == path ? stats_response : dup._call(env)
31 status, headers, self.app = app.call(env)
33 # the Rack server will start writing headers soon after this method
35 [ status, headers, self ]
40 # yield to the Rack server here for writing
45 # the Rack server should call this after #each (usually ensure-d)
49 app.close if app.respond_to?(:close)
53 body = "calling: #{stats.calling}\n" \
54 "writing: #{stats.writing}\n"
57 Linux.tcp_listener_stats(tcp).each do |addr,stats|
58 body << "#{addr} active: #{stats.active}\n" \
59 "#{addr} queued: #{stats.queued}\n"
61 Linux.unix_listener_stats(unix).each do |addr,stats|
62 body << "#{addr} active: #{stats.active}\n" \
63 "#{addr} queued: #{stats.queued}\n"
68 "Content-Type" => "text/plain",
69 "Content-Length" => body.size.to_s,
71 [ 200, headers, [ body ] ]