OneFlight (OneFlight v0.1.0)

Copy Markdown View Source

Collapses concurrent duplicate calls into one supervised execution per key.

one_flight is not a cache. It only shares work that is already in progress; after a flight completes, the result is discarded.

Example

iex> {:ok, _pid} = start_supervised({OneFlight, name: ExampleFlights})
iex> OneFlight.run(:key, fn -> :value end, name: ExampleFlights)
{:ok, :value}

Summary

Functions

Starts a flight and returns a handle that can be awaited.

Waits for an async flight result.

Detaches key so the next caller starts a fresh flight.

Runs fun once for concurrent callers using the same key.

Runs fun once and unwraps a successful result.

Returns local in-flight stats for key.

Types

key()

@type key() :: term()

option()

@type option() ::
  {:name, GenServer.server()}
  | {:timeout, timeout()}
  | {:on_abandoned, :cancel | :complete}
  | {:scope, :node}

Functions

async(key, fun, opts \\ [])

@spec async(key(), (-> term()), [option()]) :: OneFlight.Flight.t()

Starts a flight and returns a handle that can be awaited.

await(flight, timeout \\ 5000)

@spec await(OneFlight.Flight.t(), timeout()) ::
  {:ok, term()} | {:error, OneFlight.Error.t()}

Waits for an async flight result.

forget(key, opts \\ [])

@spec forget(key(), [option()]) :: :ok

Detaches key so the next caller starts a fresh flight.

run(key, fun, opts \\ [])

@spec run(key(), (-> term()), [option()]) ::
  {:ok, term()} | {:error, OneFlight.Error.t()}

Runs fun once for concurrent callers using the same key.

run!(key, fun, opts \\ [])

@spec run!(key(), (-> term()), [option()]) :: term()

Runs fun once and unwraps a successful result.

Raises OneFlight.Error when the non-bang API would return an error tuple.

stats(key, opts \\ [])

@spec stats(key(), [option()]) :: %{
  in_flight?: boolean(),
  waiters_count: non_neg_integer()
}

Returns local in-flight stats for key.