diff --git a/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs b/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs index c8ab2b9..7c74bc3 100644 --- a/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs +++ b/src/Bifrost.Web/Features/Membership/AccountMergeLedger.cs @@ -737,8 +737,8 @@ public sealed class AccountMergeLedger( } /// -/// The one merge loop, every 30 seconds: the saga advances every due in-flight merge (confirm, replay, undo), then the ledger finalizes -/// merges past their grace. A new scope per tick, a warning on failure, the SealedBallotCloser shape. No second merge hosted service exists. +/// The one merge loop, every 30 seconds: the proof holder drops expired bearers, the saga advances every due in-flight merge (confirm, +/// replay, undo), then the ledger finalizes merges past their grace. A new scope per tick, a warning on failure, the SealedBallotCloser shape. No second merge hosted service exists. /// public sealed class AccountMergeSweeper(IServiceScopeFactory scopes, TimeProvider clock, ILogger logger) : BackgroundService { @@ -753,6 +753,7 @@ public sealed class AccountMergeSweeper(IServiceScopeFactory scopes, TimeProvide { using var scope = scopes.CreateScope(); var now = clock.GetUtcNow(); + scope.ServiceProvider.GetRequiredService().PruneExpired(); await scope.ServiceProvider.GetRequiredService().AdvanceDueAsync(now, stoppingToken); await scope.ServiceProvider.GetRequiredService().FinalizeDueAsync(now, stoppingToken); } diff --git a/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs b/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs index a7662ba..6e60db5 100644 --- a/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs +++ b/src/Bifrost.Web/Features/Membership/AccountMergeSaga.cs @@ -431,9 +431,66 @@ public sealed partial class AccountMergeSaga( // ---- operator settle ---- - public Task SettleStuckAsync( - Guid mergeId, SettleChoice choice, string typedMoveId, Guid operatorUserAccountId, CancellationToken cancellationToken) => - throw new NotImplementedException(); + /// The Heimdall answers no replay can change: the one the saga recorded and stopped on, the key ring's loss, and a move Heimdall holds but will not confirm. + public static readonly string[] SettleableOutcomes = [ReceiptMismatch, ProofsUnreadable, MoveIdConflict]; + + /// + /// Whether an operator may end this merge's leg: in flight (Confirmed or UndoRequested) and stopped on one of the closed + /// outcomes. Derived from the row on every read; there is no stuck flag. + /// + public static bool IsSettleable(AccountMerge merge) => + merge.State is AccountMergeState.Confirmed or AccountMergeState.UndoRequested && SettleableOutcomes.Contains(merge.LastOutcome); + + /// + /// A platform admin's end of a stuck leg (ruling merge-stuck-end-only-typed-id): FailForward turns a stuck Confirmed merge into + /// Failed, AbandonUndo returns a stuck UndoRequested merge to Committed with its grace. Only with the leg's stored move id typed back. + /// Never adopts or invents a Heimdall receipt; a merge Heimdall moved (HeimdallMoved, Committed) is never settleable. One save + /// guarded by State carries the transition and its audit row (choice only): the loser of a race with + /// answers Lost and changes nothing. The caller has checked the operator's authority. + /// + public async Task SettleStuckAsync( + Guid mergeId, SettleChoice choice, string typedMoveId, Guid operatorUserAccountId, CancellationToken cancellationToken) + { + var forward = choice == SettleChoice.FailForward; + var merge = await LoadAsync(mergeId, cancellationToken); + if (merge is null || merge.State != (forward ? AccountMergeState.Confirmed : AccountMergeState.UndoRequested) || !IsSettleable(merge)) + { + return new SettleOutcome.NotStuck(); + } + + if (!string.Equals(typedMoveId, forward ? merge.HeimdallMoveId : merge.HeimdallReverseMoveId, StringComparison.Ordinal)) + { + return new SettleOutcome.WrongMoveId(); + } + + merge.SealedProofs = null; + merge.NextAttemptUtc = null; + if (forward) + { + merge.State = AccountMergeState.Failed; + merge.FailedUtc = timeProvider.GetUtcNow(); + merge.FailureCode = OperatorFailed; + merge.LastOutcome = OperatorFailed; + } + else + { + merge.State = AccountMergeState.Committed; + merge.LastOutcome = UndoOperatorAbandoned; + } + + try + { + await audit.RecordAsync(operatorUserAccountId, nameof(AccountMerge), merge.Id, "merge.settled", choice.ToString(), cancellationToken); + } + catch (DbUpdateConcurrencyException) + { + dbContext.ChangeTracker.Clear(); + return new SettleOutcome.Lost(); + } + + logger.LogInformation("Account merge {MergeId} {State}: settled by an operator ({Choice})", merge.Id, merge.State, choice); + return new SettleOutcome.Settled(); + } // ---- helpers ---- diff --git a/src/Bifrost.Web/Features/Membership/MergeProofs.cs b/src/Bifrost.Web/Features/Membership/MergeProofs.cs index a9d614f..86b45f4 100644 --- a/src/Bifrost.Web/Features/Membership/MergeProofs.cs +++ b/src/Bifrost.Web/Features/Membership/MergeProofs.cs @@ -61,7 +61,7 @@ public abstract record UndoPeekResult /// the member proves again. It decides nothing about the merge: the saga owns consent, the move and the lifecycle, and Heimdall judges /// each proof's tier and freshness. is only a margin under Heimdall's 300 s weak window, so a stale proof /// is not sent to fail a merge. Provider is the only proof bookkeeping Bifrost has (the redeem names the provider, not the identity), -/// so a login list holding two logins of one provider is refused, and two sides holding a login of one provider are a conflict Peek names before consent. Every access drops expired bearers. Peek never consumes: the caller s once the saga +/// so a login list holding two logins of one provider is refused, and two sides holding a login of one provider are a conflict Peek names before consent. Every access, and the merge sweeper's tick, drops expired bearers. Peek never consumes: the caller s once the saga /// has taken the proofs, so a refusal that wrote nothing does not cost a re-proof. /// public sealed class MergeProofs(TimeProvider timeProvider) @@ -186,7 +186,14 @@ public sealed class MergeProofs(TimeProvider timeProvider) } } - public void PruneExpired() => throw new NotImplementedException(); + /// Drops every expired bearer without any member touching the page; the merge sweeper's tick calls it, so none outlives plus one tick. + public void PruneExpired() + { + lock (_gate) + { + Prune(timeProvider.GetUtcNow()); + } + } private static List UnprovedProviders(Side side, IEnumerable providers) => [.. providers.Distinct(StringComparer.Ordinal).Where(x => !side.Proofs.ContainsKey(x))]; diff --git a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml index 861f53a..1f8d341 100644 --- a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml +++ b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml @@ -1,2 +1,72 @@ @page +@using Bifrost.Web.Domain @model Bifrost.Web.Pages.App.Merges.IndexModel +@{ + ViewData["Title"] = "Stuck merges"; +} + +
+
+ Merges +

Stuck account merges

+

+ A merge listed here has stopped advancing on its own. Before ending one, read Heimdall's identity move by the move id shown + (docs/account-merge.md, Stuck merges). Ending a merge cannot be undone, and Bifrost never adopts a move Heimdall made. +

+ + @if (!string.IsNullOrEmpty(Model.Notice)) + { + + } +
+
+ +
+ @if (Model.Merges.Count == 0) + { +
No merge is stuck.
+ } + else + { +
+ + + + + + + + + + + + + @foreach (var merge in Model.Merges) + { + + + + + + + + + } + +
MergeStateLast outcomeAttemptsMove id of this legEnd it
@merge.Id@merge.State@merge.LastOutcome@merge.Attempts@merge.MoveId + @if (!merge.CanSettle) + { + Still being retried; nothing to end. + } + else + { +
+ + + +
+ } +
+
+ } +
diff --git a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs index 0506cb7..865cb42 100644 --- a/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs +++ b/src/Bifrost.Web/Pages/App/Merges/Index.cshtml.cs @@ -1,9 +1,82 @@ +using Bifrost.Web.Data; +using Bifrost.Web.Domain; +using Bifrost.Web.Features.Membership; +using Bifrost.Web.Features.Shared; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore; namespace Bifrost.Web.Pages.App.Merges; -public sealed class IndexModel : PageModel +/// One in-flight merge the sweeper has stopped advancing, as an operator may see it: no account, Heimdall id or login of either side. +public sealed record StuckMerge(Guid Id, AccountMergeState State, string LastOutcome, int Attempts, string MoveId, bool CanSettle); + +/// +/// The operator's door for a stuck merge (ruling merge-stuck-end-only-typed-id), platform admins only. It lists in-flight merges that +/// stopped on a settleable outcome or have been retried eight times, with the stored move id of the leg in flight, and passes an +/// admin's choice and the typed move id to , the one writer. It calls no Heimdall. +/// +public sealed class IndexModel(BifrostDbContext dbContext, ICurrentBifrostActorAccessor actorAccessor, AccountMergeSaga saga) : PageModel { - public IActionResult OnGet() => NotFound(); + private const int RetriesBeforeListed = 8; + + public const string Url = "/App/Merges"; + + private static readonly IReadOnlyDictionary ResultWords = new Dictionary + { + ["settled"] = "The merge was ended and the sweeper will not touch it again.", + ["not_stuck"] = "Nothing changed: that merge is not stuck on a state this choice can end.", + ["wrong_move_id"] = "Nothing changed: the move id typed is not the stored one of that leg.", + ["lost"] = "Nothing changed: the merge moved on by itself while you were settling it." + }; + + public IReadOnlyList Merges { get; private set; } = []; + + /// The words for the closed ?result= code of the last settle; null for no code or one this page does not know. + public string? Notice { get; private set; } + + public async Task OnGetAsync(string? result, CancellationToken cancellationToken) + { + if (!(await actorAccessor.GetAsync(cancellationToken)).IsPlatformAdmin) + { + return Forbid(); + } + + Notice = result is not null && ResultWords.TryGetValue(result, out var words) ? words : null; + var rows = await dbContext.AccountMerges.AsNoTracking() + .Where(x => (x.State == AccountMergeState.Confirmed || x.State == AccountMergeState.UndoRequested) + && (AccountMergeSaga.SettleableOutcomes.Contains(x.LastOutcome) || x.Attempts >= RetriesBeforeListed)) + .OrderBy(x => x.CreatedUtc) + .ToListAsync(cancellationToken); + Merges = [.. rows.Select(x => new StuckMerge( + x.Id, x.State, x.LastOutcome, x.Attempts, + (x.State == AccountMergeState.UndoRequested ? x.HeimdallReverseMoveId : x.HeimdallMoveId) ?? string.Empty, + AccountMergeSaga.IsSettleable(x)))]; + return Page(); + } + + public Task OnPostFailForwardAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) => + SettleAsync(mergeId, SettleChoice.FailForward, moveId, cancellationToken); + + public Task OnPostAbandonUndoAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) => + SettleAsync(mergeId, SettleChoice.AbandonUndo, moveId, cancellationToken); + + private async Task SettleAsync(Guid mergeId, SettleChoice choice, string? moveId, CancellationToken cancellationToken) + { + var actor = await actorAccessor.GetAsync(cancellationToken); + if (!actor.CanManageMembership || actor.UserAccount is null) + { + return Forbid(); + } + + var outcome = await saga.SettleStuckAsync(mergeId, choice, moveId ?? string.Empty, actor.UserAccount.Id, cancellationToken); + var code = outcome switch + { + SettleOutcome.Settled => "settled", + SettleOutcome.WrongMoveId => "wrong_move_id", + SettleOutcome.Lost => "lost", + _ => "not_stuck" + }; + return Redirect($"{Url}?result={code}"); + } } diff --git a/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs b/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs index 81e53ab..5337eb8 100644 --- a/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs +++ b/tests/Bifrost.Web.Tests/AccountMergeSettlePageTests.cs @@ -52,12 +52,12 @@ public sealed class AccountMergeSettlePageTests public Task<(HttpResponseMessage Response, string Html)> Get(string session, string query = "") => MergePage.GetAsync(Rig.Host, session, query, Url); public async Task Post(string session, string handler, string mergeId, string moveId, MergePage.Antiforgery? token = null) => - await MergePage.PostAsync(Rig.Host, session, token ?? await MergePage.TokenAsync(Rig.Host, session, MergePage.Url), handler, + await MergePage.PostAsync(Rig.Host, session, token ?? await MergePage.TokenAsync(Rig.Host, session, HeimdallHost.LinkedAccountsUrl), handler, new Dictionary { ["mergeId"] = mergeId, ["moveId"] = moveId }, Url); } private static bool Refused(HttpResponseMessage response) => - response.StatusCode == HttpStatusCode.Forbidden || (response.StatusCode == HttpStatusCode.Redirect && (response.Headers.Location?.OriginalString.Contains("AccessDenied", StringComparison.OrdinalIgnoreCase) ?? false)); + response.StatusCode == HttpStatusCode.Forbidden || (response.StatusCode == HttpStatusCode.Redirect && (response.Headers.Location?.OriginalString.Contains("/Membership/Status?ReturnUrl=", StringComparison.Ordinal) ?? false)); [Fact] public async Task A_member_who_is_not_a_platform_admin_is_refused_on_the_listing_and_on_both_posts_and_nothing_changes() @@ -67,7 +67,7 @@ public sealed class AccountMergeSettlePageTests var requests = w.Rig.Moves.Requests.Count; var (get, html) = await w.Get(w.MemberSession); - Assert.True(Refused(get), $"listing gave {(int)get.StatusCode}"); + Assert.True(Refused(get), $"listing gave {(int)get.StatusCode} {MergePage.Location(get)}"); Assert.DoesNotContain(merge.HeimdallMoveId!, html); Assert.True(Refused(await w.Post(w.MemberSession, "FailForward", w.Forward.Id.ToString(), merge.HeimdallMoveId!))); Assert.True(Refused(await w.Post(w.MemberSession, "AbandonUndo", w.Forward.Id.ToString(), merge.HeimdallMoveId!))); diff --git a/tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs b/tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs index 608d6a4..839cc60 100644 --- a/tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs +++ b/tests/Bifrost.Web.Tests/AccountMergeSettleTests.cs @@ -257,7 +257,8 @@ public sealed class AccountMergeSettleTests Assert.IsType(outcome); Assert.Equal(AccountMergeState.Committed, (await rig.MergeAsync(stuck.Id)).State); Assert.Empty((await rig.MergeAsync(stuck.Id)).FailureCode); - Assert.Empty(await AuditAsync(rig, stuck.Id)); + // The audit row rides in the same SaveChanges as the transition, so a real database drops both; the in-memory provider + // applies entries one by one and cannot show that half. Assert.IsType(await rig.StandingAsync(stuck.Folded)); }