Sha256: 8c44548b38c75aea67b66ad35740ba61272ae8670e13044fc7fae82f3926ec34

Contents?: true

Size: 1.28 KB

Versions: 4

Compression:

Stored size: 1.28 KB

Contents

require 'fileutils'

module StackProf
  class Middleware
    def initialize(app, options = {})
      @app       = app
      @options   = options
      @num_reqs  = options[:save_every] || nil

      Middleware.mode     = options[:mode] || :cpu
      Middleware.interval = options[:interval] || 1000
      Middleware.enabled  = options[:enabled]
      Middleware.path     = options[:path] || 'tmp'
      at_exit{ Middleware.save? } if options[:save_at_exit]
    end

    def call(env)
      StackProf.start(mode: Middleware.mode, interval: Middleware.interval) if Middleware.enabled?
      @app.call(env)
    ensure
      if Middleware.enabled?
        StackProf.stop
        if @num_reqs && (@num_reqs-=1) == 0
          @num_reqs = @options[:save_every]
          Middleware.save
        end
      end
    end

    class << self
      attr_accessor :enabled, :mode, :interval, :path
      alias enabled? enabled

      def save(filename = nil)
        if results = StackProf.results
          FileUtils.mkdir_p(Middleware.path)
          filename ||= "stackprof-#{results[:mode]}-#{Process.pid}-#{Time.now.to_i}.dump"
          File.open(File.join(Middleware.path, filename), 'wb') do |f|
            f.write Marshal.dump(results)
          end
          filename
        end
      end

    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
stackprof-0.2.6 lib/stackprof/middleware.rb
stackprof-0.2.5 lib/stackprof/middleware.rb
stackprof-0.2.4 lib/stackprof/middleware.rb
stackprof-0.2.3 lib/stackprof/middleware.rb