Table of Contents

Class MongoDbMaterializedViewStore

Namespace
Excalibur.Data.MongoDB.MaterializedViews
Assembly
Excalibur.Data.MongoDB.dll

MongoDB implementation of IMaterializedViewStore.

public sealed class MongoDbMaterializedViewStore : IAtomicMaterializedViewStore, IMaterializedViewStore, IAsyncDisposable
Inheritance
MongoDbMaterializedViewStore
Implements
Inherited Members

Remarks

Stores materialized views as BSON documents in MongoDB with the following schema:

  • materialized_views collection for view data
  • materialized_view_positions collection for position tracking

View documents are written with an upserting replace. Checkpoint positions are never replaced: every write path advances them with $max, so a delayed or retried write carrying an older position cannot rewind the checkpoint and replay events the projection has already applied.

Views and checkpoints are partitioned by tenant. The tenant term is part of each document's identifier rather than a filter applied over it, so two tenants projecting the same named view hold distinct documents and distinct checkpoints.

A document written before this partitioning existed carries the un-prefixed identifier, so a scoped read does not find it. That direction is the safe one and it is chosen deliberately: an unfound checkpoint reads as unset, and an unset checkpoint replays from the beginning, which re-derives the view. The alternative failure -- a tenant inheriting a checkpoint written by another -- would skip the events in between with no error and no way to detect it afterwards. Replay costs time; a skip costs data.

Constructors

MongoDbMaterializedViewStore(IOptions<MongoDbMaterializedViewStoreOptions>, ILogger<MongoDbMaterializedViewStore>, ITenantContext)

Initializes a new instance of the MongoDbMaterializedViewStore class.

public MongoDbMaterializedViewStore(IOptions<MongoDbMaterializedViewStoreOptions> options, ILogger<MongoDbMaterializedViewStore> logger, ITenantContext tenantContext)

Parameters

options IOptions<MongoDbMaterializedViewStoreOptions>

The store options.

logger ILogger<MongoDbMaterializedViewStore>

The logger instance.

tenantContext ITenantContext

The ambient tenant context. Required: this store partitions documents 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.

MongoDbMaterializedViewStore(IMongoClient, IOptions<MongoDbMaterializedViewStoreOptions>, ILogger<MongoDbMaterializedViewStore>, ITenantContext)

Initializes a new instance of the MongoDbMaterializedViewStore class with an existing client.

public MongoDbMaterializedViewStore(IMongoClient client, IOptions<MongoDbMaterializedViewStoreOptions> options, ILogger<MongoDbMaterializedViewStore> logger, ITenantContext tenantContext)

Parameters

client IMongoClient

An existing MongoDB client.

options IOptions<MongoDbMaterializedViewStoreOptions>

The store options.

logger ILogger<MongoDbMaterializedViewStore>

The logger instance.

tenantContext ITenantContext

The ambient tenant context. Required: this store partitions documents 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.

Properties

SupportsAtomicWrites

Gets a value indicating whether this store instance can currently perform atomic view+position writes.

public bool SupportsAtomicWrites { get; }

Property Value

bool

true when SaveViewAndPositionAsync<TView>(string, string, TView, long, CancellationToken) commits both writes as one unit; otherwise false.

Remarks

Implementing the interface states the store is capable of atomic writes; this property states whether the current configuration enables them. A store whose atomicity is unconditional returns true constantly. A store whose atomicity requires an opt-in — a transaction mode, a replica set — returns the value of that setting, so the check reads the option that actually governs the behaviour rather than a proxy for it.

Methods

DeleteAsync(string, string, CancellationToken)

Deletes a materialized view.

public ValueTask DeleteAsync(string viewName, string viewId, CancellationToken cancellationToken)

Parameters

viewName string

The view name (typically the view type name).

viewId string

The view identifier.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask

A task representing the asynchronous operation.

Remarks

Confined to the ambient tenant, like every other operation on this store: a view stored under another tenant with the same viewName and viewId is not deleted, and the call succeeds silently because that view is not visible to this caller. An implementation that omits the tenant term here deletes another tenant's view -- silent data loss rather than a disclosure, and the projector that rebuilt it will not notice.

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.

GetAsync<TView>(string, string, CancellationToken)

Gets a materialized view by its identifier.

[RequiresUnreferencedCode("The materialized view store serializes view types reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
[RequiresDynamicCode("The materialized view store serializes view types reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
public ValueTask<TView?> GetAsync<TView>(string viewName, string viewId, CancellationToken cancellationToken) where TView : class

Parameters

viewName string

The view name (typically the view type name).

viewId string

The view identifier.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask<TView>

The view if found, or null if not found.

Type Parameters

TView

The view type.

GetPositionAsync(string, CancellationToken)

Gets the last processed position for a view.

public ValueTask<long?> GetPositionAsync(string viewName, CancellationToken cancellationToken)

Parameters

viewName string

The view name for position tracking.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask<long?>

The last processed position, or null if no position has been recorded.

Remarks

The position is used to track which events have been processed for a view, enabling catch-up subscriptions and rebuild scenarios.

ResetPositionAsync(string, CancellationToken)

Clears the recorded position for a view, so the next read reports no checkpoint at all.

public ValueTask ResetPositionAsync(string viewName, CancellationToken cancellationToken)

Parameters

viewName string

The view name for position tracking.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask

A task representing the asynchronous operation.

Remarks

Unconditional by contract. This is the operation a rebuild needs, and it is deliberately not subject to the monotonic guard that governs SavePositionAsync(string, long, CancellationToken) — a guard whose whole purpose is to refuse exactly this.

It clears rather than zeroes. GetPositionAsync(string, CancellationToken) already returns null for a view with no checkpoint, so absence is the existing representation of "start from the beginning" and needs no second encoding. Writing zero would also be indistinguishable from a view legitimately checkpointed at position zero.

It returns no outcome because it cannot refuse. Clearing an already-absent checkpoint is success, not a refusal. A store that cannot clear throws.

SaveAsync<TView>(string, string, TView, CancellationToken)

Saves a materialized view.

[RequiresUnreferencedCode("The materialized view store serializes view types reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
[RequiresDynamicCode("The materialized view store serializes view types reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
public ValueTask SaveAsync<TView>(string viewName, string viewId, TView view, CancellationToken cancellationToken) where TView : class

Parameters

viewName string

The view name (typically the view type name).

viewId string

The view identifier.

view TView

The view to save.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask

A task representing the asynchronous operation.

Type Parameters

TView

The view type.

SavePositionAsync(string, long, CancellationToken)

Advances the last processed position for a view, and reports whether the advance was taken.

public ValueTask<ViewPositionSaveOutcome> SavePositionAsync(string viewName, long position, CancellationToken cancellationToken)

Parameters

viewName string

The view name for position tracking.

position long

The position to advance to.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask<ViewPositionSaveOutcome>

Advanced when the checkpoint moved to position; RefusedAsStale when the stored checkpoint was already at or beyond it and nothing was written.

Remarks

This advance is MONOTONIC in every implementation, and the refusal is a normal outcome rather than an error. A delayed or retried write carrying an older position must not rewind the checkpoint, because the projection would then replay events it has already applied. Every store enforces that server-side.

The return value exists because the refusal used to be unobservable. This member returned ValueTask — a caller could not tell a taken advance from a refused one, and every implementation logged a successful save either way. That hid a real defect for as long as the monotonic guard existed: a caller that needed the position to go BACKWARDS was silently refused and reported success. An operation that can decline to act must say so in its signature.

To move a checkpoint backwards, use ResetPositionAsync(string, CancellationToken). Lowering a position is a different operation from advancing one, so it is a different member rather than a flag — this method cannot express it and must not be asked to.

SaveViewAndPositionAsync<TView>(string, string, TView, long, CancellationToken)

Persists a view and advances the processed position for its view name in a single durable operation.

[SuppressMessage("Maintainability", "CA1506", Justification = "The transactional save-view-and-position path coordinates the driver, session, filter and update builders; the coupling is inherent to the single atomic operation and predates the trimming annotations, which tipped a pre-existing count over the threshold.")]
[RequiresUnreferencedCode("The materialized view store serializes view types reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
[RequiresDynamicCode("The materialized view store serializes view types reflectively; supply JsonSerializerOptions with a source-generated resolver for trimming and AOT.")]
public ValueTask SaveViewAndPositionAsync<TView>(string viewName, string viewId, TView view, long position, CancellationToken cancellationToken) where TView : class

Parameters

viewName string

The logical view name the position belongs to.

viewId string

The identifier of the view instance being written.

view TView

The view to persist.

position long

The global stream position that produced view.

cancellationToken CancellationToken

Cancellation token.

Returns

ValueTask

Type Parameters

TView

The materialized view type.

Remarks

Both writes commit, or neither does. The position advance is monotonic: a lower position never overwrites a higher one, so a delayed or retried write cannot rewind the checkpoint and replay events that were already applied.

Exceptions

ArgumentException

viewName or viewId is null, empty, or white space.

ArgumentNullException

view is null.

InvalidOperationException

UseTransactions is disabled.