|
| 1 | +module Fluoride |
| 2 | + module Collector |
| 3 | + class Middleware |
| 4 | + def initialize(app, directory, tagging = nil) |
| 5 | + @app = app |
| 6 | + @directory = directory |
| 7 | + @tagging = tagging |
| 8 | + end |
| 9 | + |
| 10 | + def call(env) |
| 11 | + @app.call(env).tap do |response| |
| 12 | + record_exchange(env, response) |
| 13 | + end |
| 14 | + rescue Object => ex |
| 15 | + record_exception(env, ex) |
| 16 | + raise |
| 17 | + end |
| 18 | + |
| 19 | + private |
| 20 | + |
| 21 | + def record_exchange(env, response) |
| 22 | + store( |
| 23 | + "type" => "normal_exchange", |
| 24 | + "tags" => @tagging, |
| 25 | + "request" => request_hash(env), |
| 26 | + "response" => response_hash(response) |
| 27 | + ) |
| 28 | + end |
| 29 | + |
| 30 | + def record_exception(env, ex) |
| 31 | + store( |
| 32 | + "type" => "exception_raised", |
| 33 | + "tags" => @tagging, |
| 34 | + "request" => request_hash(env), |
| 35 | + "response" => exception_hash(ex) |
| 36 | + ) |
| 37 | + end |
| 38 | + |
| 39 | + def request_hash(env) |
| 40 | + body = nil |
| 41 | + if env['rack.input'].respond_to? :read |
| 42 | + body = env['rack.input'].read |
| 43 | + env['rack.input'].rewind rescue nil |
| 44 | + end |
| 45 | + { |
| 46 | + "content_type" => env['CONTENT_TYPE'], |
| 47 | + "accept" => env["HTTP_ACCEPT_ENCODING"], |
| 48 | + "referer" => env["HTTP_REFERER"], |
| 49 | + "cookies" => env["HTTP_COOKIE"], |
| 50 | + "authorization" => env["HTTP_AUTHORIZATION"], |
| 51 | + "method" => env["REQUEST_METHOD"], |
| 52 | + "host" => env['HTTP_HOST'] || "#{env['SERVER_NAME'] || env['SERVER_ADDR']}:#{env['SERVER_PORT']}", |
| 53 | + "path" => env["SCRIPT_NAME"].to_s + env["PATH_INFO"].to_s, |
| 54 | + "query_string" => env["QUERY_STRING"].to_s, |
| 55 | + "body" => body, |
| 56 | + } |
| 57 | + end |
| 58 | + |
| 59 | + def response_hash(response) |
| 60 | + status, headers, body = *response |
| 61 | + |
| 62 | + { |
| 63 | + "status" => status, |
| 64 | + "headers" => headers, |
| 65 | + "body" => body.to_a.join("") #every body? all of it? |
| 66 | + } |
| 67 | + end |
| 68 | + |
| 69 | + def exception_hash(ex) |
| 70 | + { |
| 71 | + "type" => ex.class.name, |
| 72 | + "message" => ex.message, |
| 73 | + "backtrace" => ex.backtrace[0..10] |
| 74 | + } |
| 75 | + end |
| 76 | + |
| 77 | + def thread_locals |
| 78 | + Thread.current[:fluoride_collector] ||= {} |
| 79 | + end |
| 80 | + |
| 81 | + def storage_path |
| 82 | + thread_locals[:storage_path] ||= File::join(@directory, "collection-#{Process.pid}-#{Thread.current.object_id}.yml") |
| 83 | + end |
| 84 | + |
| 85 | + def storage_file |
| 86 | + File::open(storage_path, "a") do |file| |
| 87 | + yield file |
| 88 | + end |
| 89 | + end |
| 90 | + |
| 91 | + def store(record) |
| 92 | + storage_file do |file| |
| 93 | + file.write(YAML::dump(record)) |
| 94 | + end |
| 95 | + end |
| 96 | + end |
| 97 | + end |
| 98 | +end |
0 commit comments