Decree.Commands.Router behaviour (decree v0.1.0)

Copy Markdown View Source

Command routing macro to allow configuration of each command to its command handler.

Example

Define a router module which uses Decree.Commands.Router and configures available commands to dispatch:

defmodule BankRouter do
  use Decree.Commands.Router

  dispatch OpenAccount,
    to: OpenAccountHandler,
    aggregate: BankAccount,
    identity: :account_number
end

The to option determines which module receives the command being dispatched. This command handler module must implement a handle/2 function. It receives the aggregate's state and the command to execute. Usually the command handler module will forward the command to the aggregate.

Once configured, you can either dispatch a command by using the module and specifying the application:

command = %OpenAccount{
  command_id: command_id,
  account_number: account_number,
  initial_balance: 1_000
}

:ok = BankRouter.dispatch(command, application: BankApp)

Or, more simply, you should include the router module in your application:

defmodule BankApp do
  use Decree.Application, otp_app: :my_app

  router MyApp.Router
end

Then dispatch commands using the app:

command = %OpenAccount{
  command_id: command_id,
  account_number: account_number,
  initial_balance: 1_000
}

:ok = BankApp.dispatch(command)

Dispatch command directly to an aggregate

You can route a command directly to an aggregate, without requiring an intermediate command handler.

Example

defmodule BankRouter do
  use Decree.Commands.Router

  # Will route to `BankAccount.open_account/2`
  dispatch OpenAccount, to: BankAccount, identity: :account_number
end

By default, you must define an execute/2 function on the aggregate module, which will be called with the aggregate's state and the command to execute. Using this approach, you must create an execute/2 clause that pattern-matches on each command that the aggregate should handle.

Alternatively, you may specify the name of a function (also receiving both the aggregate state and the command) on your aggregate module to which the command will be dispatched:

Example

defmodule BankRouter do
  use Decree.Commands.Router

  # Will route to `BankAccount.open_account/2`
  dispatch OpenAccount, to: BankAccount, function: :open_account, identity: :account_number
end

Define aggregate identity

You can define the identity field for an aggregate once using the identify macro. The configured identity will be used for all commands registered to the aggregate, unless overridden by a command registration.

Example

defmodule BankRouter do
  use Decree.Commands.Router

  identify BankAccount,
    by: :account_number,
    prefix: "bank-account-"

  dispatch OpenAccount, to: BankAccount
end

An optional identity prefix can be used to distinguish between different aggregates that would otherwise share the same identity. As an example you might have a User and a UserPreferences aggregate that you wish to share the same identity. In this scenario you should specify a prefix for each aggregate (e.g. "user-" and "user-preference-").

The prefix is used as the stream identity when appending and reading the aggregate's events: "<identity_prefix><aggregate_uuid>". It can be a string or a zero arity function returning a string.

A canonical identity

The identity a route resolves, the command's field or what the by: function answered, must be a lowercase canonical UUID (Decree.UUID.canonical?/1), which the requester mints. It is checked as it was given, before the prefix, and nothing converts, trims or downcases it: anything else, a missing field and nil included, answers {:error, :invalid_aggregate_identity} before the aggregate is opened.

An aggregate whose identity is someone else's, such as a Stripe id, declares it opaque:

identify StripeCustomer, by: :customer_id, prefix: "stripe-customer-", opaque: true

An opaque identity is any non-empty binary, taken as it is. opaque: is declared once, on the identify, or on a dispatch route for an aggregate with no identify; a route's opaque: for an aggregate that has an identify is refused when the router compiles, because the identify owns the identity. A decision's identity is never opaque: it is its stream's entity tag, so decide/2 takes no opaque:, and an identify of a decision module with opaque: true is refused when the router compiles.

Command id

Every dispatched command carries a command_id, a lowercase canonical UUID its requester mints (see Decree.Command). The default middleware Decree.Middleware.CommandId refuses any other with {:error, :command_id_required} or {:error, :invalid_command_id}. It runs after every middleware the router registers, which see the command first and whose own refusal is the answer, and before Decree.Middleware.ExtractAggregateIdentity, so a bad command_id is refused before the identity is looked at. The command_uuid a dispatch mints never stands in for it.

A router refuses, when it compiles, a command module that does not use Decree.Command only when it asks to:

use Decree.Commands.Router, require_decree_command: true

It is off by default for now, and the dispatch refusal does not depend on it.

Check a command against a rule

A route can name a Decree.Decision.Rule, which an aggregate's append for that command has to hold to, beyond its own stream. See "Rule" in dispatch/2.

Decide a command with a decision

A command can be routed to a Decree.Decision, which has no aggregate process: it reads what it names, folds it and decides, and its append is conditional on what it read. See decide/2 for the route, and for what is refused when the router compiles.

Dispatch return

By default a successful command dispatch will return :ok. You can change this behaviour by specifying a returning option.

The supported options are:

  • :aggregate_state - to return the updated aggregate state.

  • :aggregate_version - to return only the aggregate version.

  • :events - to return the resultant domain events. An empty list will be returned if no events were produced.

  • :execution_result - to return a Decree.Commands.ExecutionResult struct containing the aggregate's identity, state, version, and any events produced from the command along with their associated metadata.

  • false - don't return anything except an :ok.

