Cratis Chronicle projections: map event context
Event context in Cratis Chronicle is metadata stored alongside an event rather than in its business payload. Map it into a read model when a query needs to show when an update occurred, identify its source, or connect it to a related operation without adding those fields to every event contract.
Available event context properties
Section titled “Available event context properties”Common EventContext properties used in projection mappings include:
EventSourceId- The identifier of the event source that produced the eventSequenceNumber- The position of the event in the event sequenceOccurred- When the event occurred (timestamp)EventType- Information about the event typeEventSourceType- The type of the event sourceEventStreamType- The type of the event streamEventStreamId- The identifier of the event streamCorrelationId- The correlation identifier linking related operationsCausation- The recorded chain of causes that led to the eventCausedBy- Identity information about who caused the event
Mapping to event source ID
Section titled “Mapping to event source ID”Use ToEventSourceId() when a read model property should retain the source ID. The example also maps Occurred so the read model can report the last login or activity time:
using Cratis.Chronicle.Projections;
public class DecEventContextUserActivityProjection : IProjectionFor<DecEventContextUserActivity>{ public void Define(IProjectionBuilderFor<DecEventContextUserActivity> builder) => builder .From<DecEventContextUserLoggedIn>(_ => _ .Set(m => m.UserId).ToEventSourceId() .Set(m => m.LastLogin).ToEventContextProperty(c => c.Occurred)) .From<DecEventContextUserPerformedAction>(_ => _ .Set(m => m.UserId).ToEventSourceId() .Set(m => m.LastActivity).ToEventContextProperty(c => c.Occurred));}import io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
class DecEventContextUserActivityProjection : IProjectionFor<DecEventContextUserActivity> { override fun define(builder: IProjectionBuilderFor<DecEventContextUserActivity>) { builder .from(DecEventContextUserLoggedIn::class) { it.set(DecEventContextUserActivity::userId).toEventSourceId() it.set(DecEventContextUserActivity::lastLogin).toEventContextProperty("occurred") } .from(DecEventContextUserPerformedAction::class) { it.set(DecEventContextUserActivity::userId).toEventSourceId() it.set(DecEventContextUserActivity::lastActivity).toEventContextProperty("occurred") } }}import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
class DecEventContextUserActivityProjection implements IProjectionFor<DecEventContextUserActivity> { @Override public void define(IProjectionBuilderFor<DecEventContextUserActivity> builder) { builder .from(DecEventContextUserLoggedIn.class, fb -> { fb.set("userId").toEventSourceId(); fb.set("lastLogin").toEventContextProperty("occurred"); }) .from(DecEventContextUserPerformedAction.class, fb -> { fb.set("userId").toEventSourceId(); fb.set("lastActivity").toEventContextProperty("occurred"); }); }}defmodule MyApp.Projections.DecEventContextUserActivityProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecEventContextUserActivity
alias MyApp.Events.{DecEventContextUserLoggedIn, DecEventContextUserPerformedAction}
from DecEventContextUserLoggedIn, set: [ user_id: :event_source_id, last_login: :occurred ]
from DecEventContextUserPerformedAction, set: [ user_id: :event_source_id, last_activity: :occurred ]endimport { IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';
@projection()class DecEventContextUserActivityProjection implements IProjectionFor<DecEventContextUserActivity> { define(builder: IProjectionBuilderFor<DecEventContextUserActivity>): void { builder .from(DecEventContextUserLoggedIn, _ => _ .set(m => m.userId).toEventSourceId() .set(m => m.lastLogin).toEventContextProperty('occurred')) .from(DecEventContextUserPerformedAction, _ => _ .set(m => m.userId).toEventSourceId() .set(m => m.lastActivity).toEventContextProperty('occurred')); }}Mapping to event context properties
Section titled “Mapping to event context properties”Use ToEventContextProperty() with an accessor for the metadata you need. Here, the sequence number, occurrence time, and correlation ID are mapped explicitly; matching business properties still use AutoMap.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record DecEventContextUserAction(string UserId, string ActionType);
public class DecEventContextAuditTrailProjection : IProjectionFor<DecEventContextAuditEntry>{ public void Define(IProjectionBuilderFor<DecEventContextAuditEntry> builder) => builder .From<DecEventContextUserAction>(_ => _ .Set(m => m.EventId).ToEventContextProperty(c => c.SequenceNumber) .Set(m => m.OccurredAt).ToEventContextProperty(c => c.Occurred) .Set(m => m.CorrelationId).ToEventContextProperty(c => c.CorrelationId));}import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.IProjectionBuilderForimport io.cratis.chronicle.projections.IProjectionFor
@EventTypedata class DecEventContextUserAction(val userId: String, val actionType: String)
class DecEventContextAuditTrailProjection : IProjectionFor<DecEventContextAuditEntry> { override fun define(builder: IProjectionBuilderFor<DecEventContextAuditEntry>) { builder .autoMap() .from(DecEventContextUserAction::class) { it.set(DecEventContextAuditEntry::eventId).toEventContextProperty("sequenceNumber") it.set(DecEventContextAuditEntry::occurredAt).toEventContextProperty("occurred") it.set(DecEventContextAuditEntry::correlationId).toEventContextProperty("correlationId") } }}import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.IProjectionBuilderFor;import io.cratis.chronicle.projections.IProjectionFor;
@EventTyperecord DecEventContextUserAction(String userId, String actionType) {}
class DecEventContextAuditTrailProjection implements IProjectionFor<DecEventContextAuditEntry> { @Override public void define(IProjectionBuilderFor<DecEventContextAuditEntry> builder) { builder .autoMap() .from(DecEventContextUserAction.class, fb -> { fb.set("eventId").toEventContextProperty("sequenceNumber"); fb.set("occurredAt").toEventContextProperty("occurred"); fb.set("correlationId").toEventContextProperty("correlationId"); }); }}defmodule MyApp.Events.DecEventContextUserAction do use Cratis.Chronicle.Events.EventType, id: "dec-event-context-user-action"
defstruct [:user_id, :action_type]end
defmodule MyApp.Projections.DecEventContextAuditTrailProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecEventContextAuditEntry
alias MyApp.Events.DecEventContextUserAction
from DecEventContextUserAction, set: [ event_id: "$context.sequenceNumber", occurred_at: :occurred, correlation_id: "$context.correlationId" ]endimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';
@eventType()class DecEventContextUserAction { userId = ''; actionType = '';}
@projection()class DecEventContextAuditTrailProjection implements IProjectionFor<DecEventContextAuditEntry> { define(builder: IProjectionBuilderFor<DecEventContextAuditEntry>): void { builder .autoMap() .from(DecEventContextUserAction, _ => _ .set(m => m.eventId).toEventContextProperty('sequenceNumber') .set(m => m.occurredAt).toEventContextProperty('occurred') .set(m => m.correlationId).toEventContextProperty('correlationId')); }}Read models with context data
Section titled “Read models with context data”Declare target properties for the metadata your query returns. The activity model stores timestamps, while the audit-entry model also stores sequence and correlation values:
public record DecEventContextUserActivity( string UserId, DateTimeOffset LastLogin, DateTimeOffset LastActivity);
public record DecEventContextAuditEntry( ulong EventId, DateTimeOffset OccurredAt, string CorrelationId, string ActionType, string UserId);data class DecEventContextUserActivity( val userId: String = "", val lastLogin: String = "", val lastActivity: String = "")
data class DecEventContextAuditEntry( val eventId: Long = 0, val occurredAt: String = "", val correlationId: String = "", val actionType: String = "", val userId: String = "")class DecEventContextUserActivity { public String userId = ""; public String lastLogin = ""; public String lastActivity = "";}
class DecEventContextAuditEntry { public long eventId = 0; public String occurredAt = ""; public String correlationId = ""; public String actionType = ""; public String userId = "";}defmodule MyApp.ReadModels.DecEventContextUserActivity do use Cratis.Chronicle.ReadModels.ReadModel
defstruct [:user_id, :last_login, :last_activity]end
defmodule MyApp.ReadModels.DecEventContextAuditEntry do use Cratis.Chronicle.ReadModels.ReadModel
defstruct [:event_id, :occurred_at, :correlation_id, :action_type, :user_id]endclass DecEventContextUserActivity { userId = ''; lastLogin = new Date(); lastActivity = new Date();}
class DecEventContextAuditEntry { eventId: bigint = 0n; occurredAt = new Date(); correlationId = ''; actionType = ''; userId = '';}Composite keys with event context
Section titled “Composite keys with event context”Context values can also help identify the instance to update. This example uses the occurrence timestamp and sequence number as parts of a composite key:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record DecEventContextUserActionForKey(string UserId, string ActionType);
public record DecEventContextEventLogKey(DateTimeOffset Date, ulong SequenceNumber);
public record DecEventContextEventLogEntry( DecEventContextEventLogKey Id, string ActionType, string UserId);
public class DecEventContextEventLogProjection : IProjectionFor<DecEventContextEventLogEntry>{ public void Define(IProjectionBuilderFor<DecEventContextEventLogEntry> builder) => builder .From<DecEventContextUserActionForKey>(_ => _ .UsingCompositeKey<DecEventContextEventLogKey>(_ => _ .Set(k => k.Date).ToEventContextProperty(c => c.Occurred) .Set(k => k.SequenceNumber).ToEventContextProperty(c => c.SequenceNumber)));}Kotlin does not support this workflow yet.`ICompositeKeyBuilderFor.property(targetPropertyName, eventPropertyName)` only pairs a read modelproperty with a plain event property name — there is no way to source a composite key part from anevent context property (e.g. `Occurred`, `SequenceNumber`), and there is no typed composite-keyresult shape like C#'s `UsingCompositeKey<TKey>`.Java does not support this workflow yet.`ICompositeKeyBuilderFor.property(targetPropertyName, eventPropertyName)` only pairs a read modelproperty with a plain event property name — there is no way to source a composite key part from anevent context property (e.g. `Occurred`, `SequenceNumber`), and there is no typed composite-keyresult shape like C#'s `UsingCompositeKey<TKey>`.defmodule MyApp.Events.DecEventContextUserActionForKey do use Cratis.Chronicle.Events.EventType, id: "dec-event-context-user-action-for-key"
defstruct [:user_id, :action_type]end
defmodule MyApp.ReadModels.DecEventContextEventLogKey do defstruct [:date, :sequence_number]end
defmodule MyApp.ReadModels.DecEventContextEventLogEntry do use Cratis.Chronicle.ReadModels.ReadModel
defstruct [:id, :action_type, :user_id]end
defmodule MyApp.Projections.DecEventContextEventLogProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecEventContextEventLogEntry
alias MyApp.Events.DecEventContextUserActionForKey
from DecEventContextUserActionForKey, key: {:composite, [ date: {:event_context, "Occurred"}, sequence_number: {:event_context, "SequenceNumber"} ]}endTypeScript does not support this workflow yet.Event context in children and joins
Section titled “Event context in children and joins”The same context-mapping methods are available inside child and join mappings. This child-collection example stores a timestamp and sequence number on each activity item:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections;
[EventType]public record DecEventContextActivityPerformed(string ActivityId, string ActivityType);
public record DecEventContextActivityLogEntry( string ActivityId, DateTimeOffset Timestamp, ulong SequenceNumber);
public record DecEventContextUserWithActivityLog( IEnumerable<DecEventContextActivityLogEntry> ActivityLog);
public class DecEventContextUserActivityLogProjection : IProjectionFor<DecEventContextUserWithActivityLog>{ public void Define(IProjectionBuilderFor<DecEventContextUserWithActivityLog> builder) => builder .Children(m => m.ActivityLog, children => children .IdentifiedBy(e => e.ActivityId) .From<DecEventContextActivityPerformed>(_ => _ .UsingKey(e => e.ActivityId) .Set(m => m.Timestamp).ToEventContextProperty(c => c.Occurred) .Set(m => m.SequenceNumber).ToEventContextProperty(c => c.SequenceNumber)));}Kotlin does not support this workflow yet.`ISetBuilderFor` (used by both the top-level `from()` and the child `from()` builders) only has`to()`, `toEventSourceId()` and `toProperty()` — `toEventContextProperty()` exists solely on`IAllSetBuilderFor`, reachable only through `fromEvery()`/`fromAll()`, which apply to every event theprojection observes rather than a single event type inside a child collection.Java does not support this workflow yet.`ISetBuilderFor` (used by both the top-level `from()` and the child `from()` builders) only has`to()`, `toEventSourceId()` and `toProperty()` — `toEventContextProperty()` exists solely on`IAllSetBuilderFor`, reachable only through `fromEvery()`/`fromAll()`, which apply to every event theprojection observes rather than a single event type inside a child collection.defmodule MyApp.Events.DecEventContextActivityPerformed do use Cratis.Chronicle.Events.EventType, id: "dec-event-context-activity-performed"
defstruct [:activity_id, :activity_type]end
defmodule MyApp.ReadModels.DecEventContextActivityLogEntry do use Cratis.Chronicle.ReadModels.ReadModel
defstruct activity_id: nil, timestamp: nil, sequence_number: 0end
defmodule MyApp.ReadModels.DecEventContextUserWithActivityLog do use Cratis.Chronicle.ReadModels.ReadModel, types: [activity_log: {:list, MyApp.ReadModels.DecEventContextActivityLogEntry}]
defstruct activity_log: []end
defmodule MyApp.Projections.DecEventContextUserActivityLogProjection do use Cratis.Chronicle.Projections.Projection, model: MyApp.ReadModels.DecEventContextUserWithActivityLog
children :activity_log, identified_by: :activity_id do from MyApp.Events.DecEventContextActivityPerformed, key: :activity_id, set: [ activity_id: :activity_id, timestamp: :occurred, sequence_number: "$eventContext(SequenceNumber)" ] endendimport { eventType, IProjectionBuilderFor, IProjectionFor, projection } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class DecEventContextActivityPerformed { @field(String) readonly activityId: string; @field(String) readonly activityType: string;
constructor(activityId: string, activityType: string) { this.activityId = activityId; this.activityType = activityType; }}
class DecEventContextActivityLogEntry { @field(String) activityId = ''; @field(Date) timestamp = new Date(); @field(Number) sequenceNumber: bigint = 0n;}
class DecEventContextUserWithActivityLog { @field(Array, { genericArguments: [DecEventContextActivityLogEntry] }) activityLog: DecEventContextActivityLogEntry[] = [];}
@projection('', DecEventContextUserWithActivityLog)class DecEventContextUserActivityLogProjection implements IProjectionFor<DecEventContextUserWithActivityLog> { define(builder: IProjectionBuilderFor<DecEventContextUserWithActivityLog>): void { builder .children<DecEventContextActivityLogEntry>(m => m.activityLog, children => children .identifiedBy(e => e.activityId) .autoMap() .from(DecEventContextActivityPerformed, _ => _ .usingKey(e => e.activityId) .set(m => m.timestamp).toEventContextProperty('occurred') .set(m => m.sequenceNumber).toEventContextProperty('sequenceNumber'))); }}
@eventType()class DecEventContextOrderLineAdded { @field(String) readonly productId: string;
constructor(productId: string) { this.productId = productId; }}
class DecEventContextOrderLine { lineId = ''; productId = '';}
class DecEventContextOrder { @field(Array, { genericArguments: [DecEventContextOrderLine] }) lines: DecEventContextOrderLine[] = [];}
// addChild can take the child key and the parent key from the event context:// each line is identified by the sequence number of the event that added it.// The event has no lineId property, so AutoMap copies productId without overwriting the key.@projection('', DecEventContextOrder)class DecEventContextOrderProjection implements IProjectionFor<DecEventContextOrder> { define(builder: IProjectionBuilderFor<DecEventContextOrder>): void { builder.from(DecEventContextOrderLineAdded, from => from .addChild(model => model.lines, child => child .identifiedBy(line => line.lineId) .usingKeyFromContext('sequenceNumber') .usingParentKeyFromContext('eventSourceId'))); }}Event definitions
Section titled “Event definitions”The event payloads keep their business fields; timestamps and sequence numbers come from context instead:
using Cratis.Chronicle.Events;
[EventType]public record DecEventContextUserLoggedIn(string Username);
[EventType]public record DecEventContextUserPerformedAction(string UserId, string ActionType);import io.cratis.chronicle.events.EventType
@EventTypedata class DecEventContextUserLoggedIn(val username: String)
@EventTypedata class DecEventContextUserPerformedAction(val userId: String, val actionType: String)import io.cratis.chronicle.events.EventType;
@EventTyperecord DecEventContextUserLoggedIn(String username) {}
@EventTyperecord DecEventContextUserPerformedAction(String userId, String actionType) {}defmodule MyApp.Events.DecEventContextUserLoggedIn do use Cratis.Chronicle.Events.EventType, id: "dec-event-context-user-logged-in"
defstruct [:username]end
defmodule MyApp.Events.DecEventContextUserPerformedAction do use Cratis.Chronicle.Events.EventType, id: "dec-event-context-user-performed-action"
defstruct [:user_id, :action_type]endimport { eventType } from '@cratis/chronicle';
@eventType()class DecEventContextUserLoggedIn { username = '';}
@eventType()class DecEventContextUserPerformedAction { userId = ''; actionType = '';}Common use cases
Section titled “Common use cases”Audit trails
Section titled “Audit trails”Map Occurred, SequenceNumber, and CausedBy when the query needs timing, sequence position, and the recorded identity behind an update. Choose which events and business values the audit view must retain; metadata alone is not a complete audit trail.
Debugging and diagnostics
Section titled “Debugging and diagnostics”Store CorrelationId when you need to look up related events or operations carrying that identifier.
Time-based queries
Section titled “Time-based queries”Use Occurred to group or filter results by occurrence time. For weekly keys, pair the ISO week number with its week-year as shown in composite keys.
Event ordering
Section titled “Event ordering”Store SequenceNumber to retain an event’s position within its event sequence. Copying it into a property does not sort a child collection or establish order across different sequences.
Source tracking
Section titled “Source tracking”Use EventSourceId to identify the event source associated with an update.
For metadata that should update across the event types your projection already handles, continue with FromEvery. Use FromAll only when unrelated event types in the sequence should contribute too.