Skip to content

Aggregates 1.0.0

Choose a tag to compare

@FleaFX FleaFX released this 24 Oct 08:44
· 3 commits to main since this release
6a3808e

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) from ReactAsync and the command executes when it is due.
  • Sagas can request a deadline: implement ISaga<TState, TEvent, TDeadline> and yield Deadline.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, and onError: SubscriptionErrorMode.Block on a contract retries a failing event until it succeeds instead of parking it.
  • SubscriptionMonitor and SubscriptionHealthCheck report the state of every subscription and scheduler in the host.
  • EventMetadata has a public constructor, so DeserializeMetadata can be implemented.
  • Register an EventTypeRegistry in DI and subscriptions filter on event type on the server.
  • RecordSqlPositions() records the position of an event in the same SQL transaction, which makes UseSql projections exactly-once.
  • New Aggregates.Analyzers package: the AGG0001 analyzer 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 every WithResolver overload on SagasOptions are gone, and ISaga<TState, TEvent> now requires IEnumerable<AggregateIdentifier> Correlate(TEvent @event, EventMetadata metadata). Move the body of each WithResolver lambda into the Correlate of its saga and remove the WithResolver calls. 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> and ISagaHandler<TState, TEvent> are removed; a handler is resolved by its concrete class. Remove decorators, registrations and fakes that referenced them.
  • SubscriptionMessage gained a positional Source parameter of the new EventReference type: 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 by Subscribe(SubscriptionRequest request, CancellationToken). Implement the new signature in a custom subscription factory; SubscriptionRequest carries FromPosition, StartFromEnd, the EventTypes to deliver and the ProgressInterval.
  • Saga timeouts are now deferred commands: SagaTimeout and SagaTimeout.At(due, command) are replaced by DeferredCommand and the DeferUntil(due) extension on ICommand. In the scheduling infrastructure, SagaTimeoutRequest became DeferredCommandRequest, SagaTimeoutFormat and SagaTimeoutEnvelope became ScheduledFormat and ScheduledEnvelope, and ISagaTimeoutStore and SagaTimeoutEntry became IScheduledStore and ScheduledEntry; ScheduledFormat.WriteCommandRequest and TryReadCommandRequest became WriteRequest and TryReadRequest, and IScheduledStore.DeserializeCommand became Deserialize. Update code that used the timeout API or that wrote custom saga scheduling infrastructure.
  • ParkedMessage identifies a parked message by Id (an opaque string) instead of Revision (its revision in parked-{id}), and IParkedMessages.ReplayAsync and DismissAsync take that id. Use message.Id where you used message.Revision; the stored format is unchanged, so existing parked streams keep working.
  • The records ParkedMessage, ParkedMessageReplay, SubscriptionCheckpoint, SubscriptionStatus, GroupPlan, MigrationPlan and SubscriptionPlan no longer have a primary constructor: their properties are required init. Construct them with an object initializer and read them by property, instead of positional arguments or Deconstruct.
  • CommitDelegate and SagaCommitDelegate take a CancellationToken as their second parameter, and UnitOfWorkScope passes its token (a new optional constructor parameter) to the commit. Update custom commit delegates and the lambdas you pass to UnitOfWorkScope; a commit now honours the caller's cancellation.
  • The three contract attributes derive from the new SubscriptionContractAttribute and validate their arguments (name must not be empty, version must be at least 1). They gained two optional parameters: continueFrom, between @namespace and startFromEnd, and onError last. Passing startFromEnd as the fourth positional argument of a projection or policy contract no longer compiles; use the named argument.
  • AggregateIdentifier is a readonly struct whose Value is init-only and validated: null, empty, whitespace and $-prefixed values throw ArgumentException, also when a serializer sets the property, and UnitOfWork.Attach rejects a default identifier. Remove code that sets Value after construction and any id that starts with $, because such streams are reserved by the store.
  • EventContractAttribute is sealed and TryUpgrade is internal; call the public static EventContractAttribute.Upgrade(object) instead, and stop deriving from the attribute.
  • RegisteredPolicies, RegisteredProjections and RegisteredSagas are 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 to Aggregates.KurrentDB.Internal and Aggregates.MSSP.Internal. These namespaces are not covered by semantic versioning. Add the using if you referenced those types; their constructors changed as well, and SubscriptionLoop.RunAsync now takes a SubscriptionRegistration, which gained Predecessors.
  • The DataExtensions helper (with ToTableValuedParameter) is removed, and Aggregates.Projections.Sql no longer depends on Microsoft.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; UseSql works unchanged with any ADO.NET provider.

Behaviour changes

  • ISaga.ReactAsync receives the saga state from before the event, as in 0.x; it used to receive the state after Apply. Where a saga relied on the state after the event, compute it with state.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> or ISaga<,>, 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 own Deserialize is no longer needed.
  • Loading an aggregate or a saga fails with an InvalidOperationException when an event in its own stream can't be read: an unknown stored type, a type outside the handler's TEvent, 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 unrelated ConcurrencyException. 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.FromTypes and FromAssemblies throw when two event types share a contract name, and when an upgrader doesn't implement IUpgradeEvent<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 OperationCanceledException thrown by a handler itself, an HttpClient timeout 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 Deserialize or DeserializeMetadata that throws, a failing Correlate, and checkpoint-store and parked-sink failures now lead to a new subscription after the backoff of SubscriptionResubscribeOptions. 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, after MaxInterval (5 seconds), or when the subscription stops, instead of after every message. After a crash at most MaxBatchSize messages 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-checkpoint events and parked messages as $aggregates-parked events, in checkpoint-{id} and parked-{id}, where earlier previews wrote CheckpointStored and ParkedMessage. Existing checkpoints stay readable: the store reads the last event of checkpoint-{id} whatever its type. The old events stay in the store and a subscription that replays from the start receives them once, so return null from Deserialize for 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 in Correlate, 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}). The checkpoint-{id} and parked-{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 with startFromEnd. 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-replayed or $aggregates-parked-dismissed entry in the same parked-{id} stream, in link format. Deferred commands and saga deadlines park under parked-scheduled-{id}.
  • Deferred commands and saga deadlines are stored as $aggregates-scheduled-command and $aggregates-scheduled-deadline entries: in the saga stream for a saga, in scheduled-requests-{id}-{revision}@{stream} for a policy. Deliveries and markers go to scheduled-{id} ($aggregates-scheduled-delivered, $aggregates-scheduled-marker), the scheduler's checkpoint to checkpoint-scheduled-{id} and its parked requests to parked-scheduled-{id}. Requests written by an earlier preview, as $aggregates-timeout entries with their deliveries in timeouts-{id}, are not read: the scheduler only reads the $aggregates-scheduled prefix, so requests that were still pending are lost, and a saga stream that holds such an entry fails to load.