Class PostgresSnapshotStore
- Namespace
- Excalibur.EventSourcing.Postgres
- Assembly
- Excalibur.EventSourcing.Postgres.dll
Postgres implementation of ISnapshotStore.
public sealed class PostgresSnapshotStore : ISnapshotStore
- Inheritance
-
PostgresSnapshotStore
- Implements
- Inherited Members
Remarks
Provides atomic snapshot operations with upsert (insert-or-update) semantics. Uses INSERT ... ON CONFLICT for thread-safe concurrent snapshot saves. Stores only the latest snapshot per aggregate (no snapshot history).
This class supports two constructor patterns:
- Simple: Connection string for most users
- Advanced: NpgsqlDataSource for multi-database, pooling, or IDb integration
Uses ValueTask for interface compliance, though SQL operations are inherently async.
Constructors
PostgresSnapshotStore(NpgsqlDataSource, ILogger<PostgresSnapshotStore>, ITenantContext, string, string)
Initializes a new instance of the PostgresSnapshotStore class with an NpgsqlDataSource.
public PostgresSnapshotStore(NpgsqlDataSource dataSource, ILogger<PostgresSnapshotStore> logger, ITenantContext tenantContext, string schema = "public", string table = "event_store_snapshots")
Parameters
dataSourceNpgsqlDataSourceAn Npgsql.NpgsqlDataSource that manages connection pooling. Using NpgsqlDataSource is the recommended pattern per Npgsql documentation.
loggerILogger<PostgresSnapshotStore>The logger instance.
tenantContextITenantContextThe ambient tenant context. Required: this store partitions rows 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.
schemastringThe schema name for the snapshot store table. Default: "public".
tablestringThe snapshot store table name. Default: "event_store_snapshots".
Remarks
This is the advanced constructor for scenarios that need custom connection management:
- Multi-database setups with marker interfaces (e.g., IDomainDb, IEventStoreDb)
- Custom connection pooling
- Integration with IDb abstraction
PostgresSnapshotStore(string, ILogger<PostgresSnapshotStore>, ITenantContext)
Initializes a new instance of the PostgresSnapshotStore class.
public PostgresSnapshotStore(string connectionString, ILogger<PostgresSnapshotStore> logger, ITenantContext tenantContext)
Parameters
connectionStringstringThe Postgres connection string.
loggerILogger<PostgresSnapshotStore>The logger instance.
tenantContextITenantContextThe ambient tenant context. Required: this store resolves the tenant partition it reads and writes from here.
Remarks
This is the simple constructor for a single-tenant host. It resolves no ambient tenant context, so every read, save, and delete spans all rows in the table regardless of which tenant wrote them.
Do not use this overload in a multi-tenant host. Use PostgresSnapshotStore(NpgsqlDataSource, ILogger<PostgresSnapshotStore>, ITenantContext, string, string) and supply the ambient tenant context, which restricts every operation to the resolved tenant's own rows. That overload also covers multi-database setups and custom connection pooling.
Methods
DeleteSnapshotsAsync(string, string, CancellationToken)
Deletes all snapshots for an aggregate.
public ValueTask DeleteSnapshotsAsync(string aggregateId, string aggregateType, CancellationToken cancellationToken)
Parameters
aggregateIdstringThe aggregate identifier.
aggregateTypestringThe aggregate type name.
cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask
A task that represents the asynchronous delete operation.
DeleteSnapshotsOlderThanAsync(string, string, long, CancellationToken)
Deletes snapshots older than a specified version.
public ValueTask DeleteSnapshotsOlderThanAsync(string aggregateId, string aggregateType, long olderThanVersion, CancellationToken cancellationToken)
Parameters
aggregateIdstringThe aggregate identifier.
aggregateTypestringThe aggregate type name.
olderThanVersionlongDelete snapshots with version less than this value.
cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask
A task that represents the asynchronous delete operation.
GetLatestSnapshotAsync(string, string, CancellationToken)
Gets the latest snapshot for an aggregate.
public ValueTask<ISnapshot?> GetLatestSnapshotAsync(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: a snapshot stored under
another tenant for this aggregateId is reported as not found, the same as one
that was never taken.
SaveSnapshotAsync(ISnapshot, CancellationToken)
Saves a snapshot for an aggregate, keeping the highest version stored for it.
public ValueTask SaveSnapshotAsync(ISnapshot snapshot, CancellationToken cancellationToken)
Parameters
snapshotISnapshotThe snapshot to save.
cancellationTokenCancellationTokenCancellation token.
Returns
- ValueTask
A task that represents the asynchronous save operation.
Remarks
Total. Every well-formed snapshot is an acceptable argument. There is no version, payload size, or identifier shape a caller must avoid, and no state of the store in which a save is illegal.
Monotone upsert, scoped to the interval since the last deletion. After
SaveSnapshotAsync returns normally, the version readable for
(aggregateId, aggregateType) within the ambient tenant is at least the version passed. A
save carrying a version lower than or equal to the stored one is a successful no-op. Monotonicity
does NOT hold across a deletion: DeleteSnapshotsAsync,
DeleteSnapshotsOlderThanAsync and provider-level expiry all remove stored versions, after
which a save may legitimately make a LOWER version readable than was readable before. Saves and
deletions on the same key are not ordered with respect to one another, so a save superseded by a
concurrent deletion has not dropped a snapshot. A caller that requires a specific version to be
readable must re-read it; a normal return does not entitle the caller to infer which version is
readable now, only that the store established one at least as high at the moment it completed. A
store that returns normally having neither stored the snapshot nor established that is in
violation; unresolvable contention is reported as ConcurrencyException, never as success.
Modifies only its own key. No other aggregate, aggregate type, or tenant is observably affected.
Faults. Throws only for an invalid argument, for cancellation, or for an infrastructure failure that prevented the store from establishing the outcome above. Implementations MUST NOT report a lost race as a fault, and MUST NOT return normally having neither stored the snapshot nor established that a version at least as high is stored — a silent drop reports success for a snapshot nobody holds.
Exceptions
- ConcurrencyException
May be thrown by an implementation that retries a contended write when it exhausts its attempts without either storing the snapshot or establishing that a version at least as high is already stored. This is the infrastructure-failure case above, reported in the abstraction's own currency: the outcome is UNKNOWN, which is why it is a fault rather than the successful no-op that a proven supersede produces. Implementations that write without retrying cannot reach this state and do not throw it.