Chronik v0.1.10 Chronik.Aggregate behaviour View Source

The Chronik.Aggregate is the base for all aggregates in Chronik.

The module that implements the Chronik.Aggregate behaviour module can be configured with a number of options:

  • shutdown_timeout indicates Chronik to shutdown the aggregate GenServer after a number of milliseconds. Defualt value is 15 minutes.

  • snapshot_every indicates that a snapshot must be done on the Chronik.Store every snapshot_every domain events processed. Default value is 100. This configuration is looked up in the :chronik app under the given module.

Example

defmodule DomainEvents do
  defmodule CounterCreated do
    defstruct [:id]
  end

  defmodule CounterIncremented do
    defstruct [:id, :increment]
  end
end

defmodule Counter do
  @behaviour Chronik.Aggregate

  alias Chronik.Aggregate
  alias DomainEvents.CounterCreated
  alias DomainEvents.CounterIncremented

  defstruct [:id, value: 0]

  # Public API

  def create(id), do: Aggregate.command(__MODULE__, id, {:create, id})

  def increment(id, increment),
    do: Aggregate.command(__MODULE__, id, {:increment, increment})

  # Command handlers

  def handle_command({:create, id}, nil) do
    %CounterCreated{id: id}
  end
  def handle_command({:create, _id}, _state) do
    raise "counter alredy created"
  end
  def handle_command({:increment, increment}, %Counter{id: id}) do
    %CounterIncremented{id: id, increment: increment}
  end

  # Event handlers

  def handle_event(%CounterCreated{id: id}, nil) do
    %Counter{id: id}
  end
  def handle_event(%CounterIncremented{increment: i}, %Counter{} = state) do
    update_in(state.value, &(&1 + i))
  end
end

The application code must implement the handle_command and handle_event callbacks.

Link to this section Summary

Types

The state represents the state of an aggregate

t()

An aggregate is identified by its module and an id

Functions

Returns a specification to start this module under a supervisor

The command function is the entry point to Chronik aggregate. It sends the cmd request to the Aggregate identifed by module and id. The timeout is either :infinity or a number of milliseconds (defaults to 5000)

Invoked when the server is started. start_link/3 or start/3 will block until it returns

Start a Chronik.Aggregate with callbacks on module with id id

The state(module, id) function returns the current aggregate state

Callbacks

The handle_command is the entry point for commands on an aggregate

The handle_event is the transition function for the aggregate. After command validation, the aggregate generates a number of domain events and then the aggregate state is updated for each event with this function

Link to this section Types

The state represents the state of an aggregate.

Is used in the to validate a command (in handle_command) and in handle_event callback.

An aggregate is identified by its module and an id.

Link to this section Functions

Returns a specification to start this module under a supervisor.

See Supervisor.

Link to this function command(module, id, cmd, timeout \\ 5000) View Source
command(
  module :: module(),
  id :: Chronik.id(),
  cmd :: term(),
  timeout :: :infinity | non_neg_integer()
) :: :ok | {:error, String.t()}

The command function is the entry point to Chronik aggregate. It sends the cmd request to the Aggregate identifed by module and id. The timeout is either :infinity or a number of milliseconds (defaults to 5000).

The results is either :ok or {:error, reason} in case of failure.

Invoked when the server is started. start_link/3 or start/3 will block until it returns.

args is the argument term (second argument) passed to start_link/3.

Returning {:ok, state} will cause start_link/3 to return {:ok, pid} and the process to enter its loop.

Returning {:ok, state, timeout} is similar to {:ok, state} except handle_info(:timeout, state) will be called after timeout milliseconds if no messages are received within the timeout.

Returning {:ok, state, :hibernate} is similar to {:ok, state} except the process is hibernated before entering the loop. See c:handle_call/3 for more information on hibernation.

Returning :ignore will cause start_link/3 to return :ignore and the process will exit normally without entering the loop or calling c:terminate/2. If used when part of a supervision tree the parent supervisor will not fail to start nor immediately try to restart the GenServer. The remainder of the supervision tree will be (re)started and so the GenServer should not be required by other processes. It can be started later with Supervisor.restart_child/2 as the child specification is saved in the parent supervisor. The main use cases for this are:

  • The GenServer is disabled by configuration but might be enabled later.
  • An error occurred and it will be handled by a different mechanism than the Supervisor. Likely this approach involves calling Supervisor.restart_child/2 after a delay to attempt a restart.

Returning {:stop, reason} will cause start_link/3 to return {:error, reason} and the process to exit with reason reason without entering the loop or calling c:terminate/2.

Callback implementation for GenServer.init/1.

Link to this function start_link(module, id) View Source
start_link(module :: module(), id :: Chronik.id()) ::
  {:ok, pid()} | {:error, reason :: String.t()}

Start a Chronik.Aggregate with callbacks on module with id id.

The state(module, id) function returns the current aggregate state.

This should only be used for debugging purposes.

Link to this section Callbacks

Link to this callback handle_command(cmd, state) View Source
handle_command(cmd :: Chronik.command(), state :: state()) ::
  [Chronik.domain_event()] | no_return()

The handle_command is the entry point for commands on an aggregate.

The command format is application dependend. Throughout Chronik, commands are tagged tuples where the first element is an atom indicating the command to execute and the remaining elements are arguments to the command. E.g: {:add_item, 13, "Elixir Book", "$15.00"}

Example

def handle_command({:add_item, id, book, price}, %Cart{}) do
  %ItemsAdded{id: id, book: book, price: price}
end

This handle_command validate the command. If the command is valid on the given state, the function should return a list (or a single) of domain events. If the command is invalid the handle_command should raise an exception.

Link to this callback handle_event(event, state) View Source
handle_event(event :: Chronik.domain_event(), state :: state()) :: state()

The handle_event is the transition function for the aggregate. After command validation, the aggregate generates a number of domain events and then the aggregate state is updated for each event with this function.

Note that this function can not fail since the domain event where generated by a valid command.