Class: Findbug::BackgroundPersister
- Inherits:
-
Object
- Object
- Findbug::BackgroundPersister
- Defined in:
- lib/findbug/background_persister.rb
Overview
BackgroundPersister runs a background thread that periodically moves events from the Redis buffer to the database.
WHY A BACKGROUND THREAD?
We want Findbug to work “out of the box” without requiring users to:
-
Set up Sidekiq/ActiveJob
-
Configure recurring jobs
-
Run separate worker processes
A background thread achieves this by running inside the Rails process.
THREAD SAFETY
-
Uses Mutex for start/stop synchronization
-
Only one persister thread runs at a time
-
Safe to call start! multiple times (idempotent)
GRACEFUL SHUTDOWN
The thread checks a @running flag and exits cleanly when stopped. We also register an at_exit hook to ensure cleanup.
LIMITATIONS
-
Only persists in the process where it’s started
-
In multi-process setups (Puma cluster), each process has its own thread
-
For high-volume apps, users should use the ActiveJob approach instead
Constant Summary collapse
- DEFAULT_INTERVAL =
seconds
30
Class Method Summary collapse
-
.persist_now! ⇒ Object
Force an immediate persist (useful for testing).
- .running? ⇒ Boolean
- .start!(interval: nil) ⇒ Object
- .stop! ⇒ Object
Class Method Details
.persist_now! ⇒ Object
Force an immediate persist (useful for testing)
75 76 77 |
# File 'lib/findbug/background_persister.rb', line 75 def persist_now! perform_persist end |
.running? ⇒ Boolean
70 71 72 |
# File 'lib/findbug/background_persister.rb', line 70 def running? @running == true && @thread&.alive? end |
.start!(interval: nil) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/findbug/background_persister.rb', line 41 def start!(interval: nil) return if @running @mutex ||= Mutex.new @mutex.synchronize do return if @running @interval = interval || Findbug.config.persist_interval || DEFAULT_INTERVAL @running = true @thread = Thread.new { run_loop } @thread.name = "findbug-persister" @thread.abort_on_exception = false Findbug.logger.info("[Findbug] Background persister started (interval: #{@interval}s)") end end |
.stop! ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/findbug/background_persister.rb', line 58 def stop! return unless @running @mutex.synchronize do @running = false @thread&.wakeup rescue nil # Wake from sleep @thread&.join(5) # Wait up to 5 seconds @thread = nil Findbug.logger.info("[Findbug] Background persister stopped") end end |