Class MongoDbEventStore
- Namespace
- Excalibur.EventSourcing.MongoDB
- Assembly
- Excalibur.EventSourcing.MongoDB.dll
MongoDB implementation of IEventStore.
[SuppressMessage("Maintainability", "CA1506:Avoid excessive class coupling", Justification = "Event store implementations inherently couple with many SDK and abstraction types.")]
public sealed class MongoDbEventStore : IEventStore, IServiceProvider, IEventStoreErasure, IAsyncDisposable
- Inheritance
-
MongoDbEventStore
- Implements
- Inherited Members
Remarks
Provides atomic event appends with optimistic concurrency control using MongoDB's UNIQUE index. A UNIQUE compound index on (streamId, aggregateType, version) enforces version uniqueness.
When a version conflict occurs, MongoDB returns error code 11000 (duplicate key), which is caught and translated to a concurrency conflict result.
Global ordering is provided via an atomic counter document using FindOneAndUpdate.
Supports pluggable serialization via IPayloadSerializer for event payloads, with backward compatibility for existing JSON-serialized events.
Constructors
MongoDbEventStore(IOptions<MongoDbEventStoreOptions>, ILogger<MongoDbEventStore>, ITenantContext)
Initializes a new instance of the MongoDbEventStore class.
public MongoDbEventStore(IOptions<MongoDbEventStoreOptions> options, ILogger<MongoDbEventStore> logger, ITenantContext tenantContext)
Parameters
optionsIOptions<MongoDbEventStoreOptions>The event store options.
loggerILogger<MongoDbEventStore>The logger instance.
tenantContextITenantContextThe ambient tenant context. Required: this store partitions events by tenant, and it resolves that partition from here, so there is no state in which the partition is undecided. A single-tenant host receives the framework default context and operates as the one canonical tenant.
MongoDbEventStore(IOptions<MongoDbEventStoreOptions>, ILogger<MongoDbEventStore>, ITenantContext, ISerializer?, IPayloadSerializer?)
Initializes a new instance of the MongoDbEventStore class with optional serializers.
public MongoDbEventStore(IOptions<MongoDbEventStoreOptions> options, ILogger<MongoDbEventStore> logger, ITenantContext tenantContext, ISerializer? internalSerializer, IPayloadSerializer? payloadSerializer)
Parameters
optionsIOptions<MongoDbEventStoreOptions>The event store options.
loggerILogger<MongoDbEventStore>The logger instance.
tenantContextITenantContextThe ambient tenant context. Required: this store partitions events by tenant, and it resolves that partition from here, so there is no state in which the partition is undecided. A single-tenant host receives the framework default context and operates as the one canonical tenant.
internalSerializerISerializerOptional internal serializer for envelope support.
payloadSerializerIPayloadSerializerOptional pluggable serializer for event payloads.
MongoDbEventStore(IMongoClient, IOptions<MongoDbEventStoreOptions>, ILogger<MongoDbEventStore>, ITenantContext, ISerializer?, IPayloadSerializer?)
Initializes a new instance of the MongoDbEventStore class with an existing client.
[ActivatorUtilitiesConstructor]
public MongoDbEventStore(IMongoClient client, IOptions<MongoDbEventStoreOptions> options, ILogger<MongoDbEventStore> logger, ITenantContext tenantContext, ISerializer? internalSerializer = null, IPayloadSerializer? payloadSerializer = null)
Parameters
clientIMongoClientAn existing MongoDB client.
optionsIOptions<MongoDbEventStoreOptions>The event store options.
loggerILogger<MongoDbEventStore>The logger instance.
tenantContextITenantContextThe ambient tenant context. Required: this store partitions events by tenant, and it resolves that partition from here, so there is no state in which the partition is undecided. A single-tenant host receives the framework default context and operates as the one canonical tenant.
internalSerializerISerializerOptional internal serializer for envelope support.
payloadSerializerIPayloadSerializerOptional pluggable serializer for event payloads.
Methods
AppendAsync(string, string, IEnumerable<IDomainEvent>, long, CancellationToken)
Appends events to the store with optimistic concurrency control.
public ValueTask<AppendResult> AppendAsync(string aggregateId, string aggregateType, IEnumerable<IDomainEvent> events, long expectedVersion, CancellationToken cancellationToken)
Parameters
aggregateIdstringThe aggregate identifier. Must not be null, empty, or white space.
aggregateTypestringThe aggregate type name. Must not be null, empty, or white space.
eventsIEnumerable<IDomainEvent>The events to append. Must not be null.
expectedVersionlongThe version the stream is expected to currently be at, or
-1when the stream does not yet exist. See the version base stated in the remarks below.cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask<AppendResult>
The result of the append operation, carrying the stream's version after the append in NextExpectedVersion.
Remarks
Version base. Stream versions are zero-based and contiguous. The first event appended to a
new stream is version 0, and each subsequent event takes the next integer. A stream that
does not yet exist has no current version, which expectedVersion expresses as
-1. Appending N events to a new stream therefore leaves it at version N-1:
that is the value NextExpectedVersion reports, and the value the next
append must pass as expectedVersion — it is the version the stream is now at,
not the version the next event will receive. Appending no events leaves the version unchanged and
reports back the version it was given.
An identifier that is null, empty, or white space is a usage error, never a legitimate stream: accepting one would fabricate a stream key and write events where no reader will ever look. Every implementation therefore rejects such an argument by throwing, rather than reporting a failed AppendResult — a returned result models a domain or infrastructure outcome, not a caller defect. Implementations validate their arguments before any I/O or concurrency check is attempted.
Outcome or defect. The line between a returned AppendResult and a thrown exception is whether the identical call could ever succeed without a change to the calling program. A version clash could, once the caller reloads, so it is reported as a result carrying IsConcurrencyConflict; an infrastructure fault may be reported as Failed only when non-commit is established. A lost commit acknowledgement with inconclusive recovery is Unknown, even if a later read sees a different stream version or no matching rows. Retry classification does not establish commit certainty. An event type the configured resolver does not declare could not — no retry, reload or reconfiguration reaches it — so it throws, as do a blank identifier, a batch above the provider's atomic limit, and cancellation. Every implementation of this interface answers the same way; a caller may rely on that rather than on which provider is configured.
Cancellation propagates. A cancelled append raises OperationCanceledException rather than reporting a failed result: reporting it as a store failure would invite a caller to retry inside a scope that has already been cancelled. Cancellation after dispatch does not prove rollback. Reconcile outside the cancelled operation using the original tenant, stream, event identities, payloads and expected version; do not regenerate events or rebase the append merely because its acknowledgement was not received.
Confined to the ambient tenant established for this store instance: the appended events join only
this tenant's stream for aggregateId, and the optimistic-concurrency check
against expectedVersion is evaluated within that same partition — another
tenant holding a stream under the same aggregateId can neither cause nor observe
a conflict here.
Exceptions
- ArgumentException
aggregateIdoraggregateTypeis empty or white space.- ArgumentNullException
aggregateId,aggregateType, oreventsis null.- EventBatchTooLargeException
eventscontains more events than the underlying store can append atomically. The exception carries the offending count and the limit, so a caller may split the batch and retry.- EventTypeNotDeclaredException
An event's runtime type is not declared by the type-info resolver the host configured, so it cannot be serialized. Nothing is appended. The identical call cannot succeed until the type is declared, which is why this is thrown rather than reported as a failed AppendResult.
DisposeAsync()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
public ValueTask DisposeAsync()
Returns
- ValueTask
A task that represents the asynchronous dispose operation.
EraseEventsAsync(string, string, Guid, CancellationToken)
Erases all event payloads for the specified aggregate, replacing them with a tombstone marker.
public Task<int> EraseEventsAsync(string aggregateId, string aggregateType, Guid erasureRequestId, CancellationToken cancellationToken)
Parameters
aggregateIdstringThe aggregate whose events should be erased.
aggregateTypestringThe aggregate type name.
erasureRequestIdGuidThe GDPR erasure request tracking ID for audit purposes.
cancellationTokenCancellationTokenCancellation token.
Returns
Remarks
Confined to the ambient tenant established for this store instance: tombstones events only in the
caller's own tenant's stream for aggregateId, and cannot reach or be triggered
by another tenant's stream under the same identifier.
IsErasedAsync(string, string, CancellationToken)
Checks whether erasure has been performed for the specified aggregate.
public Task<bool> IsErasedAsync(string aggregateId, string aggregateType, CancellationToken cancellationToken)
Parameters
aggregateIdstringThe aggregate identifier.
aggregateTypestringThe aggregate type name.
cancellationTokenCancellationTokenCancellation token.
Returns
Remarks
Confined to the ambient tenant established for this store instance: answers for the caller's own tenant's stream, never another tenant's stream under the same identifier.
LoadAsync(string, string, long, CancellationToken)
Loads events for an aggregate from a specific version.
public ValueTask<IReadOnlyList<StoredEvent>> LoadAsync(string aggregateId, string aggregateType, long fromVersion, CancellationToken cancellationToken)
Parameters
aggregateIdstringThe aggregate identifier. Must not be null, empty, or white space.
aggregateTypestringThe aggregate type name. Must not be null, empty, or white space.
fromVersionlongThe version to start loading from, exclusive: the result begins at the next version after this one. Versions are zero-based, so
-1loads the whole stream. See the version base stated on AppendAsync(string, string, IEnumerable<IDomainEvent>, long, CancellationToken).cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask<IReadOnlyList<StoredEvent>>
The events for the aggregate from the specified version in order.
Remarks
Confined identically to the zero-argument overload above: none of another tenant's events for
this aggregateId, and every one of the caller's own from
fromVersion onward.
Exceptions
- ArgumentException
aggregateIdoraggregateTypeis empty or white space.- ArgumentNullException
aggregateIdoraggregateTypeis null.
LoadAsync(string, string, CancellationToken)
Loads all events for an aggregate.
public ValueTask<IReadOnlyList<StoredEvent>> LoadAsync(string aggregateId, string aggregateType, CancellationToken cancellationToken)
Parameters
aggregateIdstringThe aggregate identifier. Must not be null, empty, or white space.
aggregateTypestringThe aggregate type name. Must not be null, empty, or white space.
cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask<IReadOnlyList<StoredEvent>>
The events for the aggregate in version order.
Remarks
Confined to the ambient tenant established for this store instance: returns none of another
tenant's events for this aggregateId, and every one of the caller's own — a
store that returns fewer than the caller's own full history satisfies neither this contract nor
the aggregate that must replay from it.
Exceptions
- ArgumentException
aggregateIdoraggregateTypeis empty or white space.- ArgumentNullException
aggregateIdoraggregateTypeis null.