Mill votes: ranked, paged read and not-yet-voted-by-this-network filter (#41)

This commit is contained in:
Heimdall 2026-11-10 21:06:56 +00:00
commit 12a153f66f
6 changed files with 787 additions and 0 deletions

View file

@ -23,6 +23,18 @@ public sealed record StanceCounts(int Up, int Down);
public sealed record ConceptTally(int Up, int Down, StanceCounts Members);
public enum RankOrder
{
Net,
Total,
Newest
}
// One row of the ranked read: counts and the subject's title only, never a voter key, account id or network tag.
public sealed record RankedSubject(string Key, string Title, ConceptTally Tally);
public sealed record RankedPage(IReadOnlyList<RankedSubject> Items, string? NextCursor);
public sealed record ConceptSubjectView(
string Collection,
string Key,
@ -189,6 +201,74 @@ public sealed class ConceptAppraisalService(
StringComparer.Ordinal);
}
// The ranked read: live subjects of one collection ordered by net (up minus down), total (up plus down) or
// registration time, largest first, ties by key ascending, so the order is total and a cursor names a position.
// The cursor is keyset: the next page is whatever sorts after the last row's (value, key), so a vote landing
// between pages can move rows but never makes a page repeat the cursor's own row. With unvoted and a client
// address, subjects whose stored tag equals the client's are left out (no address filters nothing) ("not yet voted by this network"); the tag is only compared
// inside the query and is never returned. Null when the collection has no live subject.
public async Task<RankedPage?> GetRankedAsync(
string collection,
RankOrder order,
int limit,
RankCursor? after,
bool unvoted,
IPAddress? client,
CancellationToken cancellationToken)
{
var live = await dbContext.ConceptSubjects.AsNoTracking()
.Where(x => x.Collection == collection && x.RetiredAtUtc == null)
.Select(x => new { x.Id, x.Key, x.Title, x.RegisteredAtUtc })
.ToListAsync(cancellationToken);
if (live.Count == 0)
{
return null;
}
var ids = live.Select(x => x.Id).ToList();
var groups = await dbContext.ConceptAppraisals.AsNoTracking()
.Where(x => ids.Contains(x.SubjectId))
.GroupBy(x => new { x.SubjectId, x.Stance, IsMember = x.VoterClass == VoterClass.Member })
.Select(g => new { g.Key.SubjectId, g.Key.Stance, g.Key.IsMember, Count = g.Count() })
.ToListAsync(cancellationToken);
var voted = new HashSet<Guid>();
if (unvoted && client is not null)
{
var opts = options.Value;
var tag = NetworkPrefix.Tag(client, opts.IPv4PrefixLength, opts.IPv6PrefixLength, opts.NetworkTagSecret);
voted = (await dbContext.ConceptAppraisals.AsNoTracking()
.Where(x => ids.Contains(x.SubjectId) && x.NetworkTag == tag)
.Select(x => x.SubjectId)
.ToListAsync(cancellationToken)).ToHashSet();
}
var rows = live
.Where(s => !voted.Contains(s.Id))
.Select(s =>
{
var tally = Tally(groups.Where(g => g.SubjectId == s.Id).Select(g => (g.Stance, g.IsMember, g.Count)));
var value = order switch
{
RankOrder.Net => (long)tally.Up - tally.Down,
RankOrder.Total => (long)tally.Up + tally.Down,
_ => s.RegisteredAtUtc.UtcTicks
};
return (Value: value, s.Key, s.Title, Tally: tally);
})
.Where(r => after is null || r.Value < after.Value || (r.Value == after.Value && string.CompareOrdinal(r.Key, after.Key) > 0))
.OrderByDescending(r => r.Value)
.ThenBy(r => r.Key, StringComparer.Ordinal)
.Take(limit + 1)
.ToList();
var page = rows.Take(limit).ToList();
var next = rows.Count > limit
? new RankCursor(order, unvoted, page[^1].Value, page[^1].Key).Encode()
: null;
return new RankedPage(page.Select(r => new RankedSubject(r.Key, r.Title, r.Tally)).ToList(), next);
}
public async Task<ConceptSubjectView?> GetSubjectAsync(
string collection,
string key,

View file

@ -65,4 +65,89 @@ public static class ConceptTallyExport
response.Headers.CacheControl = "public, max-age=60";
return Results.Json(tallies);
}).AllowAnonymous().RequireCors(CorsPolicy);
public const int DefaultPageSize = 50;
public const int MaxPageSize = 100;
// The ranked, paged read beside the map: GET /public/concepts/{collection}/ranked
// ?sort=net|total|newest (default net) &limit=1..100 (default 50) &cursor=<opaque> &unvoted=network
// returns { items: [{ key, title, up, down, members: { up, down } }], next_cursor }. The query is a closed
// shape: an unknown or repeated key, an out-of-range value or a cursor that is not exactly one this route issued
// for the same sort and filter is a 400. unvoted=network leaves out the concepts the caller's own network tag
// has already voted on; the tag is derived from the connection and compared inside the query, never accepted
// from the request and never returned. That answer depends on the caller, so it is never cached.
public static IEndpointConventionBuilder MapConceptRankedExport(this IEndpointRouteBuilder app) =>
app.MapGet(RoutePrefix + "/{collection}/ranked", async (
string collection,
HttpContext http,
ConceptAppraisalService appraisals,
CancellationToken cancellationToken) =>
{
if (!ConceptKey.IsValid(collection))
{
return Results.NotFound();
}
if (!TryReadRankedQuery(http.Request.Query, out var order, out var limit, out var cursor, out var unvoted))
{
return JsonText(new { error = "request_invalid" }, StatusCodes.Status400BadRequest);
}
var page = await appraisals.GetRankedAsync(
collection, order, limit, cursor, unvoted, http.Connection.RemoteIpAddress, cancellationToken);
if (page is null)
{
return Results.NotFound();
}
http.Response.Headers.CacheControl = unvoted ? "private, no-store" : "public, max-age=60";
return JsonText(new
{
items = page.Items.Select(i => new
{
key = i.Key,
title = i.Title,
up = i.Tally.Up,
down = i.Tally.Down,
members = new { up = i.Tally.Members.Up, down = i.Tally.Members.Down }
}),
next_cursor = page.NextCursor
}, StatusCodes.Status200OK);
}).AllowAnonymous().RequireCors(CorsPolicy);
private static IResult JsonText(object body, int status) =>
Results.Text(System.Text.Json.JsonSerializer.Serialize(body), "application/json", statusCode: status);
internal static bool TryReadRankedQuery(
IQueryCollection query, out RankOrder order, out int limit, out RankCursor? cursor, out bool unvoted)
{
order = RankOrder.Net;
limit = DefaultPageSize;
cursor = null;
unvoted = false;
foreach (var (key, values) in query)
{
if (values.Count != 1 || values[0] is not { } value)
{
return false;
}
switch (key)
{
case "sort" when value == "net": order = RankOrder.Net; break;
case "sort" when value == "total": order = RankOrder.Total; break;
case "sort" when value == "newest": order = RankOrder.Newest; break;
case "limit" when int.TryParse(value, System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out var n) &&
n is >= 1 and <= MaxPageSize && value == n.ToString(System.Globalization.CultureInfo.InvariantCulture):
limit = n;
break;
case "cursor" when RankCursor.TryDecode(value, out var decoded): cursor = decoded; break;
case "unvoted" when value == "network": unvoted = true; break;
default: return false;
}
}
return cursor is null || (cursor.Order == order && cursor.Unvoted == unvoted);
}
}

View file

@ -0,0 +1,59 @@
using System.Globalization;
using System.Text;
using Microsoft.AspNetCore.WebUtilities;
namespace Bifrost.Web.Features.ConceptVotes;
// The opaque cursor of the ranked read: the last row's sort value and key, plus the order and filter it was issued
// for, so a cursor cannot be replayed under another order or filter. Text "1|order|u|value|key", base64url without
// padding; the length cap only bounds decoding work. Not signed: it names a position in public data and grants nothing. Decoding is strict and canonical (a
// cursor that does not re-encode to the same text is refused), and every field is re-validated, so no cursor text
// reaches a query unparsed.
public sealed record RankCursor(RankOrder Order, bool Unvoted, long Value, string Key)
{
public const int MaxLength = 200;
public string Encode() =>
WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(
string.Create(CultureInfo.InvariantCulture, $"1|{(int)Order}|{(Unvoted ? 1 : 0)}|{Value}|{Key}")));
public static bool TryDecode(string? text, out RankCursor cursor)
{
cursor = null!;
if (string.IsNullOrEmpty(text) || text.Length > MaxLength)
{
return false;
}
string plain;
try
{
var bytes = WebEncoders.Base64UrlDecode(text);
plain = new UTF8Encoding(false, true).GetString(bytes);
}
catch (Exception ex) when (ex is FormatException or ArgumentException)
{
return false;
}
var parts = plain.Split('|');
if (parts.Length != 5 || parts[0] != "1" ||
!int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var order) ||
!Enum.IsDefined((RankOrder)order) ||
parts[2] is not ("0" or "1") ||
!long.TryParse(parts[3], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var value) ||
!ConceptKey.IsValid(parts[4]))
{
return false;
}
var candidate = new RankCursor((RankOrder)order, parts[2] == "1", value, parts[4]);
if (candidate.Encode() != text)
{
return false;
}
cursor = candidate;
return true;
}
}

View file

@ -293,6 +293,7 @@ app.MapGet("/readyz", async (ReadinessService readinessService, CancellationToke
}).AllowAnonymous();
app.MapConceptTallyExport();
app.MapConceptRankedExport();
if (oidcOptions is not null)
{