Cratis Chronicle unique property constraints
A Cratis Chronicle unique property constraint prevents different event sources from claiming the same value, such as an email address or handle. The source that owns a value can append it again without a violation, so use this rule to protect ownership of a value rather than to prevent repeated events.
In .NET, apply [Unique] to the event property. The client discovers the declaration on registered event types and sends its constraint definition to the Kernel when it starts.
Defining a unique property constraint
Section titled “Defining a unique property constraint”The declaration below reserves the email address for the event source that appends the registration event. Another source cannot claim that address while it is held:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsModelBoundUniqueProjectCreated([property: Unique] string Name, string Description);import io.cratis.chronicle.constraints.Uniqueimport io.cratis.chronicle.events.EventType
@EventTypedata class ConstraintsModelBoundUniqueProjectCreated(@Unique val name: String, val description: String)import io.cratis.chronicle.constraints.Unique;import io.cratis.chronicle.events.EventType;
@EventTyperecord ConstraintsModelBoundUniqueProjectCreated(@Unique String name, String description) {}defmodule MyApp.Events.ConstraintsModelBoundUniqueProjectCreated do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-project-created"
defstruct [:name, :description]
unique(:name)endimport { eventType, unique } from '@cratis/chronicle';
@eventType('constraints-model-bound-project-created')class CmbProjectCreated { @unique() name = ''; description = '';}Re-claiming a value
Section titled “Re-claiming a value”A unique property value belongs to an event source, not to a single append. The same event source may append its current value again without violating the constraint. If it claims a different value, the new value replaces its previous claim, freeing the old value for another event source.
Do not constrain a property containing the event source’s own id to prevent a second event on that source: it will re-claim its own value and pass. To allow an event type only once per event source, use a unique event type constraint instead.
Keeping every value
Section titled “Keeping every value”If one project accumulates many version ids, retaining only its latest id lets another project reuse an earlier one. In .NET, set Mode = UniqueConstraintMode.PerValue to reserve every value until you explicitly release it. The default, PerEventSource, keeps the replacement behavior described above. Elixir exposes the same retention choice through :mode; the example here uses the .NET attribute.
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ScheduleVersionRegistered( [property: Unique("ScheduleVersionId", Mode = UniqueConstraintMode.PerValue)] string VersionId);
[EventType][RemoveConstraint("ScheduleVersionId", Properties = [nameof(VersionId)])]public record ScheduleVersionRemoved(string VersionId);
[EventType][RemoveConstraint("ScheduleVersionId")]public record ScheduleVersionsRemoved;Appending two different version ids for the same project now keeps both reserved. Another project cannot claim either; the original project may append either again without a violation. ScheduleVersionRemoved releases only the id carried by that event, and only if its event source owns that value. ScheduleVersionsRemoved, which declares no removal properties, releases all values held by that event source in the constraint’s scope.
For a composite value, list removal properties in the same order as the constrained properties. A value-carrying event with no constrained properties present claims nothing and does not release earlier values. Properties sharing a constraint name must declare the same mode.
Strongly-typed properties
Section titled “Strongly-typed properties”In .NET, [Unique] also works on event properties typed as ConceptAs<T>. A concept gives a domain value its own type, such as EmailAddress, while wrapping a primitive such as string or Guid. Chronicle checks uniqueness using that underlying value:
using Cratis.Concepts;using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
public record ConstraintsModelBoundUniqueEmailAddress(string Value) : ConceptAs<string>(Value);
[EventType]public record ConstraintsModelBoundUniqueAuthorRegistered([property: Unique(name: "UniqueAuthorEmail")] ConstraintsModelBoundUniqueEmailAddress Email);import io.cratis.fundamentals.concepts.ConceptAsimport io.cratis.chronicle.constraints.Uniqueimport io.cratis.chronicle.events.EventType
data class ConstraintsModelBoundUniqueEmailAddress(val value: String) : ConceptAs<String> { override fun value(): String = value}
@EventTypedata class ConstraintsModelBoundUniqueAuthorRegistered( @Unique(id = "UniqueAuthorEmail") val email: ConstraintsModelBoundUniqueEmailAddress)import io.cratis.fundamentals.concepts.ConceptAs;import io.cratis.chronicle.constraints.Unique;import io.cratis.chronicle.events.EventType;
record ConstraintsModelBoundUniqueEmailAddress(String value) implements ConceptAs<String> {}
@EventTyperecord ConstraintsModelBoundUniqueAuthorRegistered( @Unique(id = "UniqueAuthorEmail") ConstraintsModelBoundUniqueEmailAddress email) {}defmodule MyApp.Concepts.ConstraintsModelBoundUniqueEmailAddress do use Cratis.Chronicle.Concept, type: :stringend
defmodule MyApp.Events.ConstraintsModelBoundUniqueAuthorRegistered do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-author-registered"
unique :email, name: "UniqueAuthorEmail"
defstruct email: %MyApp.Concepts.ConstraintsModelBoundUniqueEmailAddress{}endimport { ConceptAs } from '@cratis/fundamentals';import { eventType, unique } from '@cratis/chronicle';
class CmbEmailAddress extends ConceptAs<string> { static readonly valueType = String;}
@eventType('constraints-model-bound-author-registered')class CmbAuthorRegistered { @unique('UniqueAuthorEmail') email = new CmbEmailAddress('');}Grouping constraints across event types
Section titled “Grouping constraints across event types”When multiple event types share the same constraint name, Chronicle groups them into a single constraint. A value introduced by any of the participating events is checked against all others:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsModelBoundUniqueUserRegistered([property: Unique(name: "UniqueEmail")] string Email, string DisplayName);
[EventType]public record ConstraintsModelBoundUniqueUserEmailChanged([property: Unique(name: "UniqueEmail")] string NewEmail);import io.cratis.chronicle.constraints.Uniqueimport io.cratis.chronicle.events.EventType
@EventTypedata class ConstraintsModelBoundUniqueUserRegistered( @Unique(id = "UniqueEmail") val email: String, val displayName: String)
@EventTypedata class ConstraintsModelBoundUniqueUserEmailChanged(@Unique(id = "UniqueEmail") val newEmail: String)import io.cratis.chronicle.constraints.Unique;import io.cratis.chronicle.events.EventType;
@EventTyperecord ConstraintsModelBoundUniqueUserRegistered(@Unique(id = "UniqueEmail") String email, String displayName) {}
@EventTyperecord ConstraintsModelBoundUniqueUserEmailChanged(@Unique(id = "UniqueEmail") String newEmail) {}defmodule MyApp.Events.ConstraintsModelBoundUniqueUserRegistered do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-user-registered"
defstruct [:email, :display_name]
unique(:email, name: "UniqueEmail")end
defmodule MyApp.Events.ConstraintsModelBoundUniqueUserEmailChanged do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-user-email-changed"
defstruct [:new_email]
unique(:new_email, name: "UniqueEmail")endimport { eventType, unique } from '@cratis/chronicle';
@eventType('constraints-model-bound-user-registered')class CmbUserRegistered { @unique('UniqueEmail') email = ''; displayName = '';}
@eventType('constraints-model-bound-user-email-changed')class CmbUserEmailChanged { @unique('UniqueEmail') newEmail = '';}Both events now participate in UniqueEmail. A user can change to an unclaimed email address, but neither the registration event nor the email-change event can claim an address held by another event source. Under the default retention mode, changing the address frees the user’s previous one.
Scoping to the event log
Section titled “Scoping to the event log”An event sequence is a separately indexed collection of events, such as the event log or outbox. By default, a constraint applies to every sequence its event type is appended to. Forwarding an event to the outbox therefore claims its value in the outbox’s index too; a removal event in the log does not release that outbox claim.
If the rule should protect only the event log, set EventSequences on the .NET [Unique] attribute. The Kernel neither validates nor indexes the constraint for sequences outside that selection:
using Cratis.Chronicle.EventSequences;using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType][RemoveConstraint("ConstraintsModelBoundUniqueEventLogInvitationEmail")]public record ConstraintsModelBoundUniqueEventLogInvitationRevoked;
[EventType]public record ConstraintsModelBoundUniqueEventLogInvitationSent( [property: Unique("ConstraintsModelBoundUniqueEventLogInvitationEmail", EventSequences = [EventSequenceId.LogId])] string Email);import { eventType, EventSequenceId, removeConstraint, unique } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()@removeConstraint('ConstraintsModelBoundUniqueEventLogInvitationEmail')class ConstraintsModelBoundUniqueEventLogInvitationRevoked {}
@eventType()class ConstraintsModelBoundUniqueEventLogInvitationSent { // Scoped to the event log, so a copy forwarded to the outbox does not claim the email there. @unique({ name: 'ConstraintsModelBoundUniqueEventLogInvitationEmail', eventSequences: [EventSequenceId.eventLog] }) @field(String) readonly email: string;
constructor(email: string) { this.email = email; }}When properties share a constraint name, their event sequence selections are combined. If any of those properties leaves EventSequences unset, the combined constraint applies to every sequence. Set the selection on every participating property to keep the rule limited to the log.
Changing the sequences takes effect when the client next registers its constraints. The kernel then rebuilds, in every namespace, the index of each sequence the constraint now applies to but did not before, from the events already in that sequence. A sequence the constraint no longer applies to stops validating it, and its index is no longer read until the constraint applies there again, when it is rebuilt.
Violation message
Section titled “Violation message”Supply a message to explain why the caller’s append was rejected. Without one, Chronicle uses its default violation message. The .NET, TypeScript, Kotlin, and Java model-bound declarations accept fixed messages. Kotlin and Java use the annotations in io.cratis:chronicle. Elixir accepts :message as a string or a {Module, :function} callback:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType]public record ConstraintsModelBoundUniqueMessageProjectCreated([property: Unique(message: "A project with this name already exists.")] string Name, string Description);// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.constraints.Uniqueimport io.cratis.chronicle.events.EventType
@EventTypedata class ConstraintsModelBoundUniqueMessageProjectCreated( @Unique(message = "A project with this name already exists.") val name: String, val description: String)// Requires io.cratis:chronicle 6.5.0 or later.import io.cratis.chronicle.constraints.Unique;import io.cratis.chronicle.events.EventType;
@EventTyperecord ConstraintsModelBoundUniqueMessageProjectCreated( @Unique(message = "A project with this name already exists.") String name, String description) {}defmodule MyApp.Events.ConstraintsModelBoundUniqueMessageProjectCreated do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-message-project-created"
defstruct [:name, :description]
unique(:name, message: "A project with this name already exists.")endimport { eventType, unique } from '@cratis/chronicle';
@eventType('constraints-model-bound-message-project-created')class CmbMessageProjectCreated { @unique(undefined, 'A project with this name already exists.') name = ''; description = '';}Releasing a constraint
Section titled “Releasing a constraint”Declare which event releases the value when its owner no longer needs it. In .NET, apply [RemoveConstraint] to that event type. Appending it releases the named constraint’s claims for that event source, so another source can claim the freed values:
using Cratis.Concepts;using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
public record ConstraintsModelBoundUniqueUserId(Guid Value) : ConceptAs<Guid>(Value);
[EventType][RemoveConstraint("UniqueEmail")]public record ConstraintsModelBoundUniqueUserRemoved(ConstraintsModelBoundUniqueUserId UserId);import io.cratis.chronicle.constraints.RemoveConstraintimport io.cratis.chronicle.events.EventType
@EventType@RemoveConstraint("UniqueEmail")data class ConstraintsModelBoundUniqueUserRemoved(val userId: String)import io.cratis.chronicle.constraints.RemoveConstraint;import io.cratis.chronicle.events.EventType;
@EventType@RemoveConstraint("UniqueEmail")record ConstraintsModelBoundUniqueUserRemoved(String userId) {}defmodule MyApp.Events.ConstraintsModelBoundUniqueUserRemoved do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-user-removed"
defstruct [:user_id]
remove_constraint("UniqueEmail")endimport { eventType, removeConstraint } from '@cratis/chronicle';
@eventType('constraints-model-bound-user-removed')@removeConstraint('UniqueEmail')class CmbUserRemoved { userId = '';}The removal declaration must exactly match the constraint name. In .NET, an unnamed property constraint defaults to the property name. Use an explicit name when several event types share the rule.
An event type can release more than one constraint by stacking multiple attributes:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType][RemoveConstraint("UniqueEmail")][RemoveConstraint("UniqueUsername")]public record ConstraintsModelBoundUniqueMultiRemoveUserRemoved(ConstraintsModelBoundUniqueUserId UserId);import io.cratis.chronicle.constraints.RemoveConstraintimport io.cratis.chronicle.events.EventType
@EventType@RemoveConstraint("UniqueEmail")@RemoveConstraint("UniqueUsername")data class ConstraintsModelBoundUniqueMultiRemoveUserRemoved(val userId: String)import io.cratis.chronicle.constraints.RemoveConstraint;import io.cratis.chronicle.events.EventType;
@EventType@RemoveConstraint("UniqueEmail")@RemoveConstraint("UniqueUsername")record ConstraintsModelBoundUniqueMultiRemoveUserRemoved(String userId) {}defmodule MyApp.Events.ConstraintsModelBoundUniqueMultiRemoveUserRemoved do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-multi-remove-user-removed"
defstruct [:user_id]
remove_constraint("UniqueEmail") remove_constraint("UniqueUsername")endimport { eventType, removeConstraint } from '@cratis/chronicle';
@eventType('constraints-model-bound-user-multi-removed')@removeConstraint('UniqueEmail')@removeConstraint('UniqueUsername')class CmbUserMultiRemoved { userId = '';}In .NET, more than one event type can release the same constraint. Name it from each event that ends the lifecycle so each can free the held values. Kotlin and Java accept only one removal event type per constraint name and keep the first one discovered:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Events.Constraints;
[EventType][RemoveConstraint("UniqueInvitedEmail")]public record ConstraintsModelBoundUniqueSeveralInvitationAccepted;
[EventType][RemoveConstraint("UniqueInvitedEmail")]public record ConstraintsModelBoundUniqueSeveralInvitationRevoked;
[EventType][RemoveConstraint("UniqueInvitedEmail")]public record ConstraintsModelBoundUniqueSeveralInvitationExpired;Kotlin does not support this workflow yet.Java does not support this workflow yet.defmodule MyApp.Events.ConstraintsModelBoundUniqueSeveralInvitationAccepted do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-several-invitation-accepted"
defstruct []
remove_constraint("UniqueInvitedEmail")end
defmodule MyApp.Events.ConstraintsModelBoundUniqueSeveralInvitationRevoked do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-several-invitation-revoked"
defstruct []
remove_constraint("UniqueInvitedEmail")end
defmodule MyApp.Events.ConstraintsModelBoundUniqueSeveralInvitationExpired do use Cratis.Chronicle.Events.EventType, id: "constraints-model-bound-unique-several-invitation-expired"
defstruct []
remove_constraint("UniqueInvitedEmail")endimport { eventType, removeConstraint } from '@cratis/chronicle';
@eventType('constraints-model-bound-invitation-accepted')@removeConstraint('UniqueInvitedEmail')class CmbInvitationAccepted {}
@eventType('constraints-model-bound-invitation-revoked')@removeConstraint('UniqueInvitedEmail')class CmbInvitationRevoked {}
@eventType('constraints-model-bound-invitation-expired')@removeConstraint('UniqueInvitedEmail')class CmbInvitationExpired {}How constraints are enforced
Section titled “How constraints are enforced”The client reads the model-bound declarations and registers constraint definitions. The Kernel builds the indexes and checks appends against them server-side. Clients also resolve custom violation messages for the append results they return.
For case-insensitive matching or scope configuration beyond the attribute’s options, use the declarative unique property constraint.