Repository navigation
API Reference
Complete reference for all public types, interfaces, and attributes in the Aggregates library.
Versioning. Everything on this page follows semantic versioning, except the types in the Aggregates.Subscriptions.Internal, Aggregates.KurrentDB.Internal and Aggregates.MSSP.Internal namespaces and members marked as internal infrastructure (see Internal types): they are public only so that the Aggregates packages can use them, and may change in any release. A new member on a public interface comes with a default implementation, so your implementations keep compiling.
The state of an aggregate or saga. Implement this on your state record.
public interface IState<out TState, in TEvent> where TState : IState<TState, TEvent> {
static abstract TState Initial { get; }
TState Apply(TEvent @event);
}| Member | Description |
|---|---|
Initial |
The empty starting state. Static abstract — defined on the implementing type. |
Apply(event) |
Applies the event and returns the next state. Must always succeed. |
Marker interface. All commands implement this.
public interface ICommand;A command that targets an aggregate and produces events.
public interface ICommand<in TState, out TEvent> : ICommand
where TState : IState<TState, TEvent> {
AggregateIdentifier Id { get; }
IAsyncEnumerable<TEvent> ProgressAsync(TState state, CancellationToken cancellationToken = default);
}| Member | Description |
|---|---|
Id |
Identifies the target aggregate. |
ProgressAsync |
Validates the current state and yields events. Allowed to throw; this is the domain rule enforcement point. |
Handles a command end-to-end: loads the aggregate, runs ProgressAsync, and persists the result. Registered automatically; inject this into your application code.
public interface ICommandHandler<in TCommand> where TCommand : ICommand {
ValueTask HandleAsync(TCommand command, CancellationToken cancellationToken = default);
}Dispatches a command without knowing its concrete type. Useful when the command type is only known at runtime (e.g. from a saga).
public interface ICommandDispatcher {
ValueTask DispatchAsync(ICommand command, CancellationToken cancellationToken = default);
}A command a saga or a policy defers until later. Yield command.DeferUntil(due) from ReactAsync among the other commands; see Deferred commands.
public sealed record DeferredCommand : ICommand {
public DeferredCommand(DateTimeOffset due, ICommand command);
public DateTimeOffset Due { get; }
public ICommand Command { get; }
}
public static class DeferredCommandExtensions {
public static DeferredCommand DeferUntil(this ICommand command, DateTimeOffset due);
}| Member | Description |
|---|---|
Due |
When the command runs. A time in the past runs it right away. |
Command |
The command to run, usually an ICommand<TState, TEvent> of an aggregate. It is stored until it is due, so the storage integration's Serialize/Deserialize must know its type under a stable name. A null command throws ArgumentNullException; a DeferredCommand throws ArgumentException. |
yield return new CancelUnpaidOrder(placed.OrderId, deadline).DeferUntil(clock.StartOfDay(deadline));The command runs at least once, possibly late: it decides from the state of its aggregate whether it still applies. There is no cancel. The scheduler of the saga or policy starts by itself on its first deferred command. Only sagas and policies can defer a command: ICommandDispatcher has no handler for a DeferredCommand.
Internal tracking interface for the aggregate root. You do not implement this directly — EntityRoot<TState, TEvent> does.
public interface IAggregateRoot {
AggregateVersion Version { get; }
IEnumerable<object> GetChanges();
}The concrete aggregate root. Maintains state, tracks pending changes, and applies commands.
public sealed class EntityRoot<TState, TEvent>(TState? state, AggregateVersion version)
: IAggregateRoot
where TState : IState<TState, TEvent> {
public TState State { get; }
public AggregateVersion Version { get; }
public IEnumerable<object> GetChanges();
public ValueTask AcceptAsync<TCommand>(TCommand command, CancellationToken cancellationToken = default)
where TCommand : ICommand<TState, TEvent>;
}A string-based identifier for an aggregate or saga. Its value is the name of the stream the aggregate or saga is stored in.
public readonly record struct AggregateIdentifier(string Value) {
public string Value { get; init; }
public static implicit operator AggregateIdentifier(string value);
public override string ToString();
}The constructor, the conversion from string and the init of Value (used by serializers such as System.Text.Json, and by with) throw an ArgumentException for a value that is null, empty or whitespace, or that starts with $. So an event or command that holds such an id can't be deserialized either: such streams are reserved by the store (on KurrentDB, $$x is the metadata of stream x). UnitOfWork.Attach rejects default(AggregateIdentifier).
The revision of an aggregate at load time. Used for optimistic concurrency.
public record struct AggregateVersion {
public static explicit operator long(AggregateVersion version);
public static explicit operator AggregateVersion(long version);
}Thrown when a commit is rejected because the aggregate was modified concurrently.
public class ConcurrencyException(
AggregateIdentifier identifier,
AggregateVersion expectedVersion,
AggregateVersion actualVersion) : Exception {
public AggregateIdentifier Identifier { get; }
public AggregateVersion ExpectedVersion { get; }
public AggregateVersion ActualVersion { get; }
}RetryCommandHandler catches this automatically and retries up to three times.
Maps a .NET event type to a stable event store type name and optionally wires an upgrader.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class EventContractAttribute(
string name,
int version = 1,
Type? eventUpgrader = null,
string? @namespace = null) : Attribute {
public Type? EventUpgrader { get; }
public static object? Upgrade(object? @event);
public override string ToString(); // e.g. "Orders.ItemAdded@v2"
}| Parameter | Description |
|---|---|
name |
The event name in the store. |
version |
The version number, appended as @v{n}. Defaults to 1. |
eventUpgrader |
A type implementing IUpgradeEvent<TOld, TNew> that upgrades this version to the next one. Put it on the old version: TOld is the attributed type (or a base type or interface of it). Exposed as EventUpgrader. A type that doesn't implement IUpgradeEvent<,> throws ArgumentOutOfRangeException. The upgrader needs a public parameterless constructor (no dependency injection); it is created on its first use, and EventTypeRegistry checks the constructor at startup. |
namespace |
Optional prefix, separated by a dot. |
| Member | Description |
|---|---|
Upgrade(event) |
Upgrades event with the upgrader on its type (through its first IUpgradeEvent), then the result with the upgrader on its type, until a type has none. Returns null for null, and the same instance when the type has no upgrader. The storage integrations apply it to everything their Deserialize returns; see Event contracts and schema evolution. |
A bidirectional mapping between CLR event types and the type names used to store them. Build one instance at startup by scanning your event assemblies, then use it inside the Serialize and Deserialize delegates on the storage integration options.
For each type decorated with [EventContract], the stored name is taken from EventContractAttribute.ToString() (e.g. Orders.ItemAdded@v2). Types without the attribute fall back to their short CLR type name.
Register all event type versions — current and historical — in the same registry so that old events stored under an earlier type name can still be looked up and deserialized. The storage integrations upgrade them after Deserialize (EventContractAttribute.Upgrade); building the registry checks every upgrader.
Register the registry in the service collection to let subscriptions filter on event type; see Event-type filter. Without a registered registry, every subscription receives every event type.
public sealed class EventTypeRegistry {
public static EventTypeRegistry FromAssemblies(params Assembly[] assemblies);
public static EventTypeRegistry FromTypes(params Type[] types);
public IReadOnlyList<string> GetTypeNames(Type eventType);
public string GetTypeName(Type type);
public string GetTypeName<TEvent>(TEvent @event);
public bool TryGetType(string typeName, out Type type);
}| Method | Description |
|---|---|
FromAssemblies(assemblies) |
Scans the given assemblies for non-abstract types decorated with [EventContract] and builds the registry. Checks the upgraders like FromTypes. |
FromTypes(types) |
Builds the registry from exactly the given types, current and historical. Useful when one assembly holds the events of several services. Throws InvalidOperationException when an upgrader doesn't implement IUpgradeEvent<TOld, TNew> exactly once with a TOld that accepts the type it sits on; the message lists every misconfigured upgrader, e.g. - Shop.OrderLinesUpdatedV4: eventUpgrader OrderLinesUpdatedV3ToV4 implements IUpgradeEvent<OrderLinesUpdatedV3, OrderLinesUpdatedV4>.
|
GetTypeNames(eventType) |
The stored names of every type a subscription on eventType can receive: the registry's concrete types assignable to eventType, and the types that upgrade to such a type, directly or through a chain of upgraders. Types without [EventContract] count with their short name. Sorted, without duplicates; typeof(object) gives every type. Used by the subscription loop to filter on the server. |
GetTypeName(type) |
Returns the stored type name for a CLR type. Falls back to type.Name when no [EventContract] is present. |
GetTypeName<TEvent>(event) |
Convenience overload — equivalent to GetTypeName(@event.GetType()). Uses the runtime type, so it works correctly when the declared type is a base class or interface. |
TryGetType(typeName, out type) |
Looks up the CLR type for a stored type name. Returns false when the name is unknown (e.g. a removed event or an event from another service). |
var registry = EventTypeRegistry.FromAssemblies(typeof(OrderPlaced).Assembly);
.AddKurrentDb(o => {
o.Serialize = evt => new SerializedEvent(
registry.GetTypeName(evt),
JsonSerializer.SerializeToUtf8Bytes(evt, evt.GetType()));
o.Deserialize = (typeName, data) =>
registry.TryGetType(typeName, out var clrType)
? JsonSerializer.Deserialize(data.Span, clrType)
: null;
});Upgrades an old version of an event to the next version.
public interface IUpgradeEvent<in TOldVersion, out TNewVersion> {
TNewVersion Upgrade(TOldVersion @event);
}Wire it with [EventContract(…, eventUpgrader: typeof(…))] on TOldVersion, and implement it once per upgrader class. The upgrader needs a public parameterless constructor.
Loads an aggregate from the event store. Registered by the storage integration.
public interface IRepository<TState, TEvent>
where TState : IState<TState, TEvent> {
ValueTask<EntityRoot<TState, TEvent>> LoadAsync(
AggregateIdentifier identifier,
CancellationToken cancellationToken = default);
}Throws AggregateRootNotFoundException when no events exist for the given identifier.
An ambient, async-local scope that accumulates metadata entries for the event(s) written during a single command execution. Opened automatically by MetadataAwareCommandHandler; you can also write to it directly via MetadataScope.Current?.Add(...).
public sealed class MetadataScope : IAsyncDisposable {
public MetadataScope();
public MetadataScope(EventMetadata seed);
public static MetadataScope? Current { get; }
public void Add(string key, object? value,
MetadataMultiplicity multiplicity = MetadataMultiplicity.Single);
public EventMetadata Snapshot();
}| Member | Description |
|---|---|
MetadataScope() |
Opens a new empty scope and pushes it onto the ambient stack. |
MetadataScope(seed) |
Opens a new scope pre-populated from seed and pushes it onto the stack. Array values in the seed are restored as accumulators so further Multiple additions append correctly. |
Current |
The innermost active scope, or null when no scope is active. |
Add |
Adds or updates an entry. Single overwrites; Multiple appends (duplicates are ignored). |
Snapshot |
Materialises the current entries as an immutable EventMetadata. Multiple entries are converted to arrays. |
Scopes nest: creating a new scope pushes it; disposing pops it. The expected usage is await using var scope = new MetadataScope(...).
Controls how repeated writes to the same key are handled.
public enum MetadataMultiplicity {
Single, // overwrite — only the last value is kept
Multiple // accumulate — all distinct values are kept as an array
}An immutable snapshot of a MetadataScope. Implements IReadOnlyDictionary<string, object?>. Multiple entries appear as object?[].
public sealed class EventMetadata : IReadOnlyDictionary<string, object?> {
public static EventMetadata Empty { get; }
}Apply to a state or command class to automatically populate the ambient MetadataScope whenever an instance of that type is processed by EntityRoot.AcceptAsync.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct,
AllowMultiple = true, Inherited = true)]
public abstract class MetadataAttribute(
string key,
MetadataMultiplicity multiplicity = MetadataMultiplicity.Single) : Attribute {
public string Key { get; }
public MetadataMultiplicity Multiplicity { get; }
public abstract ValueTask<object?> GetValueAsync(
object context, CancellationToken cancellationToken);
}Subclass this and override GetValueAsync. The context parameter is the decorated object (state or command); cast it to the expected type in your implementation.
// Example: stamp a correlation identifier from the command onto every event.
sealed class CorrelationIdAttribute() : MetadataAttribute("correlationId") {
public override ValueTask<object?> GetValueAsync(object context, CancellationToken ct) =>
ValueTask.FromResult<object?>(((MyCommand)context).CorrelationId);
}
[CorrelationId]
record MyCommand(AggregateIdentifier Id, string CorrelationId, ...) : ICommand<...> { ... }Configuration passed to AddAggregates.
public sealed class AggregatesOptions {
public AggregatesOptions ScanAssemblies(params Assembly[] assemblies);
public AggregatesOptions ScanTypes(params Type[] types);
}| Method | Description |
|---|---|
ScanAssemblies |
Discovers all ICommand<TState, TEvent> implementations in the given assemblies and registers a CommandHandler for each. |
ScanTypes |
Same, but only for the given types. Use it to register an explicit set of commands instead of everything in an assembly. |
Both can be combined; a type found by both is registered once.
IServiceCollection.AddAggregates(Action<AggregatesOptions>? configure = null) → IAggregatesBuilderRegisters the full command handler decorator chain. Returns a builder for attaching a storage integration.
Implements the routing and the reaction logic for a saga. A class implements it once; registration fails otherwise. To react to several event types, use a marker interface as TEvent and pattern matching in Correlate, ReactAsync and the state's Apply.
public interface ISaga<in TSagaState, in TEvent>
where TSagaState : IState<TSagaState, TEvent> {
IEnumerable<AggregateIdentifier> Correlate(TEvent @event, EventMetadata metadata);
IAsyncEnumerable<ICommand> ReactAsync(
TSagaState state,
TEvent @event,
CancellationToken cancellationToken = default);
}| Method | Description |
|---|---|
Correlate |
Returns the id of each saga instance that reacts to the event: the names of their saga streams. [] when none does. Called once per event, on a saga resolved from a fresh DI scope, so it can use the saga's dependencies; a failure is retried and then parked like a failing reaction. Derive the ids from the event and its metadata only, so that a redelivered or replayed event reaches the same instances. Two sagas that return the same id share a stream: give each saga its own prefix or metadata key. An id can't start with $ (see AggregateIdentifier); such an event is parked like a failing reaction. |
ReactAsync |
Reacts to the event once for each saga instance Correlate returned. |
| Parameter | Description |
|---|---|
metadata |
The stored metadata of the event, for ids written to metadata when the event was committed. |
state |
The saga state before the incoming event: what the saga knew until now. Use state.Apply(@event) for the state after it. |
event |
The triggering event. |
// Ids from the event body
public IEnumerable<AggregateIdentifier> Correlate(IOrderEvent @event, EventMetadata metadata) =>
[new AggregateIdentifier($"order-fulfillment-{@event.OrderId}")];
// Ids from metadata
public IEnumerable<AggregateIdentifier> Correlate(IOrderEvent @event, EventMetadata metadata) =>
metadata.TryGetValue("OrderFulfillmentId", out var value) && value is object?[] ids
? ids.OfType<string>().Select(id => new AggregateIdentifier(id))
: [];Besides commands, ReactAsync can yield commands deferred with DeferUntil and, in a saga that implements ISaga<TSagaState, TEvent, TDeadline>, deadlines requested with Deadline.At.
A saga that also receives the deadlines it requests. Implement it instead of ISaga<TSagaState, TEvent>, from which it inherits: it is registered, resolved and subscribed like any saga. See Saga deadlines.
public interface ISaga<in TSagaState, in TEvent, in TDeadline> : ISaga<TSagaState, TEvent>
where TSagaState : IState<TSagaState, TEvent> {
IAsyncEnumerable<ICommand> ReactToDeadlineAsync(
TSagaState state,
TDeadline deadline,
CancellationToken cancellationToken = default);
}| Parameter | Description |
|---|---|
state |
The current state of the saga. The deadline doesn't change it: Apply is not called, and nothing is stored for the deadline itself. It can lag behind the aggregates. |
deadline |
The payload the saga requested the deadline with. |
ReactToDeadlineAsync yields commands, deferred commands and new deadlines. Delivery is at least once and can be late: recognise a deadline that no longer applies from its payload and the state, and yield nothing. A class implements ISaga<,,> once (AddSagas throws otherwise); to receive several kinds of deadlines, use a marker interface or base type of your own as TDeadline.
A deadline a saga requests. Yield Deadline.At(due, payload) from ReactAsync or ReactToDeadlineAsync among the commands. The request is stored with the saga's state, and once due has passed, payload is delivered back to the same saga instance through ReactToDeadlineAsync.
public sealed record Deadline : ICommand {
public static Deadline At(DateTimeOffset due, object payload);
public DateTimeOffset Due { get; }
public object Payload { get; }
}| Member | Description |
|---|---|
Due |
When the deadline is delivered. A time in the past delivers it right away. |
Payload |
What the saga receives: an instance of its TDeadline. It is stored until it is due, so the storage integration's Serialize/Deserialize must know its type under a stable name. A null payload throws ArgumentNullException; a Deadline or DeferredCommand throws ArgumentException. |
yield return Deadline.At(planned.Due.AddDays(14), new PaymentDue(planned.PaymentId, planned.Due));A saga that doesn't implement ISaga<,,>, or a payload that isn't its TDeadline, fails the reaction with an InvalidOperationException; so does a deferred deadline (Deadline.At(...).DeferUntil(...)). There is no cancel. Only sagas request deadlines: from a policy, a Deadline is dispatched as a command and fails. Use a deferred command instead when the command is known at the request.
Assigns a stable identity to a saga for checkpointing and versioning.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public sealed class SagaContractAttribute(
string name,
int version = 1,
string? @namespace = null,
string? continueFrom = null,
bool startFromEnd = false,
SubscriptionErrorMode onError = SubscriptionErrorMode.Park) : Attribute {
public IReadOnlyList<string> Predecessors { get; }
public string? ContinueFrom { get; }
public bool StartFromEnd { get; }
public SubscriptionErrorMode OnError { get; }
public override string ToString(); // e.g. "Orders.OrderFulfillment@v2"
}| Parameter / member | Description |
|---|---|
name |
The saga name. |
version |
The version number. Defaults to 1. |
namespace |
Optional prefix. |
continueFrom |
The subscription id whose checkpoint a new version continues from when it has none of its own. Omitted: every previous version, nearest first. ContinueFrom.None (""): none, so the saga replays. See Where a subscription starts. |
startFromEnd |
When true, starts from the current end of the stream on first run — skips historical events. A predecessor's checkpoint wins over it. |
onError |
What the subscription does with an event that still fails after all retries: SubscriptionErrorMode.Park (the default) parks it and continues; Block retries it until it succeeds. See SubscriptionErrorMode. |
Predecessors |
The ids derived from continueFrom and version, nearest first, e.g. ["Orders.OrderFulfillment@v2", "Orders.OrderFulfillment@v1"] for @v3. |
ContinueFrom |
The nearest predecessor (the first of Predecessors), or null. |
OnError |
The onError argument. |
The saga's state is kept across a version bump: saga streams are named by the ids Correlate returns, not by the contract.
Configuration passed to AddSagas.
public sealed class SagasOptions {
public SagasOptions ScanAssemblies(params Assembly[] assemblies);
public SagasOptions ScanTypes(params Type[] types);
}| Method | Description |
|---|---|
ScanAssemblies |
Discovers all ISaga<TSagaState, TEvent> implementations in the given assemblies, including those that implement ISaga<TSagaState, TEvent, TDeadline>. |
ScanTypes |
Same, but only for the given types. Use it to run only some sagas of an assembly in a host. |
Every discovered saga gets a subscription, which routes each event with the saga's own Correlate.
Only needed when you write your own saga repository, commit delegate or storage integration; the KurrentDB and MSSP packages provide all of it.
| Type | Description |
|---|---|
SagaRoot.GetChanges() |
Yields EventReferences (links), DeferredCommandRequests and DeadlineRequests. A custom SagaCommitDelegate stores each request with ScheduledFormat.WriteRequest (including its Cause), as a ScheduledFormat.CommandRequestEventType or DeadlineRequestEventType entry, in the same append as the links. |
SagaRoot.AcceptDeadlineAsync(deadline, request, saga) |
Lets the saga react to a due deadline with its current state. Records no change for the deadline itself, only the requests of the reaction, with request as their cause; returns [] without reacting when the loaded stream already holds requests with that cause. |
DeadlineRequest |
(string Owner, DateTimeOffset Due, object Payload) with EventReference? Cause: what a saga root records for a yielded Deadline. |
BaseSagaRepository.SagaStreamEntry |
Has a Kind (Link or ScheduledRequest), a Cause, and a factory SagaStreamEntry.ScheduledRequest(reference, cause = null). A custom repository yields a scheduled request for each CommandRequestEventType and DeadlineRequestEventType entry, with the cause it reads with ScheduledFormat.TryReadRequest: it counts for the version but doesn't change the state, and its cause marks a deadline as handled. |
The shared types (DeferredCommandRequest, ScheduledFormat, IScheduledStore) are in Aggregates.Subscriptions.
Implements the reaction logic for a stateless policy. A class implements it once; registration fails otherwise. Use a marker interface (or object) for TEvent to react to several event types, in the order they were stored.
public interface IPolicy<in TEvent> {
IAsyncEnumerable<ICommand> ReactAsync(TEvent @event, CancellationToken cancellationToken = default);
}A policy can defer a command with DeferUntil. The deferred commands of one reaction are stored after the other commands were dispatched, in one append, once per event; see Deferred commands of a policy.
Assigns a stable identity to a policy for checkpointing and versioning.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public sealed class PolicyContractAttribute(
string name,
int version = 1,
string? @namespace = null,
string? continueFrom = null,
bool startFromEnd = false,
SubscriptionErrorMode onError = SubscriptionErrorMode.Park) : Attribute {
public IReadOnlyList<string> Predecessors { get; }
public string? ContinueFrom { get; }
public bool StartFromEnd { get; }
public SubscriptionErrorMode OnError { get; }
public override string ToString(); // e.g. "Users.SendWelcomeEmail@v1"
}| Parameter | Description |
|---|---|
name |
The policy name. |
version |
The version number. Defaults to 1. |
namespace |
Optional prefix. |
continueFrom |
As on SagaContractAttribute: by default a new version continues from the previous versions' checkpoint, so a bump doesn't dispatch the history again; ContinueFrom.None replays. |
startFromEnd |
When true, starts from the current end of the stream on first run. A predecessor's checkpoint wins over it. |
onError |
As on SagaContractAttribute. |
Predecessors, ContinueFrom and OnError are as on SagaContractAttribute.
Configuration passed to AddPolicies.
public sealed class PoliciesOptions {
public PoliciesOptions ScanAssemblies(params Assembly[] assemblies);
public PoliciesOptions ScanTypes(params Type[] types);
}| Method | Description |
|---|---|
ScanAssemblies |
Discovers all IPolicy<TEvent> implementations in the given assemblies and registers a subscription for each. |
ScanTypes |
Same, but only for the given types. |
Implements the projection logic for an event type.
public interface IProjection<in TEvent> {
ValueTask<ICommit> ProjectAsync(TEvent @event, EventMetadata metadata, CancellationToken cancellationToken = default);
}A class implements it once; registration fails otherwise. Use a marker interface (or object) for TEvent to handle multiple related event types in a single projection while guaranteeing processing order.
A composable unit of pending write work.
public interface ICommit {
ICommit Use(Func<ICommit> applicator);
ICommit Use<TCommit>(Func<CancellationToken, ValueTask<TCommit>> asyncApplicator)
where TCommit : ICommit;
ValueTask CommitAsync(CancellationToken cancellationToken = default);
}| Method | Description |
|---|---|
Use(Func<ICommit>) |
Appends a synchronously produced commit to the chain. |
Use<TCommit>(Func<ct, ValueTask<TCommit>>) |
Appends an asynchronously produced commit; deferred until CommitAsync. |
CommitAsync |
Executes all pending work in the chain in order. |
The default ICommit implementation. Use Commit.Create() to start a new chain.
public sealed class Commit : ICommit {
public static ICommit Create();
}Assigns a stable identity to a projection for checkpointing and versioning.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public sealed class ProjectionContractAttribute(
string name,
int version = 1,
string? @namespace = null,
string? continueFrom = null,
bool startFromEnd = false,
SubscriptionErrorMode onError = SubscriptionErrorMode.Park) : Attribute {
public IReadOnlyList<string> Predecessors { get; }
public string? ContinueFrom { get; }
public bool StartFromEnd { get; }
public SubscriptionErrorMode OnError { get; }
public override string ToString(); // e.g. "ReadModels.Orders@v1"
}The parameters and members are as on SagaContractAttribute. To rebuild a projection from the beginning in a new version, set continueFrom: ContinueFrom.None.
Configuration passed to AddProjections.
public sealed class ProjectionsOptions {
public ProjectionsOptions ScanAssemblies(params Assembly[] assemblies);
public ProjectionsOptions ScanTypes(params Type[] types);
}| Method | Description |
|---|---|
ScanAssemblies |
Discovers all IProjection<TEvent> implementations in the given assemblies and registers a subscription for each. |
ScanTypes |
Same, but only for the given types. |
The live event a projection subscription is projecting, available to the projection and its commit.
public sealed class ProjectedEvent {
public static ProjectedEvent? Current { get; }
public string SubscriptionId { get; }
public ulong Position { get; }
public IServiceProvider Services { get; }
public int NextTransaction();
}| Member | Description |
|---|---|
Current |
The event being projected in the current asynchronous flow (AsyncLocal); null for a replayed parked event and outside a projection subscription. |
SubscriptionId |
The id of the subscription projecting the event. |
Position |
The commit position of the event. |
Services |
The services of the scope the event is projected in. |
NextTransaction |
Numbers the transactions that record the event's position, from 1; every attempt starts again from 1. Used by Aggregates.Projections.Sql; internal infrastructure, not covered by semantic versioning. |
A commit uses it to record the event's position with its writes (see Exactly-once in SQL).
public static ISqlCommit UseSql(this ICommit commit, IDbConnectionFactory connectionFactory,
IsolationLevel isolationLevel = IsolationLevel.ReadCommitted);
public interface ISqlCommit : ICommit {
ISqlCommit Query(string sql, object? parameters = null, CommandType commandType = CommandType.Text);
}
public interface IDbConnectionFactory {
ValueTask<DbConnection> CreateAsync(CancellationToken cancellationToken = default);
}UseSql appends an ISqlCommit to the chain. Its statements run in one transaction after the parent chain has committed. The public properties of parameters become command parameters.
public static IProjectionsBuilder RecordSqlPositions(this IProjectionsBuilder builder,
Action<SqlPositionsOptions>? configure = null);
public sealed class SqlPositionsOptions {
public string Schema { get; set; } = "dbo";
public string Table { get; set; } = "ProjectionPositions";
}Records the position of each projected event in the table, in the same transaction as the statements of every ISqlCommit, so a redelivered event has no effect twice in SQL. The schema and the table are created in each database on first use. Throws ArgumentException for an empty schema or table name. Calling it again replaces the earlier configuration. SQL Server only. See Exactly-once in SQL.
Describes one subscription that a hosted service runs. AddProjections, AddPolicies and AddSagas register one as a singleton instance per handler class, so IEnumerable<SubscriptionRegistration> lists the subscriptions of a host.
public sealed record SubscriptionRegistration(
string SubscriptionId,
Type HandlerType,
Type EventType,
bool StartFromEnd,
IReadOnlyList<string>? Predecessors = null) {
public SubscriptionErrorMode ErrorMode { get; init; }
}| Member | Description |
|---|---|
SubscriptionId |
The contract's string form ({namespace}.{name}@v{version}), or the handler's full type name without a contract. Names checkpoint-{id} and parked-{id}. Unique per host. |
HandlerType |
The projection, policy or saga class. |
EventType |
The TEvent of the class's handler interface. |
StartFromEnd |
Whether the subscription starts at the end of the store when it has no checkpoint. |
Predecessors |
The contract's Predecessors: the ids whose checkpoint the subscription continues from when it has none, nearest first. null or empty for none. Also the ids whose parked messages the subscription replays. |
ErrorMode |
The contract's OnError; Park without a contract. |
SubscriptionRegistrations (an internal type) holds the helpers the three packages share: FindHandlers (handler classes that implement a handler interface exactly once), GetSubscriptionId, and Add, which throws when a second class registers under an id that is already taken, when a subscription continues from itself, or when a subscription and one of its predecessors are registered in the same host. See One subscription per handler class.
Values for the continueFrom parameter of the projection, policy and saga contracts.
public static class ContinueFrom {
public const string None = "";
}None means no predecessor: a new contract version starts from the beginning (or the end with startFromEnd) instead of continuing from an older version's checkpoint. Inside a class that has its own member named ContinueFrom, write Aggregates.Subscriptions.ContinueFrom.None.
Creates subscriptions to the event stream. Implemented by storage integration packages.
public interface ISubscriptionFactory {
ISubscription Subscribe(SubscriptionRequest request, CancellationToken cancellationToken = default);
ValueTask<ulong?> GetEndPositionAsync(CancellationToken cancellationToken = default) =>
ValueTask.FromResult<ulong?>(null);
bool IsTransient(Exception exception) => true;
}| Member | Description |
|---|---|
Subscribe |
Opens a subscription as described by the SubscriptionRequest. |
GetEndPositionAsync |
The commit position of the last event in the store, or null when the transport can't tell or the store is empty. A subscription that starts from the end writes it as its first checkpoint before it subscribes. KurrentDB reads it; MSSP returns null (the default) for now. |
IsTransient |
Whether subscribing again can succeed after exception. Also used for failures of the checkpoint store and the parked-message sink. Return false only for failures that need a configuration change; the default treats every failure as transient. See Resubscribing for the KurrentDB and MSSP classification. |
Events whose type starts with $ are never delivered; the library's own bookkeeping (checkpoints, parked messages) uses that prefix. See Reserved $ event types.
What a subscription delivers, and from where.
public sealed record SubscriptionRequest(
ulong? FromPosition,
bool StartFromEnd,
IReadOnlyList<string>? EventTypes = null,
int ProgressInterval = SubscriptionCheckpointOptions.DefaultMaxFilteredEvents) {
public string? EventTypePattern { get; }
}| Member | Description |
|---|---|
FromPosition |
Exclusive starting position. null means start from the beginning (unless StartFromEnd overrides). |
StartFromEnd |
When true and FromPosition is null, starts from the current end of the stream. |
EventTypes |
The stored type names to deliver, or null to deliver every event type except $ types. The subscription loop fills it from EventTypeRegistry.GetTypeNames; see Event-type filter. |
ProgressInterval |
Number of events the store skips because of EventTypes after which it reports progress (a message with IsProgress). The loop passes SubscriptionCheckpointOptions.MaxFilteredEvents. KurrentDB rounds it up to a multiple of 32; MSSP ignores it. |
EventTypePattern |
^(?:a|b|c)$ with every name escaped, or null without EventTypes. The KurrentDB and MSSP transports filter with it. |
An active subscription. Yields SubscriptionMessage values in chronological order.
public interface ISubscription : IAsyncEnumerable<SubscriptionMessage>, IAsyncDisposable { }A deserialized event delivered by a subscription.
public readonly record struct SubscriptionMessage(
object? Event,
ulong CommitPosition,
EventReference Source,
EventMetadata Metadata) {
public Exception? DeserializationError { get; init; }
public bool IsProgress { get; init; }
public static SubscriptionMessage Progress(ulong position);
}| Member | Description |
|---|---|
Event |
The deserialized domain event, or null when the event type is unknown (Deserialize returned null; skipped, not parked), when deserialization failed, or for a progress message. |
DeserializationError |
The exception thrown by Deserialize or DeserializeMetadata, or null. When set, the subscription parks the message without retries (or, with SubscriptionErrorMode.Block, subscribes again before it). See Deserialisation failures. |
IsProgress |
true for a message without an event: the store has read every event up to CommitPosition and the filter excluded the ones it didn't deliver (KurrentDB: checkpoint reached). Never handed to a handler; the loop writes its position as the checkpoint. Create one with Progress(position). See Progress while filtered. |
CommitPosition |
The global position of this event in the underlying stream. Recorded as processed once the event has been handled; checkpoints are written in batches (see SubscriptionCheckpointOptions). |
Source |
The stream and revision of the event. Also set when deserialization failed. Sagas store it as a link; see Saga streams hold links. |
Metadata |
The metadata stored alongside the event, or EventMetadata.Empty when none is present or the integration does not provide a DeserializeMetadata delegate. |
A custom ISubscriptionFactory must fill Source; it is a positional parameter, so leaving it out does not compile.
Identifies a stored event by its stream and its revision within that stream, and reads and writes the payload of a link event to it.
public readonly record struct EventReference(string StreamId, ulong Revision) {
public const string LinkEventType = "$>";
public byte[] ToLinkData();
public static bool TryParseLinkData(ReadOnlySpan<byte> data, out EventReference reference);
public override string ToString(); // e.g. "3@order-42"
}| Member | Description |
|---|---|
LinkEventType |
The event type of a link event: $>. |
ToLinkData |
The payload of a link event to this event: "{Revision}@{StreamId}", UTF-8. |
TryParseLinkData |
Parses a link payload. The revision ends at the first @; the rest is the stream id, which may itself contain @. Returns false for anything else. |
Persists and retrieves subscription positions. Implemented by storage integration packages.
public interface ICheckpointStore {
ValueTask<ulong?> GetAsync(string subscriptionId, CancellationToken cancellationToken = default);
ValueTask StoreAsync(string subscriptionId, ulong position, CancellationToken cancellationToken = default);
}The subscription hosted services don't call StoreAsync for every message; they write through a CheckpointTracker (see Internal types). The KurrentDB and MSSP implementations append a $aggregates-checkpoint event to checkpoint-{subscriptionId}; the KurrentDB implementation also sets $maxCount to 1 on that stream.
public readonly record struct SubscriptionCheckpoint {
public required ulong Position { get; init; }
public int? AdoptedFrom { get; init; }
}
public static class CheckpointStoreExtensions {
public static ValueTask<SubscriptionCheckpoint?> GetOrAdoptAsync(this ICheckpointStore store, string subscriptionId,
IReadOnlyList<string> predecessorIds, CancellationToken cancellationToken = default);
}GetOrAdoptAsync returns the checkpoint of subscriptionId; without one, it adopts the checkpoint of the nearest predecessor that has one (stores it as the subscription's own) and reports which in AdoptedFrom (its index in predecessorIds; null for the subscription's own). null when none has a checkpoint. SubscriptionLoop and the scheduler of deferred commands use it on a contract version bump.
Receives messages that could not be processed after all retry attempts have been exhausted.
public interface IParkedMessageSink {
ValueTask ParkAsync(
string subscriptionId,
SubscriptionMessage message,
Exception exception,
CancellationToken cancellationToken = default);
}| Parameter | Description |
|---|---|
subscriptionId |
The subscription that owns the failed message. |
message |
The message that could not be processed. |
exception |
The exception from the final failed attempt. |
The default implementation (LoggingParkedMessageSink) logs a warning and returns without persisting. Storage integration packages register a persistent implementation that appends a $aggregates-parked event to a parked-{subscriptionId} stream, with the payload of ParkedFormat.WriteParked. Register your own implementation as a singleton to override either default:
services.AddSingleton<IParkedMessageSink, MyCustomParkedMessageSink>();What a subscription does with an event that still fails after all retries. Set per handler with onError on ProjectionContractAttribute, PolicyContractAttribute or SagaContractAttribute.
public enum SubscriptionErrorMode { Park, Block }| Value | Description |
|---|---|
Park |
The default. Parks the message under parked-{subscription id} and continues with the next one. Replay or dismiss it later with IParkedMessages. |
Block |
Never parks: retries the message, with the backoff of SubscriptionErrorHandlingOptions, until it succeeds, and handles no later message until then. A message that can't be deserialized makes the subscription subscribe again before it. For handlers that must keep the order, such as an outbox. |
Only the event subscription blocks; the scheduler of deferred commands and deadlines always parks. See Blocking instead of parking.
Lists, replays and dismisses parked messages. AddProjections, AddPolicies and AddSagas register it (ParkedMessages, a singleton); it needs a storage integration (AddKurrentDb() or AddMssp()), and throws an InvalidOperationException from every method without one.
public interface IParkedMessages {
ValueTask<IReadOnlyList<ParkedMessage>> ListAsync(string subscriptionId, CancellationToken cancellationToken = default);
ValueTask<ParkedMessageReplay> ReplayAsync(string subscriptionId, string id, CancellationToken cancellationToken = default);
ValueTask<IReadOnlyList<ParkedMessageReplay>> ReplayAllAsync(string subscriptionId, CancellationToken cancellationToken = default);
ValueTask DismissAsync(string subscriptionId, string id, CancellationToken cancellationToken = default);
}| Member | Description |
|---|---|
subscriptionId |
The id the messages were parked under: a subscription id, or scheduled-{subscription id} for the deferred commands and deadlines of its scheduler. Also the id of an older contract version, or of a handler this host doesn't run. |
ListAsync |
The open parked messages (neither replayed nor dismissed), oldest first. Empty when there are none. |
id |
The Id of an open message, as ListAsync returns it. ReplayAsync and DismissAsync throw an ArgumentException when it is null or empty. |
ReplayAsync |
Replays one open message through the subscription of this host that has subscriptionId as its id or as a predecessor, with the retries of SubscriptionErrorHandlingOptions. Records it as replayed when it succeeds; otherwise it stays open, and the result holds the error. Throws an InvalidOperationException when the message is not open. |
ReplayAllAsync |
Replays the open messages oldest first, and stops at the first that fails; that one is the last result. |
DismissAsync |
Records an open message as dismissed, without handling it. Throws an InvalidOperationException when the message is not open. |
See Replaying parked messages for what a replay does and what makes it fail right away.
An open parked message, as IParkedMessages.ListAsync returns it.
public sealed record ParkedMessage {
public required string SubscriptionId { get; init; }
public required string Id { get; init; }
public required DateTimeOffset ParkedAt { get; init; }
public EventReference? Source { get; init; }
public required ulong CommitPosition { get; init; }
public string? EventType { get; init; }
public required string ExceptionType { get; init; }
public required string ExceptionMessage { get; init; }
public string? StackTrace { get; init; }
}| Member | Description |
|---|---|
SubscriptionId |
The id it was parked under. |
Id |
Identifies it among the messages parked under the same id, for ReplayAsync and DismissAsync. Stays the same as long as the message is open. Opaque: compare it, don't derive anything from it. |
ParkedAt |
When it was parked (the creation time of the entry in the store). |
Source |
The stream and revision of the event, or of the request for the scheduler. null for an entry that doesn't tell: such a message can only be dismissed. |
CommitPosition |
The position of the message in the store. |
EventType |
The full CLR type name of the deserialized event, or null when it couldn't be deserialized. |
ExceptionType, ExceptionMessage, StackTrace
|
The exception of the last attempt. |
The result of replaying one parked message.
public sealed record ParkedMessageReplay {
public required ParkedMessage Message { get; init; }
public Exception? Error { get; init; }
public bool Succeeded { get; } // Error is null
}Error is the exception of the last attempt, or an InvalidOperationException that tells why the message can't be replayed now (no source, a deleted event, a type that doesn't deserialize or that the handler doesn't take, no subscription in this host).
Controls retry behaviour for all subscription hosted services.
public sealed class SubscriptionErrorHandlingOptions {
public int MaxRetries { get; set; } = 5;
public TimeSpan InitialDelay { get; set; } = TimeSpan.FromSeconds(1);
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(30);
public double BackoffMultiplier { get; set; } = 2.0;
}| Property | Default | Description |
|---|---|---|
MaxRetries |
5 |
Total number of attempts per message (including the first). |
InitialDelay |
1 s |
Delay before the second attempt. |
MaxDelay |
30 s |
Upper bound on the delay between attempts. |
BackoffMultiplier |
2.0 |
Factor by which the delay grows after each failed attempt. |
Register a custom instance as a singleton before calling AddSagas / AddPolicies / AddProjections to override all defaults at once.
Controls how often all subscription hosted services write their checkpoint, and whether a subscription may start without one.
public sealed class SubscriptionCheckpointOptions {
public int MaxBatchSize { get; set; } = 100;
public TimeSpan MaxInterval { get; set; } = TimeSpan.FromSeconds(5);
public const int DefaultMaxFilteredEvents = 4096;
public int MaxFilteredEvents { get; set; } = DefaultMaxFilteredEvents;
public bool RequireCheckpoint { get; set; }
public IList<string> AllowedWithoutCheckpoint { get; set; } = [];
}| Property | Default | Description |
|---|---|---|
MaxBatchSize |
100 |
Number of processed messages after which the checkpoint is written. After a crash, at most this many messages are delivered again. |
MaxInterval |
5 s |
Maximum age of the oldest unwritten position. Checked when a message arrives, so an idle subscription keeps its last position in memory until the next message or until it stops. |
MaxFilteredEvents |
4096 |
Number of events the store skips because of the subscription's event-type filter after which the subscription writes its position. Keep it well above the number of subscriptions on the store (in all hosts): every checkpoint is such an event for the other subscriptions. KurrentDB rounds it up to a multiple of 32; MSSP doesn't report progress yet. See Progress while filtered. |
RequireCheckpoint |
false |
When true, a subscription with no checkpoint of its own and no predecessor checkpoint to adopt fails with an InvalidOperationException before it subscribes (from the beginning and from the end alike), unless its id is in AllowedWithoutCheckpoint. Not transient: under StopHost the host stops. Doesn't apply to the scheduler of deferred commands and saga deadlines. See Where a subscription starts. |
AllowedWithoutCheckpoint |
empty | The subscription ids that may start without a checkpoint while RequireCheckpoint is on. Compared ordinally. Remove an id once its checkpoint-{id} exists. |
The pending position is always written when the subscription stops. Register a custom instance as a singleton before calling AddSagas / AddPolicies / AddProjections to override the defaults. See Checkpointing.
Controls how long all subscription hosted services wait before subscribing again after a failure.
public sealed class SubscriptionResubscribeOptions {
public TimeSpan InitialDelay { get; set; } = TimeSpan.FromSeconds(1);
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(30);
public double BackoffMultiplier { get; set; } = 2.0;
}| Property | Default | Description |
|---|---|---|
InitialDelay |
1 s |
Delay after the first failure. |
MaxDelay |
30 s |
Upper bound on the delay between attempts. |
BackoffMultiplier |
2.0 |
Factor by which the delay grows after each consecutive failure. |
There is no maximum number of attempts; the backoff starts over once a message has been processed. Separate from SubscriptionErrorHandlingOptions, which controls handler retries. Register a custom instance as a singleton before calling AddSagas / AddPolicies / AddProjections to override the defaults. See Resubscribing.
Keeps the state of every subscription and scheduler of a host. The subscription loop, the retry policy (for a blocking subscription) and the scheduler report each change of state. Registered as a singleton by AddSagas / AddPolicies / AddProjections.
public sealed class SubscriptionMonitor {
public SubscriptionMonitor(TimeProvider timeProvider);
public IReadOnlyList<SubscriptionStatus> GetStatuses();
}GetStatuses returns a snapshot, ordered by id (ordinally), of every subscription and scheduler that started in this host. A state changes when it happens, never for every processed message. Use it for your own health check or dashboard. See Health.
public sealed record SubscriptionStatus {
public required string Id { get; init; }
public required SubscriptionState State { get; init; }
public required DateTimeOffset Since { get; init; }
public ulong? Position { get; init; }
public required int Attempts { get; init; }
public Exception? Error { get; init; }
}| Property | Description |
|---|---|
Id |
The subscription id, or the id of a scheduler (scheduled-{subscription id}). |
State |
See SubscriptionState. |
Since |
When it entered State; a repeated failure doesn't change it. |
Position |
The commit position at the latest change: the last processed position (or the one it started after), or the position of the event it blocks on. null before a subscription knows a position, and for a scheduler. |
Attempts |
Consecutive failed attempts while retrying or blocked; 0 otherwise. |
Error |
The latest failure while retrying or blocked, or the failure that stopped it; null otherwise. |
public enum SubscriptionState { Running, Waiting, Retrying, Blocked, Stopped }| Value | Description |
|---|---|
Running |
Handling messages, or, for a scheduler, reading and executing its requests. A subscription starts in this state. |
Waiting |
Only a scheduler: its handler never deferred a command or requested a deadline. A scheduler starts in this state. |
Retrying |
After a transient failure, or a subscription that ended unexpectedly. A subscription is running again once a message arrives after the failure; a scheduler once the failed action succeeds or its feed reads an entry. |
Blocked |
Only a subscription with SubscriptionErrorMode.Block: an event still fails after MaxRetries attempts, or can't be deserialized. |
Stopped |
Ended: after a failure that is not transient, because the other half of its hosted service ended, or because the host stops. |
An IHealthCheck (Microsoft.Extensions.Diagnostics.HealthChecks) over SubscriptionMonitor: unhealthy when a subscription or scheduler stopped, degraded when one is retrying or blocked, healthy otherwise.
public sealed class SubscriptionHealthCheck(SubscriptionMonitor monitor) : IHealthCheck;builder.Services.AddHealthChecks()
.AddCheck<SubscriptionHealthCheck>("aggregates", tags: ["ready"]);The description names the ids that need attention ('Shop.Orders@v2' is blocked; …); the data holds one line per id (Blocked since 2026-10-20T08:00:00.0000000+00:00 at position 42 (attempt 7): Timeout). The check needs no registration of its own: AddCheck<T> creates it from the service collection. See Health.
The format of parked streams and the store that IParkedMessages lists and replays through. The storage integrations register the store; only needed when you write your own storage integration.
public static class ParkedFormat {
public const string ParkedEventType = "$aggregates-parked";
public const string ReplayedEventType = "$aggregates-parked-replayed";
public const string DismissedEventType = "$aggregates-parked-dismissed";
public static string ParkedStream(string subscriptionId); // "parked-{subscription id}"
public static byte[] WriteParked(SubscriptionMessage message, Exception exception);
}
public interface IParkedMessageStore {
IAsyncEnumerable<ParkedEntry> ReadParkedAsync(string subscriptionId, CancellationToken cancellationToken = default);
ValueTask AppendParkedAsync(string subscriptionId, string eventType, ReadOnlyMemory<byte> data, CancellationToken cancellationToken = default);
ValueTask<StoredEntry?> ReadEventAsync(EventReference source, CancellationToken cancellationToken = default);
object? Deserialize(string type, ReadOnlyMemory<byte> data);
}
public readonly record struct ParkedEntry(ulong Revision, string EventType, ReadOnlyMemory<byte> Data, DateTimeOffset Created);
public readonly record struct StoredEntry(string EventType, ReadOnlyMemory<byte> Data, EventMetadata Metadata);| Type | Description |
|---|---|
ParkedFormat |
WriteParked writes the JSON of a parked message: CommitPosition, Stream and Revision (of message.Source), EventType (the CLR type of message.Event), ExceptionType, Message and StackTrace; fields without a value are left out. A replayed or dismissed entry holds the parked message in link format ("{revision}@parked-{id}"). Reading never fails: a missing or invalid field gets its default. |
IParkedMessageStore |
Registered by each storage integration (KurrentDbParkedMessageStore, MsspParkedMessageStore). ReadParkedAsync reads parked-{id} oldest first (nothing when it doesn't exist); AppendParkedAsync appends a replayed or dismissed entry; ReadEventAsync reads an event as stored, with its metadata, or null when it no longer exists; Deserialize uses the integration's Deserialize. |
The scheduler of deferred commands, shared by sagas and policies, which also delivers saga deadlines. AddSagas and AddPolicies register the scheduler (an internal type), and the storage integrations register the store; the types below are only needed when you write your own storage integration, saga repository or commit delegate.
// The stored format.
public static class ScheduledFormat {
public const string EventTypePrefix = "$aggregates-scheduled";
public const string CommandRequestEventType = "$aggregates-scheduled-command"; // in a saga stream or a policy's request stream
public const string DeadlineRequestEventType = "$aggregates-scheduled-deadline"; // in a saga stream
public const string DeliveryEventType = "$aggregates-scheduled-delivered"; // in scheduled-{subscription id}
public const string MarkerEventType = "$aggregates-scheduled-marker"; // in scheduled-{subscription id}
public static string SchedulerStream(string subscriptionId); // "scheduled-{subscription id}"
public static string RequestStream(string subscriptionId, EventReference source); // "scheduled-requests-{subscription id}-{revision}@{stream}"
public static byte[] WriteRequest(string owner, DateTimeOffset due, string type, ReadOnlySpan<byte> data, EventReference? cause = null);
public static bool TryReadRequest(ReadOnlyMemory<byte> data, out ScheduledEnvelope envelope);
}
public readonly record struct ScheduledEnvelope(string Owner, DateTimeOffset Due, string Type, ReadOnlyMemory<byte> Data, EventReference? Cause);
// A deferred command as a change of a saga root, or as a request a policy stores.
public readonly record struct DeferredCommandRequest(string Owner, DateTimeOffset Due, ICommand Command) {
public EventReference? Cause { get; init; } // the saga deadline whose reaction deferred it
}
public interface IScheduledStore {
IAsyncEnumerable<ScheduledEntry> SubscribeAsync(ulong? after, CancellationToken cancellationToken = default);
ValueTask AppendAsync(string stream, string eventType, ReadOnlyMemory<byte> data, CancellationToken cancellationToken = default);
ValueTask<bool> TryAppendRequestsAsync(string stream, IReadOnlyList<DeferredCommandRequest> requests, CancellationToken cancellationToken = default);
ValueTask<bool> ExistsAsync(string stream, CancellationToken cancellationToken = default);
object? Deserialize(string type, ReadOnlyMemory<byte> data);
}
public readonly record struct ScheduledEntry(string EventType, ReadOnlyMemory<byte> Data, EventMetadata Metadata,
EventReference Source, ulong CommitPosition) {
public bool IsProgress { get; init; }
public static ScheduledEntry Progress(ulong position);
}| Type | Description |
|---|---|
ScheduledFormat |
The stored format: JSON with the owner (the subscription id of the saga or policy), the due time, the stored type and data (base64) of the command or deadline payload, and an optional cause (the deadline whose reaction made the request, in link format). A cause that is present but invalid makes the request invalid. A delivered entry holds the request in link format ("{revision}@{stream}"). Every type starts with EventTypePrefix, which starts with $, so no subscription receives these entries. |
DeferredCommandRequest |
What a saga root records for a yielded DeferredCommand (stored by the saga commit), and what a policy stores with TryAppendRequestsAsync. |
IScheduledStore |
Registered by each storage integration (KurrentDbScheduledStore, MsspScheduledStore). SubscribeAsync reads every entry whose type starts with EventTypePrefix, in commit order, then live; AppendAsync and ExistsAsync serve the scheduler's own stream; TryAppendRequestsAsync stores a policy's requests in one append to a stream that must not exist yet, with the metadata of the current MetadataScope, and returns false when it exists; Deserialize deserializes a command or deadline payload with the integration's Deserialize. |
Imports the positions of the persistent subscription groups that Aggregates 0.x left on a KurrentDB server as 1.0 checkpoints, deletes the groups afterwards, or rolls a group back to where 1.0 stopped. Only needed for the switch-over; see Importing 0.x subscription positions for the procedure.
public sealed class PersistentSubscriptionMigration {
public PersistentSubscriptionMigration(KurrentDBClient client,
KurrentDBPersistentSubscriptionsClient persistentSubscriptions);
public Task<MigrationPlan> PlanAsync(MigrationStep step, MigrationOptions? options = null,
CancellationToken cancellationToken = default);
public Task<MigrationPlan> ApplyAsync(MigrationPlan plan, CancellationToken cancellationToken = default);
}| Member | Description |
|---|---|
PlanAsync |
The dry-run: lists the groups (ListAllAsync), reads their checkpoints and, best effort, their event-type filters from $persistentSubscriptionConfig, and decides per group. Writes nothing. Throws ArgumentException for OnlyRegistered without Registrations. |
ApplyAsync |
Makes the plan again and executes it: writes the checkpoints, deletes the groups or creates them again. Throws InvalidOperationException, without writing anything, while a group is blocked or when the store changed since the plan was made. Returns the plan it executed; repeating it is a no-op. |
Checkpoints are written with KurrentDbCheckpointStore, in the format and with the $maxCount the subscriptions use. Listing the groups needs $ops or $admins; reading $persistentSubscriptionConfig needs $admins.
| Value | What ApplyAsync does |
|---|---|
Import |
Writes each group's position as checkpoint-{group name}. |
Delete |
Deletes the groups that have a 1.0 checkpoint. |
Rollback |
Deletes and creates again each group that has a 1.0 checkpoint, with its settings and event-type filter, starting at the first event after that checkpoint. |
public sealed class MigrationOptions {
public Func<string, bool>? IncludeGroup { get; init; }
public IReadOnlyCollection<SubscriptionRegistration>? Registrations { get; init; }
public bool OnlyRegistered { get; init; }
public EventTypeRegistry? EventTypeRegistry { get; init; }
public bool AllowAtLeastOnce { get; init; }
public bool Overwrite { get; init; }
public bool DiscardParkedMessages { get; init; }
}| Property | Description |
|---|---|
IncludeGroup |
Selects groups by name; null selects every group. |
Registrations |
The 1.0 subscriptions of the hosts that switch over (IEnumerable<SubscriptionRegistration> from their service collection). Import then shows where each one starts and warns about one that would replay; Rollback uses the checkpoint of the subscription that continued from a group (a higher version). |
OnlyRegistered |
Selects only groups whose name is the id or a predecessor of one of the Registrations. |
EventTypeRegistry |
Compares the event types each 1.0 subscription receives with the ones its 0.x group received. |
AllowAtLeastOnce |
Imports a group that is not drained at its own checkpoint instead of blocking it: events after it that 0.x already handled are handled again. |
Overwrite |
Replaces an existing 1.0 checkpoint at another position. |
DiscardParkedMessages |
Deletes or creates again groups that hold parked messages, which are lost. |
public sealed record MigrationPlan {
public required MigrationStep Step { get; init; }
public required MigrationOptions Options { get; init; }
public required IReadOnlyList<GroupPlan> Groups { get; init; }
public required IReadOnlyList<SubscriptionPlan> Subscriptions { get; init; }
public bool CanApply { get; }
public override string ToString();
}CanApply is false while any group is blocked. ToString() is the report: the counts per action, whether the plan can be applied, a table of groups and, for Import with registrations, a table of subscriptions; blocked groups and warnings first, marked !.
public sealed record GroupPlan {
public required string GroupName { get; init; }
public required GroupState State { get; init; }
public ulong? Position { get; init; }
public ulong? Checkpoint { get; init; }
public required long ParkedMessages { get; init; }
public string? EventTypeFilter { get; init; }
public required GroupAction Action { get; init; }
public required string Reason { get; init; }
public bool IsBlocked { get; }
}| Property | Description |
|---|---|
GroupName |
The group's name, which is also the 1.0 subscription id. |
State |
What the group's state says about its position (GroupState). |
Position |
The 0.x position to import: the last event read when the group is drained, the group's own checkpoint when it is not, null when there is none. |
Checkpoint |
The 1.0 checkpoint the step works with: checkpoint-{GroupName} for Import and Delete; for Rollback, the checkpoint of the 1.0 subscription that continues from the group. |
ParkedMessages |
The number of parked messages in the group. |
EventTypeFilter |
The group's event-type regular expression, or null when $persistentSubscriptionConfig is not readable. |
Action |
None, WriteCheckpoint, OverwriteCheckpoint, DeleteGroup, RecreateGroup or Blocked. |
Reason |
Why, as shown in the report. |
GroupState |
Meaning |
|---|---|
Exact |
Drained: no consumer, nothing waiting to be delivered, redelivered or acknowledged. Every event read was acknowledged, so the position is exact. |
AtLeastOnce |
Not drained, but the group has a checkpoint: importing it handles the events after it again. |
Empty |
Drained, but the group read nothing. |
Unknown |
Not drained and no checkpoint: no safe position. |
Connected |
A consumer is connected. |
NotOnAll |
A group on a stream; 0.x only created groups on $all. Never touched. |
public sealed record SubscriptionPlan {
public required string SubscriptionId { get; init; }
public required Type HandlerType { get; init; }
public required string StartsAfter { get; init; }
public required string Source { get; init; }
public required string EventTypes { get; init; }
public required bool IsWarning { get; init; }
}Where one 1.0 subscription starts after the import, resolved in the order of the subscription loop: its own checkpoint, the group under its own id, then the checkpoint or group of each predecessor, else "beginning" or "end" (a warning). EventTypes is same (n), the added and removed names (+A, -B, a warning), all for a handler of object, or - without registry or filter.
The types in the .Internal namespaces below are public only so that the Aggregates packages can use each other's infrastructure. They are hidden from IntelliSense ([EditorBrowsable(Never)]), not covered by semantic versioning, and may change in any release. They are listed here so that the rest of this page can refer to them; don't build on them.
| Type | What it does |
|---|---|
SubscriptionLoop |
Runs one subscription until the host stops: subscribes from the checkpoint (or a predecessor's, see Where a subscription starts), hands every message to the hosted service, records checkpoints, parks messages that could not be deserialized, subscribes again after a transient failure, and reports its state to SubscriptionMonitor. One instance serves every subscription. |
SubscriptionRetryPolicy |
Retries a handler with the backoff of SubscriptionErrorHandlingOptions, then parks the message, or with SubscriptionErrorMode.Block retries until it succeeds. Also used for replays, deferred commands and saga deadlines. |
Scheduler, SchedulerActivation, SchedulerActivation<THandler>
|
The scheduler of deferred commands and saga deadlines: one instance serves every saga and policy; the activation (one per handler class) writes the scheduler's stream before the handler's first request is stored. |
ScheduledDeadline |
A due saga deadline, as the scheduler hands it to the saga. |
CheckpointTracker |
Records the position of each processed message of one subscription and writes it in batches, as configured by SubscriptionCheckpointOptions. |
Backoff |
The exponential backoff with ±10% jitter of the loop, the retry policy and the scheduler. |
SubscriptionRegistrations |
The registration helpers that AddProjections, AddPolicies and AddSagas share (see One subscription per handler class). |
IReplayableSubscription |
Implemented by the projection, policy and saga hosted services, so that IParkedMessages can replay a parked message through them. |
ParkedMessages |
The implementation of IParkedMessages. |
LoggingParkedMessageSink |
The default IParkedMessageSink without a storage integration: logs a warning and keeps nothing. |
The implementations that AddKurrentDb() and AddMssp() (and the AddKurrentDb()/AddMssp() of sagas, policies and projections) register: KurrentDbCheckpointStore, KurrentDbSubscriptionFactory, KurrentDbParkedMessageSink, KurrentDbParkedMessageStore, KurrentDbScheduledStore, KurrentDbCommitHandler, and the Mssp… counterparts. Use the interfaces they implement (ICheckpointStore, ISubscriptionFactory, IParkedMessageSink, IParkedMessageStore, IScheduledStore) instead.
Also internal infrastructure, outside these namespaces: ProjectedEvent.NextTransaction() (used by Aggregates.Projections.Sql).