Aggregate state

Return the updated aggregate state as part of the dispatch result:

{:ok, %BankAccount{}} = BankApp.dispatch(command, returning: :aggregate_state)

This is useful when you want to immediately return fields from the aggregate's state without requiring a read model projection and waiting for the event(s) to be projected. It may also be appropriate to use this feature for unit tests.

However, be warned that tightly coupling an aggregate's state with read requests may be harmful. It's why CQRS enforces the separation of reads from writes by defining two separate and specialised models.

Aggregate version

You can optionally choose to return the aggregate's version as part of the dispatch result:

{:ok, aggregate_version} = BankApp.dispatch(command, returning: :aggregate_version)

This is useful when you need to wait for an event handler, such as a read model projection, to be up-to-date before querying its data.

Execution results

You can also choose to return the execution result as part of the dispatch result:

alias Decree.Commands.ExecutionResult

{:ok, %ExecutionResult{} = result} = BankApp.dispatch(command, returning: :execution_result)

Or by setting the default_dispatch_return in your application config file:

# config/config.exs
config :decree, default_dispatch_return: :execution_result

Use the execution result struct to get information from the events produced from the command.

Metadata

You can associate metadata with all events created by the command.

Supply a map containing key/value pairs comprising the metadata:

:ok = BankApp.dispatch(command, metadata: %{"ip_address" => "127.0.0.1"})

Causation id

You can associate a :causation_id with the dispatched command, which will also be persisted as the causation_id of every event the command produces. This lets you reconstruct a chain-of-causation across multiple events without persisting commands separately.

:ok = BankApp.dispatch(command, causation_id: some_event_id)

When :causation_id is not provided, the command's own command_uuid is used as the resulting events' causation_id.

An event handler that dispatches a follow-up command can pass the handled event's id (metadata.event_id) as the :causation_id, so the full causation chain is observable on the events alone.

Summary

Callbacks

Dispatch the given command to the registered handler.

Dispatch the given command to the registered handler providing a timeout.

Functions

Configure the command, or list of commands, to be decided by a Decree.Decision.

Configure the command, or list of commands, to be dispatched to the corresponding handler and aggregate.

Define an aggregate's identity

Include the given middleware module to be called before and after success or failure of each command dispatch

Types

dispatch_resp()

@type dispatch_resp() ::
  :ok
  | {:ok, aggregate_state :: struct()}
  | {:ok, aggregate_version :: non_neg_integer()}
  | {:ok, execution_result :: Decree.Commands.ExecutionResult.t()}
  | {:error, :unregistered_command}
  | {:error, reason :: term()}

Callbacks

dispatch(command)

@callback dispatch(command :: struct()) :: dispatch_resp()

Dispatch the given command to the registered handler.

Returns :ok on success, or {:error, reason} on failure.

Example

command = %OpenAccount{
  command_id: command_id,
  account_number: account_number,
  initial_balance: 1_000
}

:ok = BankRouter.dispatch(command)

dispatch(command, timeout_or_opts)

@callback dispatch(
  command :: struct(),
  timeout_or_opts :: non_neg_integer() | :infinity | Keyword.t()
) ::
  dispatch_resp()

Dispatch the given command to the registered handler providing a timeout.

  • command is a command struct which must be registered with the router.

  • timeout_or_opts is either an integer timeout, :infinity, or a keyword list of options.

    The timeout must be an integer greater than zero which specifies how many milliseconds to allow the command to be handled, or the atom :infinity to wait indefinitely. The default timeout value is five seconds.

    Alternatively, an options keyword list can be provided with the following options.

    Options:

    • causation_id - an optional UUID used to identify the cause of the command being dispatched.

    • command_uuid - an optional UUID used to identify the command being dispatched.

    • correlation_id - an optional UUID used to correlate related commands/events together.

    • metadata - an optional map containing key/value pairs comprising the metadata to be associated with all events created by the command.

    • returning - to choose what response is returned from a successful command dispatch. The default is to return an :ok.

      The available options are:

      • :aggregate_state - to return the updated aggregate state in the successful response: {:ok, aggregate_state}.

      • :aggregate_version - to include the aggregate stream version in the successful response: {:ok, aggregate_version}.

      • :events - to return the resultant domain events. An empty list will be returned if no events were produced.

      • :execution_result - to return a Decree.Commands.ExecutionResult struct containing the aggregate's identity, version, and any events produced from the command along with their associated metadata.

      • false - don't return anything except an :ok.

    • timeout - as described above.

Returns :ok on success unless the :returning option is specified where it returns one of {:ok, aggregate_state}, {:ok, aggregate_version}, or {:ok, %Decree.Commands.ExecutionResult{}}.

Returns {:error, reason} on failure.

Example

command = %OpenAccount{
  command_id: command_id,
  account_number: account_number,
  initial_balance: 1_000
}

:ok = BankRouter.dispatch(command, timeout: 30_000)

