# `Decree.Aggregates.Aggregate`
[🔗](https://github.com/sparkle-space/decree/blob/v0.1.0/lib/decree/aggregates/aggregate.ex#L1)

Aggregate is a `GenServer` process used to provide access to an
instance of an event sourced aggregate.

It allows execution of commands against an aggregate instance, and handles
persistence of created events to the configured event store. Concurrent
commands sent to an aggregate instance are serialized and executed in the
order received.

The `Decree.Commands.Router` module will locate, or start, an aggregate
instance when a command is dispatched. By default, an aggregate process will
run indefinitely once started. Its lifespan may be controlled by using the
`Decree.Aggregates.AggregateLifespan` behaviour.

## Snapshotting

By default snapshots are *not* taken for an aggregate. An aggregate declares them on its
definition:

    defmodule MyApp.ExampleAggregate do
      use Decree.Aggregate, snapshot: [every: 10, version: 1]

      # ...
    end

  - `every` - snapshot the aggregate state every so many events, a positive integer.

  - `version` - a non-negative integer, 1 when left out: the version of the snapshot's
    shape. Increment it when the state struct changes in a way an older snapshot can't be
    read into.

`Decree.Aggregate` checks both when the module compiles.

### The `snapshotting:` config, a fallback

An aggregate that declares no `snapshot:` still takes its options from the application's
`snapshotting:` config, as before. A later release removes this fallback.

    config :my_app, MyApp.Application,
      snapshotting: %{
        MyApp.ExampleAggregate => [
          snapshot_every: 10,
          snapshot_version: 1
        ]
      }

The definition wins: a module that declares `snapshot:` and is also in the config logs a
warning when the application starts, and its config entry is ignored.
`Decree.Aggregate.snapshot_options/2` answers the options in force.

### One row per version

The store keeps one snapshot row per stream and version. Code at version 1 and code at
version 2 each read and write their own row, so during a rollout neither overwrites the
other's, and a rollback finds its own row as it left it. A version bump therefore folds
each aggregate from its events, for the new version only, until a row exists for it:
`Decree.Aggregate.warm_snapshot/3` records that row without starting the aggregate, and
`Decree.Aggregate.prune_snapshots/2` deletes the older versions' rows once no running code
reads them. A hard delete of a stream deletes its rows at every version, in any pod: a
row's foreign key to its stream cascades the delete.

## Personal fields

An aggregate's fold can read an event's personal fields, listed with
`Decree.PersonalFields.Aggregate`. When one can't be read the aggregate does not guess. It
stops under `{:shutdown, :key_unknown}`, which prints no crash report, and the caller gets
`{:error, :key_unknown}`. That covers populating on dispatch, the rebuild after a
`:wrong_expected_version`, and an event appended to its stream by another process. A cold
`aggregate_state/4` exits with the tuple a call to a stopping aggregate exits with.

A plain `{:error, :key_unknown}` from preparing an append does not stop the aggregate: its
state is still good.

## Unknown event types

An aggregate whose stream holds an event of a type this release does not know (one appended
by a newer release, during a rolling deploy) refuses rather than fold past it. It stops under
`{:shutdown, :unknown_event_type}` and the caller gets `{:error, :unknown_event_type}`, in
the same places as `:key_unknown`: populating on dispatch, the rebuild after a
`:wrong_expected_version`, and a cold `aggregate_state/4`. A running aggregate never receives
such an event: the event store's publisher stops a batch before it. A command it runs
meanwhile fails to append with `:wrong_expected_version` and refuses on the rebuild. A later
event, from a later append, is still sent, and the aggregate stops on the gap it leaves: a
command already queued in its mailbox at that moment answers
`{:error, :aggregate_execution_failed}`, as for any gap, and the next command refuses with
`{:error, :unknown_event_type}`.

`format_status/1` keeps the state, and the dispatch metadata a command carries, out of crash
reports and `:sys.get_status/1`. An aggregate that uses `Decree.PersonalFields.Aggregate` can
hold decrypted state, so what leaves `apply/2`, `execute/2` or `before_execute` on one is
redacted, as that module says. There a throw leaves as an exit, `{:nocatch, reduced}`, whether
it comes while executing a command, rebuilding the state or applying an event another process
appended, and on a rule route it does while executing a command: `gen_server` reads a term
thrown from a callback as its return, and a reduced `{:noreply, _}` is a valid one. The
aggregate stops, and a caller waiting on a command gets
`{:error, :aggregate_execution_failed}`. A throw from a `Decree.Event.Tags` implementation on
an event with a declaration leaves the same way on any aggregate.

## Rules

A route with a `Decree.Decision.Rule` reads in this process, in `execute_command`, after
`before_execute` and before `execute/2`, so the reads hold up the mailbox as a rebuild does.
What they answer lives in one local variable for one `execute/2` call, on a copy of the
command, and the append goes in under a condition. Both retry loops come back through there,
so each attempt reads afresh. See `Decree.Decision.Rule`. A route with no rule, on an
aggregate with no command window, does none of this: it is the same append, with no
statement added.

## Command window

An aggregate that declares `use Decree.Aggregate, command_window: [ms: n]` reads the command
index in `execute_command` too: after `before_execute`, it calls the aggregate's
`authorize/2` on an existing stream, then reads the command item with the rule's items, if
the route has a rule, in one read, classifies the match, and appends under the condition on
every command. A duplicate or a reused id never reaches `execute/2`. See "Command window" in
`Decree.Aggregate`.

## Telemetry

* `[:decree, :aggregate, :execute, :start]`
  * Description: Emitted when an aggregate starts executing a command
  * Measurements: `%{system_time: integer()}`
  * Metadata: `%{application: Decree.Application.t(),
  aggregate_uuid: String.t(),
  aggregate_state: struct(),
  aggregate_version: non_neg_integer(),
  caller: pid(),
  execution_context: Decree.Aggregates.ExecutionContext.t()}
`

* `[:decree, :aggregate, :execute, :stop]`
  * Description: Emitted when an aggregate stops executing a command
  * Measurements: `%{duration: non_neg_integer()}`
  * Metadata: `%{application: Decree.Application.t(),
  aggregate_uuid: String.t(),
  aggregate_state: struct(),
  aggregate_version: non_neg_integer(),
  caller: pid(),
  execution_context: Decree.Aggregates.ExecutionContext.t(),
  events: [map()],
  error: nil | any()}
`

* `[:decree, :aggregate, :execute, :exception]`
  * Description: Emitted when an aggregate raises an exception
  * Measurements: `%{duration: non_neg_integer()}`
  * Metadata: `%{application: Decree.Application.t(),
  aggregate_uuid: String.t(),
  aggregate_state: struct(),
  aggregate_version: non_neg_integer(),
  caller: pid(),
  execution_context: Decree.Aggregates.ExecutionContext.t(),
  kind: :throw | :error | :exit,
  reason: any(),
  stacktrace: list()}
`

# `no_return_event`

```elixir
@type no_return_event() :: :ok | {:ok, []} | nil | []
```

# `return_event`

```elixir
@type return_event() :: struct() | [struct()] | {:ok, struct()} | {:ok, [struct()]}
```

# `state`

```elixir
@type state() :: struct()
```

# `uuid`

```elixir
@type uuid() :: String.t()
```

# `apply`

```elixir
@callback apply(aggregate :: state(), event :: struct()) :: state()
```

Apply an event to the aggregate state. Returns the updated aggregate.

# `execute`
*optional* 

```elixir
@callback execute(aggregate :: state(), command :: struct()) ::
  return_event() | no_return_event() | {:error, term()}
```

Optionally execute a command against the aggregate. Returns either no event, one event,
a list of events, or an error tuple.

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `execute`

Execute the given command against the aggregate.

  - `aggregate_module` - the aggregate's module (e.g. `BankAccount`).
  - `aggregate_uuid` - uniquely identifies an instance of the aggregate.
  - `context` - includes command execution arguments
    (see `Decree.Aggregates.ExecutionContext` for details).
  - `timeout` - a non-negative integer which specifies how many milliseconds
    to wait for a reply, or the atom :infinity to wait indefinitely.
    The default value is five seconds (5,000ms).

## Return values

Returns `{:ok, aggregate_version, events}` on success, or `{:error, error}`
on failure.

  - `aggregate_version` - the updated version of the aggregate after executing
     the command.
  - `events` - events produced by the command, can be an empty list.

# `start_link`

---

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