feat(S9): persist simulation statistics and logs to SQLite, retire zip archive
This commit is contained in:
@@ -84,6 +84,7 @@ namespace OshimaBot.Game.Services
|
|||||||
public static async Task<List<string>> StartSimulationGame(SimulationOptions options, SimulationRunContext context)
|
public static async Task<List<string>> StartSimulationGame(SimulationOptions options, SimulationRunContext context)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(context);
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
context.ArchiveRounds = options.ArchiveRounds;
|
||||||
using IDisposable scope = BeginRun(context);
|
using IDisposable scope = BeginRun(context);
|
||||||
return await StartSimulationGameCore(options).ConfigureAwait(false);
|
return await StartSimulationGameCore(options).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
@@ -701,6 +702,10 @@ namespace OshimaBot.Game.Services
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// S9:默认不再无条件落盘 zip;结果由 simulation_runs 表承载,
|
||||||
|
// 只有显式开启 ArchiveRounds(复盘 / 平衡测试)才生成 rounds_archive.zip。
|
||||||
|
if (Current.ArchiveRounds)
|
||||||
|
{
|
||||||
string zipFileName = "rounds_archive.zip";
|
string zipFileName = "rounds_archive.zip";
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -714,6 +719,7 @@ namespace OshimaBot.Game.Services
|
|||||||
result.Add(msg);
|
result.Add(msg);
|
||||||
lastRecord.Add(msg);
|
lastRecord.Add(msg);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
LastRecord = result;
|
LastRecord = result;
|
||||||
LastFullRecord = lastRecord;
|
LastFullRecord = lastRecord;
|
||||||
|
|||||||
@@ -32,6 +32,12 @@ namespace OshimaBot.Game.Services
|
|||||||
/// <summary>调试模式(输出更多运行细节)</summary>
|
/// <summary>调试模式(输出更多运行细节)</summary>
|
||||||
public bool IsDebug { get; set; }
|
public bool IsDebug { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// S9:是否把回合记录写入 rounds_archive.zip。默认 false —— 归档改由
|
||||||
|
/// simulation_runs 表承担,只有显式开启(复盘/平衡测试)才落盘。
|
||||||
|
/// </summary>
|
||||||
|
public bool ArchiveRounds { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 是否启用「角色绑定的回合奖励」(对应 <c>InitRoundRewards</c> 的 bindToCharacter)。<para/>
|
/// 是否启用「角色绑定的回合奖励」(对应 <c>InitRoundRewards</c> 的 bindToCharacter)。<para/>
|
||||||
/// <b>默认 true</b>:不启用时【命运XX】系技能(抢夺 / 剥夺 / 馈赠)与【强运】会全部静默失效。
|
/// <b>默认 true</b>:不启用时【命运XX】系技能(抢夺 / 剥夺 / 馈赠)与【强运】会全部静默失效。
|
||||||
|
|||||||
@@ -22,6 +22,9 @@ public sealed class SimulationRunContext
|
|||||||
public Random Random { get; set; } = new();
|
public Random Random { get; set; } = new();
|
||||||
public GameMap Map { get; set; } = new FastAutoMap();
|
public GameMap Map { get; set; } = new FastAutoMap();
|
||||||
|
|
||||||
|
/// <summary>S9:本局是否额外写 rounds_archive.zip(默认关闭,结果统一入库)。</summary>
|
||||||
|
public bool ArchiveRounds { get; set; }
|
||||||
|
|
||||||
/// <summary>绑定到本实例的日志回调:不依赖 AsyncLocal,跨线程回调也不会串局。</summary>
|
/// <summary>绑定到本实例的日志回调:不依赖 AsyncLocal,跨线程回调也不会串局。</summary>
|
||||||
public void WriteLine(string text)
|
public void WriteLine(string text)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -18,6 +18,12 @@ public interface ISimulationStatisticsStore
|
|||||||
|
|
||||||
/// <summary>在读锁内执行读取,避免与正在写入的模拟互相干扰。</summary>
|
/// <summary>在读锁内执行读取,避免与正在写入的模拟互相干扰。</summary>
|
||||||
T Read<T>(Func<ISimulationStatisticsStore, T> reader);
|
T Read<T>(Func<ISimulationStatisticsStore, T> reader);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 一局模拟结束后把统计与最近日志持久化。内存实现为空操作;
|
||||||
|
/// S9 的 EF Core 实现写 simulation_statistics,重启后可恢复。
|
||||||
|
/// </summary>
|
||||||
|
Task PersistAsync(CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class InMemorySimulationStatisticsStore : ISimulationStatisticsStore
|
public sealed class InMemorySimulationStatisticsStore : ISimulationStatisticsStore
|
||||||
@@ -49,4 +55,6 @@ public sealed class InMemorySimulationStatisticsStore : ISimulationStatisticsSto
|
|||||||
{
|
{
|
||||||
lock (_sync) return reader(this);
|
lock (_sync) return reader(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Task PersistAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using FunGame.Core.Entity;
|
using FunGame.Core.Entity;
|
||||||
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using OshimaBot.Game.Services;
|
using OshimaBot.Game.Services;
|
||||||
using OshimaBot.Models;
|
using OshimaBot.Models;
|
||||||
@@ -105,7 +106,8 @@ public sealed class SimulationIsolationTests
|
|||||||
InMemorySimulationStatisticsStore store = new();
|
InMemorySimulationStatisticsStore store = new();
|
||||||
store.LastRecord = ["A"];
|
store.LastRecord = ["A"];
|
||||||
store.LastFullRecord = ["A", "B"];
|
store.LastFullRecord = ["A", "B"];
|
||||||
FunGameSimulationService service = new(store, Options.Create(new ServerOptions()));
|
FunGameSimulationService service = new(store, new NoopRunRecorder(),
|
||||||
|
Options.Create(new ServerOptions()), NullLogger<FunGameSimulationService>.Instance);
|
||||||
|
|
||||||
Assert.Equal(new[] { "A" }, await service.GetLastAsync(false));
|
Assert.Equal(new[] { "A" }, await service.GetLastAsync(false));
|
||||||
Assert.Equal(2, (await service.GetLastAsync(true)).Count);
|
Assert.Equal(2, (await service.GetLastAsync(true)).Count);
|
||||||
@@ -128,4 +130,10 @@ public sealed class SimulationIsolationTests
|
|||||||
Assert.Single(ranking);
|
Assert.Single(ranking);
|
||||||
Assert.Contains("技术得分", ranking[0]);
|
Assert.Contains("技术得分", ranking[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private sealed class NoopRunRecorder : ISimulationRunRecorder
|
||||||
|
{
|
||||||
|
public Task<long> RecordAsync(SimulationRunRecord record, CancellationToken cancellationToken = default)
|
||||||
|
=> Task.FromResult(0L);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>S9:模拟统计 / 日志数据库化,验证重启恢复与默认值。</summary>
|
||||||
|
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<BotDbContext>();
|
||||||
|
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<BotDbContext>();
|
||||||
|
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<FunGameSimulationService>.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<BotDbContext>();
|
||||||
|
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<BotDbContext>(options => options.UseSqlite(Connection));
|
||||||
|
Provider = services.BuildServiceProvider();
|
||||||
|
using IServiceScope scope = Provider.CreateScope();
|
||||||
|
scope.ServiceProvider.GetRequiredService<BotDbContext>().Database.EnsureCreated();
|
||||||
|
}
|
||||||
|
|
||||||
|
public EfSimulationStatisticsStore CreateStore() => new(
|
||||||
|
Provider.GetRequiredService<IServiceScopeFactory>(),
|
||||||
|
NullLogger<EfSimulationStatisticsStore>.Instance);
|
||||||
|
|
||||||
|
public async Task<int> CountStatisticsAsync()
|
||||||
|
{
|
||||||
|
using IServiceScope scope = Provider.CreateScope();
|
||||||
|
BotDbContext context = scope.ServiceProvider.GetRequiredService<BotDbContext>();
|
||||||
|
return await context.SimulationStatistics.CountAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Provider.Dispose();
|
||||||
|
Connection.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -497,6 +497,9 @@ public static class CommandCatalog
|
|||||||
private static async Task<BotReply> RunSimulationAsync(
|
private static async Task<BotReply> RunSimulationAsync(
|
||||||
CommandDependencies deps, SimulationRequest request, CommandContext context)
|
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);
|
SimulationResult? result = await deps.Simulations.RunAsync(request, context.CancellationToken);
|
||||||
if (result is null)
|
if (result is null)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Options;
|
|||||||
using OshimaBot.Data.Entities;
|
using OshimaBot.Data.Entities;
|
||||||
using OshimaBot.Models;
|
using OshimaBot.Models;
|
||||||
using OshimaBot.Security;
|
using OshimaBot.Security;
|
||||||
|
using OshimaBot.Services;
|
||||||
|
|
||||||
namespace OshimaBot.Data;
|
namespace OshimaBot.Data;
|
||||||
|
|
||||||
@@ -35,6 +36,11 @@ public sealed class DatabaseInitializer(
|
|||||||
logger.LogInformation("已跳过数据库自动迁移(Database:ApplyMigrationsOnStartup=false)。");
|
logger.LogInformation("已跳过数据库自动迁移(Database:ApplyMigrationsOnStartup=false)。");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// S9:迁移完成后把模拟统计与最近一次日志从数据库恢复到内存工作副本。
|
||||||
|
// 用 GetService 而非构造函数注入,保证只构建 DbContext 的集成测试也能复用本类。
|
||||||
|
EfSimulationStatisticsStore? statistics = scope.ServiceProvider.GetService<EfSimulationStatisticsStore>();
|
||||||
|
if (statistics is not null) await statistics.LoadAsync(cancellationToken);
|
||||||
|
|
||||||
await SeedBootstrapApiKeyAsync(db, cancellationToken);
|
await SeedBootstrapApiKeyAsync(db, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -94,5 +94,11 @@ namespace OshimaBot.Models
|
|||||||
|
|
||||||
/// <summary>一次性绑定码有效期(秒)。</summary>
|
/// <summary>一次性绑定码有效期(秒)。</summary>
|
||||||
public int BindCodeTtlSeconds { get; set; } = 300;
|
public int BindCodeTtlSeconds { get; set; } = 300;
|
||||||
|
|
||||||
|
/// <summary>S9:是否额外把回合记录写入 rounds_archive.zip。默认关闭,结果统一入 simulation_runs 表。</summary>
|
||||||
|
public bool ArchiveSimulationRounds { get; set; }
|
||||||
|
|
||||||
|
/// <summary>S9:是否把完整模拟日志写入 simulation_runs.rounds_json(供 /上次的完整日志 重启后恢复)。</summary>
|
||||||
|
public bool StoreFullSimulationLog { get; set; } = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-2
@@ -67,8 +67,10 @@ builder.Services.AddHttpClient(QQBotService.HttpClientName, client =>
|
|||||||
client.Timeout = TimeSpan.FromSeconds(builder.Configuration.GetValue("QQBot:RequestTimeoutSeconds", 30));
|
client.Timeout = TimeSpan.FromSeconds(builder.Configuration.GetValue("QQBot:RequestTimeoutSeconds", 30));
|
||||||
});
|
});
|
||||||
builder.Services.AddSingleton<IQQBotService, QQBotService>();
|
builder.Services.AddSingleton<IQQBotService, QQBotService>();
|
||||||
// 与模拟器共享同一个统计仓储实例(S9 可换数据库实现,只需在启动前 FunGameSimulation.UseStatisticsStore)。
|
// S9:统计与模拟运行记录统一由 EF Core 实现;模拟器、查询服务与后台任务共享同一实例。
|
||||||
builder.Services.AddSingleton(FunGameSimulation.StatisticsStore);
|
builder.Services.AddSingleton<EfSimulationStatisticsStore>();
|
||||||
|
builder.Services.AddSingleton<ISimulationStatisticsStore>(sp => sp.GetRequiredService<EfSimulationStatisticsStore>());
|
||||||
|
builder.Services.AddSingleton<ISimulationRunRecorder>(sp => sp.GetRequiredService<EfSimulationStatisticsStore>());
|
||||||
builder.Services.AddSingleton<FunGameSimulationService>();
|
builder.Services.AddSingleton<FunGameSimulationService>();
|
||||||
builder.Services.AddSingleton<FunGameQueryService>();
|
builder.Services.AddSingleton<FunGameQueryService>();
|
||||||
builder.Services.AddScoped<MessageSender>();
|
builder.Services.AddScoped<MessageSender>();
|
||||||
@@ -103,6 +105,12 @@ builder.Services.AddHostedService<QQBotGatewayClient>();
|
|||||||
|
|
||||||
WebApplication app = builder.Build();
|
WebApplication app = builder.Build();
|
||||||
|
|
||||||
|
// S9:在首次模拟 / 统计读写前把 EF Core 仓储注入模拟器。
|
||||||
|
// InitializeStatistics 只为新仓储补齐字典;真正的数据库恢复由 DatabaseInitializer.LoadAsync 在迁移后完成。
|
||||||
|
EfSimulationStatisticsStore statisticsStore = app.Services.GetRequiredService<EfSimulationStatisticsStore>();
|
||||||
|
FunGameSimulation.UseStatisticsStore(statisticsStore);
|
||||||
|
FunGameSimulation.InitializeStatistics();
|
||||||
|
|
||||||
app.UseExceptionHandler();
|
app.UseExceptionHandler();
|
||||||
|
|
||||||
// 仅当 QQBot:EnableWebhook=true 时对 POST /QQBot 校验 Ed25519 签名。
|
// 仅当 QQBot:EnableWebhook=true 时对 POST /QQBot 校验 Ed25519 签名。
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
using OshimaBot.Game.Services;
|
using OshimaBot.Game.Services;
|
||||||
using OshimaBot.Models;
|
using OshimaBot.Models;
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
|
|
||||||
namespace OshimaBot.Services
|
namespace OshimaBot.Services
|
||||||
{
|
{
|
||||||
@@ -20,6 +21,9 @@ namespace OshimaBot.Services
|
|||||||
public int NormalAttackLevel { get; set; } = 2;
|
public int NormalAttackLevel { get; set; } = 2;
|
||||||
public long FixedWeaponId { get; set; }
|
public long FixedWeaponId { get; set; }
|
||||||
public int? Seed { get; set; }
|
public int? Seed { get; set; }
|
||||||
|
|
||||||
|
/// <summary>S9:触发模拟的内部用户,写入 simulation_runs.user_id;第三方/匿名请求为 null。</summary>
|
||||||
|
public long? UserId { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed record SimulationResult(
|
public sealed record SimulationResult(
|
||||||
@@ -29,16 +33,21 @@ namespace OshimaBot.Services
|
|||||||
TimeSpan Duration);
|
TimeSpan Duration);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// S8 前置:每次运行创建独立的 SimulationRunContext,静态运行态不再进程级共享;
|
/// S8 前置:每次运行创建独立的 SimulationRunContext,静态运行态不再进程级共享。
|
||||||
/// 统计与最近日志改由 ISimulationStatisticsStore 持有。引擎仍串行执行(FunGame.Core 目录为只读共享),
|
/// S9:一局结束后把结果与统计写入 SQLite(simulation_runs / simulation_statistics),
|
||||||
/// 但两个运行之间不会串种子 / 消息 / 地图 / 运行状态。
|
/// 内存仓储只作为模拟器运行期的工作副本,重启后由 LoadAsync 恢复。
|
||||||
|
/// 引擎仍串行执行(FunGame.Core 目录为只读共享)。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed class FunGameSimulationService(
|
public sealed class FunGameSimulationService(
|
||||||
ISimulationStatisticsStore statistics,
|
ISimulationStatisticsStore statistics,
|
||||||
IOptions<ServerOptions> options)
|
ISimulationRunRecorder recorder,
|
||||||
|
IOptions<ServerOptions> options,
|
||||||
|
ILogger<FunGameSimulationService> logger)
|
||||||
{
|
{
|
||||||
private readonly SemaphoreSlim _gate = new(1, 1);
|
private readonly SemaphoreSlim _gate = new(1, 1);
|
||||||
private readonly int _maximumRespawnTimes = options.Value.MaximumRespawnTimes;
|
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;
|
public bool IsRunning => _gate.CurrentCount == 0;
|
||||||
|
|
||||||
@@ -68,15 +77,18 @@ namespace OshimaBot.Services
|
|||||||
SkillLevel = Math.Clamp(request.SkillLevel, 1, 8),
|
SkillLevel = Math.Clamp(request.SkillLevel, 1, 8),
|
||||||
NormalAttackLevel = Math.Clamp(request.NormalAttackLevel, 1, 8),
|
NormalAttackLevel = Math.Clamp(request.NormalAttackLevel, 1, 8),
|
||||||
EnablePeriodicDrop = request.EnablePeriodicDrop,
|
EnablePeriodicDrop = request.EnablePeriodicDrop,
|
||||||
FixedWeaponId = request.FixedWeaponId
|
FixedWeaponId = request.FixedWeaponId,
|
||||||
|
ArchiveRounds = _archiveRounds
|
||||||
};
|
};
|
||||||
|
|
||||||
List<string> messages = await Task.Run(
|
List<string> messages = await Task.Run(
|
||||||
() => FunGameSimulation.StartSimulationGame(simulationOptions, context),
|
() => FunGameSimulation.StartSimulationGame(simulationOptions, context),
|
||||||
cancellationToken);
|
cancellationToken);
|
||||||
|
|
||||||
return new SimulationResult(messages, context.Seed, DateTimeOffset.UtcNow,
|
DateTimeOffset finishedAt = DateTimeOffset.UtcNow;
|
||||||
DateTimeOffset.UtcNow - startedAt);
|
SimulationResult result = new(messages, context.Seed, finishedAt, finishedAt - startedAt);
|
||||||
|
await PersistRunAsync(request, context.Seed, messages, startedAt, finishedAt, cancellationToken);
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -84,6 +96,27 @@ namespace OshimaBot.Services
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>持久化失败只记日志,不丢弃已经算完的模拟结果。</summary>
|
||||||
|
private async Task PersistRunAsync(
|
||||||
|
SimulationRequest request, int seed, IReadOnlyList<string> messages,
|
||||||
|
DateTimeOffset startedAt, DateTimeOffset finishedAt, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
IReadOnlyList<string> full = _storeFullLog
|
||||||
|
? statistics.Read(store => (IReadOnlyList<string>)[.. 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>读锁内读取仓储;保留给外部只读调用。</summary>
|
/// <summary>读锁内读取仓储;保留给外部只读调用。</summary>
|
||||||
public Task<T> ReadAsync<T>(Func<T> reader, CancellationToken cancellationToken = default)
|
public Task<T> ReadAsync<T>(Func<T> reader, CancellationToken cancellationToken = default)
|
||||||
=> Task.FromResult(statistics.Read(_ => reader()));
|
=> Task.FromResult(statistics.Read(_ => reader()));
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>一局模拟的入库快照。</summary>
|
||||||
|
public sealed record SimulationRunRecord(
|
||||||
|
long? UserId,
|
||||||
|
int Seed,
|
||||||
|
string OptionsJson,
|
||||||
|
IReadOnlyList<string> Messages,
|
||||||
|
IReadOnlyList<string> FullMessages,
|
||||||
|
DateTimeOffset StartedAt,
|
||||||
|
DateTimeOffset FinishedAt);
|
||||||
|
|
||||||
|
public interface ISimulationRunRecorder
|
||||||
|
{
|
||||||
|
Task<long> RecordAsync(SimulationRunRecord record, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// S9:用 SQLite 持久化模拟统计与最近日志,替代进程内字典 + rounds_archive.zip。
|
||||||
|
/// 模拟器仍直接读写内存字典(FunGame.Core 的统计对象是纯 POCO,可无损 JSON 往返),
|
||||||
|
/// 在每次运行结束时 PersistAsync 落库;应用启动时 LoadAsync 恢复,重启后状态不丢。
|
||||||
|
/// 同时实现 ISimulationRunRecorder,把每局结果写入 simulation_runs。
|
||||||
|
/// </summary>
|
||||||
|
public sealed class EfSimulationStatisticsStore(
|
||||||
|
IServiceScopeFactory scopeFactory,
|
||||||
|
ILogger<EfSimulationStatisticsStore> logger) : ISimulationStatisticsStore, ISimulationRunRecorder
|
||||||
|
{
|
||||||
|
// 数据库里保留可读中文,便于直接查表复盘。
|
||||||
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||||
|
{
|
||||||
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||||
|
};
|
||||||
|
|
||||||
|
private readonly Lock _sync = new();
|
||||||
|
|
||||||
|
public Dictionary<CoreCharacter, CharacterStatistics> CharacterStatistics { get; } = [];
|
||||||
|
public Dictionary<CoreCharacter, CharacterStatistics> TeamCharacterStatistics { get; } = [];
|
||||||
|
public IReadOnlyList<string> LastRecord { get; set; } = [];
|
||||||
|
public IReadOnlyList<string> LastFullRecord { get; set; } = [];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 由 FunGameRuntime 初始化时调用:只补齐缺失角色,不清空已加载的数据。
|
||||||
|
/// 真正的覆盖式恢复在应用启动迁移完成后由 LoadAsync 执行。
|
||||||
|
/// </summary>
|
||||||
|
public void Reset(IEnumerable<CoreCharacter> characters)
|
||||||
|
{
|
||||||
|
lock (_sync)
|
||||||
|
{
|
||||||
|
foreach (CoreCharacter character in characters)
|
||||||
|
{
|
||||||
|
CharacterStatistics.TryAdd(character, new CharacterStatistics());
|
||||||
|
TeamCharacterStatistics.TryAdd(character, new CharacterStatistics());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public T Read<T>(Func<ISimulationStatisticsStore, T> reader)
|
||||||
|
{
|
||||||
|
lock (_sync) return reader(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>启动迁移完成后调用:从数据库恢复统计字典与最近一次模拟日志。</summary>
|
||||||
|
public async Task LoadAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
|
||||||
|
|
||||||
|
List<SimulationStatistic> 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>一局结束后把两个统计字典 upsert 到 simulation_statistics。</summary>
|
||||||
|
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<BotDbContext>();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>把一局结果写入 simulation_runs,并同步内存中的「上次的日志」。</summary>
|
||||||
|
public async Task<long> RecordAsync(SimulationRunRecord record, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
using IServiceScope scope = scopeFactory.CreateScope();
|
||||||
|
BotDbContext db = scope.ServiceProvider.GetRequiredService<BotDbContext>();
|
||||||
|
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<CharacterStatistics>(json); }
|
||||||
|
catch (JsonException) { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IReadOnlyList<string> DeserializeMessages(string? json)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(json)) return [];
|
||||||
|
try { return JsonSerializer.Deserialize<List<string>>(json) ?? []; }
|
||||||
|
catch (JsonException) { return []; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -32,6 +32,8 @@
|
|||||||
"ApiKey": "",
|
"ApiKey": "",
|
||||||
"MaximumRespawnTimes": 10,
|
"MaximumRespawnTimes": 10,
|
||||||
"SuperAdminOpenIds": [],
|
"SuperAdminOpenIds": [],
|
||||||
"BindCodeTtlSeconds": 300
|
"BindCodeTtlSeconds": 300,
|
||||||
|
"ArchiveSimulationRounds": false,
|
||||||
|
"StoreFullSimulationLog": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user