Pristine.Adapters.Semaphore.Counting (Pristine v0.3.1)

Copy Markdown View Source

Counting semaphore adapter using Foundation.Semaphore.Counting.

This adapter provides connection/concurrency limiting using an ETS-backed counting semaphore. It's designed for limiting concurrent HTTP connections or other resource access patterns.

Example

# Initialize a semaphore with a limit of 10 concurrent operations
Counting.init(:http_pool, 10)

# Execute a function while holding a permit
result = Counting.with_permit(:http_pool, 5_000, fn ->
  make_http_request()
end)

# Handle timeout
case Counting.with_permit(:http_pool, 100, fn -> slow_operation() end) do
  {:error, :timeout} -> {:error, :too_busy}
  result -> result
end

Summary

Functions

Attempt to acquire a permit from the semaphore.

Get the number of available permits.

Initialize a named semaphore with a given limit.

Release a previously acquired permit back to the semaphore.

Execute a function while holding a semaphore permit.

Functions

acquire(name, timeout)

Attempt to acquire a permit from the semaphore.

Uses a spin-wait loop with short sleeps to attempt acquisition within the specified timeout.

available(name)

Get the number of available permits.

Returns the difference between the configured limit and the current count.

init(name, limit)

Initialize a named semaphore with a given limit.

The semaphore will be created in the adapter's registry and its limit will be stored for later reference.

release(name)

Release a previously acquired permit back to the semaphore.

with_permit(name, timeout, fun)

Execute a function while holding a semaphore permit.

Acquires a permit, executes the function, and releases the permit. If the permit cannot be acquired within the timeout, returns {:error, :timeout}. The permit is always released, even if the function raises an exception.