| | | 1 | | using ArturRios.Heimdall.Data.Configuration; |
| | | 2 | | using ArturRios.Heimdall.Domain.Entities; |
| | | 3 | | using ArturRios.Heimdall.Domain.Enums; |
| | | 4 | | using ArturRios.Heimdall.Domain.Persistence; |
| | | 5 | | using Microsoft.EntityFrameworkCore; |
| | | 6 | | using Npgsql; |
| | | 7 | | |
| | | 8 | | namespace ArturRios.Heimdall.Data.Persistence; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// <see cref="IScopeOwnerInvitations" /> on PostgreSQL. Every end is an <c>ExecuteUpdate</c> whose |
| | | 12 | | /// condition is "still open"; under READ COMMITTED a racing write that waits on the row re-reads it and |
| | | 13 | | /// finds the condition false, so it writes nothing. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <remarks> |
| | | 16 | | /// Acceptance spans two tables, so it is a transaction, as <see cref="ApplicationCredentialSlots" /> is: |
| | | 17 | | /// the conditional <c>UPDATE</c> first, and the <c>SCOPE_OWNER</c> insert only when it took. The insert is |
| | | 18 | | /// targeted SQL rather than a save of the person, whose whole row must never be written back (#237). |
| | | 19 | | /// </remarks> |
| | 68 | 20 | | public sealed class ScopeOwnerInvitations(AppDbContext context) : IScopeOwnerInvitations |
| | | 21 | | { |
| | | 22 | | public async Task<ScopeOwnerInvitationOpening> OpenAsync(ScopeOwnerInvitation invitation, DateTime now) |
| | | 23 | | { |
| | | 24 | | // An expired row still holds the pair's slot in the partial unique index; it ended at its expiry. |
| | 11 | 25 | | await context.ScopeOwnerInvitations |
| | 11 | 26 | | .Where(x => x.ScopeId == invitation.ScopeId && x.InviteePersonId == invitation.InviteePersonId && |
| | 11 | 27 | | x.EndedAt == null && x.ExpiresAt <= now) |
| | 22 | 28 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.EndedAt, x => (DateTime?)x.ExpiresAt)); |
| | | 29 | | |
| | 11 | 30 | | if (await FindOpenAsync(invitation, now) is { } open) |
| | | 31 | | { |
| | 2 | 32 | | return new ScopeOwnerInvitationOpening(open, Created: false); |
| | | 33 | | } |
| | | 34 | | |
| | 9 | 35 | | context.ScopeOwnerInvitations.Add(invitation); |
| | | 36 | | |
| | | 37 | | try |
| | | 38 | | { |
| | 9 | 39 | | await context.SaveChangesAsync(); |
| | | 40 | | |
| | 7 | 41 | | return new ScopeOwnerInvitationOpening(invitation, Created: true); |
| | | 42 | | } |
| | | 43 | | catch (DbUpdateException exception) |
| | 2 | 44 | | when (exception.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation }) |
| | | 45 | | { |
| | | 46 | | // A simultaneous request opened one first; the index refused this one. Answer with theirs. |
| | 2 | 47 | | context.Entry(invitation).State = EntityState.Detached; |
| | | 48 | | |
| | 2 | 49 | | var winner = await FindOpenAsync(invitation, now); |
| | | 50 | | |
| | 2 | 51 | | if (winner is null) |
| | | 52 | | { |
| | 0 | 53 | | throw; |
| | | 54 | | } |
| | | 55 | | |
| | 2 | 56 | | return new ScopeOwnerInvitationOpening(winner, Created: false); |
| | | 57 | | } |
| | 11 | 58 | | } |
| | | 59 | | |
| | | 60 | | public async Task<bool> TryEndAsync( |
| | | 61 | | ScopeOwnerInvitation invitation, ScopeOwnerInvitationOutcomes outcome, DateTime now) |
| | | 62 | | { |
| | 7 | 63 | | if (outcome == ScopeOwnerInvitationOutcomes.Accepted) |
| | | 64 | | { |
| | 1 | 65 | | throw new ArgumentException("An acceptance writes an ownership too; use TryAcceptAsync.", nameof(outcome)); |
| | | 66 | | } |
| | | 67 | | |
| | 6 | 68 | | var ended = await context.ScopeOwnerInvitations |
| | 6 | 69 | | .Where(x => x.Id == invitation.Id) |
| | 6 | 70 | | .Where(ScopeOwnerInvitation.OpenAt(now)) |
| | 12 | 71 | | .ExecuteUpdateAsync(set => set |
| | 12 | 72 | | .SetProperty(x => x.EndedAt, now) |
| | 12 | 73 | | .SetProperty(x => x.Outcome, outcome)) == 1; |
| | | 74 | | |
| | 6 | 75 | | if (ended) |
| | | 76 | | { |
| | 5 | 77 | | Record(invitation, now, outcome); |
| | | 78 | | } |
| | | 79 | | |
| | 6 | 80 | | return ended; |
| | 6 | 81 | | } |
| | | 82 | | |
| | | 83 | | public async Task<bool> TryAcceptAsync(ScopeOwnerInvitation invitation, DateTime now) |
| | | 84 | | { |
| | | 85 | | // The table name comes from the model, never from input, so building it into the SQL is safe; the |
| | | 86 | | // values stay parameters. |
| | 20 | 87 | | var ownerTable = context.Model.FindEntityType(typeof(ScopeOwner))!.GetSchemaQualifiedTableName(); |
| | 20 | 88 | | var strategy = context.Database.CreateExecutionStrategy(); |
| | | 89 | | |
| | 20 | 90 | | var accepted = await strategy.ExecuteAsync(async () => |
| | 20 | 91 | | { |
| | 20 | 92 | | await using var transaction = await context.Database.BeginTransactionAsync(); |
| | 20 | 93 | | |
| | 20 | 94 | | var ended = await context.ScopeOwnerInvitations |
| | 20 | 95 | | .Where(x => x.Id == invitation.Id) |
| | 20 | 96 | | .Where(ScopeOwnerInvitation.OpenAt(now)) |
| | 20 | 97 | | .Where(x => context.Scopes.Any(scope => scope.Id == x.ScopeId && !scope.IsDeleted)) |
| | 20 | 98 | | .Where(x => context.Persons |
| | 20 | 99 | | .Where(ScopeOwnerInvitation.EligibleInvitee) |
| | 20 | 100 | | .Any(person => person.Id == x.InviteePersonId)) |
| | 40 | 101 | | .ExecuteUpdateAsync(set => set |
| | 40 | 102 | | .SetProperty(x => x.EndedAt, now) |
| | 40 | 103 | | .SetProperty(x => x.Outcome, ScopeOwnerInvitationOutcomes.Accepted)) == 1; |
| | 20 | 104 | | |
| | 20 | 105 | | if (!ended) |
| | 20 | 106 | | { |
| | 12 | 107 | | await transaction.RollbackAsync(); |
| | 20 | 108 | | |
| | 12 | 109 | | return false; |
| | 20 | 110 | | } |
| | 20 | 111 | | |
| | 8 | 112 | | var sql = $"INSERT INTO {ownerTable} (scope_id, person_id) VALUES ({{0}}, {{1}}) ON CONFLICT DO NOTHING"; |
| | 8 | 113 | | await context.Database.ExecuteSqlRawAsync(sql, invitation.ScopeId, invitation.InviteePersonId); |
| | 20 | 114 | | |
| | 8 | 115 | | await transaction.CommitAsync(); |
| | 20 | 116 | | |
| | 8 | 117 | | return true; |
| | 20 | 118 | | }); |
| | | 119 | | |
| | 20 | 120 | | if (accepted) |
| | | 121 | | { |
| | 8 | 122 | | Record(invitation, now, ScopeOwnerInvitationOutcomes.Accepted); |
| | | 123 | | } |
| | | 124 | | |
| | 20 | 125 | | return accepted; |
| | 40 | 126 | | } |
| | | 127 | | |
| | | 128 | | public async Task<IReadOnlyList<Guid>> ForgetPersonsAsync(IReadOnlyCollection<long> personIds, DateTime now) |
| | | 129 | | { |
| | 15 | 130 | | if (personIds.Count == 0) |
| | | 131 | | { |
| | 1 | 132 | | return []; |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | // Table and column names come from the model, never from input, so building them into the SQL is |
| | | 136 | | // safe; the values stay parameters. |
| | 14 | 137 | | var invitationType = context.Model.FindEntityType(typeof(ScopeOwnerInvitation))!; |
| | 14 | 138 | | var table = invitationType.GetSchemaQualifiedTableName(); |
| | 14 | 139 | | var endedAt = Column(nameof(ScopeOwnerInvitation.EndedAt)); |
| | 14 | 140 | | var outcome = Column(nameof(ScopeOwnerInvitation.Outcome)); |
| | 14 | 141 | | var invitee = Column(nameof(ScopeOwnerInvitation.InviteePersonId)); |
| | 14 | 142 | | var publicId = Column(nameof(ScopeOwnerInvitation.PublicId)); |
| | 14 | 143 | | var ids = personIds.ToArray(); |
| | 14 | 144 | | var strategy = context.Database.CreateExecutionStrategy(); |
| | | 145 | | |
| | 14 | 146 | | return await strategy.ExecuteAsync(async () => |
| | 14 | 147 | | { |
| | 14 | 148 | | await using var transaction = await context.Database.BeginTransactionAsync(); |
| | 14 | 149 | | |
| | 14 | 150 | | // RETURNING answers with exactly the rows this UPDATE changed. A row a racing answer ended first |
| | 14 | 151 | | // fails the guard, so it is neither voided nor reported: every id returned is a void that took |
| | 14 | 152 | | // effect, and the caller audits each one (G-F7). |
| | 14 | 153 | | var sql = $$""" |
| | 14 | 154 | | UPDATE {{table}} SET {{endedAt}} = {0}, {{outcome}} = {1} |
| | 14 | 155 | | WHERE {{invitee}} = ANY({2}) AND {{endedAt}} IS NULL |
| | 14 | 156 | | RETURNING {{publicId}} AS "Value" |
| | 14 | 157 | | """; |
| | 14 | 158 | | var voided = await context.Database |
| | 14 | 159 | | .SqlQueryRaw<Guid>(sql, now, (short)ScopeOwnerInvitationOutcomes.Voided, ids) |
| | 14 | 160 | | .ToListAsync(); |
| | 14 | 161 | | |
| | 14 | 162 | | await context.ScopeOwnerInvitations |
| | 14 | 163 | | .Where(x => x.InvitedByPersonId != null && ids.Contains(x.InvitedByPersonId.Value)) |
| | 28 | 164 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.InvitedByPersonId, (long?)null)); |
| | 14 | 165 | | |
| | 14 | 166 | | await transaction.CommitAsync(); |
| | 14 | 167 | | |
| | 14 | 168 | | return (IReadOnlyList<Guid>)voided; |
| | 14 | 169 | | }); |
| | | 170 | | |
| | 56 | 171 | | string Column(string property) => invitationType.FindProperty(property)!.GetColumnName(); |
| | 29 | 172 | | } |
| | | 173 | | |
| | | 174 | | private Task<ScopeOwnerInvitation?> FindOpenAsync(ScopeOwnerInvitation invitation, DateTime now) => |
| | 13 | 175 | | context.ScopeOwnerInvitations.AsNoTracking() |
| | 13 | 176 | | .Where(x => x.ScopeId == invitation.ScopeId && x.InviteePersonId == invitation.InviteePersonId) |
| | 13 | 177 | | .Where(ScopeOwnerInvitation.OpenAt(now)) |
| | 13 | 178 | | .FirstOrDefaultAsync(); |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Brings the caller's instance in line with a write the change tracker did not see, as |
| | | 182 | | /// <c>AtomicWrites</c> does, so a later save does not write the old values back. |
| | | 183 | | /// </summary> |
| | | 184 | | private void Record(ScopeOwnerInvitation invitation, DateTime endedAt, ScopeOwnerInvitationOutcomes outcome) |
| | | 185 | | { |
| | 13 | 186 | | invitation.EndedAt = endedAt; |
| | 13 | 187 | | invitation.Outcome = outcome; |
| | | 188 | | |
| | 13 | 189 | | var entry = context.Entry(invitation); |
| | | 190 | | |
| | 13 | 191 | | if (entry.State is EntityState.Unchanged or EntityState.Modified) |
| | | 192 | | { |
| | 8 | 193 | | entry.Property(x => x.EndedAt).OriginalValue = endedAt; |
| | 8 | 194 | | entry.Property(x => x.EndedAt).IsModified = false; |
| | 8 | 195 | | entry.Property(x => x.Outcome).OriginalValue = outcome; |
| | 8 | 196 | | entry.Property(x => x.Outcome).IsModified = false; |
| | | 197 | | } |
| | 13 | 198 | | } |
| | | 199 | | } |