Repository navigation
Releases
Aggregates 1.0.2
Aggregates 1.0.2 fixes the first event of a new saga whose state is a value type.
Bug fix
- A new saga starts from
Initial, also when its state is a value type. For a saga without a stream, 1.0.0 and 1.0.1 created the root fromdefaultand relied on the constructor to fall back toTSagaState.Initial. That fallback only works for a reference type: for arecord struct,defaultis never null, so the first event was applied todefault(TSagaState). A state with an immutable collection then threw on its firstApply, and the event was parked. The saga now starts fromTSagaState.Initial. Aggregates were not affected: the command handler already started a new aggregate fromTState.Initial.
API
- The
stateparameter of the constructors ofEntityRoot<TState, TEvent>andSagaRoot<TSagaState, TEvent>is nowTStateinstead ofTState?, and the root keeps the state it is given. A new root takesTState.Initial, as the library itself does. Code that passednullfor a state that is a reference type gotInitialuntil now; it now getsnull, and the compiler warns about it. The change is binary compatible with 1.0.0.
Aggregates 1.0.1
Aggregates 1.0.1 restores two behaviours of 0.x that 1.0.0 had changed, makes the import dry-run report one more difference, and completes the migration guide. The public API is unchanged; from this release on, every package is validated against 1.0.0.
Behaviour changes
- Command metadata is collected once per command. 1.0.0 evaluated the
MetadataAttributes of a command after every event it produced, so an attribute that queries a database ran once per event. They now run once, after the last event, as in 0.x, also when the command produces no events. The attributes of the state still run after each event; for the same key withMetadataMultiplicity.Single, the command's value wins, as before. - A nested
MetadataScopestarts with the entries of the scope around it. In 1.0.0,new MetadataScope()started empty, so a scope opened inside another one (for example by two middlewares in one request) hid the outer entries from the commands. It now starts with a copy of the entries ofMetadataScope.Current, as in 0.x; what it adds doesn't reach the outer scope.new MetadataScope(seed)still starts with the seed only, so the scopes of sagas, policies, deferred commands and replays of parked messages never pick up the metadata of the host around them. To keep the 1.0.0 behaviour for a scope of your own, open it withnew MetadataScope(EventMetadata.Empty).
Migration from 0.x
- The import dry-run (
PersistentSubscriptionMigration.PlanAsync) now reports a handler ofobjectwhose 0.x group had an event-type filter as a difference:EventTypesisall (0.x: n), a warning, where it wasall. - Migrating from 0.x describes three more differences:
- Event-type filter. 0.x left out of a group's filter the event types its handler threw on in a trial when the group was created; 1.0 delivers every type assignable to the handler's event type. A handler that relied on throwing gets a marker interface on the types its 0.x group read.
- Metadata values. 0.x read every metadata value as a
JsonElement. The guide shows how to keep those values, when to choose them, and what to expect from keys withMetadataMultiplicity.Multipleand from keys passed on by sagas and policies. - Policies dispatch per
yield. 0.x collected a policy's reaction before dispatching it; 1.0 dispatches each command as it is yielded, and a retry runs the reaction again. The guide shows how to collect the commands first where that matters.
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 ...