Declare Chronicle unique event type constraints
A unique event type constraint allows a fact to happen once per event source, such as initializing a project once per project id. Unlike a unique property constraint, it checks whether the event has occurred, not whether a value belongs to another source. You can also declare a release event when the rule should reset for a new cycle.
In .NET, declare the rule with builder.Unique<TEventType>() inside IConstraint. The client’s default artifact discovery finds these implementations without separate registration. See Declarative constraints for client-specific API differences.
Defining a unique event type constraint
Section titled “Defining a unique event type constraint”This declaration allows one project initialization per event source identifier. A second initialization for the same project violates the rule; another project has its own allowance:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsUniqueEventTypeProjectInitialized;
public class ConstraintsUniqueEventTypeProjectInitialization : IConstraint{ public void Define(IConstraintBuilder builder) => builder.Unique<ConstraintsUniqueEventTypeProjectInitialized>();}import io.cratis.chronicle.constraints.Constraintimport io.cratis.chronicle.constraints.IConstraintimport io.cratis.chronicle.constraints.IConstraintBuilderimport io.cratis.chronicle.events.EventType
@EventTypeclass ConstraintsUniqueEventTypeProjectInitialized
@Constraintclass ConstraintsUniqueEventTypeProjectInitialization : IConstraint { override fun define(builder: IConstraintBuilder) { builder.uniqueFor(ConstraintsUniqueEventTypeProjectInitialized::class) }}import io.cratis.chronicle.constraints.Constraint;import io.cratis.chronicle.constraints.IConstraint;import io.cratis.chronicle.constraints.IConstraintBuilder;import io.cratis.chronicle.events.EventType;
@EventTypeclass ConstraintsUniqueEventTypeProjectInitialized {}
@Constraintclass ConstraintsUniqueEventTypeProjectInitialization implements IConstraint { @Override public void define(IConstraintBuilder builder) { builder.uniqueFor(ConstraintsUniqueEventTypeProjectInitialized.class, ""); }}defmodule MyApp.Events.ConstraintsUniqueEventTypeProjectInitialized do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-project-initialized"
unique_event_type()
defstruct []endimport { constraint, eventType, IConstraint, IConstraintBuilder } from '@cratis/chronicle';
@eventType()class ConstraintsUniqueEventTypeProjectInitialized {}
@constraint()class ConstraintsUniqueEventTypeProjectInitialization implements IConstraint { define(builder: IConstraintBuilder): void { builder.uniqueFor(ConstraintsUniqueEventTypeProjectInitialized); }}The check stays within one namespace and one event sequence. It does not enforce a single occurrence across namespaces or sequences.
Violation message
Section titled “Violation message”Provide a static message to explain why the append was refused:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsUniqueEventTypeMessageProjectInitialized;
public class ConstraintsUniqueEventTypeMessageProjectInitialization : IConstraint{ public void Define(IConstraintBuilder builder) => builder.Unique<ConstraintsUniqueEventTypeMessageProjectInitialized>( message: "A project can only be initialized once.");}// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.constraints.Constraintimport io.cratis.chronicle.constraints.IConstraintimport io.cratis.chronicle.constraints.IConstraintBuilderimport io.cratis.chronicle.events.EventType
@EventTypeclass ConstraintsUniqueEventTypeMessageProjectInitialized
@Constraintclass ConstraintsUniqueEventTypeMessageProjectInitialization : IConstraint { override fun define(builder: IConstraintBuilder) { builder.uniqueFor( ConstraintsUniqueEventTypeMessageProjectInitialized::class, message = "A project can only be initialized once." ) }}// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.constraints.Constraint;import io.cratis.chronicle.constraints.IConstraint;import io.cratis.chronicle.constraints.IConstraintBuilder;import io.cratis.chronicle.events.EventType;
@EventTypeclass ConstraintsUniqueEventTypeMessageProjectInitialized {}
@Constraintclass ConstraintsUniqueEventTypeMessageProjectInitialization implements IConstraint { @Override public void define(IConstraintBuilder builder) { builder.uniqueFor(ConstraintsUniqueEventTypeMessageProjectInitialized.class, "A project can only be initialized once."); }}defmodule MyApp.Events.ConstraintsUniqueEventTypeMessageProjectInitialized do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-message-project-initialized" defstruct []end
defmodule MyApp.Constraints.ConstraintsUniqueEventTypeMessageProjectInitialization do use Cratis.Chronicle.Events.Constraint
unique_event_type MyApp.Events.ConstraintsUniqueEventTypeMessageProjectInitialized, name: "ConstraintsUniqueEventTypeMessageProjectInitialization", message: "A project can only be initialized once."endimport { constraint, eventType, IConstraint, IConstraintBuilder } from '@cratis/chronicle';
@eventType()class ConstraintsUniqueEventTypeMessageProjectInitialized {}
@constraint()class ConstraintsUniqueEventTypeMessageProjectInitialization implements IConstraint { define(builder: IConstraintBuilder): void { builder.uniqueFor(ConstraintsUniqueEventTypeMessageProjectInitialized, 'A project can only be initialized once.'); }}Use a callback when the message needs information from the violation context:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsUniqueEventTypeCallbackProjectInitialized;
public class ConstraintsUniqueEventTypeCallbackProjectInitialization : IConstraint{ public void Define(IConstraintBuilder builder) => builder.Unique<ConstraintsUniqueEventTypeCallbackProjectInitialized>( messageCallback: violation => $"Constraint '{violation.ConstraintName}' was violated - the project has already been initialized.");}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.ConstraintsUniqueEventTypeCallbackProjectInitialized do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-callback-project-initialized" defstruct []end
defmodule MyApp.Constraints.ConstraintsUniqueEventTypeCallbackMessages do def project_already_initialized(violation) do "Constraint '#{violation."ConstraintName"}' was violated - the project has already been initialized." endend
defmodule MyApp.Constraints.ConstraintsUniqueEventTypeCallbackProjectInitialization do use Cratis.Chronicle.Events.Constraint
unique_event_type MyApp.Events.ConstraintsUniqueEventTypeCallbackProjectInitialized, name: "ConstraintsUniqueEventTypeCallbackProjectInitialization", message: {MyApp.Constraints.ConstraintsUniqueEventTypeCallbackMessages, :project_already_initialized}endTypeScript does not support this workflow yet.Constraint name
Section titled “Constraint name”Provide a name to identify the constraint explicitly. Without one, the .NET builder uses the event type identifier as the constraint name:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsUniqueEventTypeNamedProjectInitialized;
public class ConstraintsUniqueEventTypeNamedProjectInitialization : IConstraint{ public void Define(IConstraintBuilder builder) => builder.Unique<ConstraintsUniqueEventTypeNamedProjectInitialized>( name: "UniqueProjectInitialization", message: "A project can only be initialized once.");}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.ConstraintsUniqueEventTypeNamedProjectInitialized do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-named-project-initialized" defstruct []end
defmodule MyApp.Constraints.ConstraintsUniqueEventTypeNamedProjectInitialization do use Cratis.Chronicle.Events.Constraint
unique_event_type MyApp.Events.ConstraintsUniqueEventTypeNamedProjectInitialized, name: "UniqueProjectInitialization", message: "A project can only be initialized once."endimport { constraint, eventType, IConstraint, IConstraintBuilder } from '@cratis/chronicle';
@eventType()class ConstraintsUniqueEventTypeNamedProjectInitialized {}
@constraint()class ConstraintsUniqueEventTypeNamedProjectInitialization implements IConstraint { define(builder: IConstraintBuilder): void { builder.uniqueFor( ConstraintsUniqueEventTypeNamedProjectInitialized, 'A project can only be initialized once.', 'UniqueProjectInitialization'); }}Releasing a constraint
Section titled “Releasing a constraint”Without a release event, the constraint means “at most one, ever”. That fits project initialization, but not an employee who works another shift tomorrow.
Call .RemovedWith<T>() to name the event that ends a cycle. Only a covered event after the most recent removal blocks the next append. In this example, ending the employee’s shift allows another shift to start:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsUniqueEventTypeShiftStarted(string Location);
[EventType]public record ConstraintsUniqueEventTypeShiftEnded;
public class ConstraintsUniqueEventTypeOneOpenShift : IConstraint{ // At most one open shift per employee. Ending the shift releases the constraint, // so the next shift is allowed - without it the constraint could only say // "at most one, ever", and the employee's second shift would be refused forever. public void Define(IConstraintBuilder builder) => builder .Unique<ConstraintsUniqueEventTypeShiftStarted>() .RemovedWith<ConstraintsUniqueEventTypeShiftEnded>();}import io.cratis.chronicle.constraints.RemoveConstraintimport io.cratis.chronicle.constraints.Uniqueimport io.cratis.chronicle.events.EventType
// Model-bound equivalent: only one open shift per employee/event source.@EventType@Unique(id = "ConstraintsUniqueEventTypeOneOpenShift")data class ConstraintsUniqueEventTypeShiftStarted(val location: String)
@EventType@RemoveConstraint("ConstraintsUniqueEventTypeOneOpenShift")class ConstraintsUniqueEventTypeShiftEndedimport io.cratis.chronicle.constraints.RemoveConstraint;import io.cratis.chronicle.constraints.Unique;import io.cratis.chronicle.events.EventType;
// Model-bound equivalent: only one open shift per employee/event source.@EventType@Unique(id = "ConstraintsUniqueEventTypeOneOpenShift")record ConstraintsUniqueEventTypeShiftStarted(String location) {}
@EventType@RemoveConstraint("ConstraintsUniqueEventTypeOneOpenShift")record ConstraintsUniqueEventTypeShiftEnded() {}defmodule MyApp.Events.ConstraintsUniqueEventTypeShiftStarted do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-shift-started"
unique_event_type(name: "OneOpenShift")
defstruct location: ""end
defmodule MyApp.Events.ConstraintsUniqueEventTypeShiftEnded do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-shift-ended"
remove_constraint "OneOpenShift"
defstruct []endThe TypeScript client does not support this workflow yet.uniqueFor() cannot configure a removal event. Using unique().on(EventType) without properties does not enforce event-type uniqueness.The removal applies to the most recently declared unique event type constraint. It is per event source: one employee ending their shift opens only their own next cycle.
A cycle can end in more than one way, so chain .RemovedWith<T>() once for each event that ends it. Every one of them releases the constraint on its own, and the cycle ends at whichever was appended most recently:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsUniqueEventTypeSeveralLoanCheckedOut(string Title);
[EventType]public record ConstraintsUniqueEventTypeSeveralLoanReturned;
[EventType]public record ConstraintsUniqueEventTypeSeveralLoanWrittenOff;
public class ConstraintsUniqueEventTypeSeveralOneOpenLoan : IConstraint{ // A loan is open until it is returned or written off. Both end the cycle, so the // borrower can take the next loan whichever way the previous one finished. public void Define(IConstraintBuilder builder) => builder .Unique<ConstraintsUniqueEventTypeSeveralLoanCheckedOut>() .RemovedWith<ConstraintsUniqueEventTypeSeveralLoanReturned>() .RemovedWith<ConstraintsUniqueEventTypeSeveralLoanWrittenOff>();}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.ConstraintsUniqueEventTypeSeveralLoanCheckedOut do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-several-loan-checked-out" defstruct title: ""end
defmodule MyApp.Events.ConstraintsUniqueEventTypeSeveralLoanReturned do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-several-loan-returned" defstruct []end
defmodule MyApp.Events.ConstraintsUniqueEventTypeSeveralLoanWrittenOff do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-several-loan-written-off" defstruct []end
# A loan is open until it is returned or written off. Both end the cycle, so the borrower can# take the next loan whichever way the previous one finished.defmodule MyApp.Constraints.ConstraintsUniqueEventTypeSeveralOneOpenLoan do use Cratis.Chronicle.Events.Constraint
unique_event_type MyApp.Events.ConstraintsUniqueEventTypeSeveralLoanCheckedOut, name: "ConstraintsUniqueEventTypeSeveralOneOpenLoan"
removed_with MyApp.Events.ConstraintsUniqueEventTypeSeveralLoanReturned removed_with MyApp.Events.ConstraintsUniqueEventTypeSeveralLoanWrittenOffendThe TypeScript client does not support this workflow yet.uniqueFor() cannot configure removal events. Repeated removedWith() calls are supported for unique property constraints, not unique event-type constraints.Declaring several event types under one name makes them a single constraint, and the removal events declared across those declarations all apply to it.
The model-bound form expresses the same thing with [RemoveConstraint] on the event that ends the cycle.
Scoping the constraint
Section titled “Scoping the constraint”Within a namespace and event sequence, the default rule is “at most one per event source identifier”. For one open loan per borrower per branch, represent the branch as a stream id and call PerEventStreamId() before declaring the constraint. The borrower can then have one open loan at each branch:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsUniqueEventTypeScopedLoanCheckedOut(string Title);
[EventType]public record ConstraintsUniqueEventTypeScopedLoanReturned;
public class ConstraintsUniqueEventTypeOneOpenLoanPerBranch : IConstraint{ // One open loan per borrower per branch. The stream the event is appended to decides // which cycle it belongs to, so the same borrower can hold one open loan at every // branch, and returning at one branch opens the next cycle only there. public void Define(IConstraintBuilder builder) => builder .PerEventStreamId() .Unique<ConstraintsUniqueEventTypeScopedLoanCheckedOut>() .RemovedWith<ConstraintsUniqueEventTypeScopedLoanReturned>();}import io.cratis.chronicle.constraints.Constraintimport io.cratis.chronicle.constraints.IConstraintimport io.cratis.chronicle.constraints.IConstraintBuilderimport io.cratis.chronicle.events.EventType
@EventTypedata class ConstraintsUniqueEventTypeScopedLoanCheckedOut(val title: String)
@Constraintclass ConstraintsUniqueEventTypeOneLoanPerBranch : IConstraint { // One loan per borrower per branch. The stream the event is appended to decides which // branch it belongs to, so the same borrower can hold one loan at every branch. // The Kotlin fluent builder has no removedWith, so this scoped constraint is never // released by a later event - each borrower/branch pair gets exactly one checkout. override fun define(builder: IConstraintBuilder) { builder .perEventStreamId() .uniqueFor(ConstraintsUniqueEventTypeScopedLoanCheckedOut::class) }}import io.cratis.chronicle.constraints.Constraint;import io.cratis.chronicle.constraints.IConstraint;import io.cratis.chronicle.constraints.IConstraintBuilder;import io.cratis.chronicle.events.EventType;
@EventTyperecord ConstraintsUniqueEventTypeScopedLoanCheckedOut(String title) {}
@Constraintclass ConstraintsUniqueEventTypeOneLoanPerBranch implements IConstraint { // One loan per borrower per branch. The stream the event is appended to decides which // branch it belongs to, so the same borrower can hold one loan at every branch. // The Java fluent builder has no removedWith, so this scoped constraint is never // released by a later event - each borrower/branch pair gets exactly one checkout. @Override public void define(IConstraintBuilder builder) { builder .perEventStreamId() .uniqueFor(ConstraintsUniqueEventTypeScopedLoanCheckedOut.class); }}defmodule MyApp.Events.ConstraintsUniqueEventTypeScopedLoanCheckedOut do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-scoped-loan-checked-out" defstruct title: ""end
defmodule MyApp.Events.ConstraintsUniqueEventTypeScopedLoanReturned do use Cratis.Chronicle.Events.EventType, id: "constraints-unique-event-type-scoped-loan-returned" defstruct []end
# One open loan per borrower per branch. The stream the event is appended to decides which# cycle it belongs to, so the same borrower can hold one open loan at every branch, and# returning at one branch opens the next cycle only there.defmodule MyApp.Constraints.ConstraintsUniqueEventTypeOneOpenLoanPerBranch do use Cratis.Chronicle.Events.Constraint
unique_event_type MyApp.Events.ConstraintsUniqueEventTypeScopedLoanCheckedOut, name: "ConstraintsUniqueEventTypeOneOpenLoanPerBranch", scope: :per_event_stream_id
removed_with MyApp.Events.ConstraintsUniqueEventTypeScopedLoanReturnedendimport { constraint, eventType, IConstraint, IConstraintBuilder } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class ConstraintsUniqueEventTypeScopedLoanCheckedOut { @field(String) readonly title: string;
constructor(title: string) { this.title = title; }}
@constraint()class ConstraintsUniqueEventTypeOneLoanPerBranch implements IConstraint { // One checkout per borrower (event source) per branch (event stream). // The TypeScript uniqueFor API cannot configure a removal event yet, // so returning a loan does not release this constraint for another checkout. define(builder: IConstraintBuilder): void { builder .perEventStreamId() .uniqueFor(ConstraintsUniqueEventTypeScopedLoanCheckedOut); }}Use PerEventStreamType() or PerEventSourceType() when those dimensions distinguish the cycles instead. The dimensions of the event being appended decide which cycle it belongs to:
| Scope | One cycle per |
|---|---|
| (none) | event source identifier |
PerEventSourceType() |
event source identifier + event source type |
PerEventStreamType() |
event source identifier + event stream type |
PerEventStreamId() |
event source identifier + event stream id |
Chain several of them and every declared dimension has to match for two events to share a cycle — one differing dimension is a different cycle.
Within one scope, a second covered event is refused until a removal event in that same scope opens the next cycle. Returning a loan at one branch does not release the borrower’s loan at another branch.
Custom storage providers
Section titled “Custom storage providers”Scoping is enforced by the storage provider, so a provider has to be able to see which scope an append belongs to. The storage interface IUniqueEventTypesConstraintsStorage therefore has two members:
| Member | Narrows by | Who should implement it |
|---|---|---|
IsAllowedWithinScope(definition, eventSourceId, scope) |
the appending event’s typed dimension values | every provider |
IsAllowed(definition, eventSourceId, scopeKey) |
a single flattened string key | every provider, for compatibility — it stays abstract on the interface |
The kernel calls IsAllowedWithinScope. If your provider implements only IsAllowed, the interface’s default implementation flattens the scope into the same string key the provider already received. This preserves compatibility, but not isolation between scopes whose dimension values contain the key’s separator characters.
Implement IsAllowedWithinScope with a separate comparison for each typed dimension to enforce scoped isolation. You must still supply IsAllowed because it remains abstract. A compatibility wrapper can send an empty or omitted key to an unscoped IsAllowedWithinScope lookup. For a non-empty key, throw NotSupportedException rather than guess at dimensions that cannot be reconstructed.
The providers shipped with Chronicle — MongoDB, SQL and in-memory — implement the typed member and narrow natively per dimension. Calling their IsAllowed with a non-empty key throws NotSupportedException rather than answering against a scope it cannot reconstruct; an empty or omitted key is an unscoped lookup and is answered as one.
Appending several events at once
Section titled “Appending several events at once”The kernel checks events in call order, including claims made earlier in the same call. Two covered events for the same event source and scope violate the constraint even if neither is stored yet. A removal event earlier in the call opens a new cycle for a covered event later in it. If constraint validation fails, none of the call’s events are appended.
Mutually exclusive event types
Section titled “Mutually exclusive event types”Declare several event types under the same constraint name when only one of them should happen. They become one constraint allowing at most one event from the set per event source. The following rule records one terminal outcome for a person: aliased to another person or erased, but not both.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsPersonAliasedTo(Guid Target);
[EventType]public record ConstraintsPersonErased;
public class ConstraintsPersonTerminalOutcome : IConstraint{ // Both declarations share one constraint name, so they become a single constraint: // at most one event drawn from { ConstraintsPersonAliasedTo, ConstraintsPersonErased } // per person. A person merged away can no longer be erased, and neither event can // occur twice. public void Define(IConstraintBuilder builder) { builder.Unique<ConstraintsPersonAliasedTo>( name: "PersonTerminal", message: "This person already has a terminal outcome.");
builder.Unique<ConstraintsPersonErased>( name: "PersonTerminal", message: "This person already has a terminal outcome."); }}Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.ConstraintsPersonAliasedTo do use Cratis.Chronicle.Events.EventType, id: "constraints-person-aliased-to" defstruct target: ""end
defmodule MyApp.Events.ConstraintsPersonErased do use Cratis.Chronicle.Events.EventType, id: "constraints-person-erased" defstruct []end
# Both declarations share one constraint name, so they become a single constraint: at most# one event drawn from {ConstraintsPersonAliasedTo, ConstraintsPersonErased} per person. A# person merged away can no longer be erased, and neither event can occur twice.defmodule MyApp.Constraints.ConstraintsPersonTerminalOutcome do use Cratis.Chronicle.Events.Constraint
unique_event_type MyApp.Events.ConstraintsPersonAliasedTo, name: "PersonTerminal", message: "This person already has a terminal outcome."
unique_event_type MyApp.Events.ConstraintsPersonErased, name: "PersonTerminal", message: "This person already has a terminal outcome."endimport { constraint, eventType, IConstraint, IConstraintBuilder, Guid } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class ConstraintsPersonAliasedTo { @field(Guid) readonly target: Guid;
constructor(target: Guid) { this.target = target; }}
@eventType()class ConstraintsPersonErased {}
@constraint()class ConstraintsPersonTerminalOutcome implements IConstraint { // Both declarations share one constraint name, so they become a single constraint: // at most one event drawn from { ConstraintsPersonAliasedTo, ConstraintsPersonErased } // per person. A person merged away can no longer be erased, and neither event can // occur twice. define(builder: IConstraintBuilder): void { builder.uniqueFor(ConstraintsPersonAliasedTo, 'This person already has a terminal outcome.', 'PersonTerminal'); builder.uniqueFor(ConstraintsPersonErased, 'This person already has a terminal outcome.', 'PersonTerminal'); }}Each event type still cannot occur twice — that is the single-type case of the same rule. What sharing the name adds is that the first of them to be appended blocks all of the others.
The check runs inside the append, rather than in an application validator that reads first and writes later. A separate read can let competing commands both observe “no terminal event yet”; declaring the constraint gives the kernel the rule to check before storing either outcome.
How constraints are enforced
Section titled “How constraints are enforced”The Chronicle Kernel evaluates the registered rule during append, regardless of which client writes the event. The rule stays within its namespace, event sequence, and selected scope. See Constraint or decision read for the enforcement limits and for rules that need to count or compare state.