diff --git a/.gitignore b/.gitignore index c84e117..359afa2 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,9 @@ obj/ appsettings.*.local.json *.pfx +# 模拟器运行期产物(S9 用 simulation_runs 表替代) +rounds_archive.zip + # WorkBuddy 会话数据 .workbuddy/ diff --git a/OshimaBot.Game/Services/FunGameSimulation.cs b/OshimaBot.Game/Services/FunGameSimulation.cs index f792c89..7d618fb 100644 --- a/OshimaBot.Game/Services/FunGameSimulation.cs +++ b/OshimaBot.Game/Services/FunGameSimulation.cs @@ -17,57 +17,78 @@ namespace OshimaBot.Game.Services { public class FunGameSimulation { - public static Dictionary CharacterStatistics { get; } = []; - public static Dictionary TeamCharacterStatistics { get; } = []; - public static IReadOnlyList LastRecord { get; private set; } = []; - public static IReadOnlyList LastFullRecord { get; private set; } = []; - public static GameMap Map { get; } = new FastAutoMap(); + // ---- S8 前置:运行态按实例隔离,统计/日志收敛到仓储 ---- + private static readonly AsyncLocal Ambient = new(); + private static readonly SimulationRunContext DefaultContext = new(); + private static ISimulationStatisticsStore _statisticsStore = new InMemorySimulationStatisticsStore(); - public static void InitializeStatistics() + /// 当前执行流绑定的运行上下文;未在 BeginRun 作用域内时退回默认上下文。 + public static SimulationRunContext Current => Ambient.Value ?? DefaultContext; + + public static ISimulationStatisticsStore StatisticsStore => _statisticsStore; + + /// 注入自定义统计仓储(S9 可换数据库实现),须在首次模拟/统计读写前调用。 + public static void UseStatisticsStore(ISimulationStatisticsStore store) + => _statisticsStore = store ?? throw new ArgumentNullException(nameof(store)); + + /// 把后续静态状态读写绑定到指定运行上下文;AsyncLocal 随 async 流与 Task.Run 传递。 + public static IDisposable BeginRun(SimulationRunContext context) { - CharacterStatistics.Clear(); - TeamCharacterStatistics.Clear(); - LastRecord = []; - LastFullRecord = []; - - foreach (Character character in FunGameService.Characters) - { - CharacterStatistics.Add(character, new()); - TeamCharacterStatistics.Add(character, new()); - } + ArgumentNullException.ThrowIfNull(context); + SimulationRunContext? previous = Ambient.Value; + Ambient.Value = context; + return new RunScope(previous); } - 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; } = ""; + + private sealed class RunScope(SimulationRunContext? previous) : IDisposable + { + public void Dispose() => Ambient.Value = previous; + } + + // 跨运行共享:统计与最近日志由仓储持有,查询服务只读这里。 + public static Dictionary CharacterStatistics => _statisticsStore.CharacterStatistics; + public static Dictionary TeamCharacterStatistics => _statisticsStore.TeamCharacterStatistics; + public static IReadOnlyList LastRecord { get => _statisticsStore.LastRecord; private set => _statisticsStore.LastRecord = value; } + public static IReadOnlyList 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; } /// - /// 指定本局使用的随机种子;为 null 时每局自动随机
- /// 设值后(或读取 得到的上一局实际值)同一份输入数据下整局模拟可复现 + /// 指定本局种子;为 null 时每局自动随机。现在字段属于运行上下文,设置后不会泄漏到下一局。 ///
- public static int? SeedOverride { get; set; } = null; + public static int? SeedOverride { get => Current.SeedOverride; set => Current.SeedOverride = value; } - /// - /// 固定武器 Id(0 = 不固定,按品质随机)。由 传入。 - /// 用于平衡测试时消除「武器攻击力 20–170(8.5×)+ 副属性各异 + 武器类型倍率 1.41×」这组混淆变量。 - /// - public static long FixedWeaponId { get; set; } = 0; + /// 固定武器 Id(0 = 不固定)。同种子复现用,属于本局运行态。 + public static long FixedWeaponId { get => Current.FixedWeaponId; set => Current.FixedWeaponId = value; } - /// - /// 本局实际使用的随机种子(开局确定并保留,便于复现) - /// - public static int Seed { get; private set; } = 0; + /// 本局实际使用的随机种子(开局确定并保留,便于复现)。 + public static int Seed { get => Current.Seed; private set => Current.Seed = value; } - /// - /// 模拟器自己的随机数生成器(由 决定) - /// 队列创建之前的角色抽选、技能分配、分队等走它;队列创建之后一律走 。 - /// 两者同源,因此本文件内禁止使用进程级的 Random.Shared,否则整局不可复现 - /// - public static Random Random { get; private set; } = new(); + /// 本局随机数生成器(由 Seed 决定);禁止改回进程级 Random.Shared。 + public static Random Random { get => Current.Random; private set => Current.Random = value; } - public static async Task> StartSimulationGame(SimulationOptions options) + /// 兼容旧调用:使用一次性默认上下文。 + public static Task> StartSimulationGame(SimulationOptions options) + => StartSimulationGame(options, new SimulationRunContext()); + + /// S8 起推荐入口:显式绑定本次运行上下文,静态运行态不再跨局共享。 + public static async Task> StartSimulationGame(SimulationOptions options, SimulationRunContext context) + { + ArgumentNullException.ThrowIfNull(context); + using IDisposable scope = BeginRun(context); + return await StartSimulationGameCore(options).ConfigureAwait(false); + } + + private static async Task> 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 store) { diff --git a/OshimaBot.Game/Services/SimulationRunContext.cs b/OshimaBot.Game/Services/SimulationRunContext.cs new file mode 100644 index 0000000..7a15b05 --- /dev/null +++ b/OshimaBot.Game/Services/SimulationRunContext.cs @@ -0,0 +1,31 @@ +using FunGame.Core.Model.Framework; +using Milimoe.FunGameTesting.Others; + +namespace OshimaBot.Game.Services; + +/// +/// 单次模拟的运行态。S8 前置改造:原先挂在 FunGameSimulation 上的进程级 static 可变字段 +/// 全部搬到这里,每次运行一个实例,避免多用户并发/串局时互相污染。 +/// 内容目录(FunGameService.Characters/Skills/Items)是只读模板,仍保持进程级共享。 +/// +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(); + + /// 绑定到本实例的日志回调:不依赖 AsyncLocal,跨线程回调也不会串局。 + public void WriteLine(string text) + { + Msg += text + "\r\n"; + if (PrintOut) Console.WriteLine(text); + } +} diff --git a/OshimaBot.Game/Services/SimulationStatisticsStore.cs b/OshimaBot.Game/Services/SimulationStatisticsStore.cs new file mode 100644 index 0000000..befc458 --- /dev/null +++ b/OshimaBot.Game/Services/SimulationStatisticsStore.cs @@ -0,0 +1,52 @@ +using FunGame.Core.Entity; + +namespace OshimaBot.Game.Services; + +/// +/// 跨运行共享的统计与最近日志。S8 前置把读写从 FunGameSimulation 的静态字典收敛到仓储接口; +/// S9 可替换为 EF Core(simulation_statistics / simulation_runs)实现而无需改动模拟器。 +/// +public interface ISimulationStatisticsStore +{ + Dictionary CharacterStatistics { get; } + Dictionary TeamCharacterStatistics { get; } + IReadOnlyList LastRecord { get; set; } + IReadOnlyList LastFullRecord { get; set; } + + /// 按当前内容目录重建统计行(进程启动或目录热重载时调用)。 + void Reset(IEnumerable characters); + + /// 在读锁内执行读取,避免与正在写入的模拟互相干扰。 + T Read(Func reader); +} + +public sealed class InMemorySimulationStatisticsStore : ISimulationStatisticsStore +{ + private readonly Lock _sync = new(); + + public Dictionary CharacterStatistics { get; } = []; + public Dictionary TeamCharacterStatistics { get; } = []; + public IReadOnlyList LastRecord { get; set; } = []; + public IReadOnlyList LastFullRecord { get; set; } = []; + + public void Reset(IEnumerable 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(Func reader) + { + lock (_sync) return reader(this); + } +} diff --git a/OshimaBot.Tests/SimulationIsolationTests.cs b/OshimaBot.Tests/SimulationIsolationTests.cs new file mode 100644 index 0000000..32a0f8a --- /dev/null +++ b/OshimaBot.Tests/SimulationIsolationTests.cs @@ -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 ranking = await queries.GetRankingAsync(false, true); + Assert.Single(ranking); + Assert.Contains("技术得分", ranking[0]); + } +} diff --git a/OshimaBot/Program.cs b/OshimaBot/Program.cs index 64905b3..dd0ce93 100644 --- a/OshimaBot/Program.cs +++ b/OshimaBot/Program.cs @@ -66,6 +66,8 @@ 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); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddScoped(); diff --git a/OshimaBot/Services/FunGameQueryService.cs b/OshimaBot/Services/FunGameQueryService.cs index 50a5fbb..b5d83a0 100644 --- a/OshimaBot/Services/FunGameQueryService.cs +++ b/OshimaBot/Services/FunGameQueryService.cs @@ -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 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 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 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> GetRankingAsync(bool team, bool byRating, CancellationToken cancellationToken = default) - => simulations.ReadAsync(() => + => Task.FromResult(statistics.Read(store => { Dictionary source = team - ? FunGameSimulation.TeamCharacterStatistics - : FunGameSimulation.CharacterStatistics; + ? store.TeamCharacterStatistics + : store.CharacterStatistics; IEnumerable> 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() { diff --git a/OshimaBot/Services/FunGameSimulationService.cs b/OshimaBot/Services/FunGameSimulationService.cs index a9e1567..3ae6d6b 100644 --- a/OshimaBot/Services/FunGameSimulationService.cs +++ b/OshimaBot/Services/FunGameSimulationService.cs @@ -28,12 +28,19 @@ namespace OshimaBot.Services DateTimeOffset CompletedAt, TimeSpan Duration); - public sealed class FunGameSimulationService(IOptions options) + /// + /// S8 前置:每次运行创建独立的 SimulationRunContext,静态运行态不再进程级共享; + /// 统计与最近日志改由 ISimulationStatisticsStore 持有。引擎仍串行执行(FunGame.Core 目录为只读共享), + /// 但两个运行之间不会串种子 / 消息 / 地图 / 运行状态。 + /// + public sealed class FunGameSimulationService( + ISimulationStatisticsStore statistics, + IOptions 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 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 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 ReadAsync(Func reader, CancellationToken cancellationToken = default) - { - await _gate.WaitAsync(cancellationToken); - try - { - return reader(); - } - finally - { - _gate.Release(); - } - } + /// 读锁内读取仓储;保留给外部只读调用。 + public Task ReadAsync(Func reader, CancellationToken cancellationToken = default) + => Task.FromResult(statistics.Read(_ => reader())); public Task> GetLastAsync(bool full, CancellationToken cancellationToken = default) - => ReadAsync(() => + => Task.FromResult(statistics.Read(store => { - IReadOnlyList source = full ? FunGameSimulation.LastFullRecord : FunGameSimulation.LastRecord; + IReadOnlyList source = full ? store.LastFullRecord : store.LastRecord; return (IReadOnlyList)[.. source]; - }, cancellationToken); + })); } }