diff --git a/OshimaBot.Game/Services/FunGameSimulation.cs b/OshimaBot.Game/Services/FunGameSimulation.cs index 7d618fb..c2aa869 100644 --- a/OshimaBot.Game/Services/FunGameSimulation.cs +++ b/OshimaBot.Game/Services/FunGameSimulation.cs @@ -84,6 +84,7 @@ namespace OshimaBot.Game.Services public static async Task> StartSimulationGame(SimulationOptions options, SimulationRunContext context) { ArgumentNullException.ThrowIfNull(context); + context.ArchiveRounds = options.ArchiveRounds; using IDisposable scope = BeginRun(context); return await StartSimulationGameCore(options).ConfigureAwait(false); } @@ -701,18 +702,23 @@ namespace OshimaBot.Game.Services } } - string zipFileName = "rounds_archive.zip"; - try + // S9:默认不再无条件落盘 zip;结果由 simulation_runs 表承载, + // 只有显式开启 ArchiveRounds(复盘 / 平衡测试)才生成 rounds_archive.zip。 + if (Current.ArchiveRounds) { - WriteRoundsToZip(actionQueue.Rounds.ToDictionary(kv => kv.Round, kv => kv), zipFileName); - } - catch (Exception ex) - { - // 档案落盘失败(IO/权限/磁盘满等)不应连带丢弃整局模拟结果 - string msg = $"回合记录写入失败({zipFileName}):{ex.Message}"; - Console.WriteLine(ex); - result.Add(msg); - lastRecord.Add(msg); + string zipFileName = "rounds_archive.zip"; + try + { + WriteRoundsToZip(actionQueue.Rounds.ToDictionary(kv => kv.Round, kv => kv), zipFileName); + } + catch (Exception ex) + { + // 档案落盘失败(IO/权限/磁盘满等)不应连带丢弃整局模拟结果 + string msg = $"回合记录写入失败({zipFileName}):{ex.Message}"; + Console.WriteLine(ex); + result.Add(msg); + lastRecord.Add(msg); + } } LastRecord = result; diff --git a/OshimaBot.Game/Services/SimulationOptions.cs b/OshimaBot.Game/Services/SimulationOptions.cs index fc71a47..b6f7d5b 100644 --- a/OshimaBot.Game/Services/SimulationOptions.cs +++ b/OshimaBot.Game/Services/SimulationOptions.cs @@ -32,6 +32,12 @@ namespace OshimaBot.Game.Services /// 调试模式(输出更多运行细节) public bool IsDebug { get; set; } + /// + /// S9:是否把回合记录写入 rounds_archive.zip。默认 false —— 归档改由 + /// simulation_runs 表承担,只有显式开启(复盘/平衡测试)才落盘。 + /// + public bool ArchiveRounds { get; set; } + /// /// 是否启用「角色绑定的回合奖励」(对应 InitRoundRewards 的 bindToCharacter)。 /// 默认 true:不启用时【命运XX】系技能(抢夺 / 剥夺 / 馈赠)与【强运】会全部静默失效。 diff --git a/OshimaBot.Game/Services/SimulationRunContext.cs b/OshimaBot.Game/Services/SimulationRunContext.cs index 7a15b05..8ff6ad1 100644 --- a/OshimaBot.Game/Services/SimulationRunContext.cs +++ b/OshimaBot.Game/Services/SimulationRunContext.cs @@ -22,6 +22,9 @@ public sealed class SimulationRunContext public Random Random { get; set; } = new(); public GameMap Map { get; set; } = new FastAutoMap(); + /// S9:本局是否额外写 rounds_archive.zip(默认关闭,结果统一入库)。 + public bool ArchiveRounds { get; set; } + /// 绑定到本实例的日志回调:不依赖 AsyncLocal,跨线程回调也不会串局。 public void WriteLine(string text) { diff --git a/OshimaBot.Game/Services/SimulationStatisticsStore.cs b/OshimaBot.Game/Services/SimulationStatisticsStore.cs index befc458..e535cb3 100644 --- a/OshimaBot.Game/Services/SimulationStatisticsStore.cs +++ b/OshimaBot.Game/Services/SimulationStatisticsStore.cs @@ -18,6 +18,12 @@ public interface ISimulationStatisticsStore /// 在读锁内执行读取,避免与正在写入的模拟互相干扰。 T Read(Func reader); + + /// + /// 一局模拟结束后把统计与最近日志持久化。内存实现为空操作; + /// S9 的 EF Core 实现写 simulation_statistics,重启后可恢复。 + /// + Task PersistAsync(CancellationToken cancellationToken = default); } public sealed class InMemorySimulationStatisticsStore : ISimulationStatisticsStore @@ -49,4 +55,6 @@ public sealed class InMemorySimulationStatisticsStore : ISimulationStatisticsSto { lock (_sync) return reader(this); } + + public Task PersistAsync(CancellationToken cancellationToken = default) => Task.CompletedTask; } diff --git a/OshimaBot.Tests/SimulationIsolationTests.cs b/OshimaBot.Tests/SimulationIsolationTests.cs index 32a0f8a..b4b46a9 100644 --- a/OshimaBot.Tests/SimulationIsolationTests.cs +++ b/OshimaBot.Tests/SimulationIsolationTests.cs @@ -1,4 +1,5 @@ using FunGame.Core.Entity; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using OshimaBot.Game.Services; using OshimaBot.Models; @@ -105,7 +106,8 @@ public sealed class SimulationIsolationTests InMemorySimulationStatisticsStore store = new(); store.LastRecord = ["A"]; store.LastFullRecord = ["A", "B"]; - FunGameSimulationService service = new(store, Options.Create(new ServerOptions())); + FunGameSimulationService service = new(store, new NoopRunRecorder(), + Options.Create(new ServerOptions()), NullLogger.Instance); Assert.Equal(new[] { "A" }, await service.GetLastAsync(false)); Assert.Equal(2, (await service.GetLastAsync(true)).Count); @@ -128,4 +130,10 @@ public sealed class SimulationIsolationTests Assert.Single(ranking); Assert.Contains("技术得分", ranking[0]); } + + private sealed class NoopRunRecorder : ISimulationRunRecorder + { + public Task RecordAsync(SimulationRunRecord record, CancellationToken cancellationToken = default) + => Task.FromResult(0L); + } } diff --git a/OshimaBot.Tests/SimulationPersistenceTests.cs b/OshimaBot.Tests/SimulationPersistenceTests.cs new file mode 100644 index 0000000..bac62f7 --- /dev/null +++ b/OshimaBot.Tests/SimulationPersistenceTests.cs @@ -0,0 +1,199 @@ +using FunGame.Core.Entity; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using OshimaBot.Data; +using OshimaBot.Game.Services; +using OshimaBot.Models; +using OshimaBot.Services; +using Xunit; + +namespace OshimaBot.Tests; + +/// S9:模拟统计 / 日志数据库化,验证重启恢复与默认值。 +public sealed class SimulationPersistenceTests +{ + [Fact] + public async Task Restart_RestoresStatisticsAndLastLogs() + { + using PersistenceDatabase db = new(); + EfSimulationStatisticsStore first = db.CreateStore(); + await first.LoadAsync(); // 空库 + first.Reset(FunGameService.Characters); + + Character character = FunGameService.Characters[0]; + first.CharacterStatistics[character].Plays = 7; + first.TeamCharacterStatistics[character].Wins = 3; + + DateTimeOffset now = DateTimeOffset.UtcNow; + await first.RecordAsync(new SimulationRunRecord( + 42, 12345, "{\"IsTeam\":false}", ["精简A", "精简B"], + ["完整A", "完整B", "完整C"], now, now.AddSeconds(2))); + await first.PersistAsync(); + + // 全新 store 实例 + 同一数据库 = 进程重启 + EfSimulationStatisticsStore second = db.CreateStore(); + await second.LoadAsync(); + + Assert.Equal(FunGameService.Characters.Count, second.CharacterStatistics.Count); + Assert.Equal(7, second.CharacterStatistics[character].Plays); + Assert.Equal(3, second.TeamCharacterStatistics[character].Wins); + Assert.Equal(new[] { "精简A", "精简B" }, second.LastRecord); + Assert.Equal(3, second.LastFullRecord.Count); + Assert.Equal("完整C", second.LastFullRecord[2]); + } + + [Fact] + public async Task Persist_IsUpsertAndNotDuplicate() + { + using PersistenceDatabase db = new(); + EfSimulationStatisticsStore store = db.CreateStore(); + await store.LoadAsync(); + store.Reset(FunGameService.Characters); + + await store.PersistAsync(); + int firstCount = await db.CountStatisticsAsync(); + await store.PersistAsync(); + int secondCount = await db.CountStatisticsAsync(); + + Assert.Equal(FunGameService.Characters.Count * 2, firstCount); // character + team + Assert.Equal(firstCount, secondCount); + } + + [Fact] + public async Task RecordAsync_WritesSimulationRunRow() + { + using PersistenceDatabase db = new(); + EfSimulationStatisticsStore store = db.CreateStore(); + + DateTimeOffset now = DateTimeOffset.UtcNow; + long id = await store.RecordAsync(new SimulationRunRecord( + 99, 777, "{}", ["结果"], ["完整"], now, now.AddSeconds(1))); + + Assert.True(id > 0); + using IServiceScope scope = db.Provider.CreateScope(); + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + var run = await context.SimulationRuns.SingleAsync(); + Assert.Equal("777", run.Seed); + Assert.Equal(99, run.UserId); + Assert.Equal("[\"结果\"]", run.ResultJson); + Assert.Equal("[\"完整\"]", run.RoundsJson); + Assert.NotNull(run.FinishedAtUtc); + } + + [Fact] + public async Task LoadAsync_ToleratesCorruptStatsJson() + { + using PersistenceDatabase db = new(); + using (IServiceScope scope = db.Provider.CreateScope()) + { + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + context.SimulationStatistics.Add(new OshimaBot.Data.Entities.SimulationStatistic + { + Scope = "character", + CatalogId = FunGameService.Characters[0].Id.ToString(), + StatsJson = "{ 不是合法 JSON", + UpdatedAtUtc = DateTime.UtcNow + }); + await context.SaveChangesAsync(); + } + + EfSimulationStatisticsStore store = db.CreateStore(); + await store.LoadAsync(); + + Assert.Equal(0, store.CharacterStatistics[FunGameService.Characters[0]].Plays); + } + + [Fact] + public async Task RealSimulation_IsRecordedAndPersisted() + { + using PersistenceDatabase db = new(); + EfSimulationStatisticsStore store = db.CreateStore(); + await store.LoadAsync(); + store.Reset(FunGameService.Characters); + + // 与生产一致:模拟器静态委托也指向同一个 EF 仓储,结束后恢复全局实例避免污染其它测试。 + ISimulationStatisticsStore previous = FunGameSimulation.StatisticsStore; + FunGameSimulation.UseStatisticsStore(store); + try + { + FunGameSimulationService service = new(store, store, + Options.Create(new ServerOptions()), NullLogger.Instance); + SimulationResult? result = await service.RunAsync(new SimulationRequest + { + UserId = 42, Seed = 20261110, MaxRespawnTimesMix = 0 + }); + + Assert.NotNull(result); + Assert.Equal(20261110, result.Seed); + Assert.NotEmpty(await service.GetLastAsync(false)); + Assert.NotNull(await service.GetLastAsync(true)); + + using IServiceScope scope = db.Provider.CreateScope(); + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(1, await context.SimulationRuns.CountAsync()); + Assert.Equal(42, (await context.SimulationRuns.SingleAsync()).UserId); + Assert.True(await context.SimulationStatistics.CountAsync() > 0); + } + finally + { + FunGameSimulation.UseStatisticsStore(previous); + } + } + + [Fact] + public void Archiving_IsOffByDefault() + { + Assert.False(new SimulationOptions().ArchiveRounds); + Assert.False(new SimulationRunContext().ArchiveRounds); + Assert.False(new ServerOptions().ArchiveSimulationRounds); + Assert.True(new ServerOptions().StoreFullSimulationLog); + } + + [Fact] + public async Task InMemoryStore_PersistIsNoOp() + { + InMemorySimulationStatisticsStore store = new(); + await store.PersistAsync(); + await store.PersistAsync(); + Assert.Empty(store.CharacterStatistics); + } + + private sealed class PersistenceDatabase : IDisposable + { + public SqliteConnection Connection { get; } + public ServiceProvider Provider { get; } + + public PersistenceDatabase() + { + FunGameRuntime.EnsureInitialized(); + Connection = new SqliteConnection("Data Source=:memory:"); + Connection.Open(); + ServiceCollection services = new(); + services.AddLogging(); + services.AddDbContext(options => options.UseSqlite(Connection)); + Provider = services.BuildServiceProvider(); + using IServiceScope scope = Provider.CreateScope(); + scope.ServiceProvider.GetRequiredService().Database.EnsureCreated(); + } + + public EfSimulationStatisticsStore CreateStore() => new( + Provider.GetRequiredService(), + NullLogger.Instance); + + public async Task CountStatisticsAsync() + { + using IServiceScope scope = Provider.CreateScope(); + BotDbContext context = scope.ServiceProvider.GetRequiredService(); + return await context.SimulationStatistics.CountAsync(); + } + + public void Dispose() + { + Provider.Dispose(); + Connection.Dispose(); + } + } +} diff --git a/OshimaBot/Commands/CommandCatalog.cs b/OshimaBot/Commands/CommandCatalog.cs index 7ff11b4..122fc94 100644 --- a/OshimaBot/Commands/CommandCatalog.cs +++ b/OshimaBot/Commands/CommandCatalog.cs @@ -497,6 +497,9 @@ public static class CommandCatalog private static async Task RunSimulationAsync( CommandDependencies deps, SimulationRequest request, CommandContext context) { + // S9:把触发者写入 simulation_runs.user_id,便于按用户复盘; + // userId=0 的匿名 / 第三方请求留空。 + request.UserId = context.UserId > 0 ? context.UserId : null; SimulationResult? result = await deps.Simulations.RunAsync(request, context.CancellationToken); if (result is null) { diff --git a/OshimaBot/Data/DatabaseInitializer.cs b/OshimaBot/Data/DatabaseInitializer.cs index a23c9cd..5926364 100644 --- a/OshimaBot/Data/DatabaseInitializer.cs +++ b/OshimaBot/Data/DatabaseInitializer.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Options; using OshimaBot.Data.Entities; using OshimaBot.Models; using OshimaBot.Security; +using OshimaBot.Services; namespace OshimaBot.Data; @@ -35,6 +36,11 @@ public sealed class DatabaseInitializer( logger.LogInformation("已跳过数据库自动迁移(Database:ApplyMigrationsOnStartup=false)。"); } + // S9:迁移完成后把模拟统计与最近一次日志从数据库恢复到内存工作副本。 + // 用 GetService 而非构造函数注入,保证只构建 DbContext 的集成测试也能复用本类。 + EfSimulationStatisticsStore? statistics = scope.ServiceProvider.GetService(); + if (statistics is not null) await statistics.LoadAsync(cancellationToken); + await SeedBootstrapApiKeyAsync(db, cancellationToken); } diff --git a/OshimaBot/Models/BotOptions.cs b/OshimaBot/Models/BotOptions.cs index 93aa229..f86161e 100644 --- a/OshimaBot/Models/BotOptions.cs +++ b/OshimaBot/Models/BotOptions.cs @@ -94,5 +94,11 @@ namespace OshimaBot.Models /// 一次性绑定码有效期(秒)。 public int BindCodeTtlSeconds { get; set; } = 300; + + /// S9:是否额外把回合记录写入 rounds_archive.zip。默认关闭,结果统一入 simulation_runs 表。 + public bool ArchiveSimulationRounds { get; set; } + + /// S9:是否把完整模拟日志写入 simulation_runs.rounds_json(供 /上次的完整日志 重启后恢复)。 + public bool StoreFullSimulationLog { get; set; } = true; } } diff --git a/OshimaBot/Program.cs b/OshimaBot/Program.cs index 0ce21a7..f533de2 100644 --- a/OshimaBot/Program.cs +++ b/OshimaBot/Program.cs @@ -67,8 +67,10 @@ builder.Services.AddHttpClient(QQBotService.HttpClientName, client => client.Timeout = TimeSpan.FromSeconds(builder.Configuration.GetValue("QQBot:RequestTimeoutSeconds", 30)); }); builder.Services.AddSingleton(); -// 与模拟器共享同一个统计仓储实例(S9 可换数据库实现,只需在启动前 FunGameSimulation.UseStatisticsStore)。 -builder.Services.AddSingleton(FunGameSimulation.StatisticsStore); +// S9:统计与模拟运行记录统一由 EF Core 实现;模拟器、查询服务与后台任务共享同一实例。 +builder.Services.AddSingleton(); +builder.Services.AddSingleton(sp => sp.GetRequiredService()); +builder.Services.AddSingleton(sp => sp.GetRequiredService()); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(); @@ -103,6 +105,12 @@ builder.Services.AddHostedService(); WebApplication app = builder.Build(); +// S9:在首次模拟 / 统计读写前把 EF Core 仓储注入模拟器。 +// InitializeStatistics 只为新仓储补齐字典;真正的数据库恢复由 DatabaseInitializer.LoadAsync 在迁移后完成。 +EfSimulationStatisticsStore statisticsStore = app.Services.GetRequiredService(); +FunGameSimulation.UseStatisticsStore(statisticsStore); +FunGameSimulation.InitializeStatistics(); + app.UseExceptionHandler(); // 仅当 QQBot:EnableWebhook=true 时对 POST /QQBot 校验 Ed25519 签名。 diff --git a/OshimaBot/Services/FunGameSimulationService.cs b/OshimaBot/Services/FunGameSimulationService.cs index 3ae6d6b..76644de 100644 --- a/OshimaBot/Services/FunGameSimulationService.cs +++ b/OshimaBot/Services/FunGameSimulationService.cs @@ -1,6 +1,7 @@ +using System.Text.Json; +using Microsoft.Extensions.Options; using OshimaBot.Game.Services; using OshimaBot.Models; -using Microsoft.Extensions.Options; namespace OshimaBot.Services { @@ -20,6 +21,9 @@ namespace OshimaBot.Services public int NormalAttackLevel { get; set; } = 2; public long FixedWeaponId { get; set; } public int? Seed { get; set; } + + /// S9:触发模拟的内部用户,写入 simulation_runs.user_id;第三方/匿名请求为 null。 + public long? UserId { get; set; } } public sealed record SimulationResult( @@ -29,16 +33,21 @@ namespace OshimaBot.Services TimeSpan Duration); /// - /// S8 前置:每次运行创建独立的 SimulationRunContext,静态运行态不再进程级共享; - /// 统计与最近日志改由 ISimulationStatisticsStore 持有。引擎仍串行执行(FunGame.Core 目录为只读共享), - /// 但两个运行之间不会串种子 / 消息 / 地图 / 运行状态。 + /// S8 前置:每次运行创建独立的 SimulationRunContext,静态运行态不再进程级共享。 + /// S9:一局结束后把结果与统计写入 SQLite(simulation_runs / simulation_statistics), + /// 内存仓储只作为模拟器运行期的工作副本,重启后由 LoadAsync 恢复。 + /// 引擎仍串行执行(FunGame.Core 目录为只读共享)。 /// public sealed class FunGameSimulationService( ISimulationStatisticsStore statistics, - IOptions options) + ISimulationRunRecorder recorder, + IOptions options, + ILogger logger) { private readonly SemaphoreSlim _gate = new(1, 1); private readonly int _maximumRespawnTimes = options.Value.MaximumRespawnTimes; + private readonly bool _archiveRounds = options.Value.ArchiveSimulationRounds; + private readonly bool _storeFullLog = options.Value.StoreFullSimulationLog; public bool IsRunning => _gate.CurrentCount == 0; @@ -68,15 +77,18 @@ namespace OshimaBot.Services SkillLevel = Math.Clamp(request.SkillLevel, 1, 8), NormalAttackLevel = Math.Clamp(request.NormalAttackLevel, 1, 8), EnablePeriodicDrop = request.EnablePeriodicDrop, - FixedWeaponId = request.FixedWeaponId + FixedWeaponId = request.FixedWeaponId, + ArchiveRounds = _archiveRounds }; List messages = await Task.Run( () => FunGameSimulation.StartSimulationGame(simulationOptions, context), cancellationToken); - return new SimulationResult(messages, context.Seed, DateTimeOffset.UtcNow, - DateTimeOffset.UtcNow - startedAt); + DateTimeOffset finishedAt = DateTimeOffset.UtcNow; + SimulationResult result = new(messages, context.Seed, finishedAt, finishedAt - startedAt); + await PersistRunAsync(request, context.Seed, messages, startedAt, finishedAt, cancellationToken); + return result; } finally { @@ -84,6 +96,27 @@ namespace OshimaBot.Services } } + /// 持久化失败只记日志,不丢弃已经算完的模拟结果。 + private async Task PersistRunAsync( + SimulationRequest request, int seed, IReadOnlyList messages, + DateTimeOffset startedAt, DateTimeOffset finishedAt, CancellationToken cancellationToken) + { + try + { + IReadOnlyList full = _storeFullLog + ? statistics.Read(store => (IReadOnlyList)[.. store.LastFullRecord]) + : []; + await recorder.RecordAsync(new SimulationRunRecord( + request.UserId, seed, JsonSerializer.Serialize(request), messages, full, + startedAt, finishedAt), cancellationToken); + await statistics.PersistAsync(cancellationToken); + } + catch (Exception exception) + { + logger.LogWarning(exception, "模拟结果入库失败:Seed={Seed}", seed); + } + } + /// 读锁内读取仓储;保留给外部只读调用。 public Task ReadAsync(Func reader, CancellationToken cancellationToken = default) => Task.FromResult(statistics.Read(_ => reader())); diff --git a/OshimaBot/Services/SimulationPersistence.cs b/OshimaBot/Services/SimulationPersistence.cs new file mode 100644 index 0000000..c08f17c --- /dev/null +++ b/OshimaBot/Services/SimulationPersistence.cs @@ -0,0 +1,189 @@ +using System.Globalization; +using System.Text.Encodings.Web; +using System.Text.Json; +using FunGame.Core.Entity; +using CoreCharacter = FunGame.Core.Entity.Character; +using Microsoft.EntityFrameworkCore; +using OshimaBot.Data; +using OshimaBot.Data.Entities; +using OshimaBot.Game.Services; + +namespace OshimaBot.Services; + +/// 一局模拟的入库快照。 +public sealed record SimulationRunRecord( + long? UserId, + int Seed, + string OptionsJson, + IReadOnlyList Messages, + IReadOnlyList FullMessages, + DateTimeOffset StartedAt, + DateTimeOffset FinishedAt); + +public interface ISimulationRunRecorder +{ + Task RecordAsync(SimulationRunRecord record, CancellationToken cancellationToken = default); +} + +/// +/// S9:用 SQLite 持久化模拟统计与最近日志,替代进程内字典 + rounds_archive.zip。 +/// 模拟器仍直接读写内存字典(FunGame.Core 的统计对象是纯 POCO,可无损 JSON 往返), +/// 在每次运行结束时 PersistAsync 落库;应用启动时 LoadAsync 恢复,重启后状态不丢。 +/// 同时实现 ISimulationRunRecorder,把每局结果写入 simulation_runs。 +/// +public sealed class EfSimulationStatisticsStore( + IServiceScopeFactory scopeFactory, + ILogger logger) : ISimulationStatisticsStore, ISimulationRunRecorder +{ + // 数据库里保留可读中文,便于直接查表复盘。 + private static readonly JsonSerializerOptions JsonOptions = new() + { + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }; + + private readonly Lock _sync = new(); + + public Dictionary CharacterStatistics { get; } = []; + public Dictionary TeamCharacterStatistics { get; } = []; + public IReadOnlyList LastRecord { get; set; } = []; + public IReadOnlyList LastFullRecord { get; set; } = []; + + /// + /// 由 FunGameRuntime 初始化时调用:只补齐缺失角色,不清空已加载的数据。 + /// 真正的覆盖式恢复在应用启动迁移完成后由 LoadAsync 执行。 + /// + public void Reset(IEnumerable characters) + { + lock (_sync) + { + foreach (CoreCharacter character in characters) + { + CharacterStatistics.TryAdd(character, new CharacterStatistics()); + TeamCharacterStatistics.TryAdd(character, new CharacterStatistics()); + } + } + } + + public T Read(Func reader) + { + lock (_sync) return reader(this); + } + + /// 启动迁移完成后调用:从数据库恢复统计字典与最近一次模拟日志。 + public async Task LoadAsync(CancellationToken cancellationToken = default) + { + using IServiceScope scope = scopeFactory.CreateScope(); + BotDbContext db = scope.ServiceProvider.GetRequiredService(); + + List rows = await db.SimulationStatistics.AsNoTracking() + .ToListAsync(cancellationToken); + Dictionary<(string Scope, string CatalogId), CharacterStatistics> loaded = []; + foreach (SimulationStatistic row in rows) + { + CharacterStatistics? stats = DeserializeStats(row.StatsJson); + if (stats is not null) loaded[(row.Scope, row.CatalogId)] = stats; + } + + SimulationRun? last = await db.SimulationRuns.AsNoTracking() + .OrderByDescending(x => x.Id).FirstOrDefaultAsync(cancellationToken); + + lock (_sync) + { + CharacterStatistics.Clear(); + TeamCharacterStatistics.Clear(); + foreach (CoreCharacter character in FunGameService.Characters) + { + string id = character.Id.ToString(CultureInfo.InvariantCulture); + CharacterStatistics[character] = loaded.GetValueOrDefault(("character", id)) + ?? new CharacterStatistics(); + TeamCharacterStatistics[character] = loaded.GetValueOrDefault(("team", id)) + ?? new CharacterStatistics(); + } + if (last is not null) + { + LastRecord = DeserializeMessages(last.ResultJson); + LastFullRecord = DeserializeMessages(last.RoundsJson); + } + } + logger.LogInformation("模拟统计已从数据库恢复:{Rows} 条统计行,最近日志 {Lines} 行", + rows.Count, LastRecord.Count); + } + + /// 一局结束后把两个统计字典 upsert 到 simulation_statistics。 + public async Task PersistAsync(CancellationToken cancellationToken = default) + { + List<(string Scope, string CatalogId, string Json)> snapshot = []; + lock (_sync) + { + snapshot.AddRange(CharacterStatistics.Select(pair => ( + "character", pair.Key.Id.ToString(CultureInfo.InvariantCulture), + JsonSerializer.Serialize(pair.Value, JsonOptions)))); + snapshot.AddRange(TeamCharacterStatistics.Select(pair => ( + "team", pair.Key.Id.ToString(CultureInfo.InvariantCulture), + JsonSerializer.Serialize(pair.Value, JsonOptions)))); + } + if (snapshot.Count == 0) return; + + using IServiceScope scope = scopeFactory.CreateScope(); + BotDbContext db = scope.ServiceProvider.GetRequiredService(); + foreach ((string scopeKey, string catalogId, string json) in snapshot) + { + SimulationStatistic? row = await db.SimulationStatistics.FirstOrDefaultAsync( + x => x.Scope == scopeKey && x.CatalogId == catalogId, cancellationToken); + if (row is null) + { + db.SimulationStatistics.Add(new SimulationStatistic + { + Scope = scopeKey, CatalogId = catalogId, StatsJson = json, + UpdatedAtUtc = DateTime.UtcNow + }); + } + else + { + row.StatsJson = json; + row.UpdatedAtUtc = DateTime.UtcNow; + } + } + await db.SaveChangesAsync(cancellationToken); + } + + /// 把一局结果写入 simulation_runs,并同步内存中的「上次的日志」。 + public async Task RecordAsync(SimulationRunRecord record, CancellationToken cancellationToken = default) + { + using IServiceScope scope = scopeFactory.CreateScope(); + BotDbContext db = scope.ServiceProvider.GetRequiredService(); + SimulationRun run = new() + { + UserId = record.UserId, + Seed = record.Seed.ToString(CultureInfo.InvariantCulture), + OptionsJson = record.OptionsJson, + ResultJson = JsonSerializer.Serialize(record.Messages, JsonOptions), + RoundsJson = JsonSerializer.Serialize(record.FullMessages, JsonOptions), + StartedAtUtc = record.StartedAt.UtcDateTime, + FinishedAtUtc = record.FinishedAt.UtcDateTime + }; + db.SimulationRuns.Add(run); + await db.SaveChangesAsync(cancellationToken); + + lock (_sync) + { + LastRecord = [.. record.Messages]; + LastFullRecord = [.. record.FullMessages]; + } + return run.Id; + } + + private static CharacterStatistics? DeserializeStats(string json) + { + if (string.IsNullOrWhiteSpace(json)) return null; + try { return JsonSerializer.Deserialize(json); } + catch (JsonException) { return null; } + } + + private static IReadOnlyList DeserializeMessages(string? json) + { + if (string.IsNullOrWhiteSpace(json)) return []; + try { return JsonSerializer.Deserialize>(json) ?? []; } + catch (JsonException) { return []; } + } +} diff --git a/OshimaBot/appsettings.json b/OshimaBot/appsettings.json index 655f398..00ea40f 100644 --- a/OshimaBot/appsettings.json +++ b/OshimaBot/appsettings.json @@ -32,6 +32,8 @@ "ApiKey": "", "MaximumRespawnTimes": 10, "SuperAdminOpenIds": [], - "BindCodeTtlSeconds": 300 + "BindCodeTtlSeconds": 300, + "ArchiveSimulationRounds": false, + "StoreFullSimulationLog": true } }