Skip to content

API Reference

Wouter Naessens edited this page Oct 20, 2026 · 32 revisions

API Reference

Complete reference for all public types, interfaces, and attributes in the Aggregates library.


Aggregates (core)

IState<TState, TEvent>

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.

ICommand

Marker interface. All commands implement this.

public interface ICommand;

ICommand<TState, TEvent>

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.

ICommandHandler<TCommand>

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);
}

ICommandDispatcher

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);
}

DeferredCommand

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.

IAggregateRoot

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();
}

EntityRoot<TState, TEvent>

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>;
}

AggregateIdentifier

A string-based identifier for an aggregate or saga.

public record struct AggregateIdentifier(string Value) {
    public static implicit operator AggregateIdentifier(string value);
    public override string ToString();
}

AggregateVersion

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);
}

ConcurrencyException

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.


EventContractAttribute

Maps a .NET event type to a stable event store type name and optionally wires an upgrader.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class EventContractAttribute(
    string name,
    int version = 1,
    Type? eventUpgrader = null,
    string? @namespace = null) : Attribute {

    public Type? EventUpgrader { get; }
    public bool TryUpgrade(object @event, out object upgradedEvent);
    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.
namespace Optional prefix, separated by a dot.
Member Description
TryUpgrade(event, out upgraded) Runs the upgrader once, through its first IUpgradeEvent. Returns false without an upgrader.
Upgrade(event) Upgrades event with the upgrader on its type, 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.

EventTypeRegistry

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;
});

IUpgradeEvent<TOldVersion, TNewVersion>

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.


IRepository<TState, TEvent>

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.


MetadataScope

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(...).


MetadataMultiplicity

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
}

EventMetadata

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; }
}

MetadataAttribute

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<...> { ... }

AggregatesOptions

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.


AddAggregates (extension method)

IServiceCollection.AddAggregates(Action<AggregatesOptions>? configure = null) → IAggregatesBuilder

Registers the full command handler decorator chain. Returns a builder for attaching a storage integration.


Aggregates.Sagas

ISaga<TSagaState, TEvent>

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.
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.


ISaga<TSagaState, TEvent, TDeadline>

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.


Deadline

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.


SagaContractAttribute

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.


SagasOptions

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.


Saga infrastructure for storage integrations

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.

Aggregates.Policies

IPolicy<TEvent>

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.


PolicyContractAttribute

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.


PoliciesOptions

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.

Aggregates.Projections

IProjection<TEvent>

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.


ICommit

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.

Commit

The default ICommit implementation. Use Commit.Create() to start a new chain.

public sealed class Commit : ICommit {
    public static ICommit Create();
}

ProjectionContractAttribute

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.


ProjectionsOptions

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.

ProjectedEvent

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.

A commit uses it to record the event's position with its writes (see Exactly-once in SQL).


Aggregates.Projections.Sql

UseSql

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.


RecordSqlPositions (extension method)

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.


Aggregates.Subscriptions

SubscriptionRegistration

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 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.


ContinueFrom

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.


ISubscriptionFactory

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.


SubscriptionRequest

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.

ISubscription

An active subscription. Yields SubscriptionMessage values in chronological order.

public interface ISubscription : IAsyncEnumerable<SubscriptionMessage>, IAsyncDisposable { }

SubscriptionMessage

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.


EventReference

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.

ICheckpointStore

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. 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(ulong Position, int? AdoptedFrom);

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.


IParkedMessageSink

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>();

SubscriptionErrorMode

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.


IParkedMessages

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.


ParkedMessage

An open parked message, as IParkedMessages.ListAsync returns it.

public sealed record ParkedMessage(
    string SubscriptionId,
    string Id,
    DateTimeOffset ParkedAt,
    EventReference? Source,
    ulong CommitPosition,
    string? EventType,
    string ExceptionType,
    string ExceptionMessage,
    string? StackTrace);
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.

ParkedMessageReplay

The result of replaying one parked message.

public sealed record ParkedMessageReplay(ParkedMessage Message, Exception? Error) {
    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).


SubscriptionErrorHandlingOptions

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.


SubscriptionCheckpointOptions

Controls how often all subscription hosted services write their checkpoint.

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;
}
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.

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.


SubscriptionResubscribeOptions

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.


SubscriptionLoop

