AccountMergeSaga.SettleStuckAsync, the admin Merges page and the sweeper's proof prune (ruling merge-stuck-end-only-typed-id, merge-proof-bearers-memory-bound)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1480883a3b
commit
8bcd6d67e9
7 changed files with 222 additions and 13 deletions
|
|
@ -737,8 +737,8 @@ public sealed class AccountMergeLedger(
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class AccountMergeSweeper(IServiceScopeFactory scopes, TimeProvider clock, ILogger<AccountMergeSweeper> 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<MergeProofs>().PruneExpired();
|
||||
await scope.ServiceProvider.GetRequiredService<AccountMergeSaga>().AdvanceDueAsync(now, stoppingToken);
|
||||
await scope.ServiceProvider.GetRequiredService<AccountMergeLedger>().FinalizeDueAsync(now, stoppingToken);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -431,9 +431,66 @@ public sealed partial class AccountMergeSaga(
|
|||
|
||||
// ---- operator settle ----
|
||||
|
||||
public Task<SettleOutcome> SettleStuckAsync(
|
||||
Guid mergeId, SettleChoice choice, string typedMoveId, Guid operatorUserAccountId, CancellationToken cancellationToken) =>
|
||||
throw new NotImplementedException();
|
||||
/// <summary>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.</summary>
|
||||
public static readonly string[] SettleableOutcomes = [ReceiptMismatch, ProofsUnreadable, MoveIdConflict];
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static bool IsSettleable(AccountMerge merge) =>
|
||||
merge.State is AccountMergeState.Confirmed or AccountMergeState.UndoRequested && SettleableOutcomes.Contains(merge.LastOutcome);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="AdvanceAsync"/>
|
||||
/// answers Lost and changes nothing. The caller has checked the operator's authority.
|
||||
/// </summary>
|
||||
public async Task<SettleOutcome> 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 ----
|
||||
|
||||
|
|
|
|||
|
|
@ -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. <see cref="ProofLifetime"/> 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 <see cref="Clear"/>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 <see cref="Clear"/>s once the saga
|
||||
/// has taken the proofs, so a refusal that wrote nothing does not cost a re-proof.
|
||||
/// </summary>
|
||||
public sealed class MergeProofs(TimeProvider timeProvider)
|
||||
|
|
@ -186,7 +186,14 @@ public sealed class MergeProofs(TimeProvider timeProvider)
|
|||
}
|
||||
}
|
||||
|
||||
public void PruneExpired() => throw new NotImplementedException();
|
||||
/// <summary>Drops every expired bearer without any member touching the page; the merge sweeper's tick calls it, so none outlives <see cref="ProofLifetime"/> plus one tick.</summary>
|
||||
public void PruneExpired()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
Prune(timeProvider.GetUtcNow());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<string> UnprovedProviders(Side side, IEnumerable<string> providers) =>
|
||||
[.. providers.Distinct(StringComparer.Ordinal).Where(x => !side.Proofs.ContainsKey(x))];
|
||||
|
|
|
|||
|
|
@ -1,2 +1,72 @@
|
|||
@page
|
||||
@using Bifrost.Web.Domain
|
||||
@model Bifrost.Web.Pages.App.Merges.IndexModel
|
||||
@{
|
||||
ViewData["Title"] = "Stuck merges";
|
||||
}
|
||||
|
||||
<section class="panel-grid">
|
||||
<article class="panel">
|
||||
<span class="eyebrow">Merges</span>
|
||||
<h1>Stuck account merges</h1>
|
||||
<p class="panel-intro">
|
||||
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.
|
||||
</p>
|
||||
|
||||
@if (!string.IsNullOrEmpty(Model.Notice))
|
||||
{
|
||||
<p class="validation-summary-errors" role="alert">@Model.Notice</p>
|
||||
}
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="table-panel" style="margin-top: 1.5rem;">
|
||||
@if (Model.Merges.Count == 0)
|
||||
{
|
||||
<div class="empty-state" style="margin: 1.25rem;">No merge is stuck.</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-shell">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Merge</th>
|
||||
<th>State</th>
|
||||
<th>Last outcome</th>
|
||||
<th>Attempts</th>
|
||||
<th>Move id of this leg</th>
|
||||
<th>End it</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var merge in Model.Merges)
|
||||
{
|
||||
<tr>
|
||||
<td>@merge.Id</td>
|
||||
<td>@merge.State</td>
|
||||
<td>@merge.LastOutcome</td>
|
||||
<td>@merge.Attempts</td>
|
||||
<td><code>@merge.MoveId</code></td>
|
||||
<td>
|
||||
@if (!merge.CanSettle)
|
||||
{
|
||||
<span>Still being retried; nothing to end.</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" asp-page-handler="@(merge.State == AccountMergeState.UndoRequested ? "AbandonUndo" : "FailForward")">
|
||||
<input type="hidden" name="mergeId" value="@merge.Id" />
|
||||
<input type="text" name="moveId" autocomplete="off" spellcheck="false" aria-label="Type the move id to confirm" />
|
||||
<button class="button" type="submit">@(merge.State == AccountMergeState.UndoRequested ? "Give up the undo" : "Fail the merge")</button>
|
||||
</form>
|
||||
}
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
|
|
|||
|
|
@ -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
|
||||
/// <summary>One in-flight merge the sweeper has stopped advancing, as an operator may see it: no account, Heimdall id or login of either side.</summary>
|
||||
public sealed record StuckMerge(Guid Id, AccountMergeState State, string LastOutcome, int Attempts, string MoveId, bool CanSettle);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="AccountMergeSaga.SettleStuckAsync"/>, the one writer. It calls no Heimdall.
|
||||
/// </summary>
|
||||
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<string, string> ResultWords = new Dictionary<string, string>
|
||||
{
|
||||
["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<StuckMerge> Merges { get; private set; } = [];
|
||||
|
||||
/// <summary>The words for the closed <c>?result=</c> code of the last settle; null for no code or one this page does not know.</summary>
|
||||
public string? Notice { get; private set; }
|
||||
|
||||
public async Task<IActionResult> 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<IActionResult> OnPostFailForwardAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) =>
|
||||
SettleAsync(mergeId, SettleChoice.FailForward, moveId, cancellationToken);
|
||||
|
||||
public Task<IActionResult> OnPostAbandonUndoAsync(Guid mergeId, string? moveId, CancellationToken cancellationToken) =>
|
||||
SettleAsync(mergeId, SettleChoice.AbandonUndo, moveId, cancellationToken);
|
||||
|
||||
private async Task<IActionResult> 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}");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<HttpResponseMessage> 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<string, string> { ["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!)));
|
||||
|
|
|
|||
|
|
@ -257,7 +257,8 @@ public sealed class AccountMergeSettleTests
|
|||
Assert.IsType<SettleOutcome.Lost>(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<MergeStanding.Folded>(await rig.StandingAsync(stuck.Folded));
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue