acdream/tests/AcDream.Core.Net.Tests/WorldSessionCharacterSelectionTests.cs
Erik 5eaad2c88c feat(net,runtime): Campaign CC CC2 — CharacterCreate wire, 0xF643 correlation, creation status events
Wire (Core.Net):
- CharacterCreate.cs: outbound 0xF656 builder, byte-exact port of
  Proto_UI::SendCharGenResult@0x00546a70 -> ACCharGenResult::Pack@0x005c7570
  -> CG_Pack@0x005c7200. Account String16L first (packed outside CG_Pack),
  then the constant-1 u32, heritage/gender, 14 appearance strip/style/color
  u32s, 6 f64 shades (skin/hair/headgear/shirt/trousers/footwear, retail
  order), template, 6 attributes, slot, classId, numSkills + exactly 55
  u32 skill-advancement classes (ReadOnlySpan validated ==55, throws
  ArgumentException otherwise — ACE terminates the session on any other
  count via PlayerFactory.CreateResult.ClientServerSkillsMismatch), name
  String16L, startArea, isAdmin, isEnvoy, and a trailing checksum whose
  exact 19-term accumulation set (heritage+gender+3 strips+hairColor+
  eyeColor+hairStyle+headgearStyle+shirtStyle+trousersStyle+footwearStyle+
  template+6 attributes) is read byte-for-byte off CG_Pack's decompiled
  accumulator (0x005c7213-0x005c74c3) — headgearColor/shirtColor/
  trousersColor/footwearColor/shades/slot/classId are deliberately absent
  from the sum despite sitting adjacent on the wire. Cross-checked against
  ACE's CharacterCreateInfo.Unpack/Appearance.Unpack and holtburger's
  CharacterCreateRequestData (types.rs:236-369), which agree on every
  field and order. Retail routes via SendToLogon — the same queue
  CharacterDelete already uses.
- CharGenVerificationResponse.cs (new): promotes the shared 0xF643 parse
  out of CharacterRestore — full Code enum (Undef..AdminPrivilegeDenied=7,
  ACE's CharacterGenerationVerificationResponse) plus the conditional
  Ok-only identity payload (guid/String16L name/u32 secondsGreyedOut).
  CharacterRestore.Parse now delegates to it; CharacterRestore's public
  Parsed shape, Parse signature, and every existing test expectation are
  UNCHANGED.
- PacketWriter.WriteDouble: f64 little-endian helper for the shade fields.

WorldSession dispatch (Core.Net):
- Added an awaiting-request latch (None/Restore/Create), armed by
  SendRestoreCharacter/the new SendCharacterCreation immediately before
  each send (SendCharacterCreation builds the body first so a skill-count
  throw never arms the latch for a request that was never sent), cleared
  the instant a matching 0xF643 is dispatched (success OR parse failure —
  a malformed reply must never wedge the latch open) and on Dispose.
  0xF643 now routes to CharacterRestoreReceived or the new
  CharacterCreateResponseReceived (Action<CharGenVerificationResponse.Parsed>)
  by that latch; an unexpected 0xF643 with nothing outstanding logs once
  and is dropped, never misattributed. Fixed
  WorldSessionCharacterSelectionTests' restore-dispatch test, which
  previously fed a bare CharacterRestore response with no preceding
  SendRestoreCharacter — that shape is now the "no outstanding request"
  drop path by design.

Status events (Runtime + Launcher.Core, contract first):
- Amended docs/plans/2026-08-14-launcher-campaign.md §LA1's pinned status
  vocabulary to add characterCreated{guid,name} (Ok reply identity, named
  to mirror CharGenVerificationResponse's own fields and to read distinct
  from enteredWorld — retail logs a freshly created character straight in
  without a fresh characterList) and creationFailed{code,name} (raw Code
  value + its enum member name).
- SessionStatusWriter.CharacterCreated/CreationFailed implement that
  contract.
- Launcher.Core: CharacterCreatedStatusEvent/CreationFailedStatusEvent +
  StatusEventParser cases, in lockstep.

Tests: CharacterCreateTests (byte-exact layout incl. checksum term-set,
55-slot fixture, wrong-count throws), CharGenVerificationResponseTests
(every Code value), WorldSessionCharacterCreationTests (create-then-
response routes correctly, restore unaffected, no-outstanding drop,
second-response-after-consumed drop, Dispose clears the latch, a builder
throw never arms it), SessionStatusWriterTests + Launcher.Core
StatusEventParserTests/StatusFileTailerTests (pinned shape + tailer
round-trip) for the two new events.

Verified: dotnet build AcDream.slnx -c Release — 0 errors. Full solution
test run green (Core.Net.Tests 993/993, Runtime.Tests 1667/1667,
Launcher.Core.Tests 323/323, plus every other project in the solution).
WSL Ubuntu: Core.Net.Tests 993/993, Runtime.Tests 1667/1667.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 12:49:52 +02:00

289 lines
9.8 KiB
C#

using System.Buffers.Binary;
using System.Net;
using System.Reflection;
using AcDream.Core.Net.Messages;
using AcDream.Core.Net.Packets;
using AcDream.Core.Net.Tests.Transport;
namespace AcDream.Core.Net.Tests;
public sealed class WorldSessionCharacterSelectionTests
{
private sealed class NullTransport : IWorldSessionTransport
{
public void Send(ReadOnlySpan<byte> datagram) { }
public void Send(IPEndPoint remote, ReadOnlySpan<byte> datagram) { }
public int Receive(
Span<byte> destination,
TimeSpan timeout,
out IPEndPoint? from)
{
from = null;
return -1;
}
public ValueTask<NetReceiveResult> ReceiveAsync(
Memory<byte> destination,
CancellationToken cancellationToken) =>
ValueTask.FromCanceled<NetReceiveResult>(cancellationToken);
public void Dispose() { }
}
[Fact]
public void CharacterManagementSends_UseRetailQueuesAndExactBodies()
{
using var session = CreateSession();
var sent = new List<(byte[] Body, GameMessageGroup Queue)>();
session.GameMessageCapture =
(body, queue) => sent.Add((body, queue));
session.SendDeleteCharacter("Canonical", activeIndex: 3);
session.SendRestoreCharacter(0x50000001u);
Assert.Collection(
sent,
delete =>
{
Assert.Equal(GameMessageGroup.LoginQueue, delete.Queue);
Assert.Equal(
CharacterDelete.BuildRequestBody("Canonical", 3u),
delete.Body);
},
restore =>
{
Assert.Equal(GameMessageGroup.ControlQueue, restore.Queue);
Assert.Equal(
CharacterRestore.BuildRequestBody(0x50000001u),
restore.Body);
});
}
[Fact]
public void UiQueueReplies_DispatchInWireOrderAndRosterRefreshReplacesCharacters()
{
using var session = CreateSession();
// Campaign CC CC2: a restore response only dispatches when the
// session actually has an outstanding restore request armed — see
// WorldSessionCharacterCreationTests for the correlation-specific
// coverage (create routing, no-outstanding drop, teardown clears).
session.GameMessageCapture = (_, _) => { };
session.SendRestoreCharacter(0x50000001u);
var events = new List<string>();
session.CharacterListReceived += roster =>
events.Add($"roster:{roster.Characters[0].SecondsGreyedOut}");
session.CharacterDeleteAcknowledged += () => events.Add("delete");
session.CharacterRestoreReceived += restore =>
events.Add($"restore:{restore.Guid:X8}");
session.CharacterErrorReceived += error =>
events.Add($"error:{error.RawErrorCode:X}");
byte[] packet = BuildPacket(
BuildRoster(secondsGreyedOut: 0u),
BitConverter.GetBytes(CharacterDelete.Opcode),
BuildRestoreResponse(),
BuildCharacterError(CharacterError.Code.Delete),
BuildRoster(secondsGreyedOut: 1u));
InvokeProcessDatagram(session, packet);
Assert.Equal(
[
"roster:0",
"delete",
"restore:50000001",
"error:6",
"roster:1",
],
events);
CharacterList.Character current =
Assert.Single(session.Characters!.Characters);
Assert.Equal(1u, current.SecondsGreyedOut);
}
[Fact]
public void ServerName_Dispatches_AndPopulatesServerInfo()
{
// Campaign LA gate round 2 finding 3: ACE's SendConnectResponse
// enqueues CharacterList then ServerName in the same batch
// (AuthenticationHandler.cs:257-261) — assert both arrive, in wire
// order, through the same UIQueue dispatch path.
using var session = CreateSession();
var events = new List<string>();
session.CharacterListReceived += _ => events.Add("roster");
session.ServerNameReceived += info => events.Add($"world:{info.WorldName}");
byte[] packet = BuildPacket(
BuildRoster(secondsGreyedOut: 0u),
BuildServerName("sawato", currentConnections: 3, maxConnections: 100));
InvokeProcessDatagram(session, packet);
Assert.Equal(["roster", "world:sawato"], events);
Assert.NotNull(session.ServerInfo);
Assert.Equal("sawato", session.ServerInfo!.Value.WorldName);
Assert.Equal(3, session.ServerInfo!.Value.CurrentConnections);
Assert.Equal(100, session.ServerInfo!.Value.MaxConnections);
}
[Fact]
public void ImmediateEnterWorld_IgnoresNumErrorsSentinelBeforeServerReady()
{
var transport = new FakeAceTransport
{
AutoReplyServerReady = false,
};
using var session = new WorldSession(
new IPEndPoint(IPAddress.Loopback, 9000),
transport);
int errors = 0;
session.CharacterErrorReceived += _ => errors++;
ConfigureSentinelThenServerReady(transport);
session.Connect(
FakeAceTransport.DefaultAccountName,
"testpassword",
TimeSpan.FromSeconds(5));
session.EnterWorld(0, TimeSpan.FromSeconds(5));
Assert.Equal(WorldSession.State.InWorld, session.CurrentState);
Assert.Equal(0, errors);
}
[Fact]
public void PausedEnterWorld_IgnoresNumErrorsSentinelBeforeServerReady()
{
var transport = new FakeAceTransport
{
AutoReplyServerReady = false,
};
using var session = new WorldSession(
new IPEndPoint(IPAddress.Loopback, 9000),
transport);
int errors = 0;
session.CharacterErrorReceived += _ => errors++;
ConfigureSentinelThenServerReady(transport);
session.Connect(
FakeAceTransport.DefaultAccountName,
"testpassword",
TimeSpan.FromSeconds(5));
session.StartCharacterSelectionReceive();
session.EnterWorld(0, TimeSpan.FromSeconds(5));
Assert.Equal(WorldSession.State.InWorld, session.CurrentState);
Assert.Equal(0, errors);
}
private static WorldSession CreateSession() =>
new(
new IPEndPoint(IPAddress.Loopback, 9000),
new NullTransport());
private static void ConfigureSentinelThenServerReady(
FakeAceTransport transport)
{
transport.Model.MessageDispatched += body =>
{
if (BinaryPrimitives.ReadUInt32LittleEndian(body)
!= CharacterEnterWorld.EnterWorldRequestOpcode)
{
return;
}
transport.Model.EnqueueGameMessage(
BuildCharacterError(CharacterError.Code.NumErrors),
GameMessageGroup.UIQueue);
transport.Model.EnqueueGameMessage(
BitConverter.GetBytes(0xF7DFu),
GameMessageGroup.UIQueue);
};
}
private static byte[] BuildRoster(uint secondsGreyedOut)
{
var writer = new PacketWriter(96);
writer.WriteUInt32(CharacterList.Opcode);
writer.WriteUInt32(0u);
writer.WriteUInt32(1u);
writer.WriteUInt32(0x50000001u);
writer.WriteString16L("Character");
writer.WriteUInt32(secondsGreyedOut);
writer.WriteUInt32(0u);
writer.WriteUInt32(11u);
writer.WriteString16L("Canonical");
writer.WriteUInt32(1u);
writer.WriteUInt32(1u);
return writer.ToArray();
}
private static byte[] BuildServerName(
string worldName,
int currentConnections,
int maxConnections)
{
var writer = new PacketWriter(64);
writer.WriteUInt32(ServerName.Opcode);
writer.WriteUInt32(unchecked((uint)currentConnections));
writer.WriteUInt32(unchecked((uint)maxConnections));
writer.WriteString16L(worldName);
return writer.ToArray();
}
private static byte[] BuildRestoreResponse()
{
var writer = new PacketWriter(64);
writer.WriteUInt32(CharacterRestore.ResponseOpcode);
writer.WriteUInt32(1u);
writer.WriteUInt32(0x50000001u);
writer.WriteString16L("Character");
writer.WriteUInt32(0u);
return writer.ToArray();
}
private static byte[] BuildCharacterError(CharacterError.Code error)
{
byte[] body = new byte[8];
BinaryPrimitives.WriteUInt32LittleEndian(
body,
CharacterError.Opcode);
BinaryPrimitives.WriteUInt32LittleEndian(
body.AsSpan(4),
(uint)error);
return body;
}
private static byte[] BuildPacket(params byte[][] messages)
{
int length = messages.Sum(message =>
MessageFragmentHeader.Size + message.Length);
var fragments = new byte[length];
int position = 0;
uint sequence = 1u;
foreach (byte[] message in messages)
{
position += GameMessageFragment.WriteSingleFragment(
fragments.AsSpan(position),
sequence++,
GameMessageGroup.UIQueue,
message);
}
return PacketCodec.Encode(
new PacketHeader
{
Sequence = 1u,
Flags = PacketHeaderFlags.BlobFragments,
},
fragments,
outboundIsaac: null);
}
private static void InvokeProcessDatagram(
WorldSession session,
byte[] datagram)
{
MethodInfo method = typeof(WorldSession).GetMethod(
"ProcessDatagram",
BindingFlags.NonPublic | BindingFlags.Instance)!;
method.Invoke(
session,
[new ReadOnlyMemory<byte>(datagram), null, true]);
}
}