Runs one subscription until the host stops: subscribes, hands every message to a processing delegate, records checkpoints, parks messages that could not be deserialized, and subscribes again after a transient failure. Used by the saga, policy, and projection hosted services; only needed when you write your own subscription-based service. Registered as a singleton by AddSagas / AddPolicies / AddProjections.

public sealed class SubscriptionLoop {
    public SubscriptionLoop(ISubscriptionFactory subscriptionFactory, ICheckpointStore checkpointStore,
                            IParkedMessageSink parkedMessageSink, SubscriptionCheckpointOptions checkpointOptions,
                            SubscriptionResubscribeOptions resubscribeOptions, TimeProvider timeProvider,
                            ILogger<SubscriptionLoop> logger, EventTypeRegistry? eventTypeRegistry = null);
    public Task RunAsync(SubscriptionRegistration registration,
                         Func<SubscriptionMessage, CancellationToken, ValueTask> process,
                         CancellationToken stoppingToken);
}
Parameter Description
registration The subscription: its id (checkpoint and parked messages), StartFromEnd, and the Predecessors whose checkpoint it continues from when it has none of its own. See Where a subscription starts.
process Handles one deserialized message (also when Event is null). An exception it throws is treated as a subscription failure, so retry and park handler failures inside it with SubscriptionRetryPolicy.
stoppingToken Stops the loop. RunAsync then completes without an exception.

With an EventTypeRegistry (from the service collection), the loop subscribes with the stored names of the types registration.EventType can receive, computed once per RunAsync; see Event-type filter. Progress messages are not passed to process; their position is written as the checkpoint right away.

RunAsync throws only for a failure that ISubscriptionFactory.IsTransient classifies as not transient. The loop holds no state between calls, so one instance serves every subscription.


CheckpointTracker

Records the position of each processed message of one subscription and writes it to an ICheckpointStore in batches, as configured by SubscriptionCheckpointOptions. Used by SubscriptionLoop; only needed when you write your own subscription loop.

public sealed class CheckpointTracker {
    public CheckpointTracker(ICheckpointStore store, string subscriptionId,
                             SubscriptionCheckpointOptions options, TimeProvider timeProvider);
    public ulong? LastPosition { get; }
    public ValueTask AdvanceAsync(ulong position, CancellationToken cancellationToken = default);
    public ValueTask RecordProgressAsync(ulong position, CancellationToken cancellationToken = default);
    public ValueTask FlushAsync(CancellationToken cancellationToken = default);
}
Member Description
LastPosition The position of the last processed message or progress report, written or not; null before the first one. Resubscribe from here rather than from the stored checkpoint.
AdvanceAsync Records position as processed; writes it when MaxBatchSize or MaxInterval is reached.
RecordProgressAsync Records a position the store passed without delivering a message for it (a progress message) and writes it right away.
FlushAsync Writes the last recorded position, if it has not been written yet. Call it when the subscription stops.

A tracker belongs to a single subscription loop and is not thread-safe. A failed write keeps the position pending, so the next write retries it.


Backoff

The exponential backoff with ±10% jitter that the subscription loop, the retry policy and the scheduler of deferred commands use. It is public, for your own loops.

public static class Backoff {
    public static TimeSpan Delay(int attempt, TimeSpan initialDelay, TimeSpan maxDelay, double multiplier);
}

attempt is the number of failed attempts so far (1-based); the delay is initialDelay × multiplier^(attempt − 1), capped at maxDelay, plus or minus 10%.


Parked message infrastructure

The format of parked streams and the parts ParkedMessages replays through. The storage integrations register the store, and AddProjections, AddPolicies and AddSagas register their hosted services as IReplayableSubscription; only needed when you write your own storage integration or subscription-based service.

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);

public interface IReplayableSubscription {
    SubscriptionRegistration Registration { get; }
    ValueTask HandleAsync(SubscriptionMessage message, CancellationToken cancellationToken = default);
    ValueTask HandleDeadlineAsync(ScheduledDeadline deadline, CancellationToken cancellationToken = default);   // default: throws
}

