acdream/tests/AcDream.Core.Net.Tests/WorldSessionCharacterCreationTests.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

287 lines
11 KiB
C#

using System.Net;
using System.Reflection;
using AcDream.Core.Net.Messages;
using AcDream.Core.Net.Packets;
using AcDream.Core.Net.Tests.Messages;
namespace AcDream.Core.Net.Tests;
/// <summary>
/// Campaign CC CC2: the awaiting-request latch that disambiguates the two
/// message families sharing opcode 0xF643 (see
/// <see cref="CharGenVerificationResponse"/>'s doc comment) — create-then-
/// response routes to the create event, a plain restore is unaffected, an
/// unexpected/uncorrelated response is dropped rather than misattributed,
/// and teardown clears the latch. See
/// <see cref="WorldSessionCharacterSelectionTests"/> for the general
/// character-management wire-order coverage this file complements.
/// </summary>
public sealed class WorldSessionCharacterCreationTests
{
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() { }
}
private static WorldSession CreateSession() =>
new(
new IPEndPoint(IPAddress.Loopback, 9000),
new NullTransport());
private static CharacterCreate.Request MakeCreateRequest() => new(
Heritage: 1u,
Gender: 0u,
Appearance: default,
Template: 0u,
Attributes: default,
Slot: 0u,
ClassId: 1u,
Name: "NewChar",
StartArea: 0u,
IsAdmin: false,
IsEnvoy: false);
private static byte[] BuildVerificationResponseBody(uint code, uint guid, string name) =>
code == (uint)CharGenVerificationResponse.Code.Ok
? AceWireWriter.GameMessage(CharGenVerificationResponse.ResponseOpcode)
.Write(code)
.WriteGuid(guid)
.WriteString16L(name)
.Write(0u)
.ToArray()
: AceWireWriter.GameMessage(CharGenVerificationResponse.ResponseOpcode)
.Write(code)
.ToArray();
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]);
}
private static PendingLatch ReadPendingLatch(WorldSession session)
{
FieldInfo field = typeof(WorldSession).GetField(
"_pendingCharGenVerification",
BindingFlags.NonPublic | BindingFlags.Instance)!;
return (PendingLatch)field.GetValue(session)!;
}
// Mirrors WorldSession's private PendingCharGenVerificationRequest enum
// by name/ordinal — read via reflection above so the test doesn't need
// InternalsVisibleTo for a single private enum.
private enum PendingLatch { None, Restore, Create }
[Fact]
public void SendCharacterCreation_ThenOkResponse_RoutesToCreateEventNotRestore()
{
using WorldSession session = CreateSession();
session.GameMessageCapture = (_, _) => { };
session.SendCharacterCreation(
"testaccount",
MakeCreateRequest(),
new uint[CharacterCreate.SkillAdvancementClassCount]);
var createEvents = new List<CharGenVerificationResponse.Parsed>();
var restoreEvents = new List<CharacterRestore.Parsed>();
session.CharacterCreateResponseReceived += createEvents.Add;
session.CharacterRestoreReceived += restoreEvents.Add;
byte[] packet = BuildPacket(
BuildVerificationResponseBody(
(uint)CharGenVerificationResponse.Code.Ok,
0x50000010u,
"NewChar"));
InvokeProcessDatagram(session, packet);
CharGenVerificationResponse.Parsed created = Assert.Single(createEvents);
Assert.True(created.IsOk);
Assert.Equal(0x50000010u, created.Guid);
Assert.Equal("NewChar", created.Name);
Assert.Empty(restoreEvents);
Assert.Equal(PendingLatch.None, ReadPendingLatch(session));
}
[Fact]
public void SendCharacterCreation_ThenFailureResponse_RoutesToCreateEventWithNullIdentity()
{
using WorldSession session = CreateSession();
session.GameMessageCapture = (_, _) => { };
session.SendCharacterCreation(
"testaccount",
MakeCreateRequest(),
new uint[CharacterCreate.SkillAdvancementClassCount]);
CharGenVerificationResponse.Parsed? created = null;
session.CharacterCreateResponseReceived += parsed => created = parsed;
byte[] packet = BuildPacket(
BuildVerificationResponseBody(
(uint)CharGenVerificationResponse.Code.NameInUse,
guid: 0u,
name: string.Empty));
InvokeProcessDatagram(session, packet);
Assert.NotNull(created);
Assert.Equal(CharGenVerificationResponse.Code.NameInUse, created!.Value.AsCode);
Assert.False(created.Value.IsOk);
Assert.Null(created.Value.Guid);
}
[Fact]
public void SendRestoreCharacter_ThenResponse_StillRoutesToRestoreEvent()
{
// Regression guard: the correlation latch must not break the
// pre-existing restore-only flow that predates Campaign CC.
using WorldSession session = CreateSession();
session.GameMessageCapture = (_, _) => { };
session.SendRestoreCharacter(0x50000001u);
var restoreEvents = new List<CharacterRestore.Parsed>();
var createEvents = new List<CharGenVerificationResponse.Parsed>();
session.CharacterRestoreReceived += restoreEvents.Add;
session.CharacterCreateResponseReceived += createEvents.Add;
byte[] packet = BuildPacket(
BuildVerificationResponseBody(
(uint)CharGenVerificationResponse.Code.Ok,
0x50000001u,
"Restored"));
InvokeProcessDatagram(session, packet);
CharacterRestore.Parsed restored = Assert.Single(restoreEvents);
Assert.Equal(0x50000001u, restored.Guid);
Assert.Equal("Restored", restored.Name);
Assert.Empty(createEvents);
}
[Fact]
public void ResponseWithNoOutstandingRequest_IsDroppedAndNeverMisattributed()
{
using WorldSession session = CreateSession();
var restoreEvents = new List<CharacterRestore.Parsed>();
var createEvents = new List<CharGenVerificationResponse.Parsed>();
session.CharacterRestoreReceived += restoreEvents.Add;
session.CharacterCreateResponseReceived += createEvents.Add;
// No SendRestoreCharacter / SendCharacterCreation call precedes this
// — the latch is None.
byte[] packet = BuildPacket(
BuildVerificationResponseBody(
(uint)CharGenVerificationResponse.Code.Ok,
0x50000099u,
"Stray"));
InvokeProcessDatagram(session, packet);
Assert.Empty(restoreEvents);
Assert.Empty(createEvents);
Assert.Equal(PendingLatch.None, ReadPendingLatch(session));
}
[Fact]
public void SecondResponse_AfterFirstAlreadyConsumed_IsDroppedNotMisattributed()
{
// A create request is satisfied; a SECOND, uncorrelated 0xF643
// arriving afterward (e.g. a stray/replayed packet) must not be
// misread as a reply to anything.
using WorldSession session = CreateSession();
session.GameMessageCapture = (_, _) => { };
session.SendCharacterCreation(
"testaccount",
MakeCreateRequest(),
new uint[CharacterCreate.SkillAdvancementClassCount]);
var createEvents = new List<CharGenVerificationResponse.Parsed>();
session.CharacterCreateResponseReceived += createEvents.Add;
byte[] first = BuildPacket(
BuildVerificationResponseBody(
(uint)CharGenVerificationResponse.Code.Ok, 0x50000010u, "NewChar"));
InvokeProcessDatagram(session, first);
Assert.Single(createEvents);
byte[] second = BuildPacket(
BuildVerificationResponseBody(
(uint)CharGenVerificationResponse.Code.Ok, 0x50000011u, "Stray"));
InvokeProcessDatagram(session, second);
// Still exactly one — the second reply was dropped, not appended.
Assert.Single(createEvents);
}
[Fact]
public void Dispose_ClearsTheOutstandingLatch()
{
WorldSession session = CreateSession();
session.GameMessageCapture = (_, _) => { };
session.SendRestoreCharacter(0x50000001u);
Assert.Equal(PendingLatch.Restore, ReadPendingLatch(session));
session.Dispose();
Assert.Equal(PendingLatch.None, ReadPendingLatch(session));
}
[Fact]
public void BuildRequestBody_InvalidSkillCount_DoesNotArmTheLatch()
{
// The latch is armed AFTER the body is built (SendCharacterCreation
// builds first), so a builder-level throw (wrong skill count) must
// leave no outstanding request behind — nothing was actually sent.
using WorldSession session = CreateSession();
session.GameMessageCapture = (_, _) => { };
Assert.Throws<ArgumentException>(() =>
session.SendCharacterCreation(
"testaccount",
MakeCreateRequest(),
new uint[10]));
Assert.Equal(PendingLatch.None, ReadPendingLatch(session));
}
}