Functions

decide(command_module_or_modules, opts)

(macro)

Configure the command, or list of commands, to be decided by a Decree.Decision.

Example

defmodule AccountRouter do
  use Decree.Commands.Router

  decide ClaimEmail, to: EmailClaims, identity: :user_id, identity_prefix: "user-"
end

The params are to, identity, identity_prefix, stream_tag and timeout, as on dispatch/2, and identify/2 works on the decision module as it does on an aggregate. The events land on <identity_prefix><identity>, or on the members Decree.Decision.decide/2 names, under that prefix. Middleware and returning: work as on an aggregate route. See Decree.Decision.

Prefixes

A decision's stream prefix must be declared in the event store's conditional_appends: the store then refuses anything but a decision's conditional append on those streams. So that it can, a route is refused when the router compiles, with an ArgumentError, for:

  • no identity, neither identity: nor an identify with by:: no dispatch could name a stream.
  • no prefix, or "": the store could not tell these streams from any other.
  • a function prefix: nothing can compare it at build time.
  • a function identity with no stream_tag:: it has no kind for the stream's entity tag.
  • an aggregate route's or an identify's binary prefix overlapping the decision's, one being a prefix of the other: the aggregate's appends would be refused at run time.

The same overlap is refused across the routers of a Decree.Commands.CompositeRouter, and of a Decree.Application, which is one.

An aggregate's function prefix and an aggregate's bare identity, with no prefix, cannot be checked at build time. The store's refusal holds them: {:error, :plain_append_to_conditional_prefix} when such a stream lands in a declared prefix.

dispatch(command_module_or_modules, opts)

(macro)

Configure the command, or list of commands, to be dispatched to the corresponding handler and aggregate.

Example

defmodule BankRouter do
  use Decree.Commands.Router

  dispatch [OpenAccount, DepositMoney], to: BankAccount, identity: :account_number
end

Stream tag

Every event a route appends carries an entity tag for its stream, <kind>:<id>, as long as the identity the stream was routed by is a lowercase canonical UUID. Anything else, such as a Stripe id, gives no tag. The id is that identity as a string, never the stream name with its identify prefix.

The kind is the identity field's name without a trailing _id, so user_id gives user: and content_ref gives content_ref:. A route names it with stream_tag:, an atom other than nil, true or false whose name matches ^[a-z][a-z0-9_]*$, so that it fits the tag grammar. dispatch refuses anything else when the router compiles:

dispatch [RequestExport], to: Export, identity: :requester_user_id, stream_tag: :user

A function identity (by: &Module.function/1) has no field name, so it has a stream tag only when the route declares stream_tag:. The id is then what the function answered when the dispatch resolved the identity, once, before the aggregate is called.

Rule

rule: names a Decree.Decision.Rule for this route alone, so the aggregate's other commands stay plain:

dispatch RegisterUser, to: User, identity: :user_id, rule: EmailRule

The aggregate reads what the rule names, execute/2 finds the events in the command's :rule_result field, and the append goes in under a condition on what was read. The event store's conditional_appends must name the route's aggregate in targets:, which a declared prefix does not stand in for, and an application that includes the route fails to start without it: a check started right after its store raises an ArgumentError. See "Two declarations" in Decree.Decision.Rule.

dispatch refuses, with an ArgumentError when the router compiles, a rule: that is not a compiled Decree.Decision.Rule, and a command with no :rule_result field. decide/2 takes no rule:: a decision is its own rule.

Opaque identity

opaque: true takes any non-empty binary as the route's identity, rather than only a canonical UUID, for an aggregate with no identify:

dispatch RecordStripeEvent, to: StripeEvent, identity: :event_id, opaque: true

For an aggregate with an identify, opaque: belongs there, and a route's is refused when the router compiles. See "Define aggregate identity" in the module doc.

identify(aggregate_module, opts)

(macro)

Define an aggregate's identity

You can define the identity field for an aggregate using the identify macro. The configured identity will be used for all commands registered to the aggregate, unless overridden by a command registration.

Example

defmodule BankRouter do
  use Decree.Commands.Router

  identify BankAccount,
    by: :account_number,
    prefix: "bank-account-"
end

The options are by:, a field or a one-arity function, prefix:, a string or a zero-arity function, and opaque:, true for an identity that is any non-empty binary rather than a canonical UUID, false by default. See "Define aggregate identity" in the module doc.

middleware(middleware_module)

(macro)

Include the given middleware module to be called before and after success or failure of each command dispatch

The middleware module must implement the Decree.Middleware behaviour.

Middleware modules are executed in the order they are defined, and all of them before the router's default middleware: Decree.Middleware.CommandId, which refuses a command whose command_id is not a canonical UUID, then Decree.Middleware.ExtractAggregateIdentity. A registered middleware so sees every command, and its own halt is the answer.

Example

defmodule BankRouter do
  use Decree.Commands.Router

  middleware CommandLogger
  middleware MyCommandValidator
  middleware AuthorizeCommand

  dispatch [OpenAccount, DepositMoney], to: BankAccount, identity: :account_number
end