From f726101207d3176ffb8c3d85f4d3b1fd135cf882 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 14 Nov 2026 06:08:36 +0000 Subject: [PATCH] Account merge ledger: one write gate for every writer, held across the standing read and the save WriteAsAsync takes a shared Postgres advisory lock on the account (the key the chain trigger locks exclusively) across the standing read and the writer's save; CommitAsync takes the exclusive lock before it reduces. Votes, appraisals, sealed commit and reveal, patron events (RecordSupportEventAsync routes and journals in the same save, so the manual Ledger door obeys it too) and the Heimdall sign-in pass through it; SupportTargetAsync, MayWriteAsync and JournalIntakeAsync are deleted. A folded or frozen account's sign-in writes no membership. A retry of an event stranded on the folded account journals nothing. Tests: Down refuses in every merge state, Stripe journal prior owner and undo, the lock racing a freeze and a commit on live Postgres. Docs say what the lock guarantees and what it does not. Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 2 +- docs/account-merge.md | 6 +- .../ConceptVotes/ConceptAppraisalService.cs | 56 ++--- .../Features/Heimdall/HeimdallAuthService.cs | 123 +++++----- .../HeimdallPatronSupportIntakeService.cs | 38 +--- .../Features/Membership/AccountMergeLedger.cs | 81 ++++--- .../Motions/MotionGovernanceService.cs | 58 +++-- .../Features/Motions/SealedBallotService.cs | 91 ++++---- .../Features/Patronage/PatronageService.cs | 214 ++++++++++-------- .../Patronage/StripeWebhookService.cs | 58 ++--- .../AccountMergeHttpTests.cs | 58 ++++- .../AccountMergePostgresTests.cs | 144 +++++++++++- .../HeimdallCompletionTests.cs | 48 ++++ 13 files changed, 644 insertions(+), 333 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2f0fd40..e822cf2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,7 +83,7 @@ Then start the first implementation milestone: ## Live Postgres tests -Most tests run on the in-memory EF provider, which enforces no unique index, transaction, concurrency token or trigger. The tests that need a real server (`tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs`: commit atomicity, the `(MergeId, Seq)` unique index, the sweeper racing the saga, overlapping merges refused by the database, the one-current-Patron-snapshot index under racing restages, the intake journal `Seq`, the migration's roll-forward-only guard) run only when `BIFROST_TEST_PG` holds a connection string with no `Database=`, for a role that may create databases; otherwise they are skipped with that reason. Each test creates its own database, builds it through the real migrations and the class drops it, so point the variable at a disposable server: +Most tests run on the in-memory EF provider, which enforces no unique index, transaction, concurrency token or trigger. The tests that need a real server (`tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs`: commit atomicity, the `(MergeId, Seq)` unique index, the sweeper racing the saga, overlapping merges refused by the database, the one-current-Patron-snapshot index under racing restages, the intake journal `Seq`, the write gate's shared lock racing a merge's freeze and commit, the migration's roll-forward-only guard) run only when `BIFROST_TEST_PG` holds a connection string with no `Database=`, for a role that may create databases; otherwise they are skipped with that reason. Each test creates its own database, builds it through the real migrations and the class drops it, so point the variable at a disposable server: ```bash BIFROST_TEST_PG='Host=127.0.0.1;Port=54329;Username=postgres' dotnet test tests/Bifrost.Web.Tests --filter FullyQualifiedName~AccountMergePostgresTests diff --git a/docs/account-merge.md b/docs/account-merge.md index 5dc1068..cbb0460 100644 --- a/docs/account-merge.md +++ b/docs/account-merge.md @@ -18,9 +18,9 @@ An account's standing is derived from that state on every request; there is no ` | Committed, Final, UndoRequested, HeimdallReversed | `Folded(mergeId, survivorId)` | | Proposed, Failed, Undone | none | -An alias is one hop: a landed merge's survivor never folds into a third account (the `folded_is_survivor` block), so a folded account's survivor is always the account that carries the person. Heimdall patron intake reads the standing: an event for a folded account's Heimdall id records on the survivor and is journalled on the merge (`JournalIntakeAsync`, idempotent for a provider's retry), so an undo moves it back. +An alias is one hop: a landed merge's survivor never folds into a third account (the `folded_is_survivor` block), so a folded account's survivor is always the account that carries the person. Every patron event is recorded through `PatronageService.RecordSupportEventAsync`, which writes through the gate below: an event for a folded account (Heimdall intake, Stripe webhook, the admin Ledger's manual record) records on the survivor and is journalled in the same save, so an undo moves it back; a provider retry returns the stored event and journals it once if it sits on the survivor. -`CurrentBifrostActorAccessor` is the one gate for every cookie-authenticated route: a Frozen or Folded account resolves to an authenticated actor with no account (`CurrentBifrostActor.Merge` set), so no route can act as it. The OIDC authorize endpoint denies it with `MergedDescription`, and `ChatRefusalAsync` refuses its token and userinfo, so the logout reconciler ends its chat sessions. The accessor looks an account up by identity, then Heimdall id, then GitHub id; the first hit wins and several matching rows can no longer throw. The same standing is read at the other doors: the desk bearer door (`ActiveMemberIdAsync`) refuses a Frozen or Folded subject, the linked-accounts page and the link step of Heimdall completion refuse one (no login linked or unlinked, no passkey enrolled while the saga moves them), and the vote and appraisal writers read it again at the write, so an actor resolved before the merge froze the account writes nothing after it. +`CurrentBifrostActorAccessor` is the one gate for every cookie-authenticated route: a Frozen or Folded account resolves to an authenticated actor with no account (`CurrentBifrostActor.Merge` set), so no route can act as it. The OIDC authorize endpoint denies it with `MergedDescription`, and `ChatRefusalAsync` refuses its token and userinfo, so the logout reconciler ends its chat sessions. The accessor looks an account up by identity, then Heimdall id, then GitHub id; the first hit wins and several matching rows can no longer throw. The same standing is read at the other doors: the desk bearer door (`ActiveMemberIdAsync`) refuses a Frozen or Folded subject, the linked-accounts page and the link step of Heimdall completion refuse one (no login linked or unlinked, no passkey enrolled while the saga moves them), and every writer reads it again at the write, through the gate below, so an actor resolved before the merge froze the account writes nothing after it. ## Plan, commit, undo, finalize @@ -54,6 +54,6 @@ Bifrost is **roll-forward only** once a merge exists (`heimdall-body:ruling:merg ## Not covered -`MembershipSynchronizationService` still writes the profile of a GitHub-signed-in row that is not merged. Sealed-ballot rows of a folded account on a motion that is already closed stay as they are. Every writer that acts for an account (votes, concept appraisals, sealed-ballot commit and reveal) reads standing through `AccountMergeLedger.MayWriteAsync` after loading what it changes and before it mutates, and an account with a standing writes nothing. Patron events (the Heimdall intake and the Stripe webhook) route through `AccountMergeLedger.SupportTargetAsync` immediately before they record: a folded account's event lands on the survivor and is journalled, so undo moves it back. Each of these is a read followed by a save, so a request whose read precedes the commit by microseconds and whose save follows it lands on the folded account: that window is not closed. Closing it needs a lock held across the read and the save, or the tally-time voiding of design section 7; neither is built, and no operator void tool exists. A patron event or vote that falls in it stays on the folded account until it is corrected by hand in the database. +`MembershipSynchronizationService` still writes the profile of a GitHub-signed-in row that is not merged. Sealed-ballot rows of a folded account on a motion that is already closed stay as they are. Every writer that acts for an account (votes, concept appraisals, sealed-ballot commit and reveal, patron events, the Heimdall sign-in's membership) passes through `AccountMergeLedger.WriteAsAsync`. On Postgres it opens a transaction, takes a shared advisory lock on the account (`pg_advisory_xact_lock_shared(hashtextextended(id::text, 0))`, the key the chain trigger takes exclusively when a merge row is inserted or changes state), reads standing, runs the writer's save and commits. `CommitAsync` takes the exclusive lock on the folded account before it reduces, then re-reads the merge. So: a writer whose standing read found no merge saves before a merge can freeze or fold the account, and the commit's reduction sees what it saved; a merge that is already frozen or folded when the writer reads is refused (votes, appraisals, ballots, sign-in membership) or routed (patron events). Guaranteed only for writes made through the gate, and only on Postgres: the in-memory provider has no lock or transaction (tests that rest on the lock run on live Postgres), and a writer that catches a database error inside the gate cannot continue, because the transaction is aborted. Not closed: writers outside the gate (nothing in the code base today; a new one must use it), and a writer's own stale reads taken before the gate opened (the motion a vote was loaded with), which concern the motion, not the account's standing. No operator void tool exists. `UX_TierSnapshots_MembershipId_CurrentPatron` allows one current Patron snapshot per membership, so two restages of one survivor racing cannot both leave a current snapshot: the loser's save fails on the unique index, a merge commit rolls back whole and is retried by the saga, and a patron refresh re-reads and derives again. diff --git a/src/Bifrost.Web/Features/ConceptVotes/ConceptAppraisalService.cs b/src/Bifrost.Web/Features/ConceptVotes/ConceptAppraisalService.cs index 17e9ddd..602ac7a 100644 --- a/src/Bifrost.Web/Features/ConceptVotes/ConceptAppraisalService.cs +++ b/src/Bifrost.Web/Features/ConceptVotes/ConceptAppraisalService.cs @@ -81,21 +81,42 @@ public sealed class ConceptAppraisalService( ? string.Empty : NetworkPrefix.Tag(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength, opts.NetworkTagSecret); - var existing = await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken); + // A voter resolved before a merge froze the account must not write an appraisal after it: the write gate reads standing at the write. + Task Write() => voter.UserAccountId is { } voterAccountId + ? AccountMergeLedger.WriteAsAsync( + dbContext, + voterAccountId, + standing => standing is null ? WriteAppraisalAsync(subject, voter, stance, tag, cancellationToken) : Task.FromResult(CastResult.NoVoter), + cancellationToken) + : WriteAppraisalAsync(subject, voter, stance, tag, cancellationToken); - // A voter resolved before a merge froze the account must not write an appraisal after it: standing is read again at the write. - if (voter.UserAccountId is { } voterAccountId && - !await AccountMergeLedger.MayWriteAsync(dbContext, voterAccountId, cancellationToken)) + try { - return CastResult.NoVoter; + return await Write(); } + catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: UniqueViolation }) + { + // A concurrent cast by the same voter won the insert (and the failed save aborted the gate's transaction): go through the + // gate again, which now finds their row and applies this stance to it, once. + dbContext.ChangeTracker.Clear(); + if (await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken) is null) + { + throw; + } + return await Write(); + } + } + + private async Task WriteAppraisalAsync(ConceptSubject subject, VoterIdentity voter, ConceptStance stance, string tag, CancellationToken cancellationToken) + { + var existing = await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken); if (existing is not null) { return await ApplyStanceAsync(existing, stance, tag, cancellationToken); } - var row = new ConceptAppraisal + dbContext.ConceptAppraisals.Add(new ConceptAppraisal { SubjectId = subject.Id, VoterKey = voter.Key, @@ -104,26 +125,9 @@ public sealed class ConceptAppraisalService( UserAccountId = voter.UserAccountId, NetworkTag = tag, CastAtUtc = timeProvider.GetUtcNow() - }; - dbContext.ConceptAppraisals.Add(row); - - try - { - await dbContext.SaveChangesAsync(cancellationToken); - return CastResult.Recorded; - } - catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: UniqueViolation }) - { - // A concurrent cast by the same voter won the insert: apply this stance to their row, once. - dbContext.Entry(row).State = EntityState.Detached; - var winner = await FindAppraisalAsync(subject.Id, voter.Key, cancellationToken); - if (winner is null) - { - throw; - } - - return await ApplyStanceAsync(winner, stance, tag, cancellationToken); - } + }); + await dbContext.SaveChangesAsync(cancellationToken); + return CastResult.Recorded; } public async Task RetractAsync( diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs index aa2416e..bb413a9 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs @@ -803,76 +803,87 @@ public sealed class HeimdallAuthService( .ThenInclude(x => x.TierSnapshots) .SingleOrDefaultAsync(x => x.HeimdallAccountId == accountId, cancellationToken); - if (userAccount is null) + // An existing account is written as that account, through the merge ledger's write gate: a merge cannot fold it between the standing + // read and the save. A new account has no merge to race. + return userAccount is null + ? await PersistAsync(null) + : await AccountMergeLedger.WriteAsAsync(dbContext, userAccount.Id, PersistAsync, cancellationToken); + + async Task PersistAsync(MergeStanding? standing) { - userAccount = new UserAccount + if (userAccount is null) { - HeimdallAccountId = accountId, - DisplayName = displayName, - CreatedAtUtc = now, - LastSeenAtUtc = now, - MemberProfile = new MemberProfile + userAccount = new UserAccount { + HeimdallAccountId = accountId, + DisplayName = displayName, + CreatedAtUtc = now, + LastSeenAtUtc = now, + MemberProfile = new MemberProfile + { + Nickname = displayName, + Headline = $"Verified through Heimdall {provider}", + UpdatedAtUtc = now + }, + Membership = new Bifrost.Web.Domain.Membership + { + Status = grantMemberAccess ? MembershipStatus.Active : MembershipStatus.Authenticated, + CreatedAtUtc = now, + ApprovedAtUtc = grantMemberAccess ? now : null, + Notes = grantMemberAccess + ? "Activated by Heimdall member access claim" + : $"Identity verified through Heimdall {provider}" + } + }; + dbContext.UserAccounts.Add(userAccount); + } + else + { + userAccount.DisplayName = displayName; + userAccount.LastSeenAtUtc = now; + userAccount.MemberProfile ??= new MemberProfile + { + UserAccountId = userAccount.Id, Nickname = displayName, Headline = $"Verified through Heimdall {provider}", UpdatedAtUtc = now - }, - Membership = new Bifrost.Web.Domain.Membership + }; + if (userAccount.Membership is null && standing is null) { - Status = grantMemberAccess ? MembershipStatus.Active : MembershipStatus.Authenticated, - CreatedAtUtc = now, - ApprovedAtUtc = grantMemberAccess ? now : null, - Notes = grantMemberAccess - ? "Activated by Heimdall member access claim" - : $"Identity verified through Heimdall {provider}" + // Added explicitly: a row with a preset key assigned to a tracked account is taken for an existing one and the save fails. + userAccount.Membership = new Bifrost.Web.Domain.Membership { UserAccountId = userAccount.Id, CreatedAtUtc = now }; + dbContext.Memberships.Add(userAccount.Membership); + } + + // A suspension is an admin's decision: the claim neither lifts it nor, absent, imposes it. A merged row is terminal: the claim never reactivates it. + // A folded account, or one a merge has frozen, is an alias of its survivor: sign-in neither creates nor activates a membership for it. + if (grantMemberAccess && standing is null && userAccount.Membership is { IsMerged: false, Status: not MembershipStatus.Suspended }) + { + userAccount.Membership.Status = MembershipStatus.Active; + userAccount.Membership.ApprovedAtUtc ??= now; } - }; - dbContext.UserAccounts.Add(userAccount); - } - else - { - userAccount.DisplayName = displayName; - userAccount.LastSeenAtUtc = now; - userAccount.MemberProfile ??= new MemberProfile - { - UserAccountId = userAccount.Id, - Nickname = displayName, - Headline = $"Verified through Heimdall {provider}", - UpdatedAtUtc = now - }; - if (userAccount.Membership is null) - { - // Added explicitly: a row with a preset key assigned to a tracked account is taken for an existing one and the save fails. - userAccount.Membership = new Bifrost.Web.Domain.Membership { UserAccountId = userAccount.Id, CreatedAtUtc = now }; - dbContext.Memberships.Add(userAccount.Membership); } - // A suspension is an admin's decision: the claim neither lifts it nor, absent, imposes it. A merged row is terminal: the claim never reactivates it. - if (grantMemberAccess && userAccount.Membership.Status != MembershipStatus.Suspended && !userAccount.Membership.IsMerged) + userAccount.MemberProfile!.Nickname = displayName; + userAccount.MemberProfile.UpdatedAtUtc = now; + await bifrostIdentityService.EnsureIdentityAsync( + userAccount, + displayName, + cancellationToken); + if (grantMemberAccess && userAccount.Membership is { Status: MembershipStatus.Active }) { - userAccount.Membership.Status = MembershipStatus.Active; - userAccount.Membership.ApprovedAtUtc ??= now; + ApplicationBootstrapper.EnsureRole( + userAccount.Membership, + MemberRole.StandardMember, + null, + now, + "Heimdall member access"); } - } - userAccount.MemberProfile!.Nickname = displayName; - userAccount.MemberProfile.UpdatedAtUtc = now; - await bifrostIdentityService.EnsureIdentityAsync( - userAccount, - displayName, - cancellationToken); - if (grantMemberAccess && userAccount.Membership!.Status == MembershipStatus.Active) - { - ApplicationBootstrapper.EnsureRole( - userAccount.Membership!, - MemberRole.StandardMember, - null, - now, - "Heimdall member access"); - } + await dbContext.SaveChangesAsync(cancellationToken); - await dbContext.SaveChangesAsync(cancellationToken); - return userAccount; + return userAccount!; + } } private static HeimdallEntitlementPolicy BuildDiscordPolicy(HeimdallOptions options) diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs index 57c565f..02b41c2 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallPatronSupportIntakeService.cs @@ -5,7 +5,6 @@ using System.Text.Json.Serialization; using Bifrost.Web.Configuration; using Bifrost.Web.Data; using Bifrost.Web.Domain; -using Bifrost.Web.Features.Membership; using Bifrost.Web.Features.Patronage; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -15,7 +14,6 @@ namespace Bifrost.Web.Features.Heimdall; public sealed class HeimdallPatronSupportIntakeService( BifrostDbContext dbContext, PatronageService patronageService, - AccountMergeLedger mergeLedger, IOptions heimdallOptions) { private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) @@ -70,30 +68,21 @@ public sealed class HeimdallPatronSupportIntakeService( .AsNoTracking() .SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken); - if (existingEvent is not null) - { - // A provider retry of an event already processed: journal it if the account has since folded (idempotent). - if (user is not null && await mergeLedger.SupportTargetAsync(user.Id, cancellationToken) is { MergeId: { } retriedMergeId }) - { - await mergeLedger.JournalIntakeAsync(retriedMergeId, user.Id, existingEvent.Id, cancellationToken); - } - - return HeimdallPatronSupportIntakeResult.Processed( - $"Already processed {request.Provider} patron support event {request.ProviderEventId}.", - existingEvent.Id); - } - if (user is null) { - return HeimdallPatronSupportIntakeResult.BadRequest( - $"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}."); + return existingEvent is not null + ? HeimdallPatronSupportIntakeResult.Processed( + $"Already processed {request.Provider} patron support event {request.ProviderEventId}.", + existingEvent.Id) + : HeimdallPatronSupportIntakeResult.BadRequest( + $"No Bifrost account is linked to Heimdall account {request.HeimdallAccountId}."); } - // A folded account's events record on the survivor and are journalled on the merge, so an undo moves them back. - var target = await mergeLedger.SupportTargetAsync(user.Id, cancellationToken); + // The write gate behind RecordSupportEventAsync routes a folded account's event to its survivor and journals it, and on a + // provider retry returns the stored event, journalling it if it sits on the survivor and was left unjournalled. var supportEvent = await patronageService.RecordSupportEventAsync( actorUserAccountId: null, - userAccountId: target.RecordOnAccountId, + userAccountId: user.Id, request.Kind, request.Amount, request.CurrencyCode, @@ -107,13 +96,10 @@ public sealed class HeimdallPatronSupportIntakeService( request.Notes, cancellationToken); - if (target.MergeId is { } mergeId) - { - await mergeLedger.JournalIntakeAsync(mergeId, user.Id, supportEvent.Id, cancellationToken); - } - return HeimdallPatronSupportIntakeResult.Processed( - $"Processed {request.Provider} patron support event {request.ProviderEventId}.", + existingEvent is not null + ? $"Already processed {request.Provider} patron support event {request.ProviderEventId}." + : $"Processed {request.Provider} patron support event {request.ProviderEventId}.", supportEvent.Id); } diff --git a/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs b/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs index f540061..c84d6f8 100644 --- a/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs +++ b/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs @@ -7,9 +7,6 @@ using Microsoft.EntityFrameworkCore; namespace Bifrost.Web.Features.Membership; /// How an account stands under a merge: the folded account of an unfinished merge is Frozen, of a landed one Folded. -/// Where a patron event for an account lands; is set when the account is folded and the event must be journalled. -public sealed record SupportTarget(Guid ForAccountId, Guid RecordOnAccountId, Guid? MergeId); - public abstract record MergeStanding(Guid MergeId) { public sealed record Frozen(Guid MergeId) : MergeStanding(MergeId); @@ -74,23 +71,45 @@ public sealed class AccountMergeLedger( } /// - /// The one standing-at-write rule: an account with a merge standing (frozen or folded) writes nothing as itself. Every writer that - /// acts for an account (votes, appraisals, sealed ballots) calls this after loading what it will change and before it mutates, - /// so an actor resolved before the merge froze the account cannot write after it. It reads, then the writer saves: the - /// microseconds between the two are the window the saga cannot close without a lock or tally-time voiding (docs/account-merge.md). + /// The one gate every writer that acts for an account passes through (votes, appraisals, sealed ballots, patron events, the Heimdall + /// sign-in's membership). On Postgres it holds a shared advisory lock on the account, the key the chain trigger locks exclusively + /// when a merge row is inserted or changes state and that takes exclusively before it reduces, across the + /// standing read and everything saves, then commits. So a merge cannot freeze or fold the account between a + /// writer's standing read and its save: it waits for the writer, and a writer that starts after it reads the new standing. The + /// lock covers writes made through this gate and nothing else; it is held until the transaction ends, so a writer must not + /// catch a database error inside and carry on (the transaction is already aborted). On the in-memory + /// provider there is no lock and no transaction: the standing is read, then the writer saves. /// - public static async Task MayWriteAsync(BifrostDbContext db, Guid userAccountId, CancellationToken cancellationToken) => - await StandingAsync(db, userAccountId, cancellationToken) is null; + public static async Task WriteAsAsync(BifrostDbContext db, Guid userAccountId, Func> write, CancellationToken cancellationToken) + { + await using var transaction = await BeginAsync(db, cancellationToken); + await LockAsync(db, userAccountId, exclusive: false, cancellationToken); + var result = await write(await StandingAsync(db, userAccountId, cancellationToken)); + if (transaction is not null) + { + await transaction.CommitAsync(cancellationToken); + } - /// - /// The one routing of patron support: an event for a folded account lands on its survivor, anything else on the account itself. - /// The Heimdall intake and the Stripe webhook both resolve through here, immediately before they record, and journal a folded - /// event with . - /// - public async Task SupportTargetAsync(Guid userAccountId, CancellationToken cancellationToken) => - await StandingAsync(dbContext, userAccountId, cancellationToken) is MergeStanding.Folded folded - ? new SupportTarget(userAccountId, folded.SurvivorId, folded.MergeId) - : new SupportTarget(userAccountId, userAccountId, null); + return result; + } + + /// A transaction for the caller to commit, or null where there is none to open: not Postgres, or one already open (its owner commits). + private static async Task BeginAsync(BifrostDbContext db, CancellationToken cancellationToken) => + db.Database.IsNpgsql() && db.Database.CurrentTransaction is null ? await db.Database.BeginTransactionAsync(cancellationToken) : null; + + /// The account's lock, on the key the chain trigger uses (hashtextextended of the id's text). A no-op off Postgres. + private static async Task LockAsync(BifrostDbContext db, Guid userAccountId, bool exclusive, CancellationToken cancellationToken) + { + if (!db.Database.IsNpgsql()) + { + return; + } + + var key = userAccountId.ToString(); + await (exclusive + ? db.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock(hashtextextended({key}, 0))", cancellationToken) + : db.Database.ExecuteSqlInterpolatedAsync($"SELECT pg_advisory_xact_lock_shared(hashtextextended({key}, 0))", cancellationToken)); + } /// Writes nothing. lets the saga re-plan a merge it already holds without it blocking itself. public async Task PlanAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? exceptMergeId = null) @@ -190,6 +209,12 @@ public sealed class AccountMergeLedger( public async Task CommitAsync(Guid mergeId, CancellationToken cancellationToken) { var merge = await dbContext.AccountMerges.SingleAsync(x => x.Id == mergeId, cancellationToken); + + // The exclusive lock first, so no writer that read the folded account's standing is still to save when the reduction reads its + // rows, then the state again: a commit that waited here found the merge landed and returns its receipt. + await using var transaction = await BeginAsync(dbContext, cancellationToken); + await LockAsync(dbContext, merge.FoldedUserAccountId, exclusive: true, cancellationToken); + await dbContext.Entry(merge).ReloadAsync(cancellationToken); if (merge.State is AccountMergeState.Committed or AccountMergeState.Final) { return merge; @@ -221,6 +246,11 @@ public sealed class AccountMergeLedger( merge.CommittedUtc = now; merge.GraceEndsUtc = now + Grace; await dbContext.SaveChangesAsync(cancellationToken); + if (transaction is not null) + { + await transaction.CommitAsync(cancellationToken); + } + return merge; } catch @@ -444,25 +474,24 @@ public sealed class AccountMergeLedger( } /// - /// Journals a patron event that landed on a folded account's survivor during grace, so undo moves it back with the rest. Idempotent: - /// the intake calls it again when the provider retries an event it already processed. + /// Stages the journal entry for a patron event that is on a folded account's survivor, so undo moves it back with the rest; saved + /// with the event by , the only caller. Idempotent: a provider retry stages nothing. /// - public async Task JournalIntakeAsync(Guid mergeId, Guid foldedUserAccountId, Guid supportEventId, CancellationToken cancellationToken) + public static async Task StageIntakeJournalAsync(BifrostDbContext db, Guid mergeId, Guid foldedUserAccountId, Guid supportEventId, DateTimeOffset now, CancellationToken cancellationToken) { - if (await dbContext.AccountMergeEntries.AnyAsync( + if (await db.AccountMergeEntries.AnyAsync( x => x.MergeId == mergeId && x.Kind == AccountMergeEntryKind.PatronSupportEvent && x.RecordId == supportEventId, cancellationToken)) { return; } - var seq = await dbContext.AccountMergeEntries.Where(x => x.MergeId == mergeId).MaxAsync(x => (int?)x.Seq, cancellationToken) ?? 0; - dbContext.AccountMergeEntries.Add(Journal( + var seq = await db.AccountMergeEntries.Where(x => x.MergeId == mergeId).MaxAsync(x => (int?)x.Seq, cancellationToken) ?? 0; + db.AccountMergeEntries.Add(Journal( mergeId, seq + 1, new MergePlanEntry(AccountMergeEntryKind.PatronSupportEvent, AccountMergeEntryAction.Moved, supportEventId, foldedUserAccountId), - timeProvider.GetUtcNow())); - await dbContext.SaveChangesAsync(cancellationToken); + now)); } private sealed class Reduction( diff --git a/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs b/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs index cfe46b6..ba60a2f 100644 --- a/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs +++ b/src/Bifrost.Web/Features/Motions/MotionGovernanceService.cs @@ -63,34 +63,44 @@ public sealed class MotionGovernanceService( return; } - // An actor resolved before a merge froze this account must not write a vote after it: standing is read again at the write. - if (!await AccountMergeLedger.MayWriteAsync(dbContext, actorUser.Id, cancellationToken)) + // An actor resolved before a merge froze this account must not write a vote after it: the write gate reads standing at the write. + var wrote = await AccountMergeLedger.WriteAsAsync(dbContext, actorUser.Id, async standing => + { + if (standing is not null) + { + return false; + } + + var vote = motion.Votes.SingleOrDefault(x => x.UserAccountId == actorUser.Id); + if (vote is null) + { + dbContext.Votes.Add(new Vote + { + MotionId = motionId, + UserAccountId = actorUser.Id, + Choice = choice, + Weight = actor.EffectiveVotingWeight, + Comment = comment?.Trim() ?? string.Empty, + CastAtUtc = timeProvider.GetUtcNow() + }); + } + else + { + vote.Choice = choice; + vote.Weight = actor.EffectiveVotingWeight; + vote.Comment = comment?.Trim() ?? string.Empty; + vote.CastAtUtc = timeProvider.GetUtcNow(); + } + + await dbContext.SaveChangesAsync(cancellationToken); + return true; + }, cancellationToken); + + if (!wrote) { return; } - var vote = motion.Votes.SingleOrDefault(x => x.UserAccountId == actorUser.Id); - if (vote is null) - { - dbContext.Votes.Add(new Vote - { - MotionId = motionId, - UserAccountId = actorUser.Id, - Choice = choice, - Weight = actor.EffectiveVotingWeight, - Comment = comment?.Trim() ?? string.Empty, - CastAtUtc = timeProvider.GetUtcNow() - }); - } - else - { - vote.Choice = choice; - vote.Weight = actor.EffectiveVotingWeight; - vote.Comment = comment?.Trim() ?? string.Empty; - vote.CastAtUtc = timeProvider.GetUtcNow(); - } - - await dbContext.SaveChangesAsync(cancellationToken); await auditTrailService.RecordAsync( actorUser.Id, nameof(Motion), diff --git a/src/Bifrost.Web/Features/Motions/SealedBallotService.cs b/src/Bifrost.Web/Features/Motions/SealedBallotService.cs index f6e2922..7fc3af0 100644 --- a/src/Bifrost.Web/Features/Motions/SealedBallotService.cs +++ b/src/Bifrost.Web/Features/Motions/SealedBallotService.cs @@ -100,22 +100,27 @@ public sealed class SealedBallotService( throw new SealedBallotException(SealedBallotFailure.Invalid, "A commitment is 64 lowercase hex characters (SHA-256)."); } - var ballot = await dbContext.SealedBallots - .SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken); - await RequireStandingAsync(user.Id, cancellationToken); - if (ballot is null) + var ballot = await AccountMergeLedger.WriteAsAsync(dbContext, user.Id, async standing => { - ballot = new SealedBallot { MotionId = motionId, UserAccountId = user.Id }; - dbContext.SealedBallots.Add(ballot); - } - else - { - ballot.Revision++; - } + RequireStanding(standing); + var written = await dbContext.SealedBallots + .SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken); + if (written is null) + { + written = new SealedBallot { MotionId = motionId, UserAccountId = user.Id }; + dbContext.SealedBallots.Add(written); + } + else + { + written.Revision++; + } + + written.Commitment = commitment; + written.CommittedAtUtc = now; + await dbContext.SaveChangesAsync(cancellationToken); + return written; + }, cancellationToken); - ballot.Commitment = commitment; - ballot.CommittedAtUtc = now; - await dbContext.SaveChangesAsync(cancellationToken); await auditTrailService.RecordAsync( user.Id, nameof(Motion), motionId, "sealed.committed", $"{actor.DisplayName} committed a sealed ballot (revision {ballot.Revision}), commitment {commitment}.", @@ -161,37 +166,43 @@ public sealed class SealedBallotService( // RevealSeq and Status are concurrency tokens. A conflict means either the close froze the set (refuse, truthfully) or // another voter's reveal landed first while the window is still open (re-read the row and write again). - for (var attempt = 0; ; attempt++) + // Standing is read once, under the gate's lock, which holds across every attempt: a merge cannot freeze the account between them. + await AccountMergeLedger.WriteAsAsync(dbContext, user.Id, async standing => { - await RequireStandingAsync(user.Id, cancellationToken); - ballot.RevealedCandidate = candidate; - ballot.RevealedReason = reason; - ballot.Salt = document.Salt; - ballot.RevealedAtUtc = now; - motion.RevealSeq++; - try + RequireStanding(standing); + for (var attempt = 0; ; attempt++) { - await dbContext.SaveChangesAsync(cancellationToken); - break; - } - catch (DbUpdateConcurrencyException error) - { - foreach (var entry in error.Entries) + ballot.RevealedCandidate = candidate; + ballot.RevealedReason = reason; + ballot.Salt = document.Salt; + ballot.RevealedAtUtc = now; + motion.RevealSeq++; + try { - await entry.ReloadAsync(cancellationToken); + await dbContext.SaveChangesAsync(cancellationToken); + break; } - - if (PhaseOf(motion, now) != SealedPhase.Reveal) + catch (DbUpdateConcurrencyException error) { - throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The motion closed; the reveal window is over."); - } + foreach (var entry in error.Entries) + { + await entry.ReloadAsync(cancellationToken); + } - if (attempt >= 4) - { - throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The reveal is contended; send it again."); + if (PhaseOf(motion, now) != SealedPhase.Reveal) + { + throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The motion closed; the reveal window is over."); + } + + if (attempt >= 4) + { + throw new SealedBallotException(SealedBallotFailure.WrongPhase, "The reveal is contended; send it again."); + } } } - } + + return true; + }, cancellationToken); await auditTrailService.RecordAsync( user.Id, nameof(Motion), motionId, "sealed.revealed", @@ -362,10 +373,10 @@ public sealed class SealedBallotService( private static string NameOf(UserAccount user) => user.MemberProfile?.Nickname ?? user.DisplayName; - // A member resolved before a merge froze the account must not write a ballot after it: standing is read again at the write. - private async Task RequireStandingAsync(Guid userAccountId, CancellationToken cancellationToken) + // A member resolved before a merge froze the account must not write a ballot after it: the write gate reads standing at the write. + private static void RequireStanding(MergeStanding? standing) { - if (!await AccountMergeLedger.MayWriteAsync(dbContext, userAccountId, cancellationToken)) + if (standing is not null) { throw new SealedBallotException(SealedBallotFailure.Forbidden, "An active member is required."); } diff --git a/src/Bifrost.Web/Features/Patronage/PatronageService.cs b/src/Bifrost.Web/Features/Patronage/PatronageService.cs index 86168d5..e8cfbfe 100644 --- a/src/Bifrost.Web/Features/Patronage/PatronageService.cs +++ b/src/Bifrost.Web/Features/Patronage/PatronageService.cs @@ -1,5 +1,6 @@ using Bifrost.Web.Data; using Bifrost.Web.Domain; +using Bifrost.Web.Features.Membership; using Bifrost.Web.Features.Shared; using Microsoft.EntityFrameworkCore; @@ -12,6 +13,11 @@ public sealed class PatronageService( { private const string CurrentPatronIndex = "UX_TierSnapshots_MembershipId_CurrentPatron"; + /// + /// Records a patron event for an account, through the merge ledger's write gate: an event for a folded account lands on its survivor + /// and is journalled in the same save (an undo moves it back); an event for a frozen account lands on it, where the commit's + /// reduction finds it. A provider retry returns the stored event and, if it sits on a folded account's survivor, journals it once. + /// public async Task RecordSupportEventAsync( Guid? actorUserAccountId, Guid userAccountId, @@ -29,105 +35,128 @@ public sealed class PatronageService( CancellationToken cancellationToken, Guid? projectId = null) { - var user = await dbContext.UserAccounts - .Include(x => x.Membership) - .SingleAsync(x => x.Id == userAccountId, cancellationToken); - - if (user.Membership is null || user.Membership.Status == MembershipStatus.Suspended) - { - throw new InvalidOperationException("Patron support can only be recorded for an unsuspended Bifrost account."); - } - - if (amount <= 0 && kind != PatronSupportEventKind.SupportAdjustment) - { - throw new InvalidOperationException("Patron support amount must be greater than zero."); - } - - if (amount == 0) - { - throw new InvalidOperationException("Patron support amount must not be zero."); - } - - if (kind == PatronSupportEventKind.SupportAdjustment && amount > 0) - { - throw new InvalidOperationException("Patron support adjustments must reduce support."); - } - var normalizedProviderEventId = providerEventId.Trim(); - if (provider != ExternalPatronProvider.Manual && string.IsNullOrWhiteSpace(normalizedProviderEventId)) + var (supportEvent, recordedOn, isNew, recordedFor) = await AccountMergeLedger.WriteAsAsync(dbContext, userAccountId, async standing => { - throw new InvalidOperationException("External patron provider events require a provider event id."); - } + var folded = standing as MergeStanding.Folded; + var recordOnId = folded?.SurvivorId ?? userAccountId; + var now = timeProvider.GetUtcNow(); - var existingProviderEvent = string.IsNullOrWhiteSpace(normalizedProviderEventId) - ? null - : await dbContext.PatronSupportEvents - .SingleOrDefaultAsync(x => x.Provider == provider && x.ProviderEventId == normalizedProviderEventId, cancellationToken); + var existingProviderEvent = string.IsNullOrWhiteSpace(normalizedProviderEventId) + ? null + : await dbContext.PatronSupportEvents + .SingleOrDefaultAsync(x => x.Provider == provider && x.ProviderEventId == normalizedProviderEventId, cancellationToken); - if (existingProviderEvent is not null) - { - return existingProviderEvent; - } - - var now = timeProvider.GetUtcNow(); - var normalizedCurrency = string.IsNullOrWhiteSpace(currencyCode) - ? "USD" - : currencyCode.Trim().ToUpperInvariant(); - - if (kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport) - { - var existingCurrentEvents = await dbContext.PatronSupportEvents - .Where(x => x.UserAccountId == userAccountId && - x.Kind == PatronSupportEventKind.RecurringSupportSnapshot && - x.IsCurrentRecurringSupport) - .ToListAsync(cancellationToken); - - foreach (var existing in existingCurrentEvents) + if (existingProviderEvent is not null) { - existing.IsCurrentRecurringSupport = false; + if (folded is not null && existingProviderEvent.UserAccountId == folded.SurvivorId) + { + await AccountMergeLedger.StageIntakeJournalAsync(dbContext, folded.MergeId, userAccountId, existingProviderEvent.Id, now, cancellationToken); + await dbContext.SaveChangesAsync(cancellationToken); + } + + return (existingProviderEvent, recordOnId, false, string.Empty); } + + var user = await dbContext.UserAccounts + .Include(x => x.Membership) + .SingleAsync(x => x.Id == recordOnId, cancellationToken); + + if (user.Membership is null || user.Membership.Status == MembershipStatus.Suspended) + { + throw new PatronSupportRefusedException(); + } + + if (amount <= 0 && kind != PatronSupportEventKind.SupportAdjustment) + { + throw new InvalidOperationException("Patron support amount must be greater than zero."); + } + + if (amount == 0) + { + throw new InvalidOperationException("Patron support amount must not be zero."); + } + + if (kind == PatronSupportEventKind.SupportAdjustment && amount > 0) + { + throw new InvalidOperationException("Patron support adjustments must reduce support."); + } + + if (provider != ExternalPatronProvider.Manual && string.IsNullOrWhiteSpace(normalizedProviderEventId)) + { + throw new InvalidOperationException("External patron provider events require a provider event id."); + } + + var normalizedCurrency = string.IsNullOrWhiteSpace(currencyCode) + ? "USD" + : currencyCode.Trim().ToUpperInvariant(); + + if (kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport) + { + var existingCurrentEvents = await dbContext.PatronSupportEvents + .Where(x => x.UserAccountId == recordOnId && + x.Kind == PatronSupportEventKind.RecurringSupportSnapshot && + x.IsCurrentRecurringSupport) + .ToListAsync(cancellationToken); + + foreach (var existing in existingCurrentEvents) + { + existing.IsCurrentRecurringSupport = false; + } + } + + var created = new PatronSupportEvent + { + UserAccountId = recordOnId, + ProjectId = projectId, + Kind = kind, + ExternalSupportId = externalSupportId.Trim(), + Provider = provider, + ProviderEventId = normalizedProviderEventId, + ProviderPayerId = providerPayerId.Trim(), + ProviderSubscriptionId = providerSubscriptionId.Trim(), + Amount = amount, + CurrencyCode = normalizedCurrency, + IsCurrentRecurringSupport = kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport, + SupportedAtUtc = supportedAtUtc.ToUniversalTime(), + RecordedAtUtc = now, + Notes = notes.Trim() + }; + + dbContext.PatronSupportEvents.Add(created); + dbContext.PointTransactions.Add(new PointTransaction + { + UserAccountId = recordOnId, + ProjectId = projectId, + Type = PointTransactionType.PatronSupport, + Amount = amount, + IsDecaying = kind == PatronSupportEventKind.OneTimeDonation, + CreatedAtUtc = now, + Note = $"Recorded {provider} {kind} patron support event {created.ExternalSupportId}." + }); + + if (folded is not null) + { + await AccountMergeLedger.StageIntakeJournalAsync(dbContext, folded.MergeId, userAccountId, created.Id, now, cancellationToken); + } + + await dbContext.SaveChangesAsync(cancellationToken); + return (created, recordOnId, true, user.DisplayName); + }, cancellationToken); + + if (isNew) + { + await auditTrailService.RecordAsync( + actorUserAccountId, + nameof(PatronSupportEvent), + supportEvent.Id, + "patron-support.recorded", + $"Recorded {amount:0.##} {supportEvent.CurrencyCode} {provider} {kind} patron support for {recordedFor}.", + cancellationToken); + + await RefreshPatronTierSnapshotAsync(actorUserAccountId, recordedOn, cancellationToken); } - var supportEvent = new PatronSupportEvent - { - UserAccountId = userAccountId, - ProjectId = projectId, - Kind = kind, - ExternalSupportId = externalSupportId.Trim(), - Provider = provider, - ProviderEventId = normalizedProviderEventId, - ProviderPayerId = providerPayerId.Trim(), - ProviderSubscriptionId = providerSubscriptionId.Trim(), - Amount = amount, - CurrencyCode = normalizedCurrency, - IsCurrentRecurringSupport = kind == PatronSupportEventKind.RecurringSupportSnapshot && isCurrentRecurringSupport, - SupportedAtUtc = supportedAtUtc.ToUniversalTime(), - RecordedAtUtc = now, - Notes = notes.Trim() - }; - - dbContext.PatronSupportEvents.Add(supportEvent); - dbContext.PointTransactions.Add(new PointTransaction - { - UserAccountId = userAccountId, - ProjectId = projectId, - Type = PointTransactionType.PatronSupport, - Amount = amount, - IsDecaying = kind == PatronSupportEventKind.OneTimeDonation, - CreatedAtUtc = now, - Note = $"Recorded {provider} {kind} patron support event {supportEvent.ExternalSupportId}." - }); - - await dbContext.SaveChangesAsync(cancellationToken); - await auditTrailService.RecordAsync( - actorUserAccountId, - nameof(PatronSupportEvent), - supportEvent.Id, - "patron-support.recorded", - $"Recorded {amount:0.##} {normalizedCurrency} {provider} {kind} patron support for {user.DisplayName}.", - cancellationToken); - - await RefreshPatronTierSnapshotAsync(actorUserAccountId, userAccountId, cancellationToken); return supportEvent; } @@ -249,6 +278,9 @@ public sealed class PatronageService( } } +/// The account patron support would record on has no membership or is suspended. +public sealed class PatronSupportRefusedException() : InvalidOperationException("Patron support can only be recorded for an unsuspended Bifrost account."); + public sealed record PatronPointSummary( decimal RecurringPoints, decimal HistoricalPoints, diff --git a/src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs b/src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs index 34142ad..4dbcda7 100644 --- a/src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs +++ b/src/Bifrost.Web/Features/Patronage/StripeWebhookService.cs @@ -5,7 +5,6 @@ using System.Text.Json.Serialization; using Bifrost.Web.Configuration; using Bifrost.Web.Data; using Bifrost.Web.Domain; -using Bifrost.Web.Features.Membership; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; @@ -14,7 +13,6 @@ namespace Bifrost.Web.Features.Patronage; public sealed class StripeWebhookService( BifrostDbContext dbContext, PatronageService patronageService, - AccountMergeLedger mergeLedger, IOptions options) { private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); @@ -68,18 +66,7 @@ public sealed class StripeWebhookService( var patronageAccount = await ResolvePatronageAccountAsync(session, stripeOptions, cancellationToken); - // A checkout opened by an account that has since folded pays the survivor, as the Heimdall intake does: the same routing owner. - var target = patronageAccount is null - ? null - : await mergeLedger.SupportTargetAsync(patronageAccount.Id, cancellationToken); - if (patronageAccount is not null && target!.RecordOnAccountId != patronageAccount.Id) - { - patronageAccount = await dbContext.UserAccounts - .Include(x => x.Membership) - .SingleOrDefaultAsync(x => x.Id == target.RecordOnAccountId, cancellationToken); - } - - if (patronageAccount?.Membership is null || patronageAccount.Membership.Status == MembershipStatus.Suspended) + if (patronageAccount is null) { return StripeWebhookResult.NotConfigured( "Stripe checkout session is not linked to an unsuspended Bifrost patron account."); @@ -96,26 +83,31 @@ public sealed class StripeWebhookService( ? "USD" : session.Currency.ToUpperInvariant(); - var supportEvent = await patronageService.RecordSupportEventAsync( - actorUserAccountId: null, - patronageAccount.Id, - PatronSupportEventKind.OneTimeDonation, - amount, - currencyCode, - session.Id, - ExternalPatronProvider.Stripe, - stripeEvent.Id, - session.Customer, - string.Empty, - DateTimeOffset.FromUnixTimeSeconds(stripeEvent.Created), - isCurrentRecurringSupport: false, - BuildNotes(session), - cancellationToken, - projectId.ProjectId); - - if (target!.MergeId is { } mergeId) + // A checkout opened by an account that has since folded pays the survivor: the write gate behind RecordSupportEventAsync routes it. + PatronSupportEvent supportEvent; + try { - await mergeLedger.JournalIntakeAsync(mergeId, target.ForAccountId, supportEvent.Id, cancellationToken); + supportEvent = await patronageService.RecordSupportEventAsync( + actorUserAccountId: null, + patronageAccount.Id, + PatronSupportEventKind.OneTimeDonation, + amount, + currencyCode, + session.Id, + ExternalPatronProvider.Stripe, + stripeEvent.Id, + session.Customer, + string.Empty, + DateTimeOffset.FromUnixTimeSeconds(stripeEvent.Created), + isCurrentRecurringSupport: false, + BuildNotes(session), + cancellationToken, + projectId.ProjectId); + } + catch (PatronSupportRefusedException) + { + return StripeWebhookResult.NotConfigured( + "Stripe checkout session is not linked to an unsuspended Bifrost patron account."); } return StripeWebhookResult.Processed("Stripe patronage support event recorded."); diff --git a/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs b/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs index 7382c1e..e11b769 100644 --- a/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs +++ b/tests/Bifrost.Web.Tests/AccountMergeHttpTests.cs @@ -261,7 +261,63 @@ public sealed class AccountMergeHttpTests(TestWebApplicationFactory factory) : I Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); Assert.Equal([s.Survivor], await EventOwnersAsync(s)); - Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); + var entry = Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); + Assert.Equal(s.Folded, entry.PriorUserAccountId); // the journal names the folded account as the previous owner + + await SetStateAsync(merge, AccountMergeState.HeimdallReversed); + await UndoAsync(merge); + Assert.Equal([s.Folded], await EventOwnersAsync(s)); // so an undo sends the donation back where it was opened + } + + private Task UndoAsync(Guid merge) => + WithDb(async db => + { + using var scope = factory.Services.CreateScope(); + await scope.ServiceProvider.GetRequiredService().UndoLocalAsync(merge, default); + return 0; + }); + + [Fact] + public async Task The_admin_ledgers_manual_patron_record_for_a_folded_account_lands_on_the_survivor_and_is_journalled() + { + var s = await SeedAsync(); + var merge = await CommitMergeAsync(s); + + await WithDb(async db => + { + using var scope = factory.Services.CreateScope(); + await scope.ServiceProvider.GetRequiredService().RecordSupportEventAsync( + s.Survivor, s.Folded, PatronSupportEventKind.OneTimeDonation, 10m, "USD", "manual-1", ExternalPatronProvider.Manual, + string.Empty, string.Empty, string.Empty, DateTimeOffset.UtcNow, false, string.Empty, default); // as Pages/App/Ledger records it + return 0; + }); + + Assert.Equal([s.Survivor], await EventOwnersAsync(s)); + var entry = Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); + Assert.Equal(s.Folded, entry.PriorUserAccountId); + } + + [Fact] + public async Task A_provider_retry_of_an_event_stranded_on_the_folded_account_journals_nothing_because_nothing_moved() + { + var s = await SeedAsync(); + var merge = await CommitMergeAsync(s); + var eventId = $"WH-{Guid.NewGuid():N}"; + await WithDb(async db => // recorded on the folded account by a delivery that straddled the commit + { + db.PatronSupportEvents.Add(new PatronSupportEvent + { + UserAccountId = s.Folded, Provider = ExternalPatronProvider.PayPal, ProviderEventId = eventId, ExternalSupportId = "CAPTURE-1", + Kind = PatronSupportEventKind.OneTimeDonation, Amount = 25m, SupportedAtUtc = DateTimeOffset.UtcNow, RecordedAtUtc = DateTimeOffset.UtcNow + }); + await db.SaveChangesAsync(); + return 0; + }); + + Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId)); + + Assert.DoesNotContain(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); + Assert.Equal([s.Folded], await EventOwnersAsync(s)); } [Fact] diff --git a/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs b/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs index 0ec037d..95112c1 100644 --- a/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs +++ b/tests/Bifrost.Web.Tests/AccountMergePostgresTests.cs @@ -1,5 +1,6 @@ using Bifrost.Web.Data; using Bifrost.Web.Domain; +using Bifrost.Web.Features.Motions; using Bifrost.Web.Features.Patronage; using Bifrost.Web.Features.Shared; using Microsoft.EntityFrameworkCore; @@ -206,7 +207,7 @@ public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFi await world.VoteAsync(motion, survivor, VoteChoice.For); await world.VoteAsync(motion, folded, VoteChoice.Against); var merge = await world.MergeAsync(survivor, folded); - var committers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new Rendezvous()); + var committers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world)); async Task TryCommit() { @@ -223,9 +224,8 @@ public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFi var results = await Task.WhenAll(Task.Run(TryCommit), Task.Run(TryCommit)); - Assert.Equal(1, results.Count(x => x is null)); - // The loser is refused by the unique index, the token, or Postgres picking it as the deadlock victim. - Assert.All(results.OfType(), e => Assert.True(Chain(e).Any(x => x is DbUpdateException), e.ToString())); + // The second commit waits on the folded account's exclusive lock, then finds the merge landed and returns its receipt. + Assert.All(results, e => Assert.Null(e)); var journal = await world.JournalAsync(merge); Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count()); Assert.Equal(1, journal.Count(x => x.Kind == AccountMergeEntryKind.Vote)); @@ -533,15 +533,147 @@ public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFi var committed = (await world.JournalAsync(merge)).Count; Assert.True(committed > 0); - var events = new[] { Guid.NewGuid(), Guid.NewGuid() }; + var events = new[] { $"WH-{Guid.NewGuid():N}", $"WH-{Guid.NewGuid():N}" }; foreach (var id in events.Concat(events)) // each twice: the provider retries { await using var db = world.Db(); - await world.Ledger(db).JournalIntakeAsync(merge.Id, folded.Id, id, default); + await new PatronageService(db, new AuditTrailService(db, world.Clock), world.Clock).RecordSupportEventAsync( + null, folded.Id, PatronSupportEventKind.OneTimeDonation, 1m, "USD", "ext", ExternalPatronProvider.PayPal, id, + string.Empty, string.Empty, AccountMergeLedgerTests.T0, false, string.Empty, default); } var journal = await world.JournalAsync(merge); Assert.Equal(committed + 2, journal.Count); Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count()); } + + [PostgresTheory] + [InlineData(AccountMergeState.Proposed)] + [InlineData(AccountMergeState.Confirmed)] + [InlineData(AccountMergeState.HeimdallMoved)] + [InlineData(AccountMergeState.Final)] + [InlineData(AccountMergeState.UndoRequested)] + [InlineData(AccountMergeState.HeimdallReversed)] + [InlineData(AccountMergeState.Undone)] + [InlineData(AccountMergeState.Failed)] + public async Task Reverting_the_migration_is_refused_for_a_merge_in_any_state(AccountMergeState state) + { + var world = await postgres.NewWorldAsync(); + await world.MergeAsync(await world.AccountAsync("survivor"), await world.AccountAsync("folded"), state); + + await using var db = world.Db(); + var error = await Assert.ThrowsAnyAsync(() => db.GetService().MigrateAsync("20261113120000_AddPasskeyCredentials")); + Assert.Contains("roll-forward only", Pg(error).MessageText); + } + + // ---- the write gate ---- + + [PostgresFact] + public async Task A_vote_that_read_no_merge_saves_before_a_merge_can_freeze_the_account_and_the_commit_then_moves_it() + { + var world = await postgres.NewWorldAsync(); + var survivor = await world.AccountAsync("survivor"); + var folded = await world.AccountAsync("folded"); + var motion = await world.MotionAsync(); + var actor = await world.ActorAsync(folded.Id); + Task? freeze = null; + var blocked = false; + var voters = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () => + { + // The vote has read its standing (none) and is about to save: the freeze lands here and must wait for the save. + freeze = Task.Run(() => world.MergeAsync(survivor, folded, AccountMergeState.Confirmed)); + await Task.Delay(1500); + blocked = !freeze.IsCompleted; + })); + + await using (var db = voters.Db()) + { + await voters.Motions(db).CastVoteAsync(actor, motion.Id, VoteChoice.For, null, default); + } + + var merge = await freeze!.WaitAsync(TimeSpan.FromSeconds(30)); + Assert.True(blocked); + await world.SetStateAsync(merge, AccountMergeState.HeimdallMoved); + await world.CommitAsync(merge); + + var votes = await world.AllVotesAsync(motion); + Assert.Equal(survivor.Id, Assert.Single(votes).UserAccountId); // the commit saw the vote and moved it: no second voice stays on the folded account + Assert.Single(await world.JournalAsync(merge), x => x.Kind == AccountMergeEntryKind.Vote); + } + + [PostgresFact] + public async Task A_patron_event_that_read_a_Frozen_account_saves_before_the_commit_reduces_and_the_commit_moves_it() + { + var world = await postgres.NewWorldAsync(); + var survivor = await world.AccountAsync("survivor"); + var folded = await world.AccountAsync("folded"); + var merge = await world.MergeAsync(survivor, folded); // HeimdallMoved: the folded account is Frozen + Task? commit = null; + var blocked = false; + var recorders = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () => + { + commit = Task.Run(() => world.CommitAsync(merge)); // takes the folded account's exclusive lock before it reduces + await Task.Delay(1500); + blocked = !commit.IsCompleted; + })); + + await using (var db = recorders.Db()) + { + await new PatronageService(db, new AuditTrailService(db, recorders.Clock), recorders.Clock).RecordSupportEventAsync( + null, folded.Id, PatronSupportEventKind.OneTimeDonation, 1m, "USD", "ext", ExternalPatronProvider.PayPal, "WH-frozen", + string.Empty, string.Empty, AccountMergeLedgerTests.T0, false, string.Empty, default); + } + + await commit!.WaitAsync(TimeSpan.FromSeconds(30)); + Assert.True(blocked); + await using var read = world.Db(); + Assert.Equal(survivor.Id, (await read.PatronSupportEvents.SingleAsync()).UserAccountId); // the reduction found the event and moved it + Assert.Single(await world.JournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent); + } + + [PostgresFact] + public async Task A_sealed_reveal_that_retries_on_a_conflict_keeps_its_lock_so_no_merge_freezes_the_account_between_attempts() + { + const string salt = "00112233445566778899aabbccddeeff"; + var world = await postgres.NewWorldAsync(); + var survivor = await world.AccountAsync("survivor"); + var folded = await world.AccountAsync("folded"); + var other = await world.AccountAsync("other"); + var moderator = await world.AccountAsync("moderator", moderator: true); + SealedBallotService Sealed(AccountMergeLedgerTests.World w, BifrostDbContext db) => new(db, new AuditTrailService(db, w.Clock), w.Clock); + SealedBallotDocument Doc(Guid motionId, string reason) => new(SealedBallotDocument.SchemaId, motionId, 1, "Ana", reason, salt); + + await using var setup = world.Db(); + var motionId = (await Sealed(world, setup).OpenAsync(await world.ActorAsync(moderator.Id), + new OpenSealedMotionCommand("Who", "Blind.", ["Ana", "Bo"], AccountMergeLedgerTests.T0.AddHours(1), AccountMergeLedgerTests.T0.AddHours(2)), default)).Id; + foreach (var (account, reason) in new[] { (folded, "mine"), (other, "theirs") }) + { + await using var db = world.Db(); + await Sealed(world, db).CommitAsync(await world.ActorAsync(account.Id), motionId, SealedBallotDocument.Commit(Doc(motionId, reason), account.Id), default); + } + + Task? freeze = null; + var blocked = false; + var revealers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () => + { + // The first attempt has read its standing (none). A freeze starts and must wait; another member's reveal then lands first, + // so this attempt's save conflicts on RevealSeq and the reveal retries while the freeze still waits. + freeze = Task.Run(() => world.MergeAsync(survivor, folded, AccountMergeState.Confirmed)); + await using var rival = world.Db(); + world.Clock.Now = AccountMergeLedgerTests.T0.AddMinutes(90); + await Sealed(world, rival).RevealAsync(await world.ActorAsync(other.Id), motionId, Doc(motionId, "theirs"), default); + await Task.Delay(1500); + blocked = !freeze.IsCompleted; + })); + revealers.Clock.Now = AccountMergeLedgerTests.T0.AddMinutes(90); + var actor = await world.ActorAsync(folded.Id); + + await using (var db = revealers.Db()) + { + Assert.True((await Sealed(revealers, db).RevealAsync(actor, motionId, Doc(motionId, "mine"), default)).Revealed); + } + + await freeze!.WaitAsync(TimeSpan.FromSeconds(30)); + Assert.True(blocked); + } } diff --git a/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs b/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs index f25b8c7..c619349 100644 --- a/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs +++ b/tests/Bifrost.Web.Tests/HeimdallCompletionTests.cs @@ -936,6 +936,54 @@ public sealed class HeimdallCompletionTests Assert.Equal(MembershipStatus.Active, (await host.Account(accountId))!.Membership!.Status); } + [Theory] + [InlineData(AccountMergeState.Confirmed)] + [InlineData(AccountMergeState.Committed)] + public async Task A_chat_tier_account_without_a_membership_that_a_merge_froze_or_folded_signs_in_without_getting_one(AccountMergeState state) + { + using var host = new HeimdallHost(); + var foldedId = HeimdallShapes.NewAccountId(); + var survivorId = HeimdallShapes.NewAccountId(); + Assert.True((await Genuine(host, await host.StartAsync(member: false), foldedId)).SignedIn); + Assert.True((await Genuine(host, await host.StartAsync(member: false), survivorId)).SignedIn); + await MergeAsync(host, survivorId, foldedId, state, dropFoldedMembership: true); // a chat-tier account holds none + + await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"]); + + Assert.Null((await host.Account(foldedId))!.Membership); + Assert.Equal(0, await host.Db(db => db.Memberships.CountAsync(x => x.UserAccount.HeimdallAccountId == foldedId))); + } + + [Fact] + public async Task A_frozen_accounts_sign_in_with_member_access_does_not_activate_its_membership() + { + using var host = new HeimdallHost(); + var foldedId = HeimdallShapes.NewAccountId(); + var survivorId = HeimdallShapes.NewAccountId(); + Assert.True((await Genuine(host, await host.StartAsync(member: false), foldedId)).SignedIn); + Assert.True((await Genuine(host, await host.StartAsync(member: false), survivorId)).SignedIn); + await MergeAsync(host, survivorId, foldedId, AccountMergeState.HeimdallMoved, dropFoldedMembership: false); + + await Genuine(host, await host.StartAsync(member: true), foldedId, ["member_access"]); + + Assert.Equal(MembershipStatus.Authenticated, (await host.Account(foldedId))!.Membership!.Status); + } + + private static Task MergeAsync(HeimdallHost host, string survivorId, string foldedId, AccountMergeState state, bool dropFoldedMembership) => + host.Db(async db => + { + if (dropFoldedMembership) + { + db.Memberships.RemoveRange(db.Memberships.Where(x => x.UserAccount.HeimdallAccountId == foldedId)); + } + + var folded = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == foldedId); + var survivor = await db.UserAccounts.SingleAsync(x => x.HeimdallAccountId == survivorId); + db.AccountMerges.Add(new AccountMerge { SurvivorUserAccountId = survivor.Id, FoldedUserAccountId = folded.Id, State = state, CreatedUtc = DateTimeOffset.UtcNow }); + await db.SaveChangesAsync(); + return 0; + }); + [Fact] public async Task A_chat_only_account_that_later_signs_in_with_member_access_becomes_a_member() {