acdream/tests/AcDream.Launcher.Core.Tests/Status/StatusFileTailerTests.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

241 lines
8.3 KiB
C#

using System.Text;
using AcDream.Launcher.Core.Status;
namespace AcDream.Launcher.Core.Tests.Status;
public sealed class StatusFileTailerTests : IDisposable
{
private readonly string _root;
private readonly string _path;
public StatusFileTailerTests()
{
_root = Path.Combine(
Path.GetTempPath(),
"acdream-launcher-tailer-tests",
Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
_path = Path.Combine(_root, "status.jsonl");
}
public void Dispose()
{
if (Directory.Exists(_root))
{
Directory.Delete(_root, recursive: true);
}
}
[Fact]
public void ReturnsNoEventsWhenTheFileDoesNotExistYet()
{
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void ReturnsNoEventsWhenNothingHasBeenAppendedSinceTheLastPoll()
{
AppendShared(Line("started", "s1"));
var tailer = new StatusFileTailer(_path);
Assert.Single(tailer.ReadNewEvents());
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void ReadsMultipleCompleteLinesInOnePoll()
{
AppendShared(Line("started", "s1") + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(2, events.Count);
Assert.IsType<StartedStatusEvent>(events[0]);
Assert.IsType<ConnectedStatusEvent>(events[1]);
}
[Fact]
public void ContinuesPastCompleteNonObjectJsonValuesToTheFollowingValidLine()
{
AppendShared(
"[]\nnull\n42\n\"text\"\n"
+ Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(5, events.Count);
Assert.All(events.Take(4), e => Assert.IsType<MalformedStatusEvent>(e));
Assert.IsType<ConnectedStatusEvent>(events[4]);
}
[Fact]
public void TolerateAPartialLastLineAndCompletesItOnALaterPoll()
{
string full = Line("started", "s1");
int splitAt = full.Length - 10; // cut mid-object, before the closing brace/newline
AppendShared(full[..splitAt]);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> firstPoll = tailer.ReadNewEvents();
Assert.Empty(firstPoll);
AppendShared(full[splitAt..]);
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(secondPoll);
Assert.IsType<StartedStatusEvent>(onlyEvent);
}
[Fact]
public void APartialLineFollowedByAFullLineOnlyEmitsTheCompleteOne()
{
AppendShared(Line("started", "s1"));
string partial = """{"v":1,"e":"connected","t":"2026-08-14T12:00:00Z","sessionId":"s1"""; // no closing
AppendShared(partial);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(events);
Assert.IsType<StartedStatusEvent>(onlyEvent);
// Completing the second line on a later poll produces exactly
// one more event, proving the partial bytes were retained (not
// dropped and not double-counted).
AppendShared("\"}\n");
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
StatusEvent completed = Assert.Single(secondPoll);
Assert.IsType<ConnectedStatusEvent>(completed);
}
[Fact]
public void SkipsBlankLines()
{
AppendShared("\n" + Line("started", "s1") + "\n" + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(2, events.Count);
}
[Fact]
public void ReadsWithAWriterHoldingTheFileOpenForAppend()
{
// Share-tolerant reads: the writer's handle stays open the whole
// time (FileShare.ReadWrite on both sides), matching a live host
// process appending status.jsonl while the launcher tails it.
using var writer = new FileStream(
_path,
FileMode.Create,
FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete);
var tailer = new StatusFileTailer(_path);
byte[] first = Encoding.UTF8.GetBytes(Line("started", "s1"));
writer.Write(first, 0, first.Length);
writer.Flush();
IReadOnlyList<StatusEvent> firstPoll = tailer.ReadNewEvents();
Assert.Single(firstPoll);
byte[] second = Encoding.UTF8.GetBytes(Line("connected", "s1"));
writer.Write(second, 0, second.Length);
writer.Flush();
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
Assert.Single(secondPoll);
Assert.IsType<ConnectedStatusEvent>(secondPoll[0]);
}
[Fact]
public void ReadNewEventsReturnsEmptyRatherThanThrowingOnASharingViolation()
{
// A deterministic proxy for the File.Exists -> new FileStream
// TOCTOU window (review finding F7): Windows enforces FileShare
// at the OS level, so holding an exclusive (FileShare.None)
// handle open while the tailer tries to open the same path
// reliably reproduces the IOException the tailer must now
// swallow instead of throwing out of a method documented never
// to throw. (.NET's FileStream doesn't apply mandatory locking
// on Linux by default, so this specific scenario isn't
// reproducible there — the fix itself is platform-agnostic, only
// this particular deterministic trigger is Windows-only.)
if (!OperatingSystem.IsWindows())
return;
AppendShared(Line("started", "s1"));
using var exclusiveHandle = new FileStream(
_path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
/// <summary>
/// Campaign CC CC2: the two creation-flow events round-trip through the
/// actual file-tailing pipeline (not just <see cref="StatusEventParser"/>
/// in isolation) — matching the exact camelCase shape
/// <c>AcDream.Runtime.Session.SessionStatusWriter</c> writes.
/// </summary>
[Fact]
public void TailsCharacterCreatedAndCreationFailedEvents()
{
AppendShared(
"""{"v":1,"e":"characterCreated","t":"2026-08-15T12:00:00Z","sessionId":"s1","guid":1342177296,"name":"NewChar"}"""
+ "\n"
+ """{"v":1,"e":"creationFailed","t":"2026-08-15T12:00:01Z","sessionId":"s1","code":3,"name":"NameInUse"}"""
+ "\n");
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(2, events.Count);
var created = Assert.IsType<CharacterCreatedStatusEvent>(events[0]);
Assert.Equal(1342177296u, created.Guid);
Assert.Equal("NewChar", created.Name);
var failed = Assert.IsType<CreationFailedStatusEvent>(events[1]);
Assert.Equal(3u, failed.Code);
Assert.Equal("NameInUse", failed.Name);
}
[Fact]
public void RestartsFromTheTopWhenTheFileIsTruncatedOrReplaced()
{
AppendShared(Line("started", "s1") + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
Assert.Equal(2, tailer.ReadNewEvents().Count);
File.Delete(_path);
AppendShared(Line("started", "s2"));
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(events);
Assert.Equal("s2", onlyEvent.SessionId);
}
private static string Line(string e, string sessionId) =>
$$"""{"v":1,"e":"{{e}}","t":"2026-08-14T12:00:00Z","sessionId":"{{sessionId}}"}""" + "\n";
private void AppendShared(string text)
{
using var stream = new FileStream(
_path,
FileMode.Append,
FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete);
byte[] bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
}