Sealed ballot: race-safe close, close sweep, endpoint tests, backup reader and auth findings in the doc
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d5a71eb639
commit
96da1b7a8c
7 changed files with 310 additions and 9 deletions
|
|
@ -278,6 +278,7 @@ public sealed class BifrostDbContext(DbContextOptions<BifrostDbContext> options)
|
|||
entity.Property(x => x.Status).HasConversion<string>();
|
||||
entity.Property(x => x.ApprovalThreshold).HasPrecision(6, 3);
|
||||
entity.Property(x => x.Kind).HasConversion<string>();
|
||||
entity.Property(x => x.Status).IsConcurrencyToken();
|
||||
entity.HasOne(x => x.Project)
|
||||
.WithMany(x => x.Motions)
|
||||
.HasForeignKey(x => x.ProjectId)
|
||||
|
|
|
|||
|
|
@ -941,6 +941,7 @@ namespace Bifrost.Web.Data.Migrations
|
|||
.HasColumnType("text");
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsConcurrencyToken()
|
||||
.IsRequired()
|
||||
.HasColumnType("text");
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,9 @@ using Bifrost.Web.Data;
|
|||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Shared;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Bifrost.Web.Features.Motions;
|
||||
|
||||
|
|
@ -244,6 +247,10 @@ public sealed class SealedBallotService(
|
|||
: now >= motion.CommitClosesAtUtc ? SealedPhase.Reveal
|
||||
: SealedPhase.Commit;
|
||||
|
||||
/// <summary>
|
||||
/// Closes the motion once. Motion.Status is a concurrency token, so of two racing closers exactly one SaveChanges wins;
|
||||
/// the loser reloads the winner's result and writes nothing (no second audit event).
|
||||
/// </summary>
|
||||
private async Task FinalizeAsync(Motion motion, List<SealedBallot> ballots, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var lines = ballots.OrderBy(x => x.UserAccountId)
|
||||
|
|
@ -252,13 +259,42 @@ public sealed class SealedBallotService(
|
|||
motion.Status = MotionStatus.Closed;
|
||||
motion.ResolvedAtUtc = now;
|
||||
motion.ResolutionNote = $"Sealed ballots published: {ballots.Count(x => x.RevealedAtUtc != null)} revealed, {ballots.Count(x => x.RevealedAtUtc == null)} committed but unrevealed.";
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
}
|
||||
catch (DbUpdateConcurrencyException error)
|
||||
{
|
||||
foreach (var entry in error.Entries)
|
||||
{
|
||||
await entry.ReloadAsync(cancellationToken);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await auditTrailService.RecordAsync(
|
||||
null, nameof(Motion), motion.Id, "sealed.closed",
|
||||
$"Closed sealed-ballot motion {motion.Title}; commitment digest {motion.ResultDigest}.",
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Closes every sealed-ballot motion whose deadline has passed, so a motion nobody reads still closes.</summary>
|
||||
public async Task<int> FinalizeDueAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = timeProvider.GetUtcNow();
|
||||
var due = await dbContext.Motions
|
||||
.Where(x => x.Kind == MotionKind.SealedBallot && x.Status == MotionStatus.Open && x.ClosesAtUtc <= now)
|
||||
.ToListAsync(cancellationToken);
|
||||
foreach (var motion in due)
|
||||
{
|
||||
var ballots = await dbContext.SealedBallots.Where(x => x.MotionId == motion.Id).ToListAsync(cancellationToken);
|
||||
await FinalizeAsync(motion, ballots, now, cancellationToken);
|
||||
}
|
||||
|
||||
return due.Count;
|
||||
}
|
||||
|
||||
private SealedMotionState BuildState(Motion motion, DateTimeOffset now, SealedBallotReceipt? own, Guid voterId)
|
||||
{
|
||||
var phase = PhaseOf(motion, now);
|
||||
|
|
@ -337,3 +373,25 @@ public sealed record SealedMotionResult(
|
|||
IReadOnlyList<RevealedBallot> Ballots, IReadOnlyList<AbstainedMember> Unrevealed, IReadOnlyList<AbstainedMember> NonVoters,
|
||||
string CommitmentDigest);
|
||||
public sealed record SealedCommitRequest(string Commitment);
|
||||
|
||||
/// <summary>Sweeps due sealed-ballot motions once a minute. Reads also close on demand; this covers a motion nobody reads.</summary>
|
||||
public sealed class SealedBallotCloser(IServiceScopeFactory scopes, ILogger<SealedBallotCloser> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
|
||||
do
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopes.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<SealedBallotService>().FinalizeDueAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception error) when (error is not OperationCanceledException)
|
||||
{
|
||||
logger.LogWarning(error, "Sealed-ballot close sweep failed; retrying next tick.");
|
||||
}
|
||||
}
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -122,6 +122,7 @@ builder.Services.AddScoped<BifrostIdentityService>();
|
|||
builder.Services.AddScoped<GitHubWebhookService>();
|
||||
builder.Services.AddScoped<MotionGovernanceService>();
|
||||
builder.Services.AddScoped<SealedBallotService>();
|
||||
builder.Services.AddHostedService<SealedBallotCloser>();
|
||||
builder.Services.AddScoped<MotionEveSurfaceService>();
|
||||
builder.Services.AddScoped<PatronageService>();
|
||||
builder.Services.AddScoped<StripeWebhookService>();
|
||||
|
|
@ -547,16 +548,17 @@ eveGovernance.MapGet("/surface", async (
|
|||
var sealedMotions = app.MapGroup("/api/sealed-motions")
|
||||
.RequireAuthorization(ActiveMemberRequirement.PolicyName);
|
||||
|
||||
static async Task<IResult> SealedCall(Func<Task<object>> call)
|
||||
async Task<IResult> SealedCall(Func<Task<object>> call)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Results.Ok(await call());
|
||||
return Results.Text(JsonSerializer.Serialize(await call(), appJsonSerializerOptions), "application/json");
|
||||
}
|
||||
catch (SealedBallotException error)
|
||||
{
|
||||
return Results.Json(
|
||||
new { error = error.Message },
|
||||
return Results.Text(
|
||||
JsonSerializer.Serialize(new { error = error.Message }, appJsonSerializerOptions),
|
||||
"application/json",
|
||||
statusCode: error.Failure switch
|
||||
{
|
||||
SealedBallotFailure.Forbidden => StatusCodes.Status403Forbidden,
|
||||
|
|
|
|||
Loading…
Reference in a new issue