Repository navigation
Aggregates 1.0.0
Aggregates 1.0.0
Aggregates 1.0.0 is the first stable release of the rewritten library. It targets .NET 10 and provides storage integrations for KurrentDB and MSSP. From this release on, the public API follows semantic versioning; the Aggregates.Subscriptions.Internal, Aggregates.KurrentDB.Internal and Aggregates.MSSP.Internal namespaces contain implementation details and are not covered by it.
What's new
- Sagas and policies can defer a command: yield
command.DeferUntil(due)fromReactAsyncand the command executes when it is due. - Sagas can request a deadline: implement
ISaga<TState, TEvent, TDeadline>and yieldDeadline.At(due, payload), and the same saga instance receives the payload back at that time. - Parked messages can be listed, replayed and dismissed with
IParkedMessages, andonError: SubscriptionErrorMode.Blockon a contract retries a failing event until it succeeds instead of parking it. SubscriptionMonitorandSubscriptionHealthCheckreport the state of every subscription and scheduler in the host.EventMetadatahas a public constructor, soDeserializeMetadatacan be implemented.- Register an
EventTypeRegistryin DI and subscriptions filter on event type on the server. RecordSqlPositions()records the position of an event in the same SQL transaction, which makesUseSqlprojections exactly-once.- New
Aggregates.Analyzerspackage: theAGG0001analyzer reports event types without[EventContract].
Coming from 0.x
See Migrating from 0.x.
Upgrading from a 1.0 preview
These notes cover the changes since 1.0.0-preview.6; read them in full, whatever preview you are on.
Compile-time changes
ISagaIdResolver<TEvent>,FuncSagaIdResolver<TEvent>and everyWithResolveroverload onSagasOptionsare gone, andISaga<TState, TEvent>now requiresIEnumerable<AggregateIdentifier> Correlate(TEvent @event, EventMetadata metadata). Move the body of eachWithResolverlambda into theCorrelateof its saga and remove theWithResolvercalls. A saga that had no resolver used to get no subscription; now every scanned saga runs, so scan only the sagas a host should run (ScanTypes).- The handler interfaces
IProjectionHandler<TEvent>,IPolicyHandler<TEvent>andISagaHandler<TState, TEvent>are removed; a handler is resolved by its concrete class. Remove decorators, registrations and fakes that referenced them. SubscriptionMessagegained a positionalSourceparameter of the newEventReferencetype:SubscriptionMessage(Event, CommitPosition, Source, Metadata). Pass the stream and revision of the event when you construct one, as tests and fake subscriptions do.ISubscriptionFactory.Subscribe(ulong? fromPosition, bool startFromEnd, CancellationToken)is replaced bySubscribe(SubscriptionRequest request, CancellationToken). Implement the new signature in a custom subscription factory;SubscriptionRequestcarriesFromPosition,StartFromEnd, theEventTypesto deliver and theProgressInterval.- Saga timeouts are now deferred commands:
SagaTimeoutandSagaTimeout.At(due, command)are replaced byDeferredCommandand theDeferUntil(due)extension onICommand. In the scheduling infrastructure,SagaTimeoutRequestbecameDeferredCommandRequest,SagaTimeoutFormatandSagaTimeoutEnvelopebecameScheduledFormatandScheduledEnvelope, andISagaTimeoutStoreandSagaTimeoutEntrybecameIScheduledStoreandScheduledEntry;ScheduledFormat.WriteCommandRequestandTryReadCommandRequestbecameWriteRequestandTryReadRequest, andIScheduledStore.DeserializeCommandbecameDeserialize. Update code that used the timeout API or that wrote custom saga scheduling infrastructure. ParkedMessageidentifies a parked message byId(an opaque string) instead ofRevision(its revision inparked-{id}), andIParkedMessages.ReplayAsyncandDismissAsynctake that id. Usemessage.Idwhere you usedmessage.Revision; the stored format is unchanged, so existing parked streams keep working.- The records
ParkedMessage,ParkedMessageReplay,SubscriptionCheckpoint,SubscriptionStatus,GroupPlan,MigrationPlanandSubscriptionPlanno longer have a primary constructor: their properties arerequired init. Construct them with an object initializer and read them by property, instead of positional arguments orDeconstruct. CommitDelegateandSagaCommitDelegatetake aCancellationTokenas their second parameter, andUnitOfWorkScopepasses its token (a new optional constructor parameter) to the commit. Update custom commit delegates and the lambdas you pass toUnitOfWorkScope; a commit now honours the caller's cancellation.- The three contract attributes derive from the new
SubscriptionContractAttributeand validate their arguments (namemust not be empty,versionmust be at least 1). They gained two optional parameters:continueFrom, between@namespaceandstartFromEnd, andonErrorlast. PassingstartFromEndas the fourth positional argument of a projection or policy contract no longer compiles; use the named argument. AggregateIdentifieris a readonly struct whoseValueis init-only and validated:null, empty, whitespace and$-prefixed values throwArgumentException, also when a serializer sets the property, andUnitOfWork.Attachrejects adefaultidentifier. Remove code that setsValueafter construction and any id that starts with$, because such streams are reserved by the store.EventContractAttributeis sealed andTryUpgradeis internal; call the public staticEventContractAttribute.Upgrade(object)instead, and stop deriving from the attribute.RegisteredPolicies,RegisteredProjectionsandRegisteredSagasare removed from the builder interfaces. Remove code that read them.- The shared subscription engine moved to
Aggregates.Subscriptions.Internal(SubscriptionLoop,SubscriptionRetryPolicy,Scheduler,SchedulerActivation,CheckpointTracker,Backoff,SubscriptionRegistrations,IReplayableSubscription,ParkedMessages,LoggingParkedMessageSink,ScheduledDeadline), and the KurrentDB and MSSP implementations (checkpoint stores, subscription factories, parked sinks and stores, scheduled stores, commit handlers) moved toAggregates.KurrentDB.InternalandAggregates.MSSP.Internal. These namespaces are not covered by semantic versioning. Add theusingif you referenced those types; their constructors changed as well, andSubscriptionLoop.RunAsyncnow takes aSubscriptionRegistration, which gainedPredecessors. - The
DataExtensionshelper (withToTableValuedParameter) is removed, andAggregates.Projections.Sqlno longer depends onMicrosoft.Data.SqlClient. Write a table-valued parameter yourself if you need one, and add the provider package to the application if it relied on the transitive reference;UseSqlworks unchanged with any ADO.NET provider.
Behaviour changes
ISaga.ReactAsyncreceives the saga state from before the event, as in 0.x; it used to receive the state afterApply. Where a saga relied on the state after the event, compute it withstate.Apply(@event).- A subscription without a checkpoint of its own continues from the checkpoint of its nearest predecessor contract, over the whole chain of previous versions, instead of replaying from the beginning. A version bump therefore no longer replays; replay is an explicit choice with
continueFrom: ""(ContinueFrom.None). A predecessor and a successor registered in the same host now fail at startup, so stop the old version before you start the new one. - Registration fails at startup when a class implements more than one
IProjection<T>,IPolicy<T>orISaga<,>, or when two handlers share a subscription id, also across projections, policies and sagas. Split the class, or give each handler its own contract. - Every handler class gets its own subscription: two projections, policies or sagas on the same event type now both handle every event, where previously only the first one ran.
- Event upgraders are applied on every read path: an event stored under an old contract version now reaches handlers and state as its current version, where previously a subscription skipped it silently and the repository dropped it from the state. Put the upgrader on the old version, with the attributed type as its
TOld, as in 0.x; upgrading in your ownDeserializeis no longer needed. - Loading an aggregate or a saga fails with an
InvalidOperationExceptionwhen an event in its own stream can't be read: an unknown stored type, a type outside the handler'sTEvent, a truncated stream whose first event is not at revision 0, or a saga link to an event that doesn't deserialize. Such events used to be skipped silently, after which every command on the aggregate could fail with an unrelatedConcurrencyException. Keep old event versions in the code, with an upgrader to the current one. - An event type without
[EventContract]is stored under its full type name instead of its short name, so it can be read back; previously it was skipped on every read. Renaming or moving such a class makes its stored events unreadable, so add[EventContract]to anything that lives long. The commit handlers log a warning when a stored name doesn't map back to the written type. - Startup validates the event types:
EventTypeRegistry.FromTypesandFromAssembliesthrow when two event types share a contract name, and when an upgrader doesn't implementIUpgradeEvent<TOld, TNew>exactly once for the type it sits on or has no public parameterless constructor. Rename the colliding types and fix the upgraders before you start. - An
OperationCanceledExceptionthrown by a handler itself, anHttpClienttimeout for example, is no longer treated as shutdown: the message is retried and then parked, and the scheduler no longer stops. Only cancellation by the host's stopping token stops a subscription. - Transient failures resubscribe instead of stopping the host: a dropped subscription, a
DeserializeorDeserializeMetadatathat throws, a failingCorrelate, and checkpoint-store and parked-sink failures now lead to a new subscription after the backoff ofSubscriptionResubscribeOptions. A subscription that ends because the host stops is a stop, not a failure. - Checkpoints are written in batches: after
SubscriptionCheckpointOptions.MaxBatchSize(100) processed messages, afterMaxInterval(5 seconds), or when the subscription stops, instead of after every message. After a crash at mostMaxBatchSizemessages are delivered again. Subscriptions on MSSP now also exclude event types that start with$, the library's own bookkeeping, as KurrentDB always did. - A saga reacts once per source event: when an event is redelivered after a crash between the saga commit and the checkpoint, the saga no longer reacts a second time and writes no second link.
Stored data
- Checkpoints are written as
$aggregates-checkpointevents and parked messages as$aggregates-parkedevents, incheckpoint-{id}andparked-{id}, where earlier previews wroteCheckpointStoredandParkedMessage. Existing checkpoints stay readable: the store reads the last event ofcheckpoint-{id}whatever its type. The old events stay in the store and a subscription that replays from the start receives them once, so returnnullfromDeserializefor those type names and the event is skipped. On KurrentDB,checkpoint-{id}streams now carry$maxCount: 1, so only the last checkpoint is kept. - A saga stream now holds
$>link events ("{revision}@{stream}") to the source events instead of copies of them, plus the stored deferred commands and deadlines. Saga streams written by a preview, which held copies, are no longer readable: a stream that holds anything but links and scheduled requests fails to load and the event is parked. Give every saga its own prefix inCorrelate, because two sagas that return the same id share a stream. - The subscription id of a projection is now the contract (
{namespace}.{name}@v{version}), as it already was for policies and sagas; it used to include the event type ({contract}-{TEvent.Name}). Thecheckpoint-{id}andparked-{id}streams follow the id, so a projection's checkpoint stream is renamed: after the upgrade the projection has no checkpoint and starts from the beginning, or from the end withstartFromEnd. Policies and sagas keep their ids and their checkpoints. - A parked message now also stores the stream and revision of its event and the type of the deserialized event, next to the commit position and the exception; the existing fields are unchanged. Entries written by an earlier preview still list and can be dismissed, but they have no source, so they can't be replayed. A replay or a dismissal is recorded as a
$aggregates-parked-replayedor$aggregates-parked-dismissedentry in the sameparked-{id}stream, in link format. Deferred commands and saga deadlines park underparked-scheduled-{id}. - Deferred commands and saga deadlines are stored as
$aggregates-scheduled-commandand$aggregates-scheduled-deadlineentries: in the saga stream for a saga, inscheduled-requests-{id}-{revision}@{stream}for a policy. Deliveries and markers go toscheduled-{id}($aggregates-scheduled-delivered,$aggregates-scheduled-marker), the scheduler's checkpoint tocheckpoint-scheduled-{id}and its parked requests toparked-scheduled-{id}. Requests written by an earlier preview, as$aggregates-timeoutentries with their deliveries intimeouts-{id}, are not read: the scheduler only reads the$aggregates-scheduledprefix, so requests that were still pending are lost, and a saga stream that holds such an entry fails to load.