public sealed class SubscriptionRetryPolicy {
    public SubscriptionRetryPolicy(IParkedMessageSink parkedMessageSink, SubscriptionErrorHandlingOptions options,
                                   ILogger<SubscriptionRetryPolicy>? logger = null);
    public ValueTask ExecuteAsync(Func<CancellationToken, ValueTask> handler, string subscriptionId,
                                  SubscriptionMessage message, CancellationToken cancellationToken);
    public ValueTask ExecuteAsync(Func<CancellationToken, ValueTask> handler, string subscriptionId,
                                  SubscriptionMessage message, SubscriptionErrorMode errorMode, CancellationToken cancellationToken);
    public ValueTask<Exception?> TryExecuteAsync(Func<CancellationToken, ValueTask> handler, CancellationToken cancellationToken);
}
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.
IReplayableSubscription A subscription a parked message can be replayed through. HandleAsync handles one message once, without retries or parking; HandleDeadlineAsync delivers a deadline to a saga (only sagas implement it). Implemented by the projection, policy and saga hosted services, each registered as IHostedService and as IReplayableSubscription (the same instance).
SubscriptionRetryPolicy Retries a handler with the backoff of SubscriptionErrorHandlingOptions. ExecuteAsync parks the message after MaxRetries attempts, or with SubscriptionErrorMode.Block retries until it succeeds (logging an error once when it starts blocking and information once it succeeds); the overload without a mode parks. TryExecuteAsync retries up to MaxRetries attempts and returns the exception of the last one instead of parking, or null. Neither retries an OperationCanceledException.

Deferred command infrastructure

The scheduler of deferred commands, shared by sagas and policies, which also delivers saga deadlines. AddSagas and AddPolicies register it, and the storage integrations register the store; 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
}

// A due saga deadline, as the scheduler hands it to the saga's delivery.
public readonly record struct ScheduledDeadline(EventReference Request, DateTimeOffset Due, object Payload,
    EventMetadata Metadata, ulong CommitPosition);

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);
}

public abstract class SchedulerActivation {
    public Task Activated { get; }
}
public sealed class SchedulerActivation<THandler> : SchedulerActivation {
    public SchedulerActivation(IScheduledStore store, IEnumerable<SubscriptionRegistration> registrations);
    public string SubscriptionId { get; }
    public ValueTask EnsureActivatedAsync(CancellationToken cancellationToken);
}

public sealed class Scheduler {
    public Scheduler(IScheduledStore store, ICheckpointStore checkpointStore, ISubscriptionFactory subscriptionFactory,
        SubscriptionCheckpointOptions checkpointOptions, SubscriptionResubscribeOptions resubscribeOptions,
        IServiceScopeFactory scopeFactory, SubscriptionRetryPolicy retryPolicy, IParkedMessageSink parkedMessageSink,
        TimeProvider timeProvider, ILoggerFactory loggerFactory);
    public Task RunAsync(SubscriptionRegistration registration, SchedulerActivation activation, CancellationToken stoppingToken);
    public Task RunAsync(SubscriptionRegistration registration, SchedulerActivation activation,
        Func<ScheduledDeadline, CancellationToken, ValueTask> deliverDeadline, CancellationToken stoppingToken);
}
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.
ScheduledDeadline A due saga deadline: the request (its stream is the saga id), the due time, the payload, the metadata of the request and its commit position.
SchedulerActivation<THandler> One per saga or policy class. EnsureActivatedAsync writes the scheduler's stream before the first request is stored; SubscriptionId is the owner of the handler's requests. Throws InvalidOperationException for a handler without a subscription.
Scheduler One instance serves every saga and policy; their hosted services run RunAsync next to the subscription loop. A saga's runs the overload with deliverDeadline, which receives each due deadline and retries and parks failures itself; without it (a policy), a deadline is parked.

Aggregates.KurrentDB.Migration

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.

PersistentSubscriptionMigration

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.


MigrationStep

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.

MigrationOptions

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.

MigrationPlan

public sealed record MigrationPlan(MigrationStep Step, MigrationOptions Options,
                                   IReadOnlyList<GroupPlan> Groups, IReadOnlyList<SubscriptionPlan> Subscriptions) {
    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 !.


GroupPlan

public sealed record GroupPlan(string GroupName, GroupState State, ulong? Position, ulong? Checkpoint,
                               long ParkedMessages, string? EventTypeFilter, GroupAction Action, string Reason) {
    public bool IsBlocked { get; }
}
Parameter 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.

SubscriptionPlan

public sealed record SubscriptionPlan(string SubscriptionId, Type HandlerType, string StartsAfter,
                                      string Source, string EventTypes, bool IsWarning);

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.

Clone this wiki locally