Class: ASF::AutoGC
- Inherits:
-
Object
- Object
- ASF::AutoGC
- Defined in:
- lib/whimsy/asf/rack.rb
Overview
‘use’ the following class in config.ru to automatically run Garbage Collection every ‘n’ requests, or ‘m’ minutes.
This tries to run garbage collection “out of band” (i.e., between requests), and when other requests are active (which can happen with threaded servers like Puma).
In addition to keeping memory usage bounded, this keeps the LDAP cache from going stale.
Constant Summary collapse
- @@background =
nil
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, frequency = 100, minutes = 15) ⇒ AutoGC
constructor
A new instance of AutoGC.
- #maybe_perform_gc ⇒ Object
Constructor Details
#initialize(app, frequency = 100, minutes = 15) ⇒ AutoGC
Returns a new instance of AutoGC.
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
# File 'lib/whimsy/asf/rack.rb', line 101 def initialize(app, frequency=100, minutes=15) @app = app @frequency = frequency @request_count = 0 @queue = Queue.new @mutex = Mutex.new if defined?(PhusionPassenger) # https://github.com/suyccom/yousell/blob/master/config.ru # https://www.phusionpassenger.com/library/indepth/ruby/out_of_band_work.html if PhusionPassenger.respond_to?(:require_passenger_lib) PhusionPassenger.require_passenger_lib 'rack/out_of_band_gc' else # Phusion Passenger < 4.0.33 require 'phusion_passenger/rack/out_of_band_gc' end @passenger = PhusionPassenger::Rack::OutOfBandGc.new(app, frequency) end Thread.kill(@@background) if @@background if minutes # divide minutes by frequency and use the result to determine the # time between simulated requests @@background = Thread.new do seconds = minutes * 60.0 / frequency loop do sleep seconds maybe_perform_gc end end end end |
Instance Method Details
#call(env) ⇒ Object
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
# File 'lib/whimsy/asf/rack.rb', line 136 def call(env) @queue.push 1 if @passenger @passenger.call(env) else # https://github.com/puma/puma/issues/450 status, header, body = @app.call(env) if ary = env['rack.after_reply'] ary << lambda {maybe_perform_gc} else Thread.new {sleep 0.1; maybe_perform_gc} end [status, header, body] end ensure @queue.pop end |
#maybe_perform_gc ⇒ Object
157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/whimsy/asf/rack.rb', line 157 def maybe_perform_gc @mutex.synchronize do @request_count += 1 if @queue.empty? and @request_count >= @frequency @request_count = 0 disabled = GC.enable GC.start GC.disable if disabled end end end |