| | | 1 | | using AsyncResponse; |
| | | 2 | | using AsyncResponse.DurableFlows.Internal; |
| | | 3 | | using AsyncResponse.DurableFlows.MongoDB; |
| | | 4 | | using Microsoft.Extensions.DependencyInjection.Extensions; |
| | | 5 | | using Microsoft.Extensions.Options; |
| | | 6 | | using MongoDB.Bson; |
| | | 7 | | using MongoDB.Bson.Serialization.Attributes; |
| | | 8 | | using MongoDB.Driver; |
| | | 9 | | |
| | | 10 | | namespace Microsoft.Extensions.DependencyInjection |
| | | 11 | | { |
| | | 12 | | /// <summary>DI registration for the MongoDB durable-flow state store.</summary> |
| | | 13 | | public static class MongoDurableFlowServiceCollectionExtensions |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Stores durable-flow state in MongoDB. Hosts may either register an |
| | | 17 | | /// <see cref="IMongoDatabase"/> singleton or set connection options here. |
| | | 18 | | /// </summary> |
| | | 19 | | public static AsyncResponseRegistrationBuilder WithMongoDbDurableFlows( |
| | | 20 | | this AsyncResponseRegistrationBuilder builder, |
| | | 21 | | Action<MongoDbDurableFlowOptions>? configure = null) |
| | | 22 | | { |
| | | 23 | | // Singleton on purpose: index provisioning is cached per store instance, and the |
| | | 24 | | // executor resolves the store from a fresh scope per flow execution. Host-registered |
| | | 25 | | // IMongoDatabase / IMongoClient services are reused when present; otherwise the store |
| | | 26 | | // creates and owns a client from the options. Nothing is registered as a bare |
| | | 27 | | // IMongoClient/IMongoDatabase service, so unrelated resolutions of those types are |
| | | 28 | | // never answered — or broken — by this package. |
| | | 29 | | builder.Services.TryAddSingleton(provider => |
| | | 30 | | { |
| | | 31 | | var options = provider.GetRequiredService<IOptions<MongoDbDurableFlowOptions>>(); |
| | | 32 | | |
| | | 33 | | var database = provider.GetService<IMongoDatabase>(); |
| | | 34 | | if (database is not null) |
| | | 35 | | return new MongoDbFlowStateStore(database, options); |
| | | 36 | | |
| | | 37 | | if (string.IsNullOrWhiteSpace(options.Value.DatabaseName)) |
| | | 38 | | throw new InvalidOperationException($"{nameof(MongoDbDurableFlowOptions)}.{nameof(MongoDbDurableFlow |
| | | 39 | | |
| | | 40 | | var sharedClient = provider.GetService<IMongoClient>(); |
| | | 41 | | if (sharedClient is not null) |
| | | 42 | | return new MongoDbFlowStateStore(sharedClient.GetDatabase(options.Value.DatabaseName), options); |
| | | 43 | | |
| | | 44 | | if (string.IsNullOrWhiteSpace(options.Value.ConnectionString)) |
| | | 45 | | throw new InvalidOperationException($"{nameof(MongoDbDurableFlowOptions)}.{nameof(MongoDbDurableFlow |
| | | 46 | | |
| | | 47 | | var ownedClient = new MongoClient(options.Value.ConnectionString); |
| | | 48 | | return new MongoDbFlowStateStore(ownedClient.GetDatabase(options.Value.DatabaseName), options, ownedClie |
| | | 49 | | }); |
| | | 50 | | return builder.WithDurableFlows<MongoDbFlowStateStore, MongoDbDurableFlowOptions>(configure); |
| | | 51 | | } |
| | | 52 | | } |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | namespace AsyncResponse.DurableFlows.MongoDB |
| | | 56 | | { |
| | | 57 | | /// <summary>Options for the MongoDB durable-flow state store.</summary> |
| | | 58 | | public sealed class MongoDbDurableFlowOptions : DurableFlowOptions |
| | | 59 | | { |
| | | 60 | | /// <summary>Optional MongoDB connection string used when no <see cref="IMongoDatabase"/> is registered.</summary> |
| | | 61 | | public string? ConnectionString { get; set; } |
| | | 62 | | |
| | | 63 | | /// <summary>Optional database name used when no <see cref="IMongoDatabase"/> is registered.</summary> |
| | | 64 | | public string? DatabaseName { get; set; } |
| | | 65 | | |
| | | 66 | | /// <summary>Collection storing one durable-flow ledger document per flow id.</summary> |
| | | 67 | | public string CollectionName { get; set; } = "asyncresponse_flow_state"; |
| | | 68 | | |
| | | 69 | | /// <summary>Creates the expiry index on first use.</summary> |
| | | 70 | | public bool AutoCreateIndexes { get; set; } = true; |
| | | 71 | | |
| | | 72 | | /// <summary> |
| | | 73 | | /// Maximum serialized flow-state size in bytes accepted by writes; oversized ledgers fail fast |
| | | 74 | | /// with an actionable error instead of the raw 16 MB BSON-document error the executor would |
| | | 75 | | /// retry into the dead-letter queue. Default: 15 MB (headroom under MongoDB's 16 MB document |
| | | 76 | | /// cap for the sibling fields); <c>null</c> disables the guard. |
| | | 77 | | /// </summary> |
| | | 78 | | public long? MaxStateBytes { get; set; } = 15_000_000; |
| | | 79 | | |
| | | 80 | | /// <summary>Validates option values and throws on misconfiguration.</summary> |
| | | 81 | | public void Validate() |
| | | 82 | | { |
| | | 83 | | if (string.IsNullOrWhiteSpace(CollectionName)) |
| | | 84 | | throw new InvalidOperationException($"{nameof(MongoDbDurableFlowOptions)}.{nameof(CollectionName)} must be c |
| | | 85 | | if (MaxStateBytes is <= 0) |
| | | 86 | | throw new InvalidOperationException($"{nameof(MongoDbDurableFlowOptions)}.{nameof(MaxStateBytes)} must be po |
| | | 87 | | } |
| | | 88 | | } |
| | | 89 | | |
| | | 90 | | /// <summary>MongoDB implementation of <see cref="IFlowStateStore"/>.</summary> |
| | | 91 | | public sealed class MongoDbFlowStateStore : IFlowStateStore, IDisposable |
| | | 92 | | { |
| | | 93 | | private readonly IMongoDatabase _database; |
| | | 94 | | private readonly IMongoCollection<MongoFlowStateDocument> _collection; |
| | | 95 | | private readonly MongoDbDurableFlowOptions _options; |
| | 3 | 96 | | private readonly SemaphoreSlim _ensureGate = new(1, 1); |
| | | 97 | | private readonly IMongoClient? _ownedClient; |
| | | 98 | | private bool _created; |
| | | 99 | | |
| | 3 | 100 | | public MongoDbFlowStateStore(IMongoDatabase database, IOptions<MongoDbDurableFlowOptions> options, IMongoClient? own |
| | | 101 | | { |
| | 3 | 102 | | _options = options.Value; |
| | 3 | 103 | | _options.Validate(); |
| | 3 | 104 | | _database = database; |
| | 3 | 105 | | _collection = database.GetCollection<MongoFlowStateDocument>(_options.CollectionName); |
| | 3 | 106 | | _ownedClient = ownedClient; |
| | 3 | 107 | | } |
| | | 108 | | |
| | | 109 | | public async Task<FlowState?> LoadAsync(string flowId, CancellationToken cancellationToken = default) |
| | | 110 | | { |
| | 1 | 111 | | ArgumentException.ThrowIfNullOrWhiteSpace(flowId); |
| | 1 | 112 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | | 113 | | |
| | | 114 | | // Expiry is evaluated against the server clock ($$NOW) — the same authority the TTL |
| | | 115 | | // monitor reaps with — so app clock skew can never resurrect an expired ledger or hide a |
| | | 116 | | // live one. All lease fencing below uses the same authority. |
| | 1 | 117 | | var document = await _collection.Find(BuildLiveFilter(flowId)).FirstOrDefaultAsync(cancellationToken).ConfigureA |
| | 1 | 118 | | if (document is null) |
| | 1 | 119 | | return null; |
| | | 120 | | |
| | 1 | 121 | | return document.Revision is { } revision |
| | 1 | 122 | | ? DurableFlowStoreShared.ReadState(flowId, document.StateJson, revision) |
| | 1 | 123 | | : null; |
| | 1 | 124 | | } |
| | | 125 | | |
| | | 126 | | public async Task<bool> TryCreateAsync(string flowId, FlowState state, TimeSpan ttl, CancellationToken cancellationT |
| | | 127 | | { |
| | 3 | 128 | | DurableFlowStoreShared.ValidateCreate(flowId, state, ttl); |
| | 3 | 129 | | var stateJson = DurableFlowStoreShared.SerializeBounded(flowId, state, _options.MaxStateBytes, "MongoDB"); |
| | 3 | 130 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | | 131 | | |
| | | 132 | | // Two server-side steps instead of one upsert because MongoDB rejects upserts whose query |
| | | 133 | | // uses $expr, and $expr is what lets the expired-check run on the server clock. |
| | | 134 | | // |
| | | 135 | | // Step 1: atomically replace an expired ledger in place. Filter and assignments both |
| | | 136 | | // evaluate on $$NOW, so exactly one competing creator wins and every loser then sees the |
| | | 137 | | // fresh future expiry. |
| | 3 | 138 | | var replaced = await _collection.UpdateOneAsync( |
| | 3 | 139 | | BuildExpiredReplaceFilter(flowId), |
| | 3 | 140 | | BuildStateUpdate(stateJson, state.Revision, ttl, resetLease: true), |
| | 3 | 141 | | options: null, |
| | 3 | 142 | | cancellationToken).ConfigureAwait(false); |
| | 3 | 143 | | if (replaced.ModifiedCount > 0) |
| | 1 | 144 | | return true; |
| | | 145 | | |
| | | 146 | | // Step 2: the id was absent (or the expired document was TTL-purged after step 1 looked): |
| | | 147 | | // insert a fresh ledger. A plain insert has no aggregation context, so $$NOW is |
| | | 148 | | // unavailable — instead the server clock is read with one cheap `hello` round-trip and |
| | | 149 | | // stamped client-side. Creation then uses the same authority as every $$NOW comparison |
| | | 150 | | // and refresh below, so app clock skew can never mint a ledger that is born expired or |
| | | 151 | | // outlives its TTL window. A duplicate key means a live ledger owns the id. |
| | 3 | 152 | | var serverNow = await ReadServerNowAsync(cancellationToken).ConfigureAwait(false); |
| | | 153 | | try |
| | | 154 | | { |
| | 3 | 155 | | await _collection.InsertOneAsync( |
| | 3 | 156 | | new MongoFlowStateDocument |
| | 3 | 157 | | { |
| | 3 | 158 | | FlowId = flowId, |
| | 3 | 159 | | StateJson = stateJson, |
| | 3 | 160 | | ExpiresAtUtc = DurableFlowStoreShared.AddSaturating(serverNow, ttl), |
| | 3 | 161 | | UpdatedAtUtc = serverNow, |
| | 3 | 162 | | Revision = state.Revision |
| | 3 | 163 | | }, |
| | 3 | 164 | | options: null, |
| | 3 | 165 | | cancellationToken).ConfigureAwait(false); |
| | 3 | 166 | | return true; |
| | | 167 | | } |
| | 1 | 168 | | catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey) |
| | | 169 | | { |
| | 1 | 170 | | return false; |
| | | 171 | | } |
| | 3 | 172 | | } |
| | | 173 | | |
| | | 174 | | public async Task<bool> TryUpdateAsync( |
| | | 175 | | string flowId, |
| | | 176 | | FlowState state, |
| | | 177 | | long expectedRevision, |
| | | 178 | | TimeSpan ttl, |
| | | 179 | | string? leaseId = null, |
| | | 180 | | CancellationToken cancellationToken = default) |
| | | 181 | | { |
| | 3 | 182 | | DurableFlowStoreShared.ValidateUpdate(flowId, state, expectedRevision, ttl); |
| | 3 | 183 | | var stateJson = DurableFlowStoreShared.SerializeBounded(flowId, state, _options.MaxStateBytes, "MongoDB"); |
| | 3 | 184 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | | 185 | | |
| | 3 | 186 | | var result = await _collection.UpdateOneAsync( |
| | 3 | 187 | | BuildCheckpointFilter(flowId, expectedRevision, leaseId), |
| | 3 | 188 | | BuildStateUpdate(stateJson, state.Revision, ttl, resetLease: false), |
| | 3 | 189 | | options: null, |
| | 3 | 190 | | cancellationToken).ConfigureAwait(false); |
| | | 191 | | // ModifiedCount is safe here (unlike lease renewal): a checkpoint always bumps the |
| | | 192 | | // revision, so a matched document is always modified. |
| | 3 | 193 | | return result.ModifiedCount > 0; |
| | 3 | 194 | | } |
| | | 195 | | |
| | | 196 | | public Task<bool> TryAcquireLeaseAsync(string flowId, string leaseId, TimeSpan leaseDuration, CancellationToken canc |
| | 3 | 197 | | => UpdateLeaseAsync(flowId, leaseId, leaseDuration, acquire: true, cancellationToken); |
| | | 198 | | |
| | | 199 | | public Task<bool> TryRenewLeaseAsync(string flowId, string leaseId, TimeSpan leaseDuration, CancellationToken cancel |
| | 3 | 200 | | => UpdateLeaseAsync(flowId, leaseId, leaseDuration, acquire: false, cancellationToken); |
| | | 201 | | |
| | | 202 | | public async Task ReleaseLeaseAsync(string flowId, string leaseId, CancellationToken cancellationToken = default) |
| | | 203 | | { |
| | 1 | 204 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 205 | | var filter = Builders<MongoFlowStateDocument>.Filter.Eq(item => item.FlowId, flowId) |
| | 1 | 206 | | & Builders<MongoFlowStateDocument>.Filter.Eq(item => item.LeaseId, leaseId); |
| | 1 | 207 | | var update = Builders<MongoFlowStateDocument>.Update |
| | 1 | 208 | | .Unset(item => item.LeaseId) |
| | 1 | 209 | | .Unset(item => item.LeaseExpiresAtUtc); |
| | 1 | 210 | | await _collection.UpdateOneAsync(filter, update, cancellationToken: cancellationToken).ConfigureAwait(false); |
| | 1 | 211 | | } |
| | | 212 | | |
| | | 213 | | public async Task<bool> TryDeleteAsync(string flowId, CancellationToken cancellationToken = default) |
| | | 214 | | { |
| | 1 | 215 | | ArgumentException.ThrowIfNullOrWhiteSpace(flowId); |
| | 1 | 216 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | | 217 | | |
| | 1 | 218 | | var result = await _collection.DeleteOneAsync( |
| | 1 | 219 | | Builders<MongoFlowStateDocument>.Filter.Eq(item => item.FlowId, flowId), |
| | 1 | 220 | | cancellationToken).ConfigureAwait(false); |
| | 1 | 221 | | return result.DeletedCount > 0; |
| | 1 | 222 | | } |
| | | 223 | | |
| | | 224 | | private async Task EnsureCreatedAsync(CancellationToken cancellationToken) |
| | | 225 | | { |
| | 3 | 226 | | if (_created || !_options.AutoCreateIndexes) |
| | 3 | 227 | | return; |
| | | 228 | | |
| | 1 | 229 | | await _ensureGate.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 230 | | try |
| | | 231 | | { |
| | 1 | 232 | | if (_created) |
| | 1 | 233 | | return; |
| | | 234 | | |
| | | 235 | | // A TTL index (expireAfterSeconds = 0 on the expiry timestamp) makes MongoDB itself |
| | | 236 | | // reap expired ledgers — no application-side pruning needed. Loads still filter on |
| | | 237 | | // ExpiresAtUtc because the TTL monitor only runs periodically (~60s). |
| | 1 | 238 | | var indexName = $"{_options.CollectionName}_expires_idx"; |
| | 1 | 239 | | var model = new CreateIndexModel<MongoFlowStateDocument>( |
| | 1 | 240 | | Builders<MongoFlowStateDocument>.IndexKeys.Ascending(item => item.ExpiresAtUtc), |
| | 1 | 241 | | new CreateIndexOptions { Name = indexName, ExpireAfter = TimeSpan.Zero }); |
| | | 242 | | // Do not drop or rewrite a conflicting application-owned index. MongoDB reports the |
| | | 243 | | // mismatch and startup fails, leaving the operator to correct schema intentionally. |
| | 1 | 244 | | await _collection.Indexes.CreateOneAsync(model, cancellationToken: cancellationToken).ConfigureAwait(false); |
| | 1 | 245 | | _created = true; |
| | 1 | 246 | | } |
| | | 247 | | finally |
| | | 248 | | { |
| | 1 | 249 | | _ensureGate.Release(); |
| | | 250 | | } |
| | 3 | 251 | | } |
| | | 252 | | |
| | | 253 | | /// <summary> |
| | | 254 | | /// Server clock for the one write that cannot compute it in place: plain inserts evaluate no |
| | | 255 | | /// pipeline, so <c>$$NOW</c> is out of reach. <c>hello</c> is answered by every supported |
| | | 256 | | /// server (the 4.2+ floor the <c>$$NOW</c> filters already require) and carries the node's |
| | | 257 | | /// <c>localTime</c>; reading it from the primary keeps the authority the same node whose |
| | | 258 | | /// <c>$$NOW</c> the filters evaluate against. |
| | | 259 | | /// </summary> |
| | | 260 | | private async Task<DateTime> ReadServerNowAsync(CancellationToken cancellationToken) |
| | | 261 | | { |
| | 3 | 262 | | var reply = await _database.RunCommandAsync<BsonDocument>( |
| | 3 | 263 | | new BsonDocument("hello", 1), |
| | 3 | 264 | | ReadPreference.Primary, |
| | 3 | 265 | | cancellationToken).ConfigureAwait(false); |
| | | 266 | | // Defensive: a mongo-compatible endpoint omitting localTime falls back to the app clock — |
| | | 267 | | // the pre-server-clock behavior — instead of failing every create. |
| | 3 | 268 | | return reply.TryGetValue("localTime", out var localTime) |
| | 3 | 269 | | ? localTime.ToUniversalTime() |
| | 3 | 270 | | : DateTime.UtcNow; |
| | 3 | 271 | | } |
| | | 272 | | |
| | | 273 | | private async Task<bool> UpdateLeaseAsync( |
| | | 274 | | string flowId, |
| | | 275 | | string leaseId, |
| | | 276 | | TimeSpan leaseDuration, |
| | | 277 | | bool acquire, |
| | | 278 | | CancellationToken cancellationToken) |
| | | 279 | | { |
| | 3 | 280 | | ArgumentException.ThrowIfNullOrWhiteSpace(flowId); |
| | 3 | 281 | | ArgumentException.ThrowIfNullOrWhiteSpace(leaseId); |
| | 3 | 282 | | if (leaseDuration <= TimeSpan.Zero) |
| | 1 | 283 | | throw new ArgumentOutOfRangeException(nameof(leaseDuration)); |
| | | 284 | | |
| | 3 | 285 | | await EnsureCreatedAsync(cancellationToken).ConfigureAwait(false); |
| | 3 | 286 | | var result = await _collection.UpdateOneAsync( |
| | 3 | 287 | | BuildLeaseFilter(flowId, leaseId, acquire), |
| | 3 | 288 | | BuildLeaseUpdate(leaseId, leaseDuration), |
| | 3 | 289 | | options: null, |
| | 3 | 290 | | cancellationToken).ConfigureAwait(false); |
| | | 291 | | // MatchedCount, not ModifiedCount: matching the filter proves this owner held (or could |
| | | 292 | | // take) the lease — the atomic update then applied. A renewal that lands in the same |
| | | 293 | | // millisecond as the previous one writes an identical lease_expires_at_utc, which MongoDB |
| | | 294 | | // reports as matched-but-not-modified; treating that no-op as failure would abort a |
| | | 295 | | // healthy execution mid-flight. |
| | 3 | 296 | | return result.MatchedCount > 0; |
| | 3 | 297 | | } |
| | | 298 | | |
| | | 299 | | /// <summary>Live-ledger filter: id match plus a server-clock ($$NOW) expiry check.</summary> |
| | | 300 | | internal static FilterDefinition<MongoFlowStateDocument> BuildLiveFilter(string flowId) |
| | 3 | 301 | | => Builders<MongoFlowStateDocument>.Filter.Eq(item => item.FlowId, flowId) |
| | 3 | 302 | | & ServerClockExpr(new BsonDocument("$gt", new BsonArray { "$expires_at_utc", "$$NOW" })); |
| | | 303 | | |
| | | 304 | | /// <summary>Expired-ledger filter used by create to replace a dead ledger in place.</summary> |
| | | 305 | | internal static FilterDefinition<MongoFlowStateDocument> BuildExpiredReplaceFilter(string flowId) |
| | 3 | 306 | | => Builders<MongoFlowStateDocument>.Filter.Eq(item => item.FlowId, flowId) |
| | 3 | 307 | | & ServerClockExpr(new BsonDocument("$lte", new BsonArray { "$expires_at_utc", "$$NOW" })); |
| | | 308 | | |
| | | 309 | | /// <summary> |
| | | 310 | | /// Checkpoint filter: revision fence plus server-clock expiry (and, when fenced by a lease, |
| | | 311 | | /// server-clock lease validity). |
| | | 312 | | /// </summary> |
| | | 313 | | internal static FilterDefinition<MongoFlowStateDocument> BuildCheckpointFilter(string flowId, long expectedRevision, |
| | | 314 | | { |
| | 3 | 315 | | var filter = Builders<MongoFlowStateDocument>.Filter.Eq(item => item.FlowId, flowId) |
| | 3 | 316 | | & Builders<MongoFlowStateDocument>.Filter.Eq(item => item.Revision, expectedRevision) |
| | 3 | 317 | | & ServerClockExpr(new BsonDocument("$gt", new BsonArray { "$expires_at_utc", "$$NOW" })); |
| | 3 | 318 | | if (leaseId is not null) |
| | | 319 | | { |
| | 3 | 320 | | filter &= Builders<MongoFlowStateDocument>.Filter.Eq(item => item.LeaseId, leaseId) |
| | 3 | 321 | | & ServerClockExpr(new BsonDocument("$gt", new BsonArray { "$lease_expires_at_utc", "$$NOW" })); |
| | | 322 | | } |
| | | 323 | | |
| | 3 | 324 | | return filter; |
| | | 325 | | } |
| | | 326 | | |
| | | 327 | | /// <summary> |
| | | 328 | | /// Lease filter: acquire takes a free lease (absent, expired on the server clock, or already |
| | | 329 | | /// ours); renew requires ours and still live on the server clock. A missing |
| | | 330 | | /// <c>lease_expires_at_utc</c> compares below any date, so it counts as expired for acquire |
| | | 331 | | /// and as unrenewable for renew. |
| | | 332 | | /// </summary> |
| | | 333 | | internal static FilterDefinition<MongoFlowStateDocument> BuildLeaseFilter(string flowId, string leaseId, bool acquir |
| | | 334 | | { |
| | 3 | 335 | | var filter = Builders<MongoFlowStateDocument>.Filter.Eq(item => item.FlowId, flowId) |
| | 3 | 336 | | & Builders<MongoFlowStateDocument>.Filter.Ne(item => item.Revision, null) |
| | 3 | 337 | | & ServerClockExpr(new BsonDocument("$gt", new BsonArray { "$expires_at_utc", "$$NOW" })); |
| | 3 | 338 | | filter &= acquire |
| | 3 | 339 | | ? Builders<MongoFlowStateDocument>.Filter.Or( |
| | 3 | 340 | | Builders<MongoFlowStateDocument>.Filter.Eq(item => item.LeaseId, null), |
| | 3 | 341 | | ServerClockExpr(new BsonDocument("$lte", new BsonArray { "$lease_expires_at_utc", "$$NOW" })), |
| | 3 | 342 | | Builders<MongoFlowStateDocument>.Filter.Eq(item => item.LeaseId, leaseId)) |
| | 3 | 343 | | : Builders<MongoFlowStateDocument>.Filter.Eq(item => item.LeaseId, leaseId) |
| | 3 | 344 | | & ServerClockExpr(new BsonDocument("$gt", new BsonArray { "$lease_expires_at_utc", "$$NOW" })); |
| | 3 | 345 | | return filter; |
| | | 346 | | } |
| | | 347 | | |
| | | 348 | | /// <summary> |
| | | 349 | | /// Full-state write as an aggregation-pipeline update so the expiry lands on the server clock |
| | | 350 | | /// ($$NOW + ttl). <paramref name="resetLease"/> clears the lease columns (create-over-expired |
| | | 351 | | /// replaces ownership); checkpoints leave the running lease in place. |
| | | 352 | | /// </summary> |
| | | 353 | | internal static UpdateDefinition<MongoFlowStateDocument> BuildStateUpdate(string stateJson, long revision, TimeSpan |
| | | 354 | | { |
| | 3 | 355 | | var stages = new List<BsonDocument> |
| | 3 | 356 | | { |
| | 3 | 357 | | new("$set", new BsonDocument |
| | 3 | 358 | | { |
| | 3 | 359 | | // $literal keeps the JSON payload a value: a pipeline $set treats "$"-prefixed |
| | 3 | 360 | | // strings as field paths. |
| | 3 | 361 | | ["state_json"] = new BsonDocument("$literal", stateJson), |
| | 3 | 362 | | ["expires_at_utc"] = new BsonDocument("$add", new BsonArray |
| | 3 | 363 | | { |
| | 3 | 364 | | "$$NOW", |
| | 3 | 365 | | DurableFlowStoreShared.ServerClockTtlMilliseconds(ttl) |
| | 3 | 366 | | }), |
| | 3 | 367 | | ["updated_at_utc"] = "$$NOW", |
| | 3 | 368 | | ["revision"] = revision |
| | 3 | 369 | | }) |
| | 3 | 370 | | }; |
| | 3 | 371 | | if (resetLease) |
| | 3 | 372 | | stages.Add(new BsonDocument("$unset", new BsonArray { "lease_id", "lease_expires_at_utc" })); |
| | 3 | 373 | | return Builders<MongoFlowStateDocument>.Update.Pipeline(stages.ToArray()); |
| | | 374 | | } |
| | | 375 | | |
| | | 376 | | /// <summary>Lease grant/renewal on the server clock: <c>lease_expires_at_utc = $$NOW + duration</c>.</summary> |
| | | 377 | | internal static UpdateDefinition<MongoFlowStateDocument> BuildLeaseUpdate(string leaseId, TimeSpan leaseDuration) |
| | 3 | 378 | | => Builders<MongoFlowStateDocument>.Update.Pipeline(new[] |
| | 3 | 379 | | { |
| | 3 | 380 | | new BsonDocument("$set", new BsonDocument |
| | 3 | 381 | | { |
| | 3 | 382 | | ["lease_id"] = new BsonDocument("$literal", leaseId), |
| | 3 | 383 | | ["lease_expires_at_utc"] = new BsonDocument("$add", new BsonArray |
| | 3 | 384 | | { |
| | 3 | 385 | | "$$NOW", |
| | 3 | 386 | | DurableFlowStoreShared.ServerClockTtlMilliseconds(leaseDuration) |
| | 3 | 387 | | }) |
| | 3 | 388 | | }) |
| | 3 | 389 | | }); |
| | | 390 | | |
| | | 391 | | private static FilterDefinition<MongoFlowStateDocument> ServerClockExpr(BsonDocument comparison) |
| | 3 | 392 | | => new BsonDocumentFilterDefinition<MongoFlowStateDocument>(new BsonDocument("$expr", comparison)); |
| | | 393 | | |
| | | 394 | | /// <summary>Disposes the Mongo client when the store created (and therefore owns) it.</summary> |
| | | 395 | | public void Dispose() |
| | | 396 | | { |
| | 3 | 397 | | _ensureGate.Dispose(); |
| | 3 | 398 | | (_ownedClient as IDisposable)?.Dispose(); |
| | 3 | 399 | | } |
| | | 400 | | } |
| | | 401 | | |
| | | 402 | | internal sealed class MongoFlowStateDocument |
| | | 403 | | { |
| | | 404 | | [BsonId] |
| | | 405 | | [BsonElement("_id")] |
| | | 406 | | public string FlowId { get; set; } = ""; |
| | | 407 | | |
| | | 408 | | [BsonElement("state_json")] |
| | | 409 | | public string StateJson { get; set; } = ""; |
| | | 410 | | |
| | | 411 | | [BsonElement("expires_at_utc")] |
| | | 412 | | public DateTime ExpiresAtUtc { get; set; } |
| | | 413 | | |
| | | 414 | | [BsonElement("updated_at_utc")] |
| | | 415 | | public DateTime UpdatedAtUtc { get; set; } |
| | | 416 | | |
| | | 417 | | [BsonElement("revision")] |
| | | 418 | | public long? Revision { get; set; } |
| | | 419 | | |
| | | 420 | | [BsonElement("lease_id")] |
| | | 421 | | [BsonIgnoreIfNull] |
| | | 422 | | public string? LeaseId { get; set; } |
| | | 423 | | |
| | | 424 | | [BsonElement("lease_expires_at_utc")] |
| | | 425 | | [BsonIgnoreIfNull] |
| | | 426 | | public DateTime? LeaseExpiresAtUtc { get; set; } |
| | | 427 | | } |
| | | 428 | | } |