Class: Fizzy::Bulkhead

Inherits:
Object
  • Object
show all
Defined in:
lib/fizzy/bulkhead.rb

Overview

Semaphore-based concurrency limiter (bulkhead pattern).

Limits the number of concurrent operations to prevent resource exhaustion. When the limit is reached, callers block until a slot becomes available or the timeout expires.

Examples:

bulkhead = Fizzy::Bulkhead.new(max_concurrent: 10, timeout: 5)
bulkhead.call { http.get("/boards") }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_concurrent: 10, timeout: 5) ⇒ Bulkhead

Returns a new instance of Bulkhead.

Parameters:

  • max_concurrent (Integer) (defaults to: 10)

    maximum concurrent operations

  • timeout (Numeric) (defaults to: 5)

    seconds to wait for a slot (0 = fail immediately)



16
17
18
19
20
21
22
# File 'lib/fizzy/bulkhead.rb', line 16

def initialize(max_concurrent: 10, timeout: 5)
  @max_concurrent = max_concurrent
  @timeout = timeout
  @semaphore = Mutex.new
  @condition = ConditionVariable.new
  @current = 0
end

Instance Attribute Details

#currentInteger (readonly)

Returns number of currently active operations.

Returns:

  • (Integer)

    number of currently active operations



25
26
27
# File 'lib/fizzy/bulkhead.rb', line 25

def current
  @current
end

Instance Method Details

#call { ... } ⇒ Object

Executes the block within the concurrency limit.

Yields:

  • the operation to execute

Returns:

  • the result of the block

Raises:



32
33
34
35
36
37
38
39
# File 'lib/fizzy/bulkhead.rb', line 32

def call
  acquire_slot
  begin
    yield
  ensure
    release_slot
  end
end