refactor(S8-prep): isolate simulation run state and move statistics into a store

This commit is contained in:
2026-11-10 00:07:32 +08:00
parent e89b5867cd
commit cd1f30f4a3
8 changed files with 315 additions and 82 deletions
+3
View File
@@ -16,6 +16,9 @@ obj/
appsettings.*.local.json
*.pfx
# 模拟器运行期产物(S9 用 simulation_runs 表替代)
rounds_archive.zip
# WorkBuddy 会话数据
.workbuddy/
+68 -51
View File
@@ -17,57 +17,78 @@ namespace OshimaBot.Game.Services
{
public class FunGameSimulation
{
public static Dictionary<Character, CharacterStatistics> CharacterStatistics { get; } = [];
public static Dictionary<Character, CharacterStatistics> TeamCharacterStatistics { get; } = [];
public static IReadOnlyList<string> LastRecord { get; private set; } = [];
public static IReadOnlyList<string> LastFullRecord { get; private set; } = [];
public static GameMap Map { get; } = new FastAutoMap();
// ---- S8 前置:运行态按实例隔离,统计/日志收敛到仓储 ----
private static readonly AsyncLocal<SimulationRunContext?> Ambient = new();
private static readonly SimulationRunContext DefaultContext = new();
private static ISimulationStatisticsStore _statisticsStore = new InMemorySimulationStatisticsStore();
public static void InitializeStatistics()
/// <summary>当前执行流绑定的运行上下文;未在 BeginRun 作用域内时退回默认上下文。</summary>
public static SimulationRunContext Current => Ambient.Value ?? DefaultContext;
public static ISimulationStatisticsStore StatisticsStore => _statisticsStore;
/// <summary>注入自定义统计仓储(S9 可换数据库实现),须在首次模拟/统计读写前调用。</summary>
public static void UseStatisticsStore(ISimulationStatisticsStore store)
=> _statisticsStore = store ?? throw new ArgumentNullException(nameof(store));
/// <summary>把后续静态状态读写绑定到指定运行上下文;AsyncLocal 随 async 流与 Task.Run 传递。</summary>
public static IDisposable BeginRun(SimulationRunContext context)
{
CharacterStatistics.Clear();
TeamCharacterStatistics.Clear();
LastRecord = [];
LastFullRecord = [];
ArgumentNullException.ThrowIfNull(context);
SimulationRunContext? previous = Ambient.Value;
Ambient.Value = context;
return new RunScope(previous);
}
foreach (Character character in FunGameService.Characters)
private sealed class RunScope(SimulationRunContext? previous) : IDisposable
{
CharacterStatistics.Add(character, new());
TeamCharacterStatistics.Add(character, new());
public void Dispose() => Ambient.Value = previous;
}
// 跨运行共享:统计与最近日志由仓储持有,查询服务只读这里。
public static Dictionary<Character, CharacterStatistics> CharacterStatistics => _statisticsStore.CharacterStatistics;
public static Dictionary<Character, CharacterStatistics> TeamCharacterStatistics => _statisticsStore.TeamCharacterStatistics;
public static IReadOnlyList<string> LastRecord { get => _statisticsStore.LastRecord; private set => _statisticsStore.LastRecord = value; }
public static IReadOnlyList<string> LastFullRecord { get => _statisticsStore.LastFullRecord; private set => _statisticsStore.LastFullRecord = value; }
public static GameMap Map { get => Current.Map; set => Current.Map = value; }
public static void InitializeStatistics() => _statisticsStore.Reset(FunGameService.Characters);
// 单次运行态:全部委托到 SimulationRunContext,进程内不再有共享可变字段。
public static bool IsRuning { get => Current.IsRunning; set => Current.IsRunning = value; }
public static bool IsWeb { get => Current.IsWeb; set => Current.IsWeb = value; }
public static bool IsDebug { get => Current.IsDebug; set => Current.IsDebug = value; }
public static bool PrintOut { get => Current.PrintOut; set => Current.PrintOut = value; }
public static bool DeathMatchRoundDetail { get => Current.DeathMatchRoundDetail; set => Current.DeathMatchRoundDetail = value; }
public static string Msg { get => Current.Msg; set => Current.Msg = value; }
/// <summary>
/// 指定本局种子;为 null 时每局自动随机。现在字段属于运行上下文,设置后不会泄漏到下一局。
/// </summary>
public static int? SeedOverride { get => Current.SeedOverride; set => Current.SeedOverride = value; }
/// <summary>固定武器 Id(0 = 不固定)。同种子复现用,属于本局运行态。</summary>
public static long FixedWeaponId { get => Current.FixedWeaponId; set => Current.FixedWeaponId = value; }
/// <summary>本局实际使用的随机种子(开局确定并保留,便于复现)。</summary>
public static int Seed { get => Current.Seed; private set => Current.Seed = value; }
/// <summary>本局随机数生成器(由 Seed 决定);禁止改回进程级 Random.Shared。</summary>
public static Random Random { get => Current.Random; private set => Current.Random = value; }
/// <summary>兼容旧调用:使用一次性默认上下文。</summary>
public static Task<List<string>> StartSimulationGame(SimulationOptions options)
=> StartSimulationGame(options, new SimulationRunContext());
/// <summary>S8 起推荐入口:显式绑定本次运行上下文,静态运行态不再跨局共享。</summary>
public static async Task<List<string>> StartSimulationGame(SimulationOptions options, SimulationRunContext context)
{
ArgumentNullException.ThrowIfNull(context);
using IDisposable scope = BeginRun(context);
return await StartSimulationGameCore(options).ConfigureAwait(false);
}
public static bool IsRuning { get; set; } = false;
public static bool IsWeb { get; set; } = false;
public static bool IsDebug { get; set; } = false;
public static bool PrintOut { get; set; } = false;
public static bool DeathMatchRoundDetail { get; set; } = false;
public static string Msg { get; set; } = "";
/// <summary>
/// 指定本局使用的随机种子;为 null 时每局自动随机<br/>
/// 设值后(或读取 <see cref="Seed"/> 得到的上一局实际值)同一份输入数据下整局模拟可复现
/// </summary>
public static int? SeedOverride { get; set; } = null;
/// <summary>
/// 固定武器 Id(0 = 不固定,按品质随机)。由 <see cref="SimulationOptions.FixedWeaponId"/> 传入。
/// <para/>用于平衡测试时消除「武器攻击力 20–170(8.5×)+ 副属性各异 + 武器类型倍率 1.41×」这组混淆变量。
/// </summary>
public static long FixedWeaponId { get; set; } = 0;
/// <summary>
/// 本局实际使用的随机种子(开局确定并保留,便于复现)
/// </summary>
public static int Seed { get; private set; } = 0;
/// <summary>
/// 模拟器自己的随机数生成器(由 <see cref="Seed"/> 决定)
/// <para>队列创建之前的角色抽选、技能分配、分队等走它;队列创建之后一律走 <see cref="GamingQueue.Random"/>。</para>
/// <para>两者同源,因此本文件内<b>禁止使用进程级的 <c>Random.Shared</c></b>,否则整局不可复现</para>
/// </summary>
public static Random Random { get; private set; } = new();
public static async Task<List<string>> StartSimulationGame(SimulationOptions options)
private static async Task<List<string>> StartSimulationGameCore(SimulationOptions options)
{
PrintOut = options.PrintOut;
IsWeb = options.IsWeb;
@@ -165,7 +186,7 @@ namespace OshimaBot.Game.Services
TeamGamingQueue? tgq = null;
if (isTeam)
{
tgq = new TeamGamingQueue(characters, WriteLine, seed: Seed)
tgq = new TeamGamingQueue(characters, Current.WriteLine, seed: Seed)
{
MaxRespawnTimes = -1,
MaxScoreToWin = 30
@@ -174,7 +195,7 @@ namespace OshimaBot.Game.Services
}
else
{
mgq = new MixGamingQueue(characters, WriteLine, seed: Seed)
mgq = new MixGamingQueue(characters, Current.WriteLine, seed: Seed)
{
MaxRespawnTimes = maxRespawnTimesMix
};
@@ -842,11 +863,7 @@ namespace OshimaBot.Game.Services
return roundsData;
}
public static void WriteLine(string str)
{
Msg += str + "\r\n";
if (PrintOut) Console.WriteLine(str);
}
public static void WriteLine(string str) => Current.WriteLine(str);
public static void AddStoreItems(GamingQueue queue, List<Item> store)
{
@@ -0,0 +1,31 @@
using FunGame.Core.Model.Framework;
using Milimoe.FunGameTesting.Others;
namespace OshimaBot.Game.Services;
/// <summary>
/// 单次模拟的运行态。S8 前置改造:原先挂在 FunGameSimulation 上的进程级 static 可变字段
/// 全部搬到这里,每次运行一个实例,避免多用户并发/串局时互相污染。
/// 内容目录(FunGameService.Characters/Skills/Items)是只读模板,仍保持进程级共享。
/// </summary>
public sealed class SimulationRunContext
{
public bool IsRunning { get; set; }
public bool IsWeb { get; set; }
public bool IsDebug { get; set; }
public bool PrintOut { get; set; }
public bool DeathMatchRoundDetail { get; set; }
public string Msg { get; set; } = "";
public int? SeedOverride { get; set; }
public long FixedWeaponId { get; set; }
public int Seed { get; set; }
public Random Random { get; set; } = new();
public GameMap Map { get; set; } = new FastAutoMap();
/// <summary>绑定到本实例的日志回调:不依赖 AsyncLocal,跨线程回调也不会串局。</summary>
public void WriteLine(string text)
{
Msg += text + "\r\n";
if (PrintOut) Console.WriteLine(text);
}
}
@@ -0,0 +1,52 @@
using FunGame.Core.Entity;
namespace OshimaBot.Game.Services;
/// <summary>
/// 跨运行共享的统计与最近日志。S8 前置把读写从 FunGameSimulation 的静态字典收敛到仓储接口;
/// S9 可替换为 EF Core(simulation_statistics / simulation_runs)实现而无需改动模拟器。
/// </summary>
public interface ISimulationStatisticsStore
{
Dictionary<Character, CharacterStatistics> CharacterStatistics { get; }
Dictionary<Character, CharacterStatistics> TeamCharacterStatistics { get; }
IReadOnlyList<string> LastRecord { get; set; }
IReadOnlyList<string> LastFullRecord { get; set; }
/// <summary>按当前内容目录重建统计行(进程启动或目录热重载时调用)。</summary>
void Reset(IEnumerable<Character> characters);
/// <summary>在读锁内执行读取,避免与正在写入的模拟互相干扰。</summary>
T Read<T>(Func<ISimulationStatisticsStore, T> reader);
}
public sealed class InMemorySimulationStatisticsStore : ISimulationStatisticsStore
{
private readonly Lock _sync = new();
public Dictionary<Character, CharacterStatistics> CharacterStatistics { get; } = [];
public Dictionary<Character, CharacterStatistics> TeamCharacterStatistics { get; } = [];
public IReadOnlyList<string> LastRecord { get; set; } = [];
public IReadOnlyList<string> LastFullRecord { get; set; } = [];
public void Reset(IEnumerable<Character> characters)
{
lock (_sync)
{
CharacterStatistics.Clear();
TeamCharacterStatistics.Clear();
LastRecord = [];
LastFullRecord = [];
foreach (Character character in characters)
{
CharacterStatistics.Add(character, new());
TeamCharacterStatistics.Add(character, new());
}
}
}
public T Read<T>(Func<ISimulationStatisticsStore, T> reader)
{
lock (_sync) return reader(this);
}
}
+131
View File
@@ -0,0 +1,131 @@
using FunGame.Core.Entity;
using Microsoft.Extensions.Options;
using OshimaBot.Game.Services;
using OshimaBot.Models;
using OshimaBot.Services;
using Xunit;
namespace OshimaBot.Tests;
public sealed class SimulationIsolationTests
{
[Fact]
public void RunContext_MapAndRandomArePerInstance()
{
SimulationRunContext first = new();
SimulationRunContext second = new();
Assert.NotSame(first.Map, second.Map);
Assert.NotSame(first.Random, second.Random);
Assert.Equal("", first.Msg);
Assert.Null(first.SeedOverride);
}
[Fact]
public void BeginRun_IsolatesMutableStateBetweenRuns()
{
SimulationRunContext first = new() { Msg = "A", SeedOverride = 11 };
SimulationRunContext second = new() { Msg = "B", SeedOverride = 22 };
using (FunGameSimulation.BeginRun(first))
{
FunGameSimulation.Msg += "1";
FunGameSimulation.WriteLine("2");
FunGameSimulation.IsRuning = true;
Assert.Equal("A12\r\n", first.Msg);
Assert.Equal(11, FunGameSimulation.SeedOverride);
Assert.True(FunGameSimulation.IsRuning);
}
Assert.NotSame(first, FunGameSimulation.Current);
using (FunGameSimulation.BeginRun(second))
{
Assert.Equal("B", FunGameSimulation.Msg);
Assert.Equal(22, FunGameSimulation.SeedOverride);
Assert.False(FunGameSimulation.IsRuning); // 不串上一局的运行中标记
}
Assert.Equal("A12\r\n", first.Msg);
Assert.Equal("B", second.Msg);
}
[Fact]
public void BeginRun_NestedScopeRestoresPreviousContext()
{
SimulationRunContext outer = new() { Msg = "OUT" };
using (FunGameSimulation.BeginRun(outer))
{
using (FunGameSimulation.BeginRun(new SimulationRunContext { Msg = "IN" }))
{
Assert.Equal("IN", FunGameSimulation.Msg);
}
Assert.Equal("OUT", FunGameSimulation.Msg);
}
}
[Fact]
public async Task BeginRun_FlowsIntoTaskRun()
{
SimulationRunContext context = new() { Msg = "X" };
using (FunGameSimulation.BeginRun(context))
{
await Task.Run(() => FunGameSimulation.WriteLine("Y"));
}
Assert.Equal("XY\r\n", context.Msg);
}
[Fact]
public void StaticStatistics_AreBackedByStore()
{
Assert.Same(FunGameSimulation.StatisticsStore.CharacterStatistics,
FunGameSimulation.CharacterStatistics);
Assert.Same(FunGameSimulation.StatisticsStore.TeamCharacterStatistics,
FunGameSimulation.TeamCharacterStatistics);
Assert.NotNull(FunGameSimulation.StatisticsStore.Read(store => store.LastRecord));
}
[Fact]
public void StatisticsStore_ResetRebuildsRowsForCurrentCatalog()
{
FunGameRuntime.EnsureInitialized();
InMemorySimulationStatisticsStore store = new();
store.LastRecord = ["stale"];
store.Reset(FunGameService.Characters);
Assert.Equal(FunGameService.Characters.Count, store.CharacterStatistics.Count);
Assert.Equal(FunGameService.Characters.Count, store.TeamCharacterStatistics.Count);
Assert.Empty(store.LastRecord);
Assert.Empty(store.LastFullRecord);
Assert.All(store.CharacterStatistics.Values, stats => Assert.NotNull(stats));
}
[Fact]
public async Task SimulationService_ReadsLastRecordFromStoreNotStatics()
{
InMemorySimulationStatisticsStore store = new();
store.LastRecord = ["A"];
store.LastFullRecord = ["A", "B"];
FunGameSimulationService service = new(store, Options.Create(new ServerOptions()));
Assert.Equal(new[] { "A" }, await service.GetLastAsync(false));
Assert.Equal(2, (await service.GetLastAsync(true)).Count);
Assert.False(service.IsRunning);
}
[Fact]
public async Task QueryService_ReadsStatisticsFromInjectedStore()
{
FunGameRuntime.EnsureInitialized();
InMemorySimulationStatisticsStore store = new();
Character character = FunGameService.Characters[0];
store.CharacterStatistics[character] = new CharacterStatistics();
FunGameQueryService queries = new(store);
string stats = await queries.GetStatsAsync(1, false);
Assert.Contains("参赛", stats);
List<string> ranking = await queries.GetRankingAsync(false, true);
Assert.Single(ranking);
Assert.Contains("技术得分", ranking[0]);
}
}
+2
View File
@@ -66,6 +66,8 @@ builder.Services.AddHttpClient(QQBotService.HttpClientName, client =>
client.Timeout = TimeSpan.FromSeconds(builder.Configuration.GetValue("QQBot:RequestTimeoutSeconds", 30));
});
builder.Services.AddSingleton<IQQBotService, QQBotService>();
// 与模拟器共享同一个统计仓储实例(S9 可换数据库实现,只需在启动前 FunGameSimulation.UseStatisticsStore)。
builder.Services.AddSingleton(FunGameSimulation.StatisticsStore);
builder.Services.AddSingleton<FunGameSimulationService>();
builder.Services.AddSingleton<FunGameQueryService>();
builder.Services.AddScoped<MessageSender>();
+9 -9
View File
@@ -7,7 +7,7 @@ namespace OshimaBot.Services
{
public sealed record CatalogEntry(long Id, string Name, string Category);
public sealed class FunGameQueryService(FunGameSimulationService simulations)
public sealed class FunGameQueryService(ISimulationStatisticsStore statistics)
{
public IReadOnlyList<CatalogEntry> GetCharacters()
=> [.. FunGameService.Characters.Select(character => new CatalogEntry(character.Id, character.GetName(), "角色"))];
@@ -84,14 +84,14 @@ namespace OshimaBot.Services
=> FunGameService.GenerateMagicCardPack(Random.Shared, 3)?.ToString(false, true) ?? "";
public Task<string> GetStatsAsync(int id, bool team, CancellationToken cancellationToken = default)
=> simulations.ReadAsync(() =>
=> Task.FromResult(statistics.Read(store =>
{
Character? character = FunGameService.Characters.ElementAtOrDefault(id - 1);
if (id <= 0 || character is null) return "";
Dictionary<Character, CharacterStatistics> source = team
? FunGameSimulation.TeamCharacterStatistics
: FunGameSimulation.CharacterStatistics;
? store.TeamCharacterStatistics
: store.CharacterStatistics;
if (!source.TryGetValue(character, out CharacterStatistics? stats)) return "";
StringBuilder builder = new();
@@ -107,14 +107,14 @@ namespace OshimaBot.Services
builder.AppendLine($"存活回合:{stats.LiveRound} / 行动回合:{stats.ActionTurn} / 存活时长:{stats.LiveTime:0.##}");
builder.Append($"决策数:{stats.TurnDecisions} / 决策点:{stats.UseDecisionPoints}");
return builder.ToString();
}, cancellationToken);
}));
public Task<List<string>> GetRankingAsync(bool team, bool byRating, CancellationToken cancellationToken = default)
=> simulations.ReadAsync(() =>
=> Task.FromResult(statistics.Read(store =>
{
Dictionary<Character, CharacterStatistics> source = team
? FunGameSimulation.TeamCharacterStatistics
: FunGameSimulation.CharacterStatistics;
? store.TeamCharacterStatistics
: store.CharacterStatistics;
IEnumerable<KeyValuePair<Character, CharacterStatistics>> ordered = byRating
? source.OrderByDescending(entry => entry.Value.Rating)
: source.OrderByDescending(entry => entry.Value.Winrate);
@@ -131,7 +131,7 @@ namespace OshimaBot.Services
result.Add(builder.ToString());
}
return result;
}, cancellationToken);
}));
private static Character CreateDemoCharacter()
{
+22 -25
View File
@@ -28,12 +28,19 @@ namespace OshimaBot.Services
DateTimeOffset CompletedAt,
TimeSpan Duration);
public sealed class FunGameSimulationService(IOptions<ServerOptions> options)
/// <summary>
/// S8 前置:每次运行创建独立的 SimulationRunContext,静态运行态不再进程级共享;
/// 统计与最近日志改由 ISimulationStatisticsStore 持有。引擎仍串行执行(FunGame.Core 目录为只读共享),
/// 但两个运行之间不会串种子 / 消息 / 地图 / 运行状态。
/// </summary>
public sealed class FunGameSimulationService(
ISimulationStatisticsStore statistics,
IOptions<ServerOptions> options)
{
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly int _maximumRespawnTimes = options.Value.MaximumRespawnTimes;
public bool IsRunning => FunGameSimulation.IsRuning;
public bool IsRunning => _gate.CurrentCount == 0;
public async Task<SimulationResult?> RunAsync(SimulationRequest request, CancellationToken cancellationToken = default)
{
@@ -42,7 +49,10 @@ namespace OshimaBot.Services
DateTimeOffset startedAt = DateTimeOffset.UtcNow;
try
{
FunGameSimulation.SeedOverride = request.Seed is > 0 ? request.Seed : null;
SimulationRunContext context = new()
{
SeedOverride = request.Seed is > 0 ? request.Seed : null
};
SimulationOptions simulationOptions = new()
{
PrintOut = false,
@@ -62,40 +72,27 @@ namespace OshimaBot.Services
};
List<string> messages = await Task.Run(
() => FunGameSimulation.StartSimulationGame(simulationOptions),
CancellationToken.None);
() => FunGameSimulation.StartSimulationGame(simulationOptions, context),
cancellationToken);
return new SimulationResult(
messages,
FunGameSimulation.Seed,
DateTimeOffset.UtcNow,
return new SimulationResult(messages, context.Seed, DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow - startedAt);
}
finally
{
FunGameSimulation.SeedOverride = null;
_gate.Release();
}
}
public async Task<T> ReadAsync<T>(Func<T> reader, CancellationToken cancellationToken = default)
{
await _gate.WaitAsync(cancellationToken);
try
{
return reader();
}
finally
{
_gate.Release();
}
}
/// <summary>读锁内读取仓储;保留给外部只读调用。</summary>
public Task<T> ReadAsync<T>(Func<T> reader, CancellationToken cancellationToken = default)
=> Task.FromResult(statistics.Read(_ => reader()));
public Task<IReadOnlyList<string>> GetLastAsync(bool full, CancellationToken cancellationToken = default)
=> ReadAsync(() =>
=> Task.FromResult(statistics.Read(store =>
{
IReadOnlyList<string> source = full ? FunGameSimulation.LastFullRecord : FunGameSimulation.LastRecord;
IReadOnlyList<string> source = full ? store.LastFullRecord : store.LastRecord;
return (IReadOnlyList<string>)[.. source];
}, cancellationToken);
}));
}
}