Cratis Chronicle reactors: handle events and resolve dependencies
A Cratis Chronicle reactor handler receives an event and runs the work that follows it. Choose a signature that supplies the context and dependencies that work needs, then account for how Chronicle orders delivery and reports failures.
The discovery and parameter-resolution rules below describe the .NET client. The examples include other clients where their handler APIs differ.
Event Method Discovery
Section titled “Event Method Discovery”In .NET, Chronicle matches a method to the event type of its first parameter, not to its name. Make the handler public so its purpose is clear. It can request further parameters, such as EventContext, read models, or services, and return void, Task, Task<T>, or a synchronous side-effect type.
For attribute-based event discovery, mark the event parameter’s type with [EventType]. Types nominated through explicit artifact registration do not need that attribute.
When more than one method matches
Section titled “When more than one method matches”A helper such as Task<string> Enrich(OrderPlaced @event) can match the same event as the handler that calls it. The .NET client chooses one method per event type using this precedence:
- Public methods before non-public methods.
- Methods with more parameters before methods with fewer parameters.
- Method name in ordinal order to break a remaining tie.
A private method can still become the handler when no higher-priority method matches. To keep a helper out of dispatch entirely, give it a first parameter that is not an event type. Do not rely on a private modifier alone.
Supported Signatures
Section titled “Supported Signatures”using Cratis.Chronicle.Events;
public interface ReactorHandlerSignatures<TEvent, TResult>{ void MethodName(TEvent @event); void MethodName(TEvent @event, EventContext context);
Task MethodNameAsync(TEvent @event); Task MethodNameAsync(TEvent @event, EventContext context);
Task<TResult> MethodNameReturningAsync(TEvent @event); Task<TResult> MethodNameReturningAsync(TEvent @event, EventContext context);
TResult MethodNameReturning(TEvent @event); TResult MethodNameReturning(TEvent @event, EventContext context);}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.Reactor
@EventTypedata class EventProcessingSignaturesOrderPlaced(val orderId: String)
@EventTypedata class EventProcessingSignaturesOrderShipped(val orderId: String)
@EventTypedata class EventProcessingSignaturesOrderCancelled(val orderId: String)
@EventTypedata class EventProcessingSignaturesRefundIssued(val orderId: String, val amount: Double)
@EventTypedata class EventProcessingSignaturesOrderArchived(val orderId: String)
@Reactorclass EventProcessingSignaturesReactor { // (event) - no metadata needed, no side effect fun placed(event: EventProcessingSignaturesOrderPlaced) { }
// (event, context) - suspend, no side effect suspend fun shipped(event: EventProcessingSignaturesOrderShipped, context: EventContext) { }
// (event) - returns a single side-effect event fun cancelled(event: EventProcessingSignaturesOrderCancelled) = EventProcessingSignaturesOrderArchived(event.orderId)
// (event, context) - suspend, returns a list of side-effect events suspend fun refundIssued( event: EventProcessingSignaturesRefundIssued, context: EventContext ): List<Any> = listOf(EventProcessingSignaturesOrderArchived(event.orderId))}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.Reactor;
import java.util.List;
@EventTyperecord EventProcessingSignaturesOrderPlaced(String orderId) {}
@EventTyperecord EventProcessingSignaturesOrderShipped(String orderId) {}
@EventTyperecord EventProcessingSignaturesOrderCancelled(String orderId) {}
@EventTyperecord EventProcessingSignaturesRefundIssued(String orderId, double amount) {}
@EventTyperecord EventProcessingSignaturesOrderArchived(String orderId) {}
@Reactorclass EventProcessingSignaturesReactor { // (event) - no metadata needed, no side effect void placed(EventProcessingSignaturesOrderPlaced event) { }
// (event, context) - no side effect void shipped(EventProcessingSignaturesOrderShipped event, EventContext context) { }
// (event) - returns a single side-effect event EventProcessingSignaturesOrderArchived cancelled(EventProcessingSignaturesOrderCancelled event) { return new EventProcessingSignaturesOrderArchived(event.orderId()); }
// (event, context) - returns a list of side-effect events List<Object> refundIssued(EventProcessingSignaturesRefundIssued event, EventContext context) { return List.of(new EventProcessingSignaturesOrderArchived(event.orderId())); }}defmodule ReactorSupportedSignaturesOrderPlaced do use Chronicle.Events.EventType, id: "reactor-supported-signatures-order-placed"
defstruct [:order_id]end
defmodule ReactorSupportedSignaturesReactor do use Chronicle.Reactors.Reactor
alias ReactorSupportedSignaturesOrderPlaced
@handles ReactorSupportedSignaturesOrderPlaced
# Every reactor handler has exactly this one shape: the event, then the # context map. There is no family of overloads to choose between — # dispatch always matches on the event's struct type via @handles. @impl true def handle(%ReactorSupportedSignaturesOrderPlaced{} = event, context) do process(event.order_id, Map.get(context, :occurred))
:ok end
defp process(_order_id, _occurred), do: :okendimport { EventContext } from '@cratis/chronicle';
interface ReactorHandlerSignatures<TEvent, TResult> { methodName(event: TEvent): void; methodName(event: TEvent, context: EventContext): void;
methodNameAsync(event: TEvent): Promise<void>; methodNameAsync(event: TEvent, context: EventContext): Promise<void>;
methodNameReturningAsync(event: TEvent): Promise<TResult>; methodNameReturningAsync(event: TEvent, context: EventContext): Promise<TResult>;
methodNameReturning(event: TEvent): TResult; methodNameReturning(event: TEvent, context: EventContext): TResult;}In .NET, TResult can be an event type or a sequence of known events: IEnumerable<TEvent>, TEvent[], List<TEvent>, or IReadOnlyList<TEvent>. See Returning Side Effects for supported return types and metadata resolution.
Do not carry C# overload conventions into another client. Kotlin and Java support event-typed handlers with optional context and resolvable arguments. TypeScript uses event-name conventions or explicit @handles mappings, and Elixir dispatches through @handles and handle/2. Returned-event handling also varies by client; Returning side effects covers those differences.
Event Context
Section titled “Event Context”Use EventContext when the handler needs to identify the event’s source or delivery. It includes the event source ID, sequence number, timestamps, and correlation identifiers:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
[EventType]public record ReactorAccountClosed(Guid AccountId);
public class AuditReactor : IReactor{ public void AccountClosed(ReactorAccountClosed @event, EventContext context) { WriteAudit(@event.AccountId, context.Occurred, context.EventSourceId); }
void WriteAudit(Guid accountId, DateTimeOffset occurred, EventSourceId eventSourceId) { }}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.Reactor
@EventTypedata class ReactorAccountClosed(val accountId: String)
@Reactorclass AuditReactor { fun accountClosed(event: ReactorAccountClosed, context: EventContext) { writeAudit(event.accountId, context.occurred, context.eventSourceId) }
private fun writeAudit(accountId: String, occurred: java.time.Instant, eventSourceId: String) {}}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.Reactor;import java.time.Instant;
@EventTyperecord ReactorAccountClosed(String accountId) {}
@Reactorclass AuditReactor { void accountClosed(ReactorAccountClosed event, EventContext context) { writeAudit(event.accountId(), context.getOccurred(), context.getEventSourceId()); }
private void writeAudit(String accountId, Instant occurred, String eventSourceId) {}}defmodule MyApp.Events.ReactorAccountClosed do use Chronicle.Events.EventType, id: "reactor-account-closed"
defstruct [:account_id]end
defmodule MyApp.Reactors.AuditReactor do use Chronicle.Reactors.Reactor
alias MyApp.Events.ReactorAccountClosed
@handles ReactorAccountClosed
@impl true def handle(%ReactorAccountClosed{} = event, context) do write_audit(event.account_id, Map.get(context, :occurred), Map.get(context, :event_source_id))
:ok end
defp write_audit(_account_id, _occurred, _event_source_id), do: :okendimport { EventContext, eventType, onceOnly, reactor } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class ReactorAccountClosed { @field(String) readonly accountId: string;
constructor(accountId: string) { this.accountId = accountId; }}
@reactor()class AuditReactor { // Method name must be the exact camelCase of the event's class name - // Chronicle discovers handlers by name, not by parameter type. @onceOnly() async reactorAccountClosed(event: ReactorAccountClosed, context: EventContext): Promise<void> { this.writeAudit(event.accountId, context.occurred, context.eventSourceId); }
private writeAudit(accountId: string, occurred: Date, eventSourceId: string): void {}}Taking Dependencies
Section titled “Taking Dependencies”In .NET, keep the event first and add parameters for the data or services the handler needs. Chronicle resolves them when it invokes the method, so the event determines dispatch while the remaining parameters support the work:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Keys;using Cratis.Chronicle.Projections.ModelBound;using Cratis.Chronicle.Reactors;
public interface IReactorShippingService{ Task Schedule(EventProcessingOrder order, decimal price);}
public interface IReactorPricingService{ decimal PriceFor(EventProcessingOrder order);}
[EventType]public record EventProcessingOrderPlaced(decimal Total);
// A read model is resolved by Chronicle only when a projection or reducer builds it.[FromEvent<EventProcessingOrderPlaced>]public record EventProcessingOrder([Key] string Id, decimal Total);
public class EventProcessingOrderProcessor(IReactorShippingService shipping) : IReactor{ public async Task OrderPlaced( EventProcessingOrderPlaced @event, EventContext context, EventProcessingOrder order, IReactorPricingService pricing) { await shipping.Schedule(order, pricing.PriceFor(order)); }}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.Reactorimport io.cratis.chronicle.readModels.ReadModel
@EventTypedata class EventProcessingOrderPlaced(val orderId: String)
@ReadModeldata class EventProcessingOrder(val id: String = "", val total: Double = 0.0)
interface EventProcessingShippingService { suspend fun schedule(order: EventProcessingOrder)}
@Reactorclass EventProcessingOrderProcessor(private val shipping: EventProcessingShippingService) { // `order` is looked up by the triggering event's event source id; a materialized read model // can lag this event or be null. suspend fun orderPlaced(event: EventProcessingOrderPlaced, order: EventProcessingOrder?, context: EventContext) { if (order != null) shipping.schedule(order) }}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.Reactor;import io.cratis.chronicle.readModels.ReadModel;
@EventTyperecord EventProcessingOrderPlaced(String orderId) {}
@ReadModelrecord EventProcessingOrder(String id, double total) { EventProcessingOrder() { this("", 0.0); }}
interface EventProcessingShippingService { void schedule(EventProcessingOrder order);}
@Reactorclass EventProcessingOrderProcessor { private final EventProcessingShippingService shipping;
EventProcessingOrderProcessor(EventProcessingShippingService shipping) { this.shipping = shipping; }
// `order` is looked up by the triggering event's event source id; a materialized read model // can lag this event or be null. void orderPlaced(EventProcessingOrderPlaced event, EventProcessingOrder order, EventContext context) { if (order != null) { shipping.schedule(order); } }}Elixir does not support this workflow yet.TypeScript does not support this workflow yet.For .NET parameter resolution, a type counts as a read model only when a projection or reducer builds it. An EventContext parameter receives the context wherever it appears after the event, and ReactorDelivery receives the current delivery. A read model parameter is resolved by Chronicle; other types, including a plain record, come from the service provider.
A materialized read model is read from its sink, the storage the projection or reducer writes to. That read is eventually consistent and may not include the event being handled yet. Mark the read model [Passive] to compute it from event history when requested instead. Passive reads are scoped by event source ID: a projection that joins other sources or uses a custom key can miss events through this path.
Other clients have their own dependency APIs. Kotlin and Java support argument resolvers, while TypeScript can receive a services argument containing the owning event store and its read models. Elixir’s handler receives the event and context. Select the matching client example rather than applying .NET parameter-resolution rules to all clients.
Resolving the read model key
Section titled “Resolving the read model key”By default, .NET resolves read model parameters using the event context’s EventSourceId as the key. If the read model uses another key, implement ICanResolveReadModelKey on the reactor and return the ReadModelKey to use:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Keys;using Cratis.Chronicle.Projections.ModelBound;using Cratis.Chronicle.Reactors;using Cratis.Chronicle.ReadModels;
[EventType]public record ReactorOrderLineOrderPlaced(string CustomerId);
[EventType]public record ReactorOrderLineAdded(string OrderId);
// The order read model is keyed by the order's event source id.[FromEvent<ReactorOrderLineOrderPlaced>]public record ReactorOrder([Key] string Id, string CustomerId);
public class OrderLineProcessingReactor : IReactor, ICanResolveReadModelKey{ public ReadModelKey Resolve(object @event, EventContext context) => ((ReactorOrderLineAdded)@event).OrderId;
// The line's own event source is not the order, so the key comes from the event. public Task OrderLineAdded(ReactorOrderLineAdded @event, ReactorOrder order) => Task.CompletedTask;}Kotlin does not support this workflow yet.Java does not support this workflow yet.Elixir does not support this workflow yet.TypeScript does not support this workflow yet.The resolved key applies to every read model parameter across all of that reactor’s handler methods. Use this .NET interface only when those read models share the same key selection.
Event Source Isolation
Section titled “Event Source Isolation”Events for one event source form a partition and are delivered in sequence order. Each handler invocation belongs to the source that produced the event. This ordering does not extend to events from other sources.
Concurrency Across Partitions (.NET client)
Section titled “Concurrency Across Partitions (.NET client)”Within one partition, the .NET client runs batches in arrival order. Different partitions of the same reactor can run at the same time, so shared services must be safe for concurrent use. There is no ordering across partitions.
Replay begin and end notifications wait for work in flight. Partition replay notifications run in order with that partition’s events, and results are reported to the kernel one at a time.
The concurrency bound is Reactors.MaxConcurrentPartitions in ChronicleOptions. It defaults to the processor count, capped at 8. Set it to 1 if the handler must process only one batch at a time.
Error Handling
Section titled “Error Handling”If a reactor method throws, its event source partition is marked as failed and pauses without advancing past that event. Fix the cause, then retry the failed partition so processing can resume from its last successful position. See Replay for the recovery APIs, and use Delivery Identity when an external effect might have succeeded before the handler failed.