Module: Wurk::StreamConcurrencyGuard

Extended by:
ActiveSupport::Concern
Included in:
ApiController
Defined in:
app/controllers/concerns/wurk/stream_concurrency_guard.rb

Overview

Per-process cap on concurrent SSE streams. ActionController::Live pins one Puma thread for every open /api/stream; without a bound, a burst of stale browser tabs could hold every thread and starve the JSON API. Past the cap we 503 with Retry-After — the SPA's EventSource reconnects (and its polling fallback honors Retry-After) once a slot frees. Per-process is the right scope: it's this process's own thread pool we're protecting.

Constant Summary collapse

MAX_CONCURRENT_STREAMS =
10
RETRY_AFTER_SECONDS =
3

Class Method Summary collapse

Class Method Details

.acquireObject

Reserve a stream slot; false when the cap is already reached.



21
22
23
24
25
26
27
28
# File 'app/controllers/concerns/wurk/stream_concurrency_guard.rb', line 21

def acquire
  @lock.synchronize do
    return false if @open >= MAX_CONCURRENT_STREAMS

    @open += 1
    true
  end
end

.releaseObject



30
31
32
# File 'app/controllers/concerns/wurk/stream_concurrency_guard.rb', line 30

def release
  @lock.synchronize { @open -= 1 if @open.positive? }
end