Cratis Chronicle model-bound projections: Use constant keys
Use a constant key in Cratis Chronicle when events from different event sources should update one shared read model instance. Instead of selecting an instance by the event source id, the mapping uses a fixed string, such as "metrics". This lets a counter track a total across sources rather than a separate total for each source.
FromEvent with ConstantKey
Section titled “FromEvent with ConstantKey”In .NET, set ConstantKey on the class-level [FromEvent] attribute to route that event type to a fixed instance:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Projections.ModelBound;
[EventType]public record MbConstantKeyOrderPlaced(string CustomerName, DateTimeOffset PlacedAt);
[FromEvent<MbConstantKeyOrderPlaced>(ConstantKey = "global")]public record MbConstantKeyGlobalOrderSummary( [SetFrom<MbConstantKeyOrderPlaced>(nameof(MbConstantKeyOrderPlaced.CustomerName))] string LastCustomer,
[SetFrom<MbConstantKeyOrderPlaced>(nameof(MbConstantKeyOrderPlaced.PlacedAt))] DateTimeOffset LastOrderDate);Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.ConstantKeyOrderPlaced do use Cratis.Chronicle.Events.EventType, id: "constant-key-order-placed-v1"
defstruct [:customer_name, :placed_at]end
defmodule MyApp.ReadModels.GlobalOrderSummary do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.ConstantKeyOrderPlaced
defstruct [:last_customer, :last_order_date]
# A literal `$value(...)` key expression routes every event to the same # instance, regardless of which event source produced it. from ConstantKeyOrderPlaced, key: "$value(global)", set: [last_customer: :customer_name, last_order_date: :placed_at]endimport { eventType, fromEvent, setFrom } from '@cratis/chronicle';
@eventType()export class MbConstantKeyOrderPlaced { customerName = ''; placedAt = new Date();}
@fromEvent(MbConstantKeyOrderPlaced, { constantKey: 'global' })export class MbConstantKeyGlobalOrderSummary { @setFrom(MbConstantKeyOrderPlaced, 'customerName') lastCustomer = '';
@setFrom(MbConstantKeyOrderPlaced, 'placedAt') lastOrderDate = new Date();}Every matching order-placement event updates the same summary instance, regardless of its event source. A constant key selects the destination; the property’s mappings still decide whether to replace a value, add an amount, or count the event.
Count, Increment, and Decrement with ConstantKey
Section titled “Count, Increment, and Decrement with ConstantKey”Count, Increment, and Decrement also accept ConstantKey. Give the counter events the same key when they should contribute to one shared document:
using Cratis.Chronicle.Keys;using Cratis.Chronicle.Projections.ModelBound;
[EventType]public record MbConstantKeyOrderPlacedForMetrics;
[EventType]public record MbConstantKeyUserLoggedIn;
[EventType]public record MbConstantKeyUserLoggedOut;
[EventType]public record MbConstantKeyErrorOccurred;
public record MbConstantKeySystemMetrics( [Count<MbConstantKeyOrderPlacedForMetrics>(ConstantKey = "metrics")] int TotalOrders,
[Increment<MbConstantKeyUserLoggedIn>(ConstantKey = "metrics")] [Decrement<MbConstantKeyUserLoggedOut>(ConstantKey = "metrics")] int ActiveSessions,
[Count<MbConstantKeyErrorOccurred>(ConstantKey = "metrics")] int TotalErrors);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.Countimport io.cratis.chronicle.projections.Decrementimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.Incrementimport io.cratis.chronicle.readModels.ReadModel
@EventTypeclass MbConstantKeyOrderPlacedForMetrics
@EventTypeclass MbConstantKeyUserLoggedIn
@EventTypeclass MbConstantKeyUserLoggedOut
@EventTypeclass MbConstantKeyErrorOccurred
@ReadModel@FromEvent(MbConstantKeyOrderPlacedForMetrics::class)@FromEvent(MbConstantKeyUserLoggedIn::class)@FromEvent(MbConstantKeyUserLoggedOut::class)@FromEvent(MbConstantKeyErrorOccurred::class)data class MbConstantKeySystemMetrics( @Count(MbConstantKeyOrderPlacedForMetrics::class, constantKey = "metrics") val totalOrders: Int = 0,
@Increment(MbConstantKeyUserLoggedIn::class, constantKey = "metrics") @Decrement(MbConstantKeyUserLoggedOut::class, constantKey = "metrics") val activeSessions: Int = 0,
@Count(MbConstantKeyErrorOccurred::class, constantKey = "metrics") val totalErrors: Int = 0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.Count;import io.cratis.chronicle.projections.Decrement;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.Increment;import io.cratis.chronicle.readModels.ReadModel;
@EventTypeclass MbConstantKeyOrderPlacedForMetrics {}
@EventTypeclass MbConstantKeyUserLoggedIn {}
@EventTypeclass MbConstantKeyUserLoggedOut {}
@EventTypeclass MbConstantKeyErrorOccurred {}
@ReadModel@FromEvent(eventType = MbConstantKeyOrderPlacedForMetrics.class)@FromEvent(eventType = MbConstantKeyUserLoggedIn.class)@FromEvent(eventType = MbConstantKeyUserLoggedOut.class)@FromEvent(eventType = MbConstantKeyErrorOccurred.class)class MbConstantKeySystemMetrics { @Count(eventType = MbConstantKeyOrderPlacedForMetrics.class, constantKey = "metrics") public int totalOrders = 0;
@Increment(eventType = MbConstantKeyUserLoggedIn.class, constantKey = "metrics") @Decrement(eventType = MbConstantKeyUserLoggedOut.class, constantKey = "metrics") public int activeSessions = 0;
@Count(eventType = MbConstantKeyErrorOccurred.class, constantKey = "metrics") public int totalErrors = 0;}defmodule MyApp.Events.ConstantKeyOrderPlacedForMetrics do use Cratis.Chronicle.Events.EventType, id: "constant-key-order-placed-for-metrics-v1"
defstruct []end
defmodule MyApp.Events.ConstantKeyUserLoggedIn do use Cratis.Chronicle.Events.EventType, id: "constant-key-user-logged-in-v1"
defstruct []end
defmodule MyApp.Events.ConstantKeyUserLoggedOut do use Cratis.Chronicle.Events.EventType, id: "constant-key-user-logged-out-v1"
defstruct []end
defmodule MyApp.Events.ConstantKeyErrorOccurred do use Cratis.Chronicle.Events.EventType, id: "constant-key-error-occurred-v1"
defstruct []end
defmodule MyApp.ReadModels.SystemMetrics do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.{ ConstantKeyOrderPlacedForMetrics, ConstantKeyUserLoggedIn, ConstantKeyUserLoggedOut, ConstantKeyErrorOccurred }
defstruct total_orders: 0, active_sessions: 0, total_errors: 0
from ConstantKeyOrderPlacedForMetrics, key: "$value(metrics)", count: :total_orders
from ConstantKeyUserLoggedIn, key: "$value(metrics)", add: [active_sessions: 1]
from ConstantKeyUserLoggedOut, key: "$value(metrics)", subtract: [active_sessions: 1]
from ConstantKeyErrorOccurred, key: "$value(metrics)", count: :total_errorsendimport { count, decrement, eventType, increment } from '@cratis/chronicle';
@eventType()export class MbConstantKeyOrderPlacedForMetrics {}
@eventType()export class MbConstantKeyUserLoggedIn {}
@eventType()export class MbConstantKeyUserLoggedOut {}
@eventType()export class MbConstantKeyErrorOccurred {}
export class MbConstantKeySystemMetrics { @count(MbConstantKeyOrderPlacedForMetrics, 'metrics') totalOrders = 0;
@increment(MbConstantKeyUserLoggedIn, 'metrics') @decrement(MbConstantKeyUserLoggedOut, 'metrics') activeSessions = 0;
@count(MbConstantKeyErrorOccurred, 'metrics') totalErrors = 0;}Here, the three counter properties update the "metrics" document regardless of which user or order produced the events.
Mixing event source key and constant key
Section titled “Mixing event source key and constant key”A read model can use the event source id for one event type and a constant key for another. The destination is selected per event mapping, not once for the entire read model type:
[EventType]public record MbConstantKeyUserRegistered;
[EventType]public record MbConstantKeyOrderPlacedGlobal;
[FromEvent<MbConstantKeyUserRegistered>]public record MbConstantKeyUserDashboard( [Key] Guid UserId,
string Name,
// A per-instance property alongside a constant-keyed one on the same read model [Count<MbConstantKeyOrderPlacedGlobal>(ConstantKey = "global-stats")] int PlatformTotalOrders);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.Countimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.readModels.ReadModel
@EventTypeclass MbConstantKeyUserRegistered
@EventTypeclass MbConstantKeyOrderPlacedGlobal
@ReadModel@FromEvent(MbConstantKeyUserRegistered::class)@FromEvent(MbConstantKeyOrderPlacedGlobal::class)data class MbConstantKeyUserDashboard( val name: String = "",
// A per-instance property alongside a constant-keyed one on the same read model @Count(MbConstantKeyOrderPlacedGlobal::class, constantKey = "global-stats") val platformTotalOrders: Int = 0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.Count;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.readModels.ReadModel;
@EventTypeclass MbConstantKeyUserRegistered {}
@EventTypeclass MbConstantKeyOrderPlacedGlobal {}
@ReadModel@FromEvent(eventType = MbConstantKeyUserRegistered.class)@FromEvent(eventType = MbConstantKeyOrderPlacedGlobal.class)class MbConstantKeyUserDashboard { public String name = "";
// A per-instance property alongside a constant-keyed one on the same read model @Count(eventType = MbConstantKeyOrderPlacedGlobal.class, constantKey = "global-stats") public int platformTotalOrders = 0;}defmodule MyApp.Events.ConstantKeyUserRegistered do use Cratis.Chronicle.Events.EventType, id: "constant-key-user-registered-v1"
defstruct [:name]end
defmodule MyApp.Events.ConstantKeyOrderPlacedGlobal do use Cratis.Chronicle.Events.EventType, id: "constant-key-order-placed-global-v1"
defstruct []end
defmodule MyApp.ReadModels.UserDashboard do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.{ConstantKeyUserRegistered, ConstantKeyOrderPlacedGlobal}
defstruct [:user_id, :name, platform_total_orders: 0]
# Regular, per-instance key — one document per user. from ConstantKeyUserRegistered, set: [user_id: :event_source_id, name: :name]
# A literal key routes this counter to a single shared document instead — # "global-stats", not the per-user instance above. from ConstantKeyOrderPlacedGlobal, key: "$value(global-stats)", count: :platform_total_ordersendimport { count, eventType, fromEvent, Guid } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()export class MbConstantKeyUserRegistered {}
@eventType()export class MbConstantKeyOrderPlacedGlobal {}
@fromEvent(MbConstantKeyUserRegistered)export class MbConstantKeyUserDashboard { id: Guid = Guid.empty; @field(String) name = '';
// A per-instance property alongside a constant-keyed one on the same read model @count(MbConstantKeyOrderPlacedGlobal, 'global-stats') platformTotalOrders = 0;}The registration event selects a user-specific dashboard. The order counter selects the document with key "global-stats"; it does not copy the platform total into every user’s dashboard. Both documents use the same read model type, but they are different instances.
Complete example
Section titled “Complete example”This store summary routes its counter events to the same key, so users and products contribute to one set of store-wide metrics:
// Events[EventType]public record MbConstantKeyProductPurchased(string ProductId, decimal Amount);
[EventType]public record MbConstantKeyProductReturned(string ProductId, decimal Amount);
[EventType]public record MbConstantKeyPageViewed(string PageUrl);
// Global read modelpublic record MbConstantKeyStoreMetrics( [Count<MbConstantKeyProductPurchased>(ConstantKey = "store")] int TotalPurchases,
[Count<MbConstantKeyProductReturned>(ConstantKey = "store")] int TotalReturns,
[Increment<MbConstantKeyProductPurchased>(ConstantKey = "store")] [Decrement<MbConstantKeyProductReturned>(ConstantKey = "store")] int NetTransactions,
[Count<MbConstantKeyPageViewed>(ConstantKey = "store")] int TotalPageViews);import io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.projections.Countimport io.cratis.chronicle.projections.Decrementimport io.cratis.chronicle.projections.FromEventimport io.cratis.chronicle.projections.Incrementimport io.cratis.chronicle.readModels.ReadModel
// Events@EventTypedata class MbConstantKeyProductPurchased(val productId: String, val amount: Double)
@EventTypedata class MbConstantKeyProductReturned(val productId: String, val amount: Double)
@EventTypedata class MbConstantKeyPageViewed(val pageUrl: String)
// Global read model@ReadModel@FromEvent(MbConstantKeyProductPurchased::class)@FromEvent(MbConstantKeyProductReturned::class)@FromEvent(MbConstantKeyPageViewed::class)data class MbConstantKeyStoreMetrics( @Count(MbConstantKeyProductPurchased::class, constantKey = "store") val totalPurchases: Int = 0,
@Count(MbConstantKeyProductReturned::class, constantKey = "store") val totalReturns: Int = 0,
@Increment(MbConstantKeyProductPurchased::class, constantKey = "store") @Decrement(MbConstantKeyProductReturned::class, constantKey = "store") val netTransactions: Int = 0,
@Count(MbConstantKeyPageViewed::class, constantKey = "store") val totalPageViews: Int = 0)import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.projections.Count;import io.cratis.chronicle.projections.Decrement;import io.cratis.chronicle.projections.FromEvent;import io.cratis.chronicle.projections.Increment;import io.cratis.chronicle.readModels.ReadModel;
// Events@EventTyperecord MbConstantKeyProductPurchased(String productId, double amount) {}
@EventTyperecord MbConstantKeyProductReturned(String productId, double amount) {}
@EventTyperecord MbConstantKeyPageViewed(String pageUrl) {}
// Global read model@ReadModel@FromEvent(eventType = MbConstantKeyProductPurchased.class)@FromEvent(eventType = MbConstantKeyProductReturned.class)@FromEvent(eventType = MbConstantKeyPageViewed.class)class MbConstantKeyStoreMetrics { @Count(eventType = MbConstantKeyProductPurchased.class, constantKey = "store") public int totalPurchases = 0;
@Count(eventType = MbConstantKeyProductReturned.class, constantKey = "store") public int totalReturns = 0;
@Increment(eventType = MbConstantKeyProductPurchased.class, constantKey = "store") @Decrement(eventType = MbConstantKeyProductReturned.class, constantKey = "store") public int netTransactions = 0;
@Count(eventType = MbConstantKeyPageViewed.class, constantKey = "store") public int totalPageViews = 0;}defmodule MyApp.Events.ConstantKeyProductPurchased do use Cratis.Chronicle.Events.EventType, id: "constant-key-product-purchased-v1"
defstruct [:product_id, :amount]end
defmodule MyApp.Events.ConstantKeyProductReturned do use Cratis.Chronicle.Events.EventType, id: "constant-key-product-returned-v1"
defstruct [:product_id, :amount]end
defmodule MyApp.Events.ConstantKeyPageViewed do use Cratis.Chronicle.Events.EventType, id: "constant-key-page-viewed-v1"
defstruct [:page_url]end
defmodule MyApp.ReadModels.StoreMetrics do use Cratis.Chronicle.ReadModels.ReadModel
alias MyApp.Events.{ ConstantKeyProductPurchased, ConstantKeyProductReturned, ConstantKeyPageViewed }
defstruct total_purchases: 0, total_returns: 0, net_transactions: 0, total_page_views: 0
from ConstantKeyProductPurchased, key: "$value(store)", count: :total_purchases, add: [net_transactions: 1]
from ConstantKeyProductReturned, key: "$value(store)", count: :total_returns, subtract: [net_transactions: 1]
from ConstantKeyPageViewed, key: "$value(store)", count: :total_page_viewsendimport { count, decrement, eventType, increment } from '@cratis/chronicle';
// Events@eventType()export class MbConstantKeyProductPurchased { productId = ''; amount = 0;}
@eventType()export class MbConstantKeyProductReturned { productId = ''; amount = 0;}
@eventType()export class MbConstantKeyPageViewed { pageUrl = '';}
// Global read modelexport class MbConstantKeyStoreMetrics { @count(MbConstantKeyProductPurchased, 'store') totalPurchases = 0;
@count(MbConstantKeyProductReturned, 'store') totalReturns = 0;
@increment(MbConstantKeyProductPurchased, 'store') @decrement(MbConstantKeyProductReturned, 'store') netTransactions = 0;
@count(MbConstantKeyPageViewed, 'store') totalPageViews = 0;}The matching events accumulate into the document with key "store". For the difference between an event total and a quantity that rises and falls, see counters.