AshDispatch.Dispatcher (AshDispatch v0.5.1)

View Source

Core dispatcher that handles event delivery across all transports.

This module orchestrates the dispatch process:

  1. Creates DeliveryReceipt with full content
  2. Routes to appropriate transport handler
  3. Updates receipt status based on delivery result

Receipt-First Pattern

All deliveries follow the receipt-first pattern:

  • Receipt created BEFORE delivery attempt
  • Full content stored in receipt (enables retries without re-rendering)
  • Status tracked through lifecycle: pending → scheduled/sent → failed

Transport Routing

Summary

Functions

Dispatches an event by ID with data and variables.

Low-level dispatch function that dispatches to a specific channel with a pre-built context.

Functions

dispatch(event_id, data, variables \\ %{})

Dispatches an event by ID with data and variables.

This is the high-level dispatch function that applications use. It looks up the event module, creates channels, and dispatches to all of them.

Parameters

  • event_id - The event identifier (e.g., "requests.new_reseller_request")
  • data - Map of domain data (resources, users, etc.)
  • variables - Map of template variables (tokens, simple values, etc.) - defaults to %{}

Returns

  • {:ok, results} - List of delivery receipt results
  • {:error, reason} - If event not found or dispatch fails

Data vs Variables

Use data for:

  • Domain resources (User, Order, Ticket, etc.)
  • Structured Ash resources
  • Objects that need relationship traversal

Use variables for:

  • Authentication tokens (reset_token, confirmation_token)
  • Simple template values
  • Computed values that don't need relationships

This separation prevents naming conflicts and makes the intent clearer.

Examples

# Dispatch with authentication token
AshDispatch.Dispatcher.dispatch(
  "accounts.password_reset",
  %{user: user},
  %{reset_token: token}
)

# Dispatch with invitation data
AshDispatch.Dispatcher.dispatch(
  "accounts.invited",
  %{invited_user: user, invited_by: admin},
  %{invitation_token: token, custom_message: message}
)

# Dispatch an order created event (no variables needed)
AshDispatch.Dispatcher.dispatch(
  "orders.created",
  %{order: order, user: user}
)

dispatch_channel(context, channel, event_config)

Low-level dispatch function that dispatches to a specific channel with a pre-built context.

This is used internally and by DSL-based events that build their own context. Most applications should use the high-level dispatch/2 or dispatch/3 functions instead.

Parameters

  • context - Pre-built AshDispatch.Context struct
  • channel - AshDispatch.Channel struct
  • event_config - Event configuration map (with :module, :content, etc.)

Returns

  • {:ok, receipt} - DeliveryReceipt if successful
  • {:error, reason} - If dispatch fails