feat(bp): repositories + identity generation for runtime-inserted tables

Add ValueGeneratedOnAdd to ViewerBattlePassProgress.Id and
ViewerBattlePassClaims.Id so Postgres generates IDENTITY values at
runtime. Regenerate AddBattlePass migration in-place to include the
IdentityByDefaultColumn annotations. Add IBattlePassRepository /
BattlePassRepository (season lookup + level-curve cache) and
IViewerBattlePassRepository / ViewerBattlePassRepository
(get-or-create progress, claim reads/writes).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
gamer147
2026-05-26 22:40:45 -04:00
parent 44da54c418
commit 1420c60486
8 changed files with 168 additions and 3 deletions

View File

@@ -12,7 +12,7 @@ using SVSim.Database;
namespace SVSim.Database.Migrations
{
[DbContext(typeof(SVSimDbContext))]
[Migration("20260527021011_AddBattlePass")]
[Migration("20260527023819_AddBattlePass")]
partial class AddBattlePass
{
/// <inheritdoc />
@@ -1908,8 +1908,11 @@ namespace SVSim.Database.Migrations
modelBuilder.Entity("SVSim.Database.Models.ViewerBattlePassClaimEntry", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("ClaimedAt")
.HasColumnType("timestamp with time zone");
@@ -1944,8 +1947,11 @@ namespace SVSim.Database.Migrations
modelBuilder.Entity("SVSim.Database.Models.ViewerBattlePassProgressEntry", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("CurrentPoint")
.HasColumnType("integer");

View File

@@ -1,5 +1,6 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
@@ -35,7 +36,8 @@ namespace SVSim.Database.Migrations
name: "ViewerBattlePassClaims",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false),
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ViewerId = table.Column<long>(type: "bigint", nullable: false),
SeasonId = table.Column<int>(type: "integer", nullable: false),
Track = table.Column<int>(type: "integer", nullable: false),
@@ -53,7 +55,8 @@ namespace SVSim.Database.Migrations
name: "ViewerBattlePassProgress",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false),
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ViewerId = table.Column<long>(type: "bigint", nullable: false),
SeasonId = table.Column<int>(type: "integer", nullable: false),
CurrentPoint = table.Column<int>(type: "integer", nullable: false),

View File

@@ -1905,8 +1905,11 @@ namespace SVSim.Database.Migrations
modelBuilder.Entity("SVSim.Database.Models.ViewerBattlePassClaimEntry", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTimeOffset>("ClaimedAt")
.HasColumnType("timestamp with time zone");
@@ -1941,8 +1944,11 @@ namespace SVSim.Database.Migrations
modelBuilder.Entity("SVSim.Database.Models.ViewerBattlePassProgressEntry", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("CurrentPoint")
.HasColumnType("integer");

View File

@@ -0,0 +1,53 @@
using Microsoft.EntityFrameworkCore;
using SVSim.Database.Models;
namespace SVSim.Database.Repositories.BattlePass;
public sealed class BattlePassRepository : IBattlePassRepository
{
private readonly SVSimDbContext _db;
// Process-level cache for the immutable level curve. Bootstrap re-baseline = host restart = cache cleared.
private static IReadOnlyList<BattlePassLevelEntry>? _curveCache;
private static readonly SemaphoreSlim _curveCacheLock = new(1, 1);
public BattlePassRepository(SVSimDbContext db)
{
_db = db;
}
public async Task<BattlePassSeasonEntry?> GetActiveSeasonAsync(DateTimeOffset when, CancellationToken ct)
{
return await _db.BattlePassSeasons
.AsNoTracking()
.Where(s => s.StartDate <= when && s.EndDate > when)
.OrderByDescending(s => s.StartDate)
.FirstOrDefaultAsync(ct);
}
public Task<BattlePassSeasonEntry?> GetSeasonAsync(int seasonId, CancellationToken ct) =>
_db.BattlePassSeasons.AsNoTracking().FirstOrDefaultAsync(s => s.Id == seasonId, ct);
public async Task<List<BattlePassRewardEntry>> GetSeasonRewardsAsync(int seasonId, CancellationToken ct) =>
await _db.BattlePassRewards.AsNoTracking()
.Where(r => r.SeasonId == seasonId)
.OrderBy(r => r.Track).ThenBy(r => r.Level)
.ToListAsync(ct);
public async Task<IReadOnlyList<BattlePassLevelEntry>> GetLevelCurveAsync(CancellationToken ct)
{
if (_curveCache is not null) return _curveCache;
await _curveCacheLock.WaitAsync(ct);
try
{
if (_curveCache is null)
{
_curveCache = await _db.BattlePassLevels.AsNoTracking()
.OrderBy(e => e.Level)
.ToListAsync(ct);
}
return _curveCache;
}
finally { _curveCacheLock.Release(); }
}
}

View File

@@ -0,0 +1,27 @@
using SVSim.Database.Models;
namespace SVSim.Database.Repositories.BattlePass;
public interface IBattlePassRepository
{
/// <summary>
/// Active season for the given moment (StartDate &lt;= when &lt; EndDate). Returns null
/// if none. If multiple match (overlap), the most recently started wins.
/// </summary>
Task<BattlePassSeasonEntry?> GetActiveSeasonAsync(DateTimeOffset when, CancellationToken ct);
/// <summary>
/// Season by id (no time-window filter). Used by /battle_pass/buy to validate request.season_id.
/// </summary>
Task<BattlePassSeasonEntry?> GetSeasonAsync(int seasonId, CancellationToken ct);
/// <summary>
/// All rewards for a season, both tracks. Sorted by (Track, Level) for deterministic wire order.
/// </summary>
Task<List<BattlePassRewardEntry>> GetSeasonRewardsAsync(int seasonId, CancellationToken ct);
/// <summary>
/// Global level curve. Cached after first load.
/// </summary>
Task<IReadOnlyList<BattlePassLevelEntry>> GetLevelCurveAsync(CancellationToken ct);
}

View File

@@ -0,0 +1,23 @@
using SVSim.Database.Enums;
using SVSim.Database.Models;
namespace SVSim.Database.Repositories.BattlePass;
public interface IViewerBattlePassRepository
{
/// <summary>
/// Get-or-create progress row for (viewer, season). New rows are added to the change-tracker
/// but NOT saved — caller batches with other mutations.
/// </summary>
Task<ViewerBattlePassProgressEntry> GetOrCreateProgressAsync(long viewerId, int seasonId, CancellationToken ct);
/// <summary>
/// All claim rows for (viewer, season). Used by /battle_pass/info to enrich is_received.
/// </summary>
Task<List<ViewerBattlePassClaimEntry>> GetClaimsAsync(long viewerId, int seasonId, CancellationToken ct);
/// <summary>
/// Append a claim row (in-memory; caller saves).
/// </summary>
void AddClaim(long viewerId, int seasonId, BattlePassTrack track, int level, DateTimeOffset claimedAt);
}

View File

@@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore;
using SVSim.Database.Enums;
using SVSim.Database.Models;
namespace SVSim.Database.Repositories.BattlePass;
public sealed class ViewerBattlePassRepository : IViewerBattlePassRepository
{
private readonly SVSimDbContext _db;
public ViewerBattlePassRepository(SVSimDbContext db) { _db = db; }
public async Task<ViewerBattlePassProgressEntry> GetOrCreateProgressAsync(long viewerId, int seasonId, CancellationToken ct)
{
var existing = await _db.ViewerBattlePassProgress
.FirstOrDefaultAsync(p => p.ViewerId == viewerId && p.SeasonId == seasonId, ct);
if (existing is not null) return existing;
var entry = new ViewerBattlePassProgressEntry
{
ViewerId = viewerId,
SeasonId = seasonId,
CurrentPoint = 0,
IsPremium = false,
WeeklyPoints = 0,
WeeklyPeriodStart = null,
};
_db.ViewerBattlePassProgress.Add(entry);
return entry;
}
public Task<List<ViewerBattlePassClaimEntry>> GetClaimsAsync(long viewerId, int seasonId, CancellationToken ct) =>
_db.ViewerBattlePassClaims.AsNoTracking()
.Where(c => c.ViewerId == viewerId && c.SeasonId == seasonId)
.ToListAsync(ct);
public void AddClaim(long viewerId, int seasonId, BattlePassTrack track, int level, DateTimeOffset claimedAt)
{
_db.ViewerBattlePassClaims.Add(new ViewerBattlePassClaimEntry
{
ViewerId = viewerId, SeasonId = seasonId, Track = track,
Level = level, ClaimedAt = claimedAt,
});
}
}

View File

@@ -230,12 +230,14 @@ public class SVSimDbContext : DbContext
modelBuilder.Entity<ViewerBattlePassProgressEntry>(b =>
{
b.HasKey(e => e.Id);
b.Property(e => e.Id).ValueGeneratedOnAdd();
b.HasIndex(e => new { e.ViewerId, e.SeasonId }).IsUnique();
});
modelBuilder.Entity<ViewerBattlePassClaimEntry>(b =>
{
b.HasKey(e => e.Id);
b.Property(e => e.Id).ValueGeneratedOnAdd();
b.HasIndex(e => new { e.ViewerId, e.SeasonId, e.Track, e.Level }).IsUnique();
b.HasIndex(e => new { e.ViewerId, e.SeasonId });
});