feat(headless): Campaign OP slice OP7 — declared characterOptions with seed-diff sends
Adds an optional, strict `characterOptions` block to the headless bot config (D8): keys are exactly the lane-B tier-1 (22) + tier-2 (4) bot-declarable CharacterOptionId enum-member spellings; an unknown/out-of-tier name fails config load naming the offending key, before it can ever reach the wire. HeadlessCharacterOptionsSeeder diffs declared-vs-actual once both of ACE's real preconditions are known true — GameActionLoginComplete sent (the FirstEnterWorldDone gate SetCharacterOptions 0x01A1 needs) and a real PlayerDescription has seeded RuntimeCharacterOptionsState (HasServerSeed) — learned from whichever of two hooks lands second. Every differing id routes through OP1's shared IRuntimeCharacterCommands seam: auto-save ids send SetSingleOption (0x0005) immediately; batched ids also call SetSingleOption (which only dirties the module) followed by exactly one SaveOptions flush after the whole declared set has been walked. Idempotent on reconnect by construction — no dedupe latch, the diff simply finds nothing once the server agrees. RuntimeLiveEntitySessionController gains a passive onLoginCompleteSent observation hook (additive only, never changes when/whether it sends) so the headless host can learn ACE's gate opened from any of its own two internal send sites; the third site (direct first-entry completion) is already owned by HeadlessSessionHost itself. All wiring is synchronous delegate calls on Runtime's one dedicated update thread — no new async/Task continuation, honoring #368. Tests: schema (valid parse, unknown/tier-3 name rejected naming the key, non-bool rejected, empty/absent no-op), the diff engine against a fake IRuntimeCharacterCommands (nothing-to-send, auto-save-only, batched-with- flush, mixed ordering, reconnect idempotence), and two wiring integration tests — one dispatching a real PlayerDescription game event end-to-end to a captured wire action, one proving the send lands on the same dedicated thread every Tick runs on. Full solution suite: 12,935 passed / 4 skipped / 0 failed (+17 over baseline 12,918/4/0). No register row: the characterOptions bot-config surface is acdream- native tooling over retail's own wire mechanisms (both already ported by OP1), not a retail UI port with a divergence to record. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
efe80d5a0d
commit
09cb548a32
9 changed files with 1278 additions and 5 deletions
|
|
@ -0,0 +1,289 @@
|
|||
using AcDream.Core.Net.Messages;
|
||||
using AcDream.Headless.Hosting;
|
||||
using AcDream.Runtime;
|
||||
using AcDream.Runtime.Gameplay;
|
||||
|
||||
namespace AcDream.Headless.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Campaign OP slice OP7 (2026-08-11), D8: the declared-vs-actual diff engine
|
||||
/// (<see cref="HeadlessCharacterOptionsSeeder"/>) unit-tested against a fake
|
||||
/// <see cref="IRuntimeCharacterCommands"/> so these tests never need a live
|
||||
/// session, a wire, or a physics/collision fixture — only a bare
|
||||
/// <see cref="GameRuntime"/> for its <c>CharacterOwner.Options</c> state and
|
||||
/// <c>Generation</c> token. <see cref="RuntimeCharacterOptionsState.Replace"/>
|
||||
/// stands in for "a PlayerDescription just landed" exactly like
|
||||
/// <c>LiveSessionEventRouter</c>'s own <c>onCharacterOptions</c> wiring does.
|
||||
/// </summary>
|
||||
public sealed class HeadlessCharacterOptionsSeederTests
|
||||
{
|
||||
// AutoRepeatAttack (0x00, Options1 0x00000002) is auto-save — sends
|
||||
// SetSingleOption (0x0005) immediately, per CharacterOptionTable.
|
||||
// IgnoreTradeRequests (0x03, Options1 0x00020000) is batched — dirties
|
||||
// the module; only SaveOptions flushes it. Both are exercised by name
|
||||
// throughout this file's tests.
|
||||
private const uint AutoSaveMask = 0x00000002u;
|
||||
|
||||
[Fact]
|
||||
public void DeclaredEqualsActualSendsNothing()
|
||||
{
|
||||
using GameRuntime runtime = NewRuntime();
|
||||
runtime.CharacterOwner.Options.Replace(0u, 0u);
|
||||
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
|
||||
var seeder = new HeadlessCharacterOptionsSeeder(
|
||||
new Dictionary<CharacterOptionId, bool>
|
||||
{
|
||||
[CharacterOptionId.AutoRepeatAttack] = false,
|
||||
},
|
||||
runtime,
|
||||
commands);
|
||||
|
||||
seeder.NoteLoginCompleteSent();
|
||||
seeder.NoteOptionsSeeded();
|
||||
|
||||
Assert.Empty(commands.CallOrder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AutoSaveDifferenceSendsExactlyOneSetSingleOption()
|
||||
{
|
||||
using GameRuntime runtime = NewRuntime();
|
||||
runtime.CharacterOwner.Options.Replace(0u, 0u);
|
||||
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
|
||||
var seeder = new HeadlessCharacterOptionsSeeder(
|
||||
new Dictionary<CharacterOptionId, bool>
|
||||
{
|
||||
[CharacterOptionId.AutoRepeatAttack] = true,
|
||||
},
|
||||
runtime,
|
||||
commands);
|
||||
|
||||
seeder.NoteLoginCompleteSent();
|
||||
seeder.NoteOptionsSeeded();
|
||||
|
||||
var call = Assert.Single(commands.SingleOptionCalls);
|
||||
Assert.Equal((uint)CharacterOptionId.AutoRepeatAttack, call.OptionId);
|
||||
Assert.True(call.Value);
|
||||
Assert.Equal(0, commands.SaveOptionsCallCount);
|
||||
Assert.Equal(["set:0"], commands.CallOrder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BatchedDifferenceSendsSetSingleOptionThenExactlyOneSaveOptionsAtTheEnd()
|
||||
{
|
||||
using GameRuntime runtime = NewRuntime();
|
||||
runtime.CharacterOwner.Options.Replace(0u, 0u);
|
||||
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
|
||||
var seeder = new HeadlessCharacterOptionsSeeder(
|
||||
new Dictionary<CharacterOptionId, bool>
|
||||
{
|
||||
[CharacterOptionId.IgnoreTradeRequests] = true,
|
||||
},
|
||||
runtime,
|
||||
commands);
|
||||
|
||||
seeder.NoteLoginCompleteSent();
|
||||
seeder.NoteOptionsSeeded();
|
||||
|
||||
var call = Assert.Single(commands.SingleOptionCalls);
|
||||
Assert.Equal((uint)CharacterOptionId.IgnoreTradeRequests, call.OptionId);
|
||||
Assert.True(call.Value);
|
||||
Assert.Equal(1, commands.SaveOptionsCallCount);
|
||||
Assert.Equal(["set:3", "save"], commands.CallOrder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MixedDeclarationOrdersAllSetsBeforeTheSingleFlush()
|
||||
{
|
||||
using GameRuntime runtime = NewRuntime();
|
||||
runtime.CharacterOwner.Options.Replace(0u, 0u);
|
||||
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
|
||||
var seeder = new HeadlessCharacterOptionsSeeder(
|
||||
new Dictionary<CharacterOptionId, bool>
|
||||
{
|
||||
// Declared out of id order on purpose — the seeder sorts
|
||||
// id-ascending internally, so the batched id (0x03) is
|
||||
// expected AFTER the auto-save id (0x00) regardless of
|
||||
// declaration order, with the flush always last.
|
||||
[CharacterOptionId.IgnoreTradeRequests] = true,
|
||||
[CharacterOptionId.AutoRepeatAttack] = true,
|
||||
},
|
||||
runtime,
|
||||
commands);
|
||||
|
||||
seeder.NoteLoginCompleteSent();
|
||||
seeder.NoteOptionsSeeded();
|
||||
|
||||
Assert.Equal(2, commands.SingleOptionCalls.Count);
|
||||
Assert.Equal(1, commands.SaveOptionsCallCount);
|
||||
Assert.Equal(["set:0", "set:3", "save"], commands.CallOrder);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NeitherPreconditionAloneSendsAnything()
|
||||
{
|
||||
using GameRuntime runtime = NewRuntime();
|
||||
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
|
||||
var seeder = new HeadlessCharacterOptionsSeeder(
|
||||
new Dictionary<CharacterOptionId, bool>
|
||||
{
|
||||
[CharacterOptionId.AutoRepeatAttack] = true,
|
||||
},
|
||||
runtime,
|
||||
commands);
|
||||
|
||||
// Login-complete alone: HasServerSeed is still false (no Replace
|
||||
// ever ran), so the diff cannot trust live state yet.
|
||||
seeder.NoteLoginCompleteSent();
|
||||
Assert.Empty(commands.CallOrder);
|
||||
|
||||
// Now the seed lands — both preconditions are satisfied and the
|
||||
// deferred diff runs from THIS call.
|
||||
runtime.CharacterOwner.Options.Replace(0u, 0u);
|
||||
seeder.NoteOptionsSeeded();
|
||||
|
||||
Assert.Single(commands.SingleOptionCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OptionsSeededBeforeLoginCompleteDefersUntilLoginCompleteArrives()
|
||||
{
|
||||
using GameRuntime runtime = NewRuntime();
|
||||
runtime.CharacterOwner.Options.Replace(0u, 0u);
|
||||
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
|
||||
var seeder = new HeadlessCharacterOptionsSeeder(
|
||||
new Dictionary<CharacterOptionId, bool>
|
||||
{
|
||||
[CharacterOptionId.AutoRepeatAttack] = true,
|
||||
},
|
||||
runtime,
|
||||
commands);
|
||||
|
||||
seeder.NoteOptionsSeeded();
|
||||
Assert.Empty(commands.CallOrder);
|
||||
|
||||
seeder.NoteLoginCompleteSent();
|
||||
Assert.Single(commands.SingleOptionCalls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyDeclarationNeverSendsRegardlessOfBothSignals()
|
||||
{
|
||||
using GameRuntime runtime = NewRuntime();
|
||||
runtime.CharacterOwner.Options.Replace(0xFFFFFFFFu, 0xFFFFFFFFu);
|
||||
var commands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
|
||||
var seeder = new HeadlessCharacterOptionsSeeder(
|
||||
new Dictionary<CharacterOptionId, bool>(),
|
||||
runtime,
|
||||
commands);
|
||||
|
||||
Assert.False(seeder.HasDeclaredOptions);
|
||||
seeder.NoteLoginCompleteSent();
|
||||
seeder.NoteOptionsSeeded();
|
||||
|
||||
Assert.Empty(commands.CallOrder);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// D8 idempotence — the acceptance bar is "by construction", not a
|
||||
/// special-cased dedupe: a fresh, second seeder instance (mirroring the
|
||||
/// fresh instance <c>HeadlessSessionHost.CreateEventRoute</c> constructs
|
||||
/// per reconnect) diffs against the SAME declared dictionary but against
|
||||
/// live state that already reflects what the first seeder sent — the
|
||||
/// second diff simply finds nothing to do.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ReconnectWithSameDeclarationsAgainstServerThatNowAgreesSendsNothing()
|
||||
{
|
||||
using GameRuntime runtime = NewRuntime();
|
||||
var declared = new Dictionary<CharacterOptionId, bool>
|
||||
{
|
||||
[CharacterOptionId.AutoRepeatAttack] = true,
|
||||
};
|
||||
|
||||
// First connect: server has the option OFF; the bot's declared
|
||||
// value differs, so it sends once.
|
||||
runtime.CharacterOwner.Options.Replace(0u, 0u);
|
||||
var firstCommands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
|
||||
var firstSeeder = new HeadlessCharacterOptionsSeeder(
|
||||
declared, runtime, firstCommands);
|
||||
firstSeeder.NoteLoginCompleteSent();
|
||||
firstSeeder.NoteOptionsSeeded();
|
||||
Assert.Single(firstCommands.SingleOptionCalls);
|
||||
|
||||
// Reconnect: a fresh seeder instance (per CreateEventRoute's own
|
||||
// per-route construction), and the server's fresh PlayerDescription
|
||||
// now echoes what the bot itself set last time.
|
||||
runtime.CharacterOwner.Options.ResetSession();
|
||||
runtime.CharacterOwner.Options.Replace(AutoSaveMask, 0u);
|
||||
var secondCommands = new FakeCharacterCommands(runtime.CharacterOwner.Options);
|
||||
var secondSeeder = new HeadlessCharacterOptionsSeeder(
|
||||
declared, runtime, secondCommands);
|
||||
secondSeeder.NoteLoginCompleteSent();
|
||||
secondSeeder.NoteOptionsSeeded();
|
||||
|
||||
Assert.Empty(secondCommands.CallOrder);
|
||||
}
|
||||
|
||||
private static GameRuntime NewRuntime()
|
||||
{
|
||||
var gameplay = new HeadlessGameplayOperations();
|
||||
var runtime = new GameRuntime(new GameRuntimeDependencies(
|
||||
gameplay,
|
||||
gameplay,
|
||||
gameplay,
|
||||
gameplay));
|
||||
gameplay.Bind(runtime, catalog: null, () => "account");
|
||||
return runtime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the bit into <paramref name="options"/> as part of
|
||||
/// <see cref="SetSingleOption"/>, mirroring the REAL
|
||||
/// <c>DirectGameRuntimeCommandAdapter.SetSingleOption</c> →
|
||||
/// <c>RuntimeCharacterOptionsState.TrySetOption</c> contract: the local
|
||||
/// copy updates synchronously, in the same call, before the method
|
||||
/// returns. Without this, a fake that only records the call (never
|
||||
/// mutating live state) would make a SECOND diff pass — e.g. a
|
||||
/// legitimate redundant <c>NoteLoginCompleteSent</c>/<c>NoteOptionsSeeded</c>
|
||||
/// pairing — re-find the same already-handled mismatch and re-send it,
|
||||
/// which is a fidelity gap in the fake, not a real defect: production's
|
||||
/// idempotence depends on exactly this synchronous local write.
|
||||
/// </summary>
|
||||
private sealed class FakeCharacterCommands(
|
||||
RuntimeCharacterOptionsState options) : IRuntimeCharacterCommands
|
||||
{
|
||||
internal List<(uint OptionId, bool Value)> SingleOptionCalls { get; } = [];
|
||||
internal int SaveOptionsCallCount { get; private set; }
|
||||
internal List<string> CallOrder { get; } = [];
|
||||
|
||||
public RuntimeCommandResult Advance(
|
||||
RuntimeGenerationToken expectedGeneration,
|
||||
in RuntimeAdvancementCommand command) =>
|
||||
throw new NotSupportedException(
|
||||
"HeadlessCharacterOptionsSeeder never calls Advance.");
|
||||
|
||||
public RuntimeCommandResult SetSingleOption(
|
||||
RuntimeGenerationToken expectedGeneration,
|
||||
uint optionId,
|
||||
bool value)
|
||||
{
|
||||
SingleOptionCalls.Add((optionId, value));
|
||||
CallOrder.Add($"set:{optionId}");
|
||||
options.SetOptionBit(optionId, value);
|
||||
return new RuntimeCommandResult(
|
||||
RuntimeCommandStatus.Accepted,
|
||||
expectedGeneration);
|
||||
}
|
||||
|
||||
public RuntimeCommandResult SaveOptions(
|
||||
RuntimeGenerationToken expectedGeneration)
|
||||
{
|
||||
SaveOptionsCallCount++;
|
||||
CallOrder.Add("save");
|
||||
return new RuntimeCommandResult(
|
||||
RuntimeCommandStatus.Accepted,
|
||||
expectedGeneration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,357 @@
|
|||
using System.Buffers.Binary;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using AcDream.Core.Net;
|
||||
using AcDream.Core.Net.Messages;
|
||||
using AcDream.Headless.Configuration;
|
||||
using AcDream.Headless.Credentials;
|
||||
using AcDream.Headless.Diagnostics;
|
||||
using AcDream.Headless.Hosting;
|
||||
using AcDream.Headless.Platform;
|
||||
using AcDream.Runtime;
|
||||
using AcDream.Runtime.Session;
|
||||
|
||||
namespace AcDream.Headless.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Campaign OP slice OP7 (2026-08-11), D8: end-to-end wiring proof that a
|
||||
/// declared <c>characterOptions</c> block reaches the real wire through
|
||||
/// <see cref="HeadlessSessionHost"/>'s actual production seams — not just
|
||||
/// the isolated diff engine (<see cref="HeadlessCharacterOptionsSeederTests"/>
|
||||
/// covers that with a fake command surface). A real
|
||||
/// <c>PlayerDescription</c> game event is dispatched through
|
||||
/// <c>WorldSession.GameEvents</c> exactly like a live server connection
|
||||
/// would deliver it (the same mechanism
|
||||
/// <c>LiveSessionEventRouterTests.PlayerDescription_ReplacesOptionsBeforeInvokingOnCharacterOptionsChanged</c>
|
||||
/// uses) — this proves the REAL
|
||||
/// <c>LiveCharacterSessionBindings.OnCharacterOptionsChanged</c> wiring
|
||||
/// added in <c>HeadlessSessionHost.CreateEventRoute</c>. The "LoginComplete
|
||||
/// already sent" half is driven through the <see cref="HeadlessSessionHost.OptionsSeeder"/>
|
||||
/// test seam directly — the three production sites that actually send
|
||||
/// <c>GameActionLoginComplete</c> (content-less immediate admission, direct
|
||||
/// first-entry completion, portal-space materialization completion) are
|
||||
/// each simple one-line delegate wiring already covered by their OWN
|
||||
/// existing tests (<c>RuntimeLiveEntitySessionControllerTests</c>); this
|
||||
/// class's job is to prove what happens once that signal lands, not to
|
||||
/// re-derive it.
|
||||
/// </summary>
|
||||
public sealed class HeadlessCharacterOptionsSeederWiringTests
|
||||
{
|
||||
[Fact]
|
||||
public void DeclaredOptionSendsOnceBothLoginCompleteAndTheRealPlayerDescriptionEventLand()
|
||||
{
|
||||
var operations = new FixtureSessionOperations();
|
||||
using var credential = new HeadlessCredentialSecret(
|
||||
"fixture",
|
||||
"password");
|
||||
using var host = new HeadlessSessionHost(
|
||||
Descriptor(),
|
||||
credential,
|
||||
new HeadlessDiagnosticWriter(TextWriter.Null),
|
||||
operations);
|
||||
|
||||
Assert.Equal(
|
||||
RuntimeSessionStartStatus.Connected,
|
||||
host.Start().Status);
|
||||
Assert.NotNull(host.OptionsSeeder);
|
||||
|
||||
var sent = new List<byte[]>();
|
||||
WorldSession session = operations.Sessions[^1];
|
||||
session.GameActionCapture = body => sent.Add(body);
|
||||
|
||||
// LoginComplete lands first (a legitimate production ordering —
|
||||
// see the type doc); no PlayerDescription has arrived yet, so
|
||||
// HasServerSeed is still false and nothing can send.
|
||||
host.OptionsSeeder!.NoteLoginCompleteSent();
|
||||
Assert.Empty(sent);
|
||||
|
||||
// The real PlayerDescription game event, dispatched through the
|
||||
// ACTUAL session event route production installed — proves
|
||||
// OnCharacterOptionsChanged is really wired, not just callable.
|
||||
// IgnoreAllegianceRequests (0x01, Options1 0x00000004) starts OFF
|
||||
// on the server; the declared value is ON.
|
||||
session.GameEvents.Dispatch(
|
||||
GameEventEnvelope.TryParse(
|
||||
WrapPlayerDescriptionEnvelope(options1: 0u, options2: 0u))!
|
||||
.Value);
|
||||
|
||||
byte[] action = Assert.Single(sent);
|
||||
Assert.Equal(
|
||||
SocialActions.SetSingleCharacterOptionOpcode,
|
||||
ActionOpcode(action));
|
||||
Assert.Equal(
|
||||
(uint)CharacterOptionId.IgnoreAllegianceRequests,
|
||||
BinaryPrimitives.ReadUInt32LittleEndian(action.AsSpan(12, 4)));
|
||||
Assert.Equal(1u, BinaryPrimitives.ReadUInt32LittleEndian(action.AsSpan(16, 4)));
|
||||
Assert.True(
|
||||
host.Runtime.CharacterOwner.Options.HasServerSeed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReconnectAgainstAServerThatNowAgreesSendsNothing()
|
||||
{
|
||||
var operations = new FixtureSessionOperations();
|
||||
using var credential = new HeadlessCredentialSecret(
|
||||
"fixture",
|
||||
"password");
|
||||
using var host = new HeadlessSessionHost(
|
||||
Descriptor(),
|
||||
credential,
|
||||
new HeadlessDiagnosticWriter(TextWriter.Null),
|
||||
operations);
|
||||
Assert.Equal(
|
||||
RuntimeSessionStartStatus.Connected,
|
||||
host.Start().Status);
|
||||
WorldSession firstSession = operations.Sessions[^1];
|
||||
var firstSent = new List<byte[]>();
|
||||
firstSession.GameActionCapture = body => firstSent.Add(body);
|
||||
host.OptionsSeeder!.NoteLoginCompleteSent();
|
||||
firstSession.GameEvents.Dispatch(
|
||||
GameEventEnvelope.TryParse(
|
||||
WrapPlayerDescriptionEnvelope(options1: 0u, options2: 0u))!
|
||||
.Value);
|
||||
Assert.Single(firstSent);
|
||||
|
||||
Assert.Equal(
|
||||
RuntimeSessionStartStatus.Connected,
|
||||
host.Reconnect().Status);
|
||||
Assert.NotSame(firstSession, operations.Sessions[^1]);
|
||||
WorldSession secondSession = operations.Sessions[^1];
|
||||
var secondSent = new List<byte[]>();
|
||||
secondSession.GameActionCapture = body => secondSent.Add(body);
|
||||
|
||||
host.OptionsSeeder!.NoteLoginCompleteSent();
|
||||
// The fresh PlayerDescription now echoes what the bot itself set
|
||||
// last connection — IgnoreAllegianceRequests's mask, ON.
|
||||
secondSession.GameEvents.Dispatch(
|
||||
GameEventEnvelope.TryParse(
|
||||
WrapPlayerDescriptionEnvelope(
|
||||
options1: 0x00000004u,
|
||||
options2: 0u))!
|
||||
.Value);
|
||||
|
||||
Assert.Empty(secondSent);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #368: the diff-and-send must run on Runtime's one dedicated update
|
||||
/// thread, exactly like every other gameplay-owner mutation — never a
|
||||
/// new async continuation. Mirrors
|
||||
/// <c>HeadlessProcessSchedulerTests.ProcessHostRunsStartAndEveryTickOnOneDedicatedUpdateThread</c>'s
|
||||
/// own proof shape (occupy the calling thread across real ticks so a
|
||||
/// thread-pool migration would be observable), but additionally drives
|
||||
/// a real PlayerDescription dispatch and a login-complete signal FROM
|
||||
/// INSIDE <c>ILiveSessionOperations.Tick</c> — the same call frame
|
||||
/// <c>HeadlessSessionHost.Tick</c>'s own <c>Runtime.Session.Tick()</c>
|
||||
/// reaches — so the captured send's thread id is measured at the exact
|
||||
/// point production code would run it, not simulated from the test
|
||||
/// thread.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task DiffAndSendRunsOnTheSameDedicatedUpdateThreadAsEveryTick()
|
||||
{
|
||||
var configuration = new HeadlessConfiguration
|
||||
{
|
||||
Version = 1,
|
||||
Sessions = [Descriptor()],
|
||||
};
|
||||
var operations = new SeedTriggeringSessionOperations();
|
||||
using var diagnostics = new StringWriter();
|
||||
using var host = new HeadlessProcessHost(
|
||||
configuration,
|
||||
HeadlessPathSet.Resolve(new HeadlessPathOverrides()),
|
||||
new System.IO.StringReader("fixture-password" + Environment.NewLine),
|
||||
diagnostics,
|
||||
operations);
|
||||
operations.Host = host.Sessions[0];
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
|
||||
int callerThread = Environment.CurrentManagedThreadId;
|
||||
Task<HeadlessExitCode> run = host.RunAsync(cancellation.Token);
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
while (operations.SentActions.IsEmpty
|
||||
&& stopwatch.Elapsed < TimeSpan.FromSeconds(10))
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
cancellation.Cancel();
|
||||
HeadlessExitCode result = await run;
|
||||
|
||||
Assert.Equal(HeadlessExitCode.Success, result);
|
||||
(byte[] Body, int ThreadId) sent = Assert.Single(operations.SentActions);
|
||||
Assert.Equal(
|
||||
SocialActions.SetSingleCharacterOptionOpcode,
|
||||
ActionOpcode(sent.Body));
|
||||
Assert.NotEqual(0, sent.ThreadId);
|
||||
Assert.NotEqual(callerThread, sent.ThreadId);
|
||||
Assert.Equal(operations.ConnectThreadId, sent.ThreadId);
|
||||
}
|
||||
|
||||
private static uint ActionOpcode(byte[] body) =>
|
||||
BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(8, sizeof(uint)));
|
||||
|
||||
// Minimal PlayerDescription (0x0013) body carrying only the
|
||||
// CharacterOptions1/2 trailer fields — copied from
|
||||
// LiveSessionEventRouterTests.WrapPlayerDescriptionEnvelope (mirrors
|
||||
// GameEventWiringTests.WireAll_PlayerDescription_PublishesCharacterOptions's
|
||||
// fixture layout).
|
||||
private static byte[] WrapPlayerDescriptionEnvelope(
|
||||
uint options1,
|
||||
uint options2)
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
using (var writer = new BinaryWriter(
|
||||
stream, System.Text.Encoding.UTF8, leaveOpen: true))
|
||||
{
|
||||
writer.Write(0u); // property flags
|
||||
writer.Write(0x52u); // player weenie type
|
||||
writer.Write(0u); // vector flags
|
||||
writer.Write(0u); // has health
|
||||
writer.Write(0x40u); // option flags: CharacterOptions2
|
||||
writer.Write(options1);
|
||||
writer.Write(0u); // legacy hotbar count
|
||||
writer.Write(0u); // spellbook filters
|
||||
writer.Write(options2);
|
||||
writer.Write(0u); // inventory count
|
||||
writer.Write(0u); // equipped count
|
||||
}
|
||||
|
||||
byte[] payload = stream.ToArray();
|
||||
byte[] body = new byte[GameEventEnvelope.HeaderSize + payload.Length];
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(body, GameEventEnvelope.Opcode);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(4), 0u);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(8), 0u);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(
|
||||
body.AsSpan(12), (uint)GameEventType.PlayerDescription);
|
||||
Array.Copy(payload, 0, body, GameEventEnvelope.HeaderSize, payload.Length);
|
||||
return body;
|
||||
}
|
||||
|
||||
private static HeadlessSessionDescriptor Descriptor() => new()
|
||||
{
|
||||
Id = "bot",
|
||||
Endpoint = new HeadlessEndpointDescriptor
|
||||
{
|
||||
Host = "127.0.0.1",
|
||||
Port = 9000,
|
||||
},
|
||||
Account = "account",
|
||||
Character = new HeadlessCharacterSelector
|
||||
{
|
||||
Name = "headless",
|
||||
},
|
||||
Policy = new HeadlessBotPolicyDescriptor
|
||||
{
|
||||
Id = "idle",
|
||||
},
|
||||
Credential = new HeadlessCredentialReference
|
||||
{
|
||||
Provider = HeadlessCredentialProviderKind.StandardInput,
|
||||
Reference = "fixture-password",
|
||||
},
|
||||
CharacterOptions = new Dictionary<string, bool>
|
||||
{
|
||||
["IgnoreAllegianceRequests"] = true,
|
||||
},
|
||||
};
|
||||
|
||||
private sealed class FixtureSessionOperations : ILiveSessionOperations
|
||||
{
|
||||
public List<WorldSession> Sessions { get; } = [];
|
||||
|
||||
public IPEndPoint ResolveEndpoint(string host, int port) =>
|
||||
new(IPAddress.Loopback, port);
|
||||
|
||||
public WorldSession CreateSession(IPEndPoint endpoint)
|
||||
{
|
||||
var session = new WorldSession(endpoint);
|
||||
Sessions.Add(session);
|
||||
return session;
|
||||
}
|
||||
|
||||
public void Connect(WorldSession session, string user, string password)
|
||||
{
|
||||
}
|
||||
|
||||
public CharacterList.Parsed GetCharacters(WorldSession session) =>
|
||||
new(
|
||||
0u,
|
||||
[new CharacterList.Character(0x50000001u, "Headless", 0u)],
|
||||
[],
|
||||
11,
|
||||
"account",
|
||||
true,
|
||||
true);
|
||||
|
||||
public void EnterWorld(WorldSession session, int activeCharacterIndex)
|
||||
{
|
||||
}
|
||||
|
||||
public void Tick(WorldSession session)
|
||||
{
|
||||
}
|
||||
|
||||
public void DisposeSession(WorldSession session) => session.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Thread-affinity fixture: on its first <see cref="Tick"/> call it
|
||||
/// drives login-complete plus a real PlayerDescription dispatch from
|
||||
/// INSIDE the call — the same frame production's
|
||||
/// <c>Runtime.Session.Tick()</c> reaches <c>ILiveSessionOperations.Tick</c>
|
||||
/// from. <see cref="Host"/> is wired AFTER construction (the
|
||||
/// <see cref="HeadlessSessionHost"/> does not exist yet when this fixture
|
||||
/// is passed into <see cref="HeadlessProcessHost"/>'s constructor).
|
||||
/// </summary>
|
||||
private sealed class SeedTriggeringSessionOperations : ILiveSessionOperations
|
||||
{
|
||||
private int _connectThreadId;
|
||||
private int _dispatched;
|
||||
|
||||
internal HeadlessSessionHost? Host { get; set; }
|
||||
internal int ConnectThreadId => Volatile.Read(ref _connectThreadId);
|
||||
internal ConcurrentQueue<(byte[] Body, int ThreadId)> SentActions { get; } = new();
|
||||
|
||||
public IPEndPoint ResolveEndpoint(string host, int port) =>
|
||||
new(IPAddress.Loopback, port);
|
||||
|
||||
public WorldSession CreateSession(IPEndPoint endpoint)
|
||||
{
|
||||
var session = new WorldSession(endpoint);
|
||||
session.GameActionCapture = body => SentActions.Enqueue(
|
||||
(body, Environment.CurrentManagedThreadId));
|
||||
return session;
|
||||
}
|
||||
|
||||
public void Connect(WorldSession session, string user, string password) =>
|
||||
Volatile.Write(ref _connectThreadId, Environment.CurrentManagedThreadId);
|
||||
|
||||
public CharacterList.Parsed GetCharacters(WorldSession session) =>
|
||||
new(
|
||||
0u,
|
||||
[new CharacterList.Character(0x50000001u, "Headless", 0u)],
|
||||
[],
|
||||
11,
|
||||
"account",
|
||||
true,
|
||||
true);
|
||||
|
||||
public void EnterWorld(WorldSession session, int activeCharacterIndex)
|
||||
{
|
||||
}
|
||||
|
||||
public void Tick(WorldSession session)
|
||||
{
|
||||
if (Interlocked.Exchange(ref _dispatched, 1) != 0)
|
||||
return;
|
||||
Host?.OptionsSeeder?.NoteLoginCompleteSent();
|
||||
session.GameEvents.Dispatch(
|
||||
GameEventEnvelope.TryParse(
|
||||
WrapPlayerDescriptionEnvelope(options1: 0u, options2: 0u))!
|
||||
.Value);
|
||||
}
|
||||
|
||||
public void DisposeSession(WorldSession session) => session.Dispose();
|
||||
}
|
||||
}
|
||||
177
tests/AcDream.Headless.Tests/HeadlessConfigurationLoaderTests.cs
Normal file
177
tests/AcDream.Headless.Tests/HeadlessConfigurationLoaderTests.cs
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
using System.Text.Json;
|
||||
using AcDream.Headless.Configuration;
|
||||
|
||||
namespace AcDream.Headless.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Campaign OP slice OP7 (2026-08-11), D8: schema tests for the optional
|
||||
/// per-session <c>characterOptions</c> block —
|
||||
/// docs/plans/2026-08-10-options-panel-campaign.md §4 OP7. Exercises
|
||||
/// <see cref="HeadlessConfigurationLoader.Load"/> directly (rather than
|
||||
/// through <c>HeadlessEntryPoint</c>'s CLI wrapper) so assertions can pin the
|
||||
/// exact exception type/message for the semantic "unknown name" rejection,
|
||||
/// matching the loader's own established split: type-shape violations
|
||||
/// (missing required field, wrong JSON value kind) fail during
|
||||
/// deserialization itself with a raw <see cref="JsonException"/>; semantic
|
||||
/// violations of an already-well-typed value fail with
|
||||
/// <see cref="HeadlessConfigurationException"/> (see
|
||||
/// <see cref="HeadlessConfigurationLoader"/>'s own doc comment on
|
||||
/// <c>ValidateCharacterOptions</c>).
|
||||
/// </summary>
|
||||
public sealed class HeadlessConfigurationLoaderTests
|
||||
{
|
||||
[Fact]
|
||||
public void ValidCharacterOptionsBlockParsesExactDeclaredNames()
|
||||
{
|
||||
using TemporaryConfiguration file = TemporaryConfiguration.Create(
|
||||
ConfigurationWith(Session(
|
||||
"bot",
|
||||
"BOT_PASSWORD",
|
||||
"""
|
||||
"characterOptions":{
|
||||
"IgnoreAllegianceRequests":true,
|
||||
"ListenToTradeChat":false,
|
||||
"AutoTarget":true
|
||||
}
|
||||
""")));
|
||||
|
||||
HeadlessConfiguration configuration =
|
||||
HeadlessConfigurationLoader.Load(file.Path);
|
||||
|
||||
Dictionary<string, bool>? declared =
|
||||
Assert.Single(configuration.Sessions)!.CharacterOptions;
|
||||
Assert.NotNull(declared);
|
||||
Assert.Equal(3, declared!.Count);
|
||||
Assert.True(declared["IgnoreAllegianceRequests"]);
|
||||
Assert.False(declared["ListenToTradeChat"]);
|
||||
Assert.True(declared["AutoTarget"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UnknownOptionNameFailsLoadNamingTheOffendingKey()
|
||||
{
|
||||
using TemporaryConfiguration file = TemporaryConfiguration.Create(
|
||||
ConfigurationWith(Session(
|
||||
"bot",
|
||||
"BOT_PASSWORD",
|
||||
"\"characterOptions\":{\"NotARealOption\":true}")));
|
||||
|
||||
HeadlessConfigurationException exception = Assert.Throws<
|
||||
HeadlessConfigurationException>(
|
||||
() => HeadlessConfigurationLoader.Load(file.Path));
|
||||
|
||||
Assert.Contains(
|
||||
"NotARealOption",
|
||||
exception.Message,
|
||||
StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void PresentationOnlyTierThreeOptionNameFailsLoad()
|
||||
{
|
||||
// ShowHelm is a REAL CharacterOptionId member (0x2F) but is
|
||||
// deliberately outside the tier-1+2 bot-declarable subset (research
|
||||
// doc §5.2 tier 3) — excluded by construction, not merely absent
|
||||
// from an allow-list that forgot it.
|
||||
using TemporaryConfiguration file = TemporaryConfiguration.Create(
|
||||
ConfigurationWith(Session(
|
||||
"bot",
|
||||
"BOT_PASSWORD",
|
||||
"\"characterOptions\":{\"ShowHelm\":true}")));
|
||||
|
||||
HeadlessConfigurationException exception = Assert.Throws<
|
||||
HeadlessConfigurationException>(
|
||||
() => HeadlessConfigurationLoader.Load(file.Path));
|
||||
|
||||
Assert.Contains(
|
||||
"ShowHelm",
|
||||
exception.Message,
|
||||
StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NonBoolValueFailsLoad()
|
||||
{
|
||||
using TemporaryConfiguration file = TemporaryConfiguration.Create(
|
||||
ConfigurationWith(Session(
|
||||
"bot",
|
||||
"BOT_PASSWORD",
|
||||
"\"characterOptions\":{\"IgnoreAllegianceRequests\":\"yes\"}")));
|
||||
|
||||
Assert.ThrowsAny<Exception>(
|
||||
() => HeadlessConfigurationLoader.Load(file.Path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AbsentCharacterOptionsBlockIsANoOp()
|
||||
{
|
||||
using TemporaryConfiguration file = TemporaryConfiguration.Create(
|
||||
ConfigurationWith(Session("bot", "BOT_PASSWORD")));
|
||||
|
||||
HeadlessConfiguration configuration =
|
||||
HeadlessConfigurationLoader.Load(file.Path);
|
||||
|
||||
Assert.Null(Assert.Single(configuration.Sessions)!.CharacterOptions);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EmptyCharacterOptionsBlockIsANoOp()
|
||||
{
|
||||
using TemporaryConfiguration file = TemporaryConfiguration.Create(
|
||||
ConfigurationWith(Session(
|
||||
"bot",
|
||||
"BOT_PASSWORD",
|
||||
"\"characterOptions\":{}")));
|
||||
|
||||
HeadlessConfiguration configuration =
|
||||
HeadlessConfigurationLoader.Load(file.Path);
|
||||
|
||||
Dictionary<string, bool>? declared =
|
||||
Assert.Single(configuration.Sessions)!.CharacterOptions;
|
||||
Assert.NotNull(declared);
|
||||
Assert.Empty(declared!);
|
||||
}
|
||||
|
||||
private static string ConfigurationWith(params string[] sessions) =>
|
||||
$$"""{"version":1,"sessions":[{{string.Join(",", sessions)}}]}""";
|
||||
|
||||
private static string Session(
|
||||
string id,
|
||||
string credentialReference,
|
||||
string? extraTopLevelField = null)
|
||||
{
|
||||
string suffix = extraTopLevelField is null
|
||||
? string.Empty
|
||||
: $",{extraTopLevelField}";
|
||||
return $"{{\"id\":\"{id}\",\"endpoint\":{{\"host\":\"127.0.0.1\",\"port\":9000}},"
|
||||
+ "\"account\":\"account\",\"character\":{\"index\":0},"
|
||||
+ "\"policy\":{\"id\":\"idle\"},\"credential\":"
|
||||
+ $"{{\"provider\":\"environment\",\"reference\":\"{credentialReference}\"}}"
|
||||
+ suffix
|
||||
+ "}";
|
||||
}
|
||||
|
||||
private sealed class TemporaryConfiguration : IDisposable
|
||||
{
|
||||
private TemporaryConfiguration(string path)
|
||||
{
|
||||
Path = path;
|
||||
}
|
||||
|
||||
internal string Path { get; }
|
||||
|
||||
internal static TemporaryConfiguration Create(string json)
|
||||
{
|
||||
string path = System.IO.Path.Combine(
|
||||
System.IO.Path.GetTempPath(),
|
||||
$"acdream-headless-op7-{Guid.NewGuid():N}.json");
|
||||
File.WriteAllText(path, json);
|
||||
return new TemporaryConfiguration(path);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
File.Delete(Path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue