| | | 1 | | using ArturRios.Heimdall.Data.Configuration; |
| | | 2 | | using ArturRios.Heimdall.Domain.Entities; |
| | | 3 | | using ArturRios.Heimdall.Domain.Persistence; |
| | | 4 | | using Microsoft.EntityFrameworkCore; |
| | | 5 | | |
| | | 6 | | namespace ArturRios.Heimdall.Data.Persistence; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// <see cref="IApplicationCredentialSlots" /> on PostgreSQL: a transaction that locks the |
| | | 10 | | /// application's row, counts its live credentials, and inserts only below the limit. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <remarks> |
| | | 13 | | /// A count followed by an insert is a race on its own — two requests both count one, both |
| | | 14 | | /// insert, and the application holds three live secrets. <c>SELECT … FOR UPDATE</c> on the |
| | | 15 | | /// application's row makes a second issuer for the same application wait until the first commits, |
| | | 16 | | /// and then count the row the first inserted. Other applications are not blocked. Unlike |
| | | 17 | | /// <see cref="AtomicWrites" />, this needs a transaction, because the rule spans rows a single |
| | | 18 | | /// conditional <c>UPDATE</c> cannot see. |
| | | 19 | | /// </remarks> |
| | 20 | 20 | | public sealed class ApplicationCredentialSlots(AppDbContext context) : IApplicationCredentialSlots |
| | | 21 | | { |
| | | 22 | | public async Task<bool> TryAddWithinLimitAsync(ApplicationCredential credential, int maxLive, DateTime now) |
| | | 23 | | { |
| | | 24 | | // The table name comes from the model, never from input, so building it into the SQL is safe; |
| | | 25 | | // the id stays a parameter. |
| | 16 | 26 | | var applicationTable = context.Model.FindEntityType(typeof(Application))!.GetSchemaQualifiedTableName(); |
| | 16 | 27 | | var strategy = context.Database.CreateExecutionStrategy(); |
| | | 28 | | |
| | 16 | 29 | | return await strategy.ExecuteAsync(async () => |
| | 16 | 30 | | { |
| | 16 | 31 | | await using var transaction = await context.Database.BeginTransactionAsync(); |
| | 16 | 32 | | |
| | 16 | 33 | | var sql = $"SELECT 1 FROM {applicationTable} WHERE id = {{0}} FOR UPDATE"; |
| | 16 | 34 | | await context.Database.ExecuteSqlRawAsync(sql, credential.ApplicationId); |
| | 16 | 35 | | |
| | 16 | 36 | | var live = await context.ApplicationCredentials |
| | 16 | 37 | | .Where(x => x.ApplicationId == credential.ApplicationId) |
| | 16 | 38 | | .CountAsync(ApplicationCredential.LiveAt(now)); |
| | 16 | 39 | | |
| | 16 | 40 | | if (live >= maxLive) |
| | 16 | 41 | | { |
| | 7 | 42 | | await transaction.RollbackAsync(); |
| | 16 | 43 | | |
| | 7 | 44 | | return false; |
| | 16 | 45 | | } |
| | 16 | 46 | | |
| | 9 | 47 | | context.ApplicationCredentials.Add(credential); |
| | 9 | 48 | | await context.SaveChangesAsync(); |
| | 9 | 49 | | await transaction.CommitAsync(); |
| | 16 | 50 | | |
| | 9 | 51 | | return true; |
| | 16 | 52 | | }); |
| | 32 | 53 | | } |
| | | 54 | | } |