# `Dwrr`
[🔗](https://github.com/version2beta/dwrr-elixir/blob/88c8dc71f673c35281de00d602c5ae2a4a951f7e/lib/dwrr.ex)

Pure deficit weighted round robin scheduler: no process, no I/O, no hidden state.

Scheduler values are immutable. Successful operations return the new scheduler,
possibly with a result (`{:ok, result, scheduler}`). On a tagged error no new
scheduler is returned: keep using the input you passed, which is unchanged.
Old snapshots remain valid, so one snapshot can be branched into separate pure
histories. Branches do not share writes.

Tagged errors are `:invalid_index`, `:negative_take`, `:zero_cost`,
`:cost_too_large`, `:zero_quantum` and `:quantum_too_large`. Arguments outside the
documented domain, such as a non-integer index or count, a negative count, or a
negative cost or quantum, raise `ArgumentError` instead of returning a tagged error.
Domain validation precedes shared error ordering: enqueue checks the integer index
and entire proper list of Item structs with nonnegative integer costs first;
set_quantum checks the integer index and nonnegative integer quantum first.
For domain-valid arguments, an invalid index wins, then enqueue reports the first
zero or oversized cost, and set_quantum reports zero or oversized quantum.

Values are opaque: the scheduler stores and returns them without inspecting them.
Costs and quanta are limited to 2^63-1, and each queue's credit stays within
2^64-3. These are shared scheduler limits, not BEAM limits. Fairness is by declared
cost, not time: the scheduler does not measure work, and it makes no unrestricted
fairness promise for dynamic backlogs.

Queues are FIFO and never overtake a blocked head. `take/2` returns up to `n` items
in service order. Enqueue joins the active visit; `set_quantum/3` changes only the
next grant and keeps credit. `remove_queue/1` deletes only the last queue and its
items, and `add_queue/1` may reuse that index. `remove_head/2` and `drain_queue/2`
withdraw items without debiting credit.

Requires Elixir >=1.18 and OTP >=27.

## Examples

Each example is an independent history.

```elixir
s = Dwrr.new(1)
{:ok, s} = Dwrr.enqueue(s, 0, [%Dwrr.Item{value: :job, cost: 2}])
{:ok, served, _s} = Dwrr.take(s, 1)
result = Enum.map(served, & &1.value)
# => [:job]
```

```elixir
s = Dwrr.new(1)
{:ok, old} = Dwrr.enqueue(s, 0, [%Dwrr.Item{value: :original, cost: 1}])
{:ok, served, _after_take} = Dwrr.take(old, 1)
{:ok, drained, _after_drain} = Dwrr.drain_queue(old, 0)
result = {Enum.map(served, & &1.value), Enum.map(drained, & &1.value)}
# => {[:original], [:original]}
```

```elixir
s = Dwrr.new(1)
result = Dwrr.enqueue(s, 0, [%Dwrr.Item{value: :job, cost: 0}])
# => {:error, :zero_cost}
```

# `error`

```elixir
@type error() ::
  :invalid_index
  | :negative_take
  | :zero_cost
  | :cost_too_large
  | :zero_quantum
  | :quantum_too_large
```

# `t`

```elixir
@opaque t(value)
```

# `add_queue`

```elixir
@spec add_queue(t(value)) :: {non_neg_integer(), t(value)} when value: term()
```

Append an empty queue; return {index, scheduler}.

## Examples

    iex> {index, _s} = Dwrr.add_queue(Dwrr.new(1))
    iex> index
    1

# `drain_queue`

```elixir
@spec drain_queue(t(value), integer()) ::
  {:ok, [Dwrr.Item.t(value)], t(value)} | {:error, error()}
when value: term()
```

Withdraw all queue items FIFO; return {:ok, items, scheduler} or {:error, code}.

## Examples

    iex> {:ok, items, _s} = Dwrr.drain_queue(Dwrr.new(1), 0)
    iex> items
    []

# `enqueue`

```elixir
@spec enqueue(t(value), integer(), [%Dwrr.Item{cost: non_neg_integer(), value: value}]) ::
  {:ok, t(value)} | {:error, error()}
when value: term()
```

Append a proper list of Item structs atomically; return {:ok, scheduler} or {:error, code}.

## Examples

    iex> {:ok, s} = Dwrr.enqueue(Dwrr.new(1), 0, [%Dwrr.Item{value: :job, cost: 2}])
    iex> {:ok, items, _s} = Dwrr.take(s, 1)
    iex> items
    [%Dwrr.Scheduled{queue: 0, value: :job, cost: 2}]

# `new`

```elixir
@spec new(non_neg_integer()) :: t(term())
```

Create count empty queues (nonnegative integer); return the scheduler.

## Examples

    iex> s = Dwrr.new(1)
    iex> Dwrr.take(s, 0) |> elem(1)
    []

# `remove_head`

```elixir
@spec remove_head(t(value), integer()) ::
  {:ok, Dwrr.Item.t(value) | nil, t(value)} | {:error, error()}
when value: term()
```

Withdraw one head without debiting credit; return {:ok, Item or nil, scheduler} or {:error, code}.

## Examples

    iex> {:ok, item, _s} = Dwrr.remove_head(Dwrr.new(1), 0)
    iex> item
    nil

# `remove_queue`

```elixir
@spec remove_queue(t(value)) :: t(value) when value: term()
```

Remove only the last queue, discarding items; return scheduler.

## Examples

    iex> s = Dwrr.new(1) |> Dwrr.remove_queue()
    iex> Dwrr.enqueue(s, 0, [])
    {:error, :invalid_index}

# `set_quantum`

```elixir
@spec set_quantum(t(value), integer(), non_neg_integer()) ::
  {:ok, t(value)} | {:error, error()}
when value: term()
```

Set quantum for the next grant without changing credit; return {:ok, scheduler} or {:error, code}.

## Examples

    iex> Dwrr.set_quantum(Dwrr.new(1), 0, 0)
    {:error, :zero_quantum}

# `take`

```elixir
@spec take(t(value), integer()) ::
  {:ok, [Dwrr.Scheduled.t(value)], t(value)} | {:error, error()}
when value: term()
```

Retrieve up to n Scheduled structs, preserving paused visits; return {:ok, items, scheduler} or {:error, code}.

## Examples

    iex> Dwrr.take(Dwrr.new(1), -1)
    {:error, :negative_take}

---

*Consult [api-reference.md](api-reference.md) for complete listing*
