Grove.Counter.GCounter (Grove v0.1.1)

View Source

A grow-only counter (G-Counter) CRDT.

Each replica maintains its own counter that can only be incremented. The value of the counter is the sum of all replica counters. Merge takes the pointwise maximum of all counters.

Delta-State Support

This CRDT supports delta-state replication for efficient synchronization:

  • delta/1 - Returns accumulated changes since last reset
  • reset_delta/1 - Clears the delta buffer after synchronization

Example

iex> counter = Grove.Counter.GCounter.new(:node_a)
iex> counter = Grove.Counter.GCounter.increment(counter)
iex> counter = Grove.Counter.GCounter.increment(counter, 5)
iex> Grove.Counter.GCounter.value(counter)
6

Summary

Functions

Returns the accumulated delta since the last reset.

Returns the count for a specific actor.

Increments the counter by 1.

Increments the counter by the given amount.

Merges two G-Counters by taking the pointwise maximum of all counts.

Creates a new G-Counter for the given actor.

Resets the delta buffer after synchronization.

Returns the current value of the counter (sum of all counts).

Types

actor()

@type actor() :: term()

t()

@type t() :: %Grove.Counter.GCounter{
  actor: actor(),
  counts: %{required(actor()) => non_neg_integer()},
  delta_buffer: %{required(actor()) => non_neg_integer()}
}

Functions

delta(g_counter)

@spec delta(t()) :: t()

Returns the accumulated delta since the last reset.

The delta contains only the changes made locally, which can be sent to other replicas for efficient synchronization.

get(g_counter, actor)

@spec get(t(), actor()) :: non_neg_integer()

Returns the count for a specific actor.

increment(counter)

@spec increment(t()) :: t()

Increments the counter by 1.

increment(counter, amount)

@spec increment(t(), non_neg_integer()) :: t()

Increments the counter by the given amount.

The amount must be non-negative.

merge(counter1, counter2)

@spec merge(t(), t()) :: t()

Merges two G-Counters by taking the pointwise maximum of all counts.

new(actor)

@spec new(actor()) :: t()

Creates a new G-Counter for the given actor.

reset_delta(counter)

@spec reset_delta(t()) :: t()

Resets the delta buffer after synchronization.

Call this after sending the delta to other replicas.

value(g_counter)

@spec value(t()) :: non_neg_integer()

Returns the current value of the counter (sum of all counts).