| | | 1 | | using System.Data.Common; |
| | | 2 | | using AsiBackbone.Core.CapabilityGrants; |
| | | 3 | | using AsiBackbone.Core.Entities; |
| | | 4 | | using AsiBackbone.EntityFrameworkCore.Persistence; |
| | | 5 | | using Microsoft.EntityFrameworkCore; |
| | | 6 | | |
| | | 7 | | namespace AsiBackbone.EntityFrameworkCore.CapabilityGrants; |
| | | 8 | | |
| | | 9 | | /// <summary>Provides durable, atomic capability-grant use control through a host-owned EF Core context.</summary> |
| | | 10 | | public sealed class EfCoreCapabilityGrantUseStore : ICapabilityGrantUseStore |
| | | 11 | | { |
| | | 12 | | private readonly DbContext dbContext; |
| | | 13 | | private readonly EfCoreCapabilityGrantUseStoreOptions options; |
| | | 14 | | |
| | | 15 | | /// <summary>Initializes the durable use store.</summary> |
| | 4 | 16 | | public EfCoreCapabilityGrantUseStore(DbContext dbContext, EfCoreCapabilityGrantUseStoreOptions options) |
| | | 17 | | { |
| | 4 | 18 | | ArgumentNullException.ThrowIfNull(dbContext); |
| | 4 | 19 | | ArgumentNullException.ThrowIfNull(options); |
| | 4 | 20 | | options.Validate(); |
| | 4 | 21 | | this.dbContext = dbContext; |
| | 4 | 22 | | this.options = options; |
| | 4 | 23 | | } |
| | | 24 | | |
| | | 25 | | /// <inheritdoc /> |
| | | 26 | | public async ValueTask<CapabilityGrantUseResult> TryConsumeAsync( |
| | | 27 | | CapabilityGrant grant, |
| | | 28 | | int maxUseCount, |
| | | 29 | | DateTimeOffset usedUtc, |
| | | 30 | | CancellationToken cancellationToken = default) |
| | | 31 | | { |
| | 5 | 32 | | ArgumentNullException.ThrowIfNull(grant); |
| | 5 | 33 | | ArgumentOutOfRangeException.ThrowIfLessThan(maxUseCount, 1); |
| | 5 | 34 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 35 | | |
| | 5 | 36 | | DateTimeOffset normalizedUsedUtc = usedUtc.ToUniversalTime(); |
| | 5 | 37 | | DateTimeOffset retainUntilUtc = AddClamped(grant.ExpiresUtc, options.RetentionGracePeriod); |
| | 5 | 38 | | if (normalizedUsedUtc > retainUntilUtc) |
| | | 39 | | { |
| | 0 | 40 | | return CapabilityGrantUseResult.RetentionElapsed( |
| | 0 | 41 | | "The grant is past the EF Core use store's retention horizon."); |
| | | 42 | | } |
| | | 43 | | |
| | 10 | 44 | | for (int attempt = 0; attempt <= options.ContentionRetryCount; attempt++) |
| | | 45 | | { |
| | | 46 | | try |
| | | 47 | | { |
| | 5 | 48 | | int affected = await Entries() |
| | 5 | 49 | | .Where(entity => entity.Issuer == grant.Issuer |
| | 5 | 50 | | && entity.TokenId == grant.TokenId |
| | 5 | 51 | | && entity.State == GrantUseState.Accepted |
| | 5 | 52 | | && entity.UseCount < maxUseCount) |
| | 5 | 53 | | .ExecuteUpdateAsync(setters => setters |
| | 5 | 54 | | .SetProperty(entity => entity.UseCount, entity => entity.UseCount + 1) |
| | 5 | 55 | | .SetProperty(entity => entity.LastUsedUtc, normalizedUsedUtc) |
| | 5 | 56 | | .SetProperty(entity => entity.RetainUntilUtc, retainUntilUtc) |
| | 5 | 57 | | .SetProperty(entity => entity.ConcurrencyStamp, GovernanceEntity.NewConcurrencyStamp()), cancell |
| | 5 | 58 | | .ConfigureAwait(false); |
| | | 59 | | |
| | 4 | 60 | | if (affected == 1) |
| | | 61 | | { |
| | 0 | 62 | | int count = await Entries().AsNoTracking() |
| | 0 | 63 | | .Where(entity => entity.Issuer == grant.Issuer && entity.TokenId == grant.TokenId) |
| | 0 | 64 | | .Select(entity => entity.UseCount) |
| | 0 | 65 | | .SingleAsync(cancellationToken) |
| | 0 | 66 | | .ConfigureAwait(false); |
| | 0 | 67 | | return CapabilityGrantUseResult.Accepted(count); |
| | | 68 | | } |
| | | 69 | | |
| | 4 | 70 | | CapabilityGrantUseEntity? existing = await Entries().AsNoTracking() |
| | 4 | 71 | | .SingleOrDefaultAsync( |
| | 4 | 72 | | entity => entity.Issuer == grant.Issuer && entity.TokenId == grant.TokenId, |
| | 4 | 73 | | cancellationToken) |
| | 4 | 74 | | .ConfigureAwait(false); |
| | | 75 | | |
| | 4 | 76 | | if (existing is not null) |
| | | 77 | | { |
| | 3 | 78 | | return existing.State switch |
| | 3 | 79 | | { |
| | 1 | 80 | | GrantUseState.Stopped => CapabilityGrantUseResult.Stopped("The durable capability grant is stopp |
| | 1 | 81 | | GrantUseState.Cancelled => CapabilityGrantUseResult.Cancelled("The durable capability grant is c |
| | 1 | 82 | | GrantUseState.Accepted or GrantUseState.UseLimitExceeded => CapabilityGrantUseResult.UseLimitExc |
| | 0 | 83 | | GrantUseState.Unavailable or GrantUseState.Unspecified => CapabilityGrantUseResult.Unavailable( |
| | 0 | 84 | | "The durable capability grant use record has an unavailable state."), |
| | 0 | 85 | | _ => CapabilityGrantUseResult.Unavailable("The durable capability grant use record has an unknow |
| | 3 | 86 | | }; |
| | | 87 | | } |
| | | 88 | | |
| | 1 | 89 | | _ = Entries().Add(new CapabilityGrantUseEntity |
| | 1 | 90 | | { |
| | 1 | 91 | | Id = Guid.NewGuid(), |
| | 1 | 92 | | ConcurrencyStamp = GovernanceEntity.NewConcurrencyStamp(), |
| | 1 | 93 | | Issuer = grant.Issuer, |
| | 1 | 94 | | TokenId = grant.TokenId, |
| | 1 | 95 | | UseCount = 1, |
| | 1 | 96 | | State = GrantUseState.Accepted, |
| | 1 | 97 | | LastUsedUtc = normalizedUsedUtc, |
| | 1 | 98 | | RetainUntilUtc = retainUntilUtc |
| | 1 | 99 | | }); |
| | 1 | 100 | | _ = await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 101 | | return CapabilityGrantUseResult.Accepted(1); |
| | | 102 | | } |
| | 0 | 103 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 104 | | { |
| | 0 | 105 | | throw; |
| | | 106 | | } |
| | 1 | 107 | | catch (Exception exception) when ((exception is DbUpdateException or DbException) && attempt < options.Conte |
| | | 108 | | { |
| | 0 | 109 | | dbContext.ChangeTracker.Clear(); |
| | 0 | 110 | | await Task.Delay(TimeSpan.FromMilliseconds(10 * (attempt + 1)), cancellationToken).ConfigureAwait(false) |
| | 0 | 111 | | } |
| | 0 | 112 | | catch (InvalidOperationException) when (attempt < options.ContentionRetryCount) |
| | | 113 | | { |
| | 0 | 114 | | dbContext.ChangeTracker.Clear(); |
| | 0 | 115 | | await Task.Delay(TimeSpan.FromMilliseconds(10 * (attempt + 1)), cancellationToken).ConfigureAwait(false) |
| | | 116 | | } |
| | 1 | 117 | | catch (Exception exception) when (exception is DbUpdateException or DbException or InvalidOperationException |
| | | 118 | | { |
| | 1 | 119 | | dbContext.ChangeTracker.Clear(); |
| | 1 | 120 | | return CapabilityGrantUseResult.Unavailable("The EF Core capability grant use store could not answer the |
| | | 121 | | } |
| | | 122 | | } |
| | | 123 | | |
| | 0 | 124 | | return CapabilityGrantUseResult.Unavailable("The EF Core capability grant use store exhausted contention retries |
| | 5 | 125 | | } |
| | | 126 | | |
| | | 127 | | /// <summary>Marks an issuer-scoped grant as stopped.</summary> |
| | | 128 | | public ValueTask SetStoppedAsync( |
| | | 129 | | string issuer, |
| | | 130 | | string tokenId, |
| | | 131 | | DateTimeOffset retainUntilUtc, |
| | | 132 | | CancellationToken cancellationToken = default) |
| | | 133 | | { |
| | 1 | 134 | | return SetStateAsync(issuer, tokenId, retainUntilUtc, GrantUseState.Stopped, cancellationToken); |
| | | 135 | | } |
| | | 136 | | |
| | | 137 | | /// <summary>Marks an issuer-scoped grant as cancelled.</summary> |
| | | 138 | | public ValueTask SetCancelledAsync( |
| | | 139 | | string issuer, |
| | | 140 | | string tokenId, |
| | | 141 | | DateTimeOffset retainUntilUtc, |
| | | 142 | | CancellationToken cancellationToken = default) |
| | | 143 | | { |
| | 1 | 144 | | return SetStateAsync(issuer, tokenId, retainUntilUtc, GrantUseState.Cancelled, cancellationToken); |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <summary>Purges records only after their expiry-plus-skew retention horizon.</summary> |
| | | 148 | | public async ValueTask<int> PurgeExpiredAsync( |
| | | 149 | | DateTimeOffset utcNow, |
| | | 150 | | CancellationToken cancellationToken = default) |
| | | 151 | | { |
| | 1 | 152 | | return await Entries() |
| | 1 | 153 | | .Where(entity => entity.RetainUntilUtc < utcNow.ToUniversalTime()) |
| | 1 | 154 | | .ExecuteDeleteAsync(cancellationToken) |
| | 1 | 155 | | .ConfigureAwait(false); |
| | 1 | 156 | | } |
| | | 157 | | |
| | | 158 | | private async ValueTask SetStateAsync( |
| | | 159 | | string issuer, |
| | | 160 | | string tokenId, |
| | | 161 | | DateTimeOffset retainUntilUtc, |
| | | 162 | | GrantUseState state, |
| | | 163 | | CancellationToken cancellationToken) |
| | | 164 | | { |
| | 2 | 165 | | ArgumentException.ThrowIfNullOrWhiteSpace(issuer); |
| | 2 | 166 | | ArgumentException.ThrowIfNullOrWhiteSpace(tokenId); |
| | 2 | 167 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 168 | | |
| | 2 | 169 | | CapabilityGrantUseEntity? entity = await Entries().SingleOrDefaultAsync( |
| | 2 | 170 | | item => item.Issuer == issuer.Trim() && item.TokenId == tokenId.Trim(), cancellationToken).ConfigureAwait(fa |
| | 2 | 171 | | if (entity is null) |
| | | 172 | | { |
| | 2 | 173 | | _ = Entries().Add(new CapabilityGrantUseEntity |
| | 2 | 174 | | { |
| | 2 | 175 | | Id = Guid.NewGuid(), |
| | 2 | 176 | | ConcurrencyStamp = GovernanceEntity.NewConcurrencyStamp(), |
| | 2 | 177 | | Issuer = issuer.Trim(), |
| | 2 | 178 | | TokenId = tokenId.Trim(), |
| | 2 | 179 | | State = state, |
| | 2 | 180 | | LastUsedUtc = DateTimeOffset.UnixEpoch, |
| | 2 | 181 | | RetainUntilUtc = retainUntilUtc.ToUniversalTime() |
| | 2 | 182 | | }); |
| | | 183 | | } |
| | | 184 | | else |
| | | 185 | | { |
| | 0 | 186 | | entity.State = state; |
| | 0 | 187 | | entity.RetainUntilUtc = retainUntilUtc.ToUniversalTime(); |
| | 0 | 188 | | entity.ConcurrencyStamp = GovernanceEntity.NewConcurrencyStamp(); |
| | | 189 | | } |
| | | 190 | | |
| | 2 | 191 | | _ = await dbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false); |
| | 2 | 192 | | } |
| | | 193 | | |
| | | 194 | | private DbSet<CapabilityGrantUseEntity> Entries() |
| | | 195 | | { |
| | 15 | 196 | | return dbContext.Set<CapabilityGrantUseEntity>(); |
| | | 197 | | } |
| | | 198 | | |
| | | 199 | | private static DateTimeOffset AddClamped(DateTimeOffset value, TimeSpan duration) |
| | | 200 | | { |
| | 5 | 201 | | return value > DateTimeOffset.MaxValue - duration ? DateTimeOffset.MaxValue : value + duration; |
| | | 202 | | } |
| | | 203 | | } |