Account merge ledger: roll-forward-only Down guard, standing-at-write through one owner for every writer, one current Patron snapshot per membership, memberless Heimdall sign-in, intake and Stripe routing through one owner
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
aa348d3b43
commit
537a477dc3
17 changed files with 405 additions and 54 deletions
|
|
@ -83,8 +83,12 @@ 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 migration's rollback 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 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
|
||||
```
|
||||
|
||||
## Account merges are roll-forward only
|
||||
|
||||
Once any `AccountMerges` row exists, do not deploy a build older than the `AddAccountMerges` migration, and do not revert that migration: an older build cannot read the `Merged` membership status and counts voided votes again. `Down` refuses while any merge row exists. Fix forward (`heimdall-body:ruling:merge-roll-forward-only`, `docs/account-merge.md` Rollback). Any deploy list that names a rollback must say so.
|
||||
|
|
|
|||
|
|
@ -50,8 +50,10 @@ Only the ledger writes `Membership.Status = Merged` or leaves it. The other stat
|
|||
|
||||
## Rollback
|
||||
|
||||
Voiding lives in the new build's query filter and the `VoidedByMergeId` columns. `Down` refuses to run while any vote or appraisal is voided (dropping the columns would count them again), and an older build run over the migrated schema also counts voided rows, because it has no filter. Rolling the code back while merges have landed is therefore unsafe; whether voided votes should instead leave the `Votes` table (so an older build cannot see them) is an open question for the operator, raised on the cut.
|
||||
Bifrost is **roll-forward only** once a merge exists (`heimdall-body:ruling:merge-roll-forward-only`). A build older than `AddAccountMerges` cannot read the `Merged` membership status (EF throws on `/App/Members` and on the folded account's sign-in) and has no query filter, so it counts voided votes and appraisals again. Deploy the merge migration knowing that a code rollback past it is not available after the first merge lands; fix forward. The migration's `Down` refuses while any `AccountMerges` row exists, whatever state, so it cannot drop the merge record and journal under a `Merged` membership. No tombstone table is built: it would fix only the recount, not the enum.
|
||||
|
||||
## 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. A vote written by a request that passed the standing read at the write and saved after the commit read the votes (microseconds, inside one request) is the one window left; such a vote stays live as a second voice until an operator voids it. Closing it fully needs the tally-time voiding of design section 7, which is not built.
|
||||
`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.
|
||||
|
||||
`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.
|
||||
|
|
|
|||
|
|
@ -141,6 +141,10 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
|||
entity.Property(x => x.Label).HasMaxLength(120);
|
||||
entity.Property(x => x.Weight).HasPrecision(18, 2);
|
||||
entity.HasIndex(x => new { x.MembershipId, x.Kind, x.IsCurrent });
|
||||
entity.HasIndex(x => x.MembershipId)
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UX_TierSnapshots_MembershipId_CurrentPatron")
|
||||
.HasFilter("\"Kind\" = 'Patron' AND \"IsCurrent\"");
|
||||
entity.HasOne(x => x.Membership)
|
||||
.WithMany(x => x.TierSnapshots)
|
||||
.HasForeignKey(x => x.MembershipId);
|
||||
|
|
|
|||
|
|
@ -127,6 +127,23 @@ namespace Bifrost.Web.Data.Migrations
|
|||
table: "AccountMerges",
|
||||
columns: new[] { "SurvivorUserAccountId", "State" });
|
||||
|
||||
// One current Patron snapshot per membership: two restages racing (two merges into one survivor, a merge and an intake) would
|
||||
// each demote the old row and add their own, and EffectiveVotingWeight sums the current ones. A pre-existing duplicate keeps
|
||||
// only its newest row current so the index can be built.
|
||||
migrationBuilder.Sql(@"
|
||||
UPDATE ""TierSnapshots"" t SET ""IsCurrent"" = false
|
||||
WHERE t.""Kind"" = 'Patron' AND t.""IsCurrent"" AND EXISTS (
|
||||
SELECT 1 FROM ""TierSnapshots"" o
|
||||
WHERE o.""MembershipId"" = t.""MembershipId"" AND o.""Kind"" = 'Patron' AND o.""IsCurrent""
|
||||
AND (o.""CapturedAtUtc"" > t.""CapturedAtUtc"" OR (o.""CapturedAtUtc"" = t.""CapturedAtUtc"" AND o.""Id"" > t.""Id"")));");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "UX_TierSnapshots_MembershipId_CurrentPatron",
|
||||
table: "TierSnapshots",
|
||||
column: "MembershipId",
|
||||
unique: true,
|
||||
filter: "\"Kind\" = 'Patron' AND \"IsCurrent\"");
|
||||
|
||||
// The cross-role guard no single unique index can express: a live merge's survivor is never another live merge's folded
|
||||
// account (no chains), whichever order they arrive in. Advisory locks on both accounts, taken in a fixed order, serialise two
|
||||
// transactions racing over the same account, so the second one's check sees the first's committed row.
|
||||
|
|
@ -155,19 +172,22 @@ CREATE TRIGGER ""AccountMerges_refuse_chain"" BEFORE INSERT OR UPDATE OF ""State
|
|||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
// Voiding lives only in the new build's query filter and these columns: dropping them (or running an older build over them)
|
||||
// counts every voided vote again, and a close in that window records a wrong result for good. Refuse while any is voided;
|
||||
// see docs/account-merge.md (Rollback).
|
||||
// Roll-forward only (heimdall-body:ruling:merge-roll-forward-only): once any merge exists the Merged membership status
|
||||
// cannot be read by an older build, and voided votes and appraisals would be counted again. Refuse while any merge row
|
||||
// exists; see docs/account-merge.md (Rollback).
|
||||
migrationBuilder.Sql(@"
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (SELECT 1 FROM ""Votes"" WHERE ""VoidedByMergeId"" IS NOT NULL)
|
||||
OR EXISTS (SELECT 1 FROM ""ConceptAppraisals"" WHERE ""VoidedByMergeId"" IS NOT NULL) THEN
|
||||
RAISE EXCEPTION 'AddAccountMerges cannot be reverted while merged votes or appraisals are voided';
|
||||
IF EXISTS (SELECT 1 FROM ""AccountMerges"") THEN
|
||||
RAISE EXCEPTION 'AddAccountMerges cannot be reverted once an account merge exists: Bifrost is roll-forward only';
|
||||
END IF;
|
||||
END
|
||||
$$;");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "UX_TierSnapshots_MembershipId_CurrentPatron",
|
||||
table: "TierSnapshots");
|
||||
|
||||
migrationBuilder.Sql(@"DROP TRIGGER ""AccountMerges_refuse_chain"" ON ""AccountMerges""; DROP FUNCTION ""AccountMerges_refuse_chain""();");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
|
|
|
|||
|
|
@ -1445,6 +1445,11 @@ namespace Bifrost.Web.Data.Migrations
|
|||
|
||||
b.HasIndex("MembershipId", "Kind", "IsCurrent");
|
||||
|
||||
b.HasIndex("MembershipId")
|
||||
.IsUnique()
|
||||
.HasDatabaseName("UX_TierSnapshots_MembershipId_CurrentPatron")
|
||||
.HasFilter("\"Kind\" = 'Patron' AND \"IsCurrent\"");
|
||||
|
||||
b.ToTable("TierSnapshots");
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -65,13 +65,6 @@ public sealed class ConceptAppraisalService(
|
|||
return CastResult.NoVoter;
|
||||
}
|
||||
|
||||
// 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.StandingAsync(dbContext, voterAccountId, cancellationToken) is not null)
|
||||
{
|
||||
return CastResult.NoVoter;
|
||||
}
|
||||
|
||||
var subject = await FindSubjectAsync(collection, key, cancellationToken);
|
||||
if (subject is null)
|
||||
{
|
||||
|
|
@ -89,6 +82,14 @@ public sealed class ConceptAppraisalService(
|
|||
: 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: standing is read again at the write.
|
||||
if (voter.UserAccountId is { } voterAccountId &&
|
||||
!await AccountMergeLedger.MayWriteAsync(dbContext, voterAccountId, cancellationToken))
|
||||
{
|
||||
return CastResult.NoVoter;
|
||||
}
|
||||
|
||||
if (existing is not null)
|
||||
{
|
||||
return await ApplyStanceAsync(existing, stance, tag, cancellationToken);
|
||||
|
|
|
|||
|
|
@ -840,11 +840,13 @@ public sealed class HeimdallAuthService(
|
|||
Headline = $"Verified through Heimdall {provider}",
|
||||
UpdatedAtUtc = now
|
||||
};
|
||||
userAccount.Membership ??= new Bifrost.Web.Domain.Membership
|
||||
if (userAccount.Membership is null)
|
||||
{
|
||||
UserAccountId = userAccount.Id,
|
||||
CreatedAtUtc = now
|
||||
};
|
||||
// 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)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -70,14 +70,12 @@ public sealed class HeimdallPatronSupportIntakeService(
|
|||
.AsNoTracking()
|
||||
.SingleOrDefaultAsync(x => x.HeimdallAccountId == request.HeimdallAccountId.Trim(), cancellationToken);
|
||||
|
||||
// A folded account's events record on the survivor and are journalled on the merge, so an undo moves them back.
|
||||
var folded = user is null ? null : await mergeLedger.StandingAsync(user.Id, cancellationToken) as MergeStanding.Folded;
|
||||
|
||||
if (existingEvent is not null)
|
||||
{
|
||||
if (folded is not null && user 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(folded.MergeId, user.Id, existingEvent.Id, cancellationToken);
|
||||
await mergeLedger.JournalIntakeAsync(retriedMergeId, user.Id, existingEvent.Id, cancellationToken);
|
||||
}
|
||||
|
||||
return HeimdallPatronSupportIntakeResult.Processed(
|
||||
|
|
@ -91,9 +89,11 @@ public sealed class HeimdallPatronSupportIntakeService(
|
|||
$"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);
|
||||
var supportEvent = await patronageService.RecordSupportEventAsync(
|
||||
actorUserAccountId: null,
|
||||
userAccountId: folded?.SurvivorId ?? user.Id,
|
||||
userAccountId: target.RecordOnAccountId,
|
||||
request.Kind,
|
||||
request.Amount,
|
||||
request.CurrencyCode,
|
||||
|
|
@ -107,9 +107,9 @@ public sealed class HeimdallPatronSupportIntakeService(
|
|||
request.Notes,
|
||||
cancellationToken);
|
||||
|
||||
if (folded is not null)
|
||||
if (target.MergeId is { } mergeId)
|
||||
{
|
||||
await mergeLedger.JournalIntakeAsync(folded.MergeId, user.Id, supportEvent.Id, cancellationToken);
|
||||
await mergeLedger.JournalIntakeAsync(mergeId, user.Id, supportEvent.Id, cancellationToken);
|
||||
}
|
||||
|
||||
return HeimdallPatronSupportIntakeResult.Processed(
|
||||
|
|
|
|||
|
|
@ -7,6 +7,9 @@ using Microsoft.EntityFrameworkCore;
|
|||
namespace Bifrost.Web.Features.Membership;
|
||||
|
||||
/// <summary>How an account stands under a merge: the folded account of an unfinished merge is Frozen, of a landed one Folded.</summary>
|
||||
/// <summary>Where a patron event for an account lands; <see cref="MergeId"/> is set when the account is folded and the event must be journalled.</summary>
|
||||
public sealed record SupportTarget(Guid ForAccountId, Guid RecordOnAccountId, Guid? MergeId);
|
||||
|
||||
public abstract record MergeStanding(Guid MergeId)
|
||||
{
|
||||
public sealed record Frozen(Guid MergeId) : MergeStanding(MergeId);
|
||||
|
|
@ -70,6 +73,25 @@ public sealed class AccountMergeLedger(
|
|||
: new MergeStanding.Folded(merge.Id, merge.SurvivorUserAccountId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static async Task<bool> MayWriteAsync(BifrostDbContext db, Guid userAccountId, CancellationToken cancellationToken) =>
|
||||
await StandingAsync(db, userAccountId, cancellationToken) is null;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="JournalIntakeAsync"/>.
|
||||
/// </summary>
|
||||
public async Task<SupportTarget> 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);
|
||||
|
||||
/// <summary>Writes nothing. <paramref name="exceptMergeId"/> lets the saga re-plan a merge it already holds without it blocking itself.</summary>
|
||||
public async Task<MergePlan> PlanAsync(Guid survivorId, Guid foldedId, CancellationToken cancellationToken, Guid? exceptMergeId = null)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -54,12 +54,6 @@ public sealed class MotionGovernanceService(
|
|||
{
|
||||
var actorUser = actor.UserAccount ?? throw new UnauthorizedAccessException("A linked Bifrost actor is required.");
|
||||
|
||||
// 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.StandingAsync(dbContext, actorUser.Id, cancellationToken) is not null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var motion = await dbContext.Motions
|
||||
.Include(x => x.Votes)
|
||||
.SingleAsync(x => x.Id == motionId, cancellationToken);
|
||||
|
|
@ -69,6 +63,12 @@ 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))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var vote = motion.Votes.SingleOrDefault(x => x.UserAccountId == actorUser.Id);
|
||||
if (vote is null)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ using System.Text;
|
|||
using System.Text.RegularExpressions;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Membership;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
|
@ -101,6 +102,7 @@ public sealed class SealedBallotService(
|
|||
|
||||
var ballot = await dbContext.SealedBallots
|
||||
.SingleOrDefaultAsync(x => x.MotionId == motionId && x.UserAccountId == user.Id, cancellationToken);
|
||||
await RequireStandingAsync(user.Id, cancellationToken);
|
||||
if (ballot is null)
|
||||
{
|
||||
ballot = new SealedBallot { MotionId = motionId, UserAccountId = user.Id };
|
||||
|
|
@ -161,6 +163,7 @@ public sealed class SealedBallotService(
|
|||
// another voter's reveal landed first while the window is still open (re-read the row and write again).
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
await RequireStandingAsync(user.Id, cancellationToken);
|
||||
ballot.RevealedCandidate = candidate;
|
||||
ballot.RevealedReason = reason;
|
||||
ballot.Salt = document.Salt;
|
||||
|
|
@ -359,6 +362,15 @@ 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)
|
||||
{
|
||||
if (!await AccountMergeLedger.MayWriteAsync(dbContext, userAccountId, cancellationToken))
|
||||
{
|
||||
throw new SealedBallotException(SealedBallotFailure.Forbidden, "An active member is required.");
|
||||
}
|
||||
}
|
||||
|
||||
private static UserAccount RequireMember(CurrentBifrostActor actor) =>
|
||||
actor is { IsActiveMember: true, UserAccount: { } user }
|
||||
? user
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ public sealed class PatronageService(
|
|||
AuditTrailService auditTrailService,
|
||||
TimeProvider timeProvider)
|
||||
{
|
||||
private const string CurrentPatronIndex = "UX_TierSnapshots_MembershipId_CurrentPatron";
|
||||
|
||||
public async Task<PatronSupportEvent> RecordSupportEventAsync(
|
||||
Guid? actorUserAccountId,
|
||||
Guid userAccountId,
|
||||
|
|
@ -134,21 +136,38 @@ public sealed class PatronageService(
|
|||
Guid userAccountId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
dbContext.ChangeTracker.Clear();
|
||||
|
||||
var user = await dbContext.UserAccounts
|
||||
.Include(x => x.Membership)
|
||||
.Include(x => x.PatronSupportEvents)
|
||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
||||
|
||||
if (user.Membership is null)
|
||||
// One current Patron snapshot per membership is a database invariant (UX_TierSnapshots_MembershipId_CurrentPatron). A restage that
|
||||
// lost a race to another restage of the same membership reads the winner's snapshot and derives again from the events it now sees.
|
||||
UserAccount user;
|
||||
PatronPointSummary summary;
|
||||
PatronTierDefinition? tier;
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
|
||||
dbContext.ChangeTracker.Clear();
|
||||
|
||||
user = await dbContext.UserAccounts
|
||||
.Include(x => x.Membership)
|
||||
.Include(x => x.PatronSupportEvents)
|
||||
.SingleAsync(x => x.Id == userAccountId, cancellationToken);
|
||||
|
||||
if (user.Membership is null)
|
||||
{
|
||||
throw new InvalidOperationException("Cannot refresh patron tier for a user without membership.");
|
||||
}
|
||||
|
||||
(summary, tier) = await StageTierSnapshotAsync(user.Membership, user.PatronSupportEvents, timeProvider.GetUtcNow(), cancellationToken);
|
||||
|
||||
try
|
||||
{
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
break;
|
||||
}
|
||||
catch (DbUpdateException error) when (attempt < 3 &&
|
||||
error.InnerException is Npgsql.PostgresException { SqlState: Npgsql.PostgresErrorCodes.UniqueViolation, ConstraintName: CurrentPatronIndex })
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
var (summary, tier) = await StageTierSnapshotAsync(user.Membership, user.PatronSupportEvents, timeProvider.GetUtcNow(), cancellationToken);
|
||||
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
await auditTrailService.RecordAsync(
|
||||
actorUserAccountId,
|
||||
nameof(TierSnapshot),
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ 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;
|
||||
|
||||
|
|
@ -13,6 +14,7 @@ namespace Bifrost.Web.Features.Patronage;
|
|||
public sealed class StripeWebhookService(
|
||||
BifrostDbContext dbContext,
|
||||
PatronageService patronageService,
|
||||
AccountMergeLedger mergeLedger,
|
||||
IOptions<StripeOptions> options)
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
|
|
@ -66,6 +68,17 @@ 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)
|
||||
{
|
||||
return StripeWebhookResult.NotConfigured(
|
||||
|
|
@ -83,7 +96,7 @@ public sealed class StripeWebhookService(
|
|||
? "USD"
|
||||
: session.Currency.ToUpperInvariant();
|
||||
|
||||
await patronageService.RecordSupportEventAsync(
|
||||
var supportEvent = await patronageService.RecordSupportEventAsync(
|
||||
actorUserAccountId: null,
|
||||
patronageAccount.Id,
|
||||
PatronSupportEventKind.OneTimeDonation,
|
||||
|
|
@ -100,6 +113,11 @@ public sealed class StripeWebhookService(
|
|||
cancellationToken,
|
||||
projectId.ProjectId);
|
||||
|
||||
if (target!.MergeId is { } mergeId)
|
||||
{
|
||||
await mergeLedger.JournalIntakeAsync(mergeId, target.ForAccountId, supportEvent.Id, cancellationToken);
|
||||
}
|
||||
|
||||
return StripeWebhookResult.Processed("Stripe patronage support event recorded.");
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -191,6 +191,79 @@ public sealed class AccountMergeHttpTests(TestWebApplicationFactory factory) : I
|
|||
Assert.Equal([s.Folded], await EventOwnersAsync(s));
|
||||
}
|
||||
|
||||
private Task<List<AccountMergeEntry>> PatronJournalAsync(Guid merge) =>
|
||||
WithDb(db => db.AccountMergeEntries.Where(x => x.MergeId == merge).OrderBy(x => x.Seq).ToListAsync());
|
||||
|
||||
[Fact]
|
||||
public async Task A_single_patron_event_during_grace_is_journalled_by_its_own_delivery_and_undo_moves_it_back()
|
||||
{
|
||||
var s = await SeedAsync();
|
||||
var merge = await CommitMergeAsync(s);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, $"WH-{Guid.NewGuid():N}")); // no retry follows
|
||||
|
||||
var journal = await PatronJournalAsync(merge);
|
||||
Assert.Single(journal, x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
|
||||
Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count()); // the new entry takes its own Seq
|
||||
await SetStateAsync(merge, AccountMergeState.HeimdallReversed);
|
||||
await WithDb(async db =>
|
||||
{
|
||||
using var scope = factory.Services.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<Bifrost.Web.Features.Membership.AccountMergeLedger>().UndoLocalAsync(merge, default);
|
||||
return 0;
|
||||
});
|
||||
Assert.Equal([s.Folded], await EventOwnersAsync(s));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_provider_retry_journals_an_event_the_first_delivery_left_unjournalled()
|
||||
{
|
||||
var s = await SeedAsync();
|
||||
var merge = await CommitMergeAsync(s);
|
||||
var eventId = $"WH-{Guid.NewGuid():N}";
|
||||
await WithDb(async db => // the first delivery recorded on the survivor, then died before journalling
|
||||
{
|
||||
db.PatronSupportEvents.Add(new PatronSupportEvent
|
||||
{
|
||||
UserAccountId = s.Survivor, 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.DoesNotContain(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Accepted, await IntakeAsync(s, eventId));
|
||||
|
||||
Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
|
||||
Assert.Equal([s.Survivor], await EventOwnersAsync(s));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_stripe_checkout_opened_by_an_account_that_folded_pays_the_survivor_and_is_journalled()
|
||||
{
|
||||
var s = await SeedAsync();
|
||||
var merge = await CommitMergeAsync(s);
|
||||
var payload = JsonSerializer.Serialize(new
|
||||
{
|
||||
id = $"evt_{Guid.NewGuid():N}", type = "checkout.session.completed", created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
|
||||
data = new { @object = new { id = $"cs_{Guid.NewGuid():N}", customer = "cus_1", currency = "usd", amount_total = 1900, payment_status = "paid",
|
||||
metadata = new Dictionary<string, string> { ["bifrost_user_account_id"] = s.Folded.ToString("N") } } }
|
||||
});
|
||||
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString();
|
||||
using var hasher = new HMACSHA256(Encoding.UTF8.GetBytes("whsec_test_webhook_secret"));
|
||||
using var request = new HttpRequestMessage(HttpMethod.Post, "/patronage/stripe/webhook");
|
||||
request.Headers.Add("Stripe-Signature", $"t={timestamp},v1={Convert.ToHexString(hasher.ComputeHash(Encoding.UTF8.GetBytes($"{timestamp}.{payload}"))).ToLowerInvariant()}");
|
||||
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");
|
||||
using var client = factory.CreateClient();
|
||||
|
||||
using var response = await client.SendAsync(request);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
|
||||
Assert.Equal([s.Survivor], await EventOwnersAsync(s));
|
||||
Assert.Single(await PatronJournalAsync(merge), x => x.Kind == AccountMergeEntryKind.PatronSupportEvent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_folded_bootstrap_admins_sign_in_does_not_reactivate_the_merged_membership_and_an_approval_is_refused()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Patronage;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
|
|
@ -387,28 +389,136 @@ public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFi
|
|||
// ---- rollback ----
|
||||
|
||||
[PostgresFact]
|
||||
public async Task Reverting_the_migration_is_refused_while_a_merge_has_voided_a_vote_and_allowed_after()
|
||||
public async Task Reverting_the_migration_is_refused_while_any_merge_exists_even_one_that_voided_nothing_and_allowed_after()
|
||||
{
|
||||
var world = await postgres.NewWorldAsync();
|
||||
var survivor = await world.AccountAsync("survivor");
|
||||
var folded = await world.AccountAsync("folded");
|
||||
await world.CommitAsync(await world.MergeAsync(survivor, folded)); // moves and voids nothing: only the Merged membership remains
|
||||
|
||||
await using (var db = world.Db())
|
||||
{
|
||||
var error = await Assert.ThrowsAnyAsync<Exception>(() => db.GetService<IMigrator>().MigrateAsync("20261113120000_AddPasskeyCredentials"));
|
||||
Assert.Contains("roll-forward only", Pg(error).MessageText);
|
||||
Assert.Equal("20261114120000_AddAccountMerges", (await db.Database.GetAppliedMigrationsAsync()).Last());
|
||||
}
|
||||
|
||||
await ExecuteAsync(world, "DELETE FROM \"AccountMergeEntries\"; DELETE FROM \"AccountMerges\"");
|
||||
await using var down = world.Db();
|
||||
await down.GetService<IMigrator>().MigrateAsync("20261113120000_AddPasskeyCredentials");
|
||||
Assert.Equal("20261113120000_AddPasskeyCredentials", (await down.Database.GetAppliedMigrationsAsync()).Last());
|
||||
await down.GetService<IMigrator>().MigrateAsync(); // and up again, trigger and index and all
|
||||
Assert.Equal("20261114120000_AddAccountMerges", (await down.Database.GetAppliedMigrationsAsync()).Last());
|
||||
}
|
||||
|
||||
// ---- restage and intake journal ----
|
||||
|
||||
[PostgresFact]
|
||||
public async Task Two_merges_into_one_survivor_restaging_at_once_leave_one_current_patron_snapshot_and_the_loser_commits_on_retry()
|
||||
{
|
||||
var world = await postgres.NewWorldAsync();
|
||||
var survivor = await world.AccountAsync("survivor");
|
||||
var first = await world.AccountAsync("first");
|
||||
var second = await world.AccountAsync("second");
|
||||
await using (var db = world.Db())
|
||||
{
|
||||
foreach (var who in new[] { first, second })
|
||||
{
|
||||
db.PatronSupportEvents.Add(new PatronSupportEvent
|
||||
{
|
||||
UserAccountId = who.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = 1000m,
|
||||
SupportedAtUtc = AccountMergeLedgerTests.T0, RecordedAtUtc = AccountMergeLedgerTests.T0
|
||||
});
|
||||
}
|
||||
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var one = await world.MergeAsync(survivor, first);
|
||||
var two = await world.MergeAsync(survivor, second);
|
||||
var committers = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new Rendezvous());
|
||||
|
||||
async Task<Exception?> TryCommit(AccountMerge merge)
|
||||
{
|
||||
try
|
||||
{
|
||||
await committers.CommitAsync(merge);
|
||||
return null;
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
var results = await Task.WhenAll(Task.Run(() => TryCommit(one)), Task.Run(() => TryCommit(two)));
|
||||
|
||||
Assert.Equal(1, results.Count(x => x is null));
|
||||
Assert.All(results.OfType<Exception>(), e => Assert.Contains(Chain(e), x => x is PostgresException { SqlState: "23505", ConstraintName: "UX_TierSnapshots_MembershipId_CurrentPatron" }));
|
||||
var loser = results[0] is null ? two : one;
|
||||
Assert.Equal(AccountMergeState.Committed, (await world.CommitAsync(loser)).State);
|
||||
await using var read = world.Db();
|
||||
var membership = await read.Memberships.Include(x => x.TierSnapshots).SingleAsync(x => x.UserAccountId == survivor.Id);
|
||||
Assert.Single(membership.TierSnapshots, x => x.Kind == TierSnapshotKind.Patron && x.IsCurrent);
|
||||
Assert.All(await read.PatronSupportEvents.ToListAsync(), e => Assert.Equal(survivor.Id, e.UserAccountId));
|
||||
}
|
||||
|
||||
[PostgresFact]
|
||||
public async Task A_patron_refresh_that_loses_the_restage_race_reads_the_winners_snapshot_and_derives_again()
|
||||
{
|
||||
var world = await postgres.NewWorldAsync();
|
||||
var patron = await world.AccountAsync("patron");
|
||||
await using (var db = world.Db())
|
||||
{
|
||||
db.PatronSupportEvents.Add(new PatronSupportEvent
|
||||
{
|
||||
UserAccountId = patron.Id, Kind = PatronSupportEventKind.RecurringSupportSnapshot, IsCurrentRecurringSupport = true, Amount = 1000m,
|
||||
SupportedAtUtc = AccountMergeLedgerTests.T0, RecordedAtUtc = AccountMergeLedgerTests.T0
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var clock = world.Clock;
|
||||
var rival = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world));
|
||||
var loser = AccountMergeLedgerTests.World.OnPostgres(ConnectionOf(world), new BeforeFirstSave(async () =>
|
||||
{
|
||||
await using var rivalDb = rival.Db();
|
||||
await new PatronageService(rivalDb, new AuditTrailService(rivalDb, clock), clock).RefreshPatronTierSnapshotAsync(null, patron.Id, default);
|
||||
}));
|
||||
|
||||
await using (var db = loser.Db())
|
||||
{
|
||||
var summary = await new PatronageService(db, new AuditTrailService(db, clock), clock).RefreshPatronTierSnapshotAsync(null, patron.Id, default);
|
||||
Assert.True(summary.VotingWeight > 0m);
|
||||
}
|
||||
|
||||
await using var read = world.Db();
|
||||
var snapshots = await read.TierSnapshots.Where(x => x.Kind == TierSnapshotKind.Patron).ToListAsync();
|
||||
Assert.Single(snapshots, x => x.IsCurrent);
|
||||
Assert.Equal(2, snapshots.Count); // the winner's, demoted by the retry, and the retry's own
|
||||
}
|
||||
|
||||
[PostgresFact]
|
||||
public async Task A_journalled_patron_intake_takes_the_next_seq_after_the_commits_entries_and_is_idempotent()
|
||||
{
|
||||
var world = await postgres.NewWorldAsync();
|
||||
var survivor = await world.AccountAsync("survivor");
|
||||
var folded = await world.AccountAsync("folded");
|
||||
var motion = await world.MotionAsync();
|
||||
await world.VoteAsync(motion, survivor, VoteChoice.For);
|
||||
await world.VoteAsync(motion, folded, VoteChoice.Against);
|
||||
await world.CommitAsync(await world.MergeAsync(survivor, folded));
|
||||
await world.VoteAsync(motion, folded, VoteChoice.For);
|
||||
var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
|
||||
var committed = (await world.JournalAsync(merge)).Count;
|
||||
Assert.True(committed > 0);
|
||||
|
||||
await using (var db = world.Db())
|
||||
var events = new[] { Guid.NewGuid(), Guid.NewGuid() };
|
||||
foreach (var id in events.Concat(events)) // each twice: the provider retries
|
||||
{
|
||||
var error = await Assert.ThrowsAnyAsync<Exception>(() => db.GetService<IMigrator>().MigrateAsync("20261113120000_AddPasskeyCredentials"));
|
||||
Assert.Contains("cannot be reverted", Pg(error).MessageText);
|
||||
Assert.Equal("20261114120000_AddAccountMerges", (await db.Database.GetAppliedMigrationsAsync()).Last());
|
||||
await using var db = world.Db();
|
||||
await world.Ledger(db).JournalIntakeAsync(merge.Id, folded.Id, id, default);
|
||||
}
|
||||
|
||||
await ExecuteAsync(world, "UPDATE \"Votes\" SET \"VoidedByMergeId\" = NULL, \"VoidedUtc\" = NULL");
|
||||
await using var down = world.Db();
|
||||
await down.GetService<IMigrator>().MigrateAsync("20261113120000_AddPasskeyCredentials");
|
||||
Assert.Equal("20261113120000_AddPasskeyCredentials", (await down.Database.GetAppliedMigrationsAsync()).Last());
|
||||
await down.GetService<IMigrator>().MigrateAsync(); // and up again, trigger and all
|
||||
Assert.Equal("20261114120000_AddAccountMerges", (await down.Database.GetAppliedMigrationsAsync()).Last());
|
||||
var journal = await world.JournalAsync(merge);
|
||||
Assert.Equal(committed + 2, journal.Count);
|
||||
Assert.Equal(journal.Count, journal.Select(x => x.Seq).Distinct().Count());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -916,6 +916,26 @@ public sealed class HeimdallCompletionTests
|
|||
Assert.Equal(MembershipStatus.Merged, (await host.Account(foldedId))!.Membership!.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_legacy_account_without_a_membership_row_signs_in_and_gets_one()
|
||||
{
|
||||
using var host = new HeimdallHost();
|
||||
var accountId = HeimdallShapes.NewAccountId();
|
||||
Assert.True((await Genuine(host, await host.StartAsync(member: false), accountId)).SignedIn);
|
||||
await host.Db(async db =>
|
||||
{
|
||||
db.Memberships.RemoveRange(db.Memberships.Where(x => x.UserAccount.HeimdallAccountId == accountId));
|
||||
await db.SaveChangesAsync();
|
||||
return 0;
|
||||
});
|
||||
Assert.Null((await host.Account(accountId))!.Membership);
|
||||
|
||||
var again = await Genuine(host, await host.StartAsync(member: true), accountId, ["member_access"]);
|
||||
|
||||
Assert.True(again.SignedIn);
|
||||
Assert.Equal(MembershipStatus.Active, (await host.Account(accountId))!.Membership!.Status);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_chat_only_account_that_later_signs_in_with_member_access_becomes_a_member()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -272,6 +272,45 @@ public sealed class SealedBallotTests
|
|||
Assert.Equal(1, await rig.Db.AuditEvents.CountAsync(x => x.Action == "sealed.closed"));
|
||||
}
|
||||
|
||||
private static async Task FreezeAsync(Rig rig, CurrentBifrostActor folded)
|
||||
{
|
||||
var survivor = rig.Member("Survivor");
|
||||
rig.Db.AccountMerges.Add(new AccountMerge
|
||||
{
|
||||
SurvivorUserAccountId = survivor.UserAccount!.Id, FoldedUserAccountId = folded.UserAccount!.Id, State = AccountMergeState.Confirmed, CreatedUtc = T0
|
||||
});
|
||||
await rig.Db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_commit_from_an_actor_resolved_before_the_account_froze_writes_no_ballot()
|
||||
{
|
||||
var rig = new Rig();
|
||||
var motion = await rig.OpenAsync("Ana", "Bo");
|
||||
var staleActor = rig.Member("Folded"); // resolved before the merge was confirmed
|
||||
await FreezeAsync(rig, staleActor);
|
||||
var refusal = await Assert.ThrowsAsync<SealedBallotException>(() => rig.Cast(staleActor, motion.Id, "Ana", "Mine."));
|
||||
|
||||
Assert.Equal(SealedBallotFailure.Forbidden, refusal.Failure);
|
||||
Assert.Empty(rig.Db.SealedBallots);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_reveal_from_an_actor_resolved_before_the_account_froze_changes_nothing()
|
||||
{
|
||||
var rig = new Rig();
|
||||
var motion = await rig.OpenAsync("Ana", "Bo");
|
||||
var staleActor = rig.Member("Folded");
|
||||
await rig.Cast(staleActor, motion.Id, "Ana", "Mine.");
|
||||
await FreezeAsync(rig, staleActor);
|
||||
rig.Clock.Now = T0.AddMinutes(90);
|
||||
|
||||
var refusal = await Assert.ThrowsAsync<SealedBallotException>(() => rig.Reveal(staleActor, motion.Id, "Ana", "Mine."));
|
||||
|
||||
Assert.Equal(SealedBallotFailure.Forbidden, refusal.Failure);
|
||||
Assert.Null((await rig.Db.SealedBallots.SingleAsync()).RevealedAtUtc);
|
||||
}
|
||||
|
||||
// Runs a callback once, just before the first save that closes a motion: the window between the close reading its ballots and writing.
|
||||
private sealed class BeforeCloseSave(Func<Task> action) : SaveChangesInterceptor
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue