fix(launcher): Campaign LA LA3 review fixes — contract paths omission, probe composition, graceful stop, hygiene

Opus review of LA3 returned FIX FIRST; this addresses every finding in
scope (F1-F5, F7-F12; F6 CI-lane addition excluded per instructions):

- F1 (CRITICAL): SessionProcessSettings.Paths is now nullable and left
  null by SessionConfigComposer unless a caller supplies overrides, so
  the JSON key is entirely absent instead of "paths":{} — the App-side
  loader's strict UnmappedMemberHandling.Disallow would otherwise reject
  every gui/guiSelect session-config document at load.
- F2: added SessionConfigComposer.ComposeProbe and a nullable
  SessionDescriptor.Mode field ("probe", omitted for normal play) per
  the pinned contract — no character/policy/plugins/loginCommands.
- F3: LauncherProcessSupervisor.Stop now tries
  ILauncherChildProcess.TryRequestGracefulStop (Linux: libc SIGINT via
  LibraryImport, K4-proven graceful headless logout) before
  CloseMainWindow. Windows has no reliable no-window-console equivalent
  today; filed docs/ISSUES.md #397 with the CREATE_NEW_PROCESS_GROUP +
  CTRL_BREAK fix direction. Stop()'s blocking-timeout contract is now
  documented for LA4.
- F4: LauncherProfileStore.Save chmods the Linux temp file to 0600
  immediately after creation, before any credential is serialized;
  failure paths and Load() clean up a stale .tmp.
- F5: added LauncherCoreDependencyBoundaryTests asserting Launcher.Core
  references exactly AcDream.Platform and no packages.
- F7: StatusEventParser.Parse no longer throws on a whitespace/null
  line; StatusFileTailer.ReadNewEvents swallows the File.Exists/open
  TOCTOU window (FileNotFoundException/DirectoryNotFoundException/
  IOException) instead of throwing.
- F8: Start() now kills (entire process tree) and disposes a child that
  started successfully but failed while being fed its stdin password,
  instead of orphaning it.
- F9: SetState is monotonic — once Exited, no later transition applies
  or fires StateChanged, closing a Start()-path race where a
  synchronously-exiting child could be "resurrected" to Running.
- F10: CharacterIdFormat.TryParse now requires the "0x" prefix (an
  unprefixed hand-typed decimal id is also valid hex and was silently
  misread); a parsed id of 0 is treated as unusable and falls back to
  the name selector; LauncherProfileStore.MergeRoster normalizes both
  sides through TryParse/ToHexString instead of raw string equality, so
  a legacy unprefixed-hex row self-heals via name match instead of
  duplicating.
- F11: StatusCharacterEntry.SecondsGreyedOut is now uint, matching
  CharacterRosterEntry and the host writer.
- F12: added MalformedStatusEvent, returned for a recognized `e` whose
  payload doesn't match its shape, distinguished from UnknownStatusEvent
  (an unrecognized `e`).

AllowUnsafeBlocks was added to AcDream.Launcher.Core.csproj — required
by the LibraryImport source generator's function-pointer marshalling
stub for F3's Linux SIGINT P/Invoke.

Verification: dotnet build AcDream.slnx -c Release green (0 errors);
dotnet test tests/AcDream.Launcher.Core.Tests -c Release green at 94/94
on native Windows and under WSL (Ubuntu, verified across multiple runs
for the timing-sensitive SIGINT/sharing-violation tests, no flakes
observed).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-14 16:29:39 +02:00
parent 37d74e4402
commit 26feba8186
19 changed files with 1101 additions and 105 deletions

View file

@ -5,6 +5,12 @@
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<!-- Required by the LibraryImportAttribute source generator (F3's
Linux SIGINT P/Invoke in Launching/ILauncherChildProcess.cs):
the generated marshalling stub calls through an unmanaged
function pointer, which the compiler only allows in an unsafe
context. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AcDream.Platform\AcDream.Platform.csproj" />

View file

@ -1,4 +1,5 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace AcDream.Launcher.Core.Launching;
@ -28,6 +29,26 @@ public interface ILauncherChildProcess : IDisposable
void Start();
/// <summary>
/// Attempts a graceful stop signal appropriate to the platform,
/// tried BEFORE <see cref="CloseMainWindow"/> (Campaign LA plan §LA3
/// review finding F3): a no-window console host (e.g.
/// <c>AcDream.Headless</c>) never has a main window for
/// <see cref="CloseMainWindow"/> to close, so without this step
/// <see cref="LauncherProcessSupervisor.Stop"/> always degraded
/// straight to a timeout + hard <see cref="Kill"/> — and a hard kill
/// leaves the ACE account session stuck for several minutes (a
/// documented project landmine; see CLAUDE.md
/// "Logout-before-reconnect"). On Linux this sends SIGINT (K4 proved
/// the headless host's SIGINT handler produces an ACE-confirmed
/// graceful logout). On Windows there is no reliable cross-console
/// mechanism for an arbitrary no-window child process today — see
/// <c>docs/ISSUES.md</c> for the tracked gap and fix direction; this
/// returns false there. Returns true only when the signal was
/// actually delivered; never throws.
/// </summary>
bool TryRequestGracefulStop();
/// <summary>Mirrors <see cref="Process.CloseMainWindow"/> — requests
/// a graceful close via WM_CLOSE. Returns false for a console/no-
/// window process (never throws), matching the real API.</summary>
@ -54,8 +75,16 @@ public sealed class SystemChildProcessFactory : ILauncherChildProcessFactory
new SystemChildProcess(spec);
}
internal sealed class SystemChildProcess : ILauncherChildProcess
internal sealed partial class SystemChildProcess : ILauncherChildProcess
{
// SIGINT's numeric value (POSIX-stable across Linux distributions).
// K4/Slice K already proved the headless host's SIGINT handler
// produces an ACE-confirmed graceful logout.
private const int Sigint = 2;
[LibraryImport("libc", SetLastError = true)]
private static partial int kill(int pid, int sig);
private readonly Process _process;
private bool _raisingEnabled;
@ -99,6 +128,31 @@ internal sealed class SystemChildProcess : ILauncherChildProcess
_process.Start();
}
public bool TryRequestGracefulStop()
{
if (!OperatingSystem.IsLinux())
{
// No reliable cross-console mechanism exists for an
// arbitrary no-window Windows child process — tracked gap,
// see docs/ISSUES.md.
return false;
}
try
{
return kill(_process.Id, Sigint) == 0;
}
catch
{
// Matches CloseMainWindow's "never throws" contract — the
// process may not have started yet, may have already exited
// (ESRCH), or the platform may lack libc under an unusual
// Linux runtime; any of these degrade to "signal not sent"
// rather than an exception out of Stop().
return false;
}
}
public bool CloseMainWindow() => _process.CloseMainWindow();
public void Kill() => _process.Kill(entireProcessTree: true);

View file

@ -56,9 +56,11 @@ public sealed class LauncherProcessSupervisor : IDisposable
SetState(LauncherSessionState.Starting);
bool started = false;
try
{
process.Start();
started = true;
if (password is not null)
{
@ -77,6 +79,28 @@ public sealed class LauncherProcessSupervisor : IDisposable
_process = null;
}
// A failure after the child actually started (e.g. the stdin
// pipe breaks while feeding the password) must not leave a
// live, unsupervised, undisposable child running (Campaign LA
// plan §LA3 review finding F8) — kill the whole process tree
// and release the handle before propagating the original
// failure.
if (started)
{
try
{
process.Kill();
}
catch
{
// Best-effort — the ORIGINAL failure, rethrown below,
// is what the caller needs to see; a failed cleanup
// kill must not replace it.
}
}
process.Dispose();
throw;
}
@ -84,10 +108,22 @@ public sealed class LauncherProcessSupervisor : IDisposable
}
/// <summary>
/// Requests a graceful stop (CloseMainWindow), falling back to Kill
/// if the process has not exited within <paramref name="timeout"/>.
/// A no-op if <see cref="Start"/> was never called or the process has
/// already exited.
/// Requests a graceful stop — first
/// <see cref="ILauncherChildProcess.TryRequestGracefulStop"/> (SIGINT
/// on Linux; a no-op on Windows today, see
/// <see cref="ILauncherChildProcess.TryRequestGracefulStop"/>'s docs),
/// then <see cref="ILauncherChildProcess.CloseMainWindow"/> — falling
/// back to <see cref="ILauncherChildProcess.Kill"/> if the process has
/// not exited within <paramref name="timeout"/>. A no-op if
/// <see cref="Start"/> was never called or the process has already
/// exited.
/// <para>
/// BLOCKS THE CALLING THREAD for up to <paramref name="timeout"/>
/// (via the real child's <c>WaitForExit</c>) — callers on a UI thread
/// must dispatch this off-thread rather than calling it directly (a
/// binding requirement for the LA4 Avalonia UI, which will call this
/// method from a "stop session" action).
/// </para>
/// </summary>
public void Stop(TimeSpan timeout)
{
@ -102,6 +138,7 @@ public sealed class LauncherProcessSupervisor : IDisposable
return;
}
process.TryRequestGracefulStop();
process.CloseMainWindow();
if (!process.WaitForExit(timeout) && !process.HasExited)
{
@ -121,10 +158,28 @@ public sealed class LauncherProcessSupervisor : IDisposable
SetState(LauncherSessionState.Exited);
}
/// <summary>
/// Applies a state transition, or silently ignores it (Campaign LA
/// plan §LA3 review finding F9): once <see cref="State"/> reaches the
/// terminal <see cref="LauncherSessionState.Exited"/>, no later call
/// may move it anywhere else, and <see cref="StateChanged"/> only
/// fires for a transition that was actually applied. This matters
/// because <see cref="Start"/>'s trailing
/// <c>SetState(LauncherSessionState.Running)</c> can race a
/// synchronous <see cref="OnProcessExited"/> callback fired from
/// inside <see cref="Start"/> itself (a child that dies immediately)
/// — without this guard, "Running" would silently resurrect a
/// process that has already reported its exit.
/// </summary>
private void SetState(LauncherSessionState state)
{
lock (_gate)
{
if (State == LauncherSessionState.Exited)
{
return;
}
State = state;
}

View file

@ -52,13 +52,7 @@ public static class SessionConfigComposer
ArgumentNullException.ThrowIfNull(paths);
ArgumentException.ThrowIfNullOrWhiteSpace(sessionId);
string sessionDirectory = Path.Combine(
paths.CacheDirectory,
"launcher",
"sessions",
sessionId);
string configFilePath = Path.Combine(sessionDirectory, "session.json");
string statusFilePath = Path.Combine(sessionDirectory, "status.jsonl");
(string configFilePath, string statusFilePath) = BuildSessionPaths(paths, sessionId);
SessionCharacterSelector? selector = character.LaunchMode == LaunchMode.GuiSelect
? null
@ -92,7 +86,69 @@ public static class SessionConfigComposer
{
Process = new SessionProcessSettings
{
Paths = new SessionPathOverrides(),
Content = new SessionContentDescriptor
{
DatDirectory = install.DatDirectory,
PreparedAssetPath = install.PreparedAssetPath,
},
},
Sessions = [descriptor],
};
return new ComposedSessionConfig(
sessionId,
configFilePath,
statusFilePath,
document);
}
/// <summary>
/// Builds a probe session-config document (Campaign LA plan §LA2/
/// §LA3 review finding F2): the session carries <c>mode: "probe"</c>,
/// no <c>character</c> selector, and no <c>policy</c> — the host
/// reports the account's character roster over the status stream and
/// exits without entering the world. <c>plugins</c>/<c>loginCommands</c>
/// don't apply to a probe and are always omitted, exactly like an
/// empty configured set on a normal session.
/// </summary>
public static ComposedSessionConfig ComposeProbe(
ServerProfile server,
AccountProfile account,
LauncherInstallRecord install,
ApplicationPathSet paths,
string sessionId)
{
ArgumentNullException.ThrowIfNull(server);
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(install);
ArgumentNullException.ThrowIfNull(paths);
ArgumentException.ThrowIfNullOrWhiteSpace(sessionId);
(string configFilePath, string statusFilePath) = BuildSessionPaths(paths, sessionId);
var descriptor = new SessionDescriptor
{
Id = sessionId,
Mode = "probe",
Endpoint = new SessionEndpointDescriptor
{
Host = server.Host,
Port = server.Port,
},
Account = account.Account,
Character = null,
Policy = null,
Credential = new SessionCredentialDescriptor(),
Plugins = null,
LoginCommands = null,
LoginCommandDelayMs = null,
StatusFile = statusFilePath,
};
var document = new SessionConfigDocument
{
Process = new SessionProcessSettings
{
Content = new SessionContentDescriptor
{
DatDirectory = install.DatDirectory,
@ -149,9 +205,28 @@ public static class SessionConfigComposer
public static string Serialize(SessionConfigDocument document) =>
JsonSerializer.Serialize(document, SerializerOptions);
private static (string ConfigFilePath, string StatusFilePath) BuildSessionPaths(
ApplicationPathSet paths,
string sessionId)
{
string sessionDirectory = Path.Combine(
paths.CacheDirectory,
"launcher",
"sessions",
sessionId);
return (
Path.Combine(sessionDirectory, "session.json"),
Path.Combine(sessionDirectory, "status.jsonl"));
}
private static SessionCharacterSelector BuildSelector(CharacterProfile character)
{
if (CharacterIdFormat.TryParse(character.Id, out uint id))
// A parsed id of 0 is not a usable selector — both host loaders
// (App/Headless) reject `id: 0` outright, so falling through to
// the name selector here is the only shape that reaches a real
// character (Campaign LA plan §LA3 review finding F10).
if (CharacterIdFormat.TryParse(character.Id, out uint id) && id != 0)
{
return new SessionCharacterSelector { Id = id };
}

View file

@ -29,7 +29,18 @@ public sealed class SessionConfigDocument
public sealed class SessionProcessSettings
{
public SessionPathOverrides Paths { get; init; } = new();
/// <summary>
/// PINNED CONTRACT (Campaign LA plan §LA3 review, finding F1): the
/// <c>paths</c> KEY is entirely OMITTED from the written JSON unless
/// a caller explicitly supplies overrides — never an empty object.
/// The App-side loader parses with strict
/// <c>UnmappedMemberHandling.Disallow</c> and has no <c>paths</c>
/// member of its own, so an emitted <c>"paths":{}</c> is a null-
/// omission artifact (the object's own members are all optional and
/// omit cleanly, but the containing property was never null itself)
/// that would fail every gui/guiSelect launch at config load.
/// </summary>
public SessionPathOverrides? Paths { get; init; }
public SessionContentDescriptor Content { get; init; } = new();
}
@ -65,6 +76,13 @@ public sealed class SessionDescriptor
{
public string Id { get; init; } = string.Empty;
/// <summary>Present only for a probe session (<c>"probe"</c>,
/// Campaign LA plan §LA2/§LA3) — the host reports the account's
/// character roster and exits without entering the world. OMITTED
/// entirely for a normal gui/guiSelect/headless play session.
/// </summary>
public string? Mode { get; init; }
public SessionEndpointDescriptor Endpoint { get; init; } = new();
public string Account { get; init; } = string.Empty;

View file

@ -13,6 +13,15 @@ public static class CharacterIdFormat
public static string ToHexString(uint id) =>
"0x" + id.ToString("X8", CultureInfo.InvariantCulture);
/// <summary>
/// Parses <paramref name="text"/> as a hex character id — the
/// <c>0x</c> prefix (case-insensitive) is REQUIRED (Campaign LA plan
/// §LA3 review finding F10). Every all-digit id is ALSO a valid hex
/// number (e.g. <c>"12345678"</c>), so accepting a bare unprefixed
/// string as hex silently reinterprets a hand-typed decimal id and
/// selects the wrong character; requiring the prefix makes "this is
/// hex" an explicit, unambiguous signal instead of a guess.
/// </summary>
public static bool TryParse(string? text, out uint id)
{
id = 0;
@ -20,8 +29,10 @@ public static class CharacterIdFormat
return false;
ReadOnlySpan<char> span = text.AsSpan().Trim();
if (span.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
span = span[2..];
if (!span.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
return false;
span = span[2..];
return uint.TryParse(
span,

View file

@ -66,6 +66,13 @@ public sealed class LauncherProfileStore
/// </summary>
public bool Load()
{
// Opportunistic cleanup of a stale ".tmp" left behind by a Save()
// that crashed between creating the temp file and the atomic
// rename (Campaign LA plan §LA3 review finding F4) — a stray
// temp file carries the same plaintext credentials as the real
// store and should not linger.
DeleteStaleTempFile(FilePath + ".tmp");
if (!File.Exists(FilePath))
{
Document = new LauncherProfileDocument();
@ -108,9 +115,16 @@ public sealed class LauncherProfileStore
/// <summary>
/// Persists <see cref="Document"/> to <see cref="FilePath"/> via a
/// write-then-atomic-rename so a crash mid-write never leaves a
/// truncated credentials file. On Linux, restricts the final file to
/// owner read/write (0600) per Campaign LA's plaintext-credential
/// decision (spec §5, decisions log).
/// truncated credentials file. On Linux, the temp file is chmod'd to
/// owner read/write (0600) immediately after creation — BEFORE any
/// plaintext credential is serialized into it — so there is no window
/// where the temp file carries the process umask's (potentially
/// world/group-readable) default permissions while holding a
/// password; the final path gets the same restriction after the
/// rename (Campaign LA's plaintext-credential decision, spec §5,
/// decisions log; the temp-file window itself is review finding F4).
/// A failure between temp-file creation and the rename deletes the
/// stale temp file rather than leaving it behind.
/// </summary>
public void Save()
{
@ -121,12 +135,27 @@ public sealed class LauncherProfileStore
}
string tempPath = FilePath + ".tmp";
using (FileStream stream = File.Create(tempPath))
try
{
JsonSerializer.Serialize(stream, Document, SerializerOptions);
}
using (FileStream stream = File.Create(tempPath))
{
if (OperatingSystem.IsLinux())
{
File.SetUnixFileMode(
tempPath,
UnixFileMode.UserRead | UnixFileMode.UserWrite);
}
File.Move(tempPath, FilePath, overwrite: true);
JsonSerializer.Serialize(stream, Document, SerializerOptions);
}
File.Move(tempPath, FilePath, overwrite: true);
}
catch
{
DeleteStaleTempFile(tempPath);
throw;
}
if (OperatingSystem.IsLinux())
{
@ -136,6 +165,23 @@ public sealed class LauncherProfileStore
}
}
private static void DeleteStaleTempFile(string tempPath)
{
try
{
if (File.Exists(tempPath))
{
File.Delete(tempPath);
}
}
catch
{
// Best-effort cleanup only — the caller's own exception (a
// failed Save()) or the fresh Load() already in progress is
// what matters; a cleanup failure must not mask either.
}
}
// --- Server CRUD -----------------------------------------------
public ServerProfile AddServer(string name, string host, int port)
@ -312,16 +358,26 @@ public sealed class LauncherProfileStore
foreach (CharacterRosterEntry entry in roster)
{
string idText = CharacterIdFormat.ToHexString(entry.Id);
CharacterProfile? existing = profile.Characters.Find(
character => string.Equals(
character.Id,
idText,
StringComparison.OrdinalIgnoreCase));
// Defensive fallback for a hand-edited file where a character
// row was added with a name but no id yet.
// Normalize BOTH sides through TryParse/ToHexString rather
// than a raw string compare (Campaign LA plan §LA3 review
// finding F10): a stored id that round-trips to the same
// uint (different case, or — before this fix — no "0x"
// prefix) must match even though its text isn't byte-
// identical to the canonical form this method itself always
// writes.
CharacterProfile? existing = profile.Characters.Find(
character => CharacterIdFormat.TryParse(character.Id, out uint existingId)
&& existingId == entry.Id);
// Defensive fallback for a row whose id is missing OR
// unparseable (e.g. a hand-edited id with no "0x" prefix,
// which TryParse now rejects outright) — match by name
// instead so a later merge self-heals the id into the
// canonical form rather than creating a permanent duplicate
// row.
existing ??= profile.Characters.Find(
character => character.Id is null
character => !CharacterIdFormat.TryParse(character.Id, out _)
&& string.Equals(
character.Name,
entry.Name,

View file

@ -26,7 +26,7 @@ public sealed record ConnectedStatusEvent : StatusEvent;
public readonly record struct StatusCharacterEntry(
uint Id,
string Name,
int SecondsGreyedOut);
uint SecondsGreyedOut);
public sealed record CharacterListStatusEvent : StatusEvent
{
@ -79,3 +79,18 @@ public sealed record UnknownStatusEvent : StatusEvent
{
public required string RawJson { get; init; }
}
/// <summary>
/// A status line whose <c>e</c> value IS one of the recognized event
/// names, but whose payload does not match that event's expected shape
/// (a missing required field, or a field present with the wrong JSON
/// kind). Distinguished from <see cref="UnknownStatusEvent"/> (Campaign
/// LA plan §LA3 review finding F12) so a launcher can tell "a newer/older
/// host sent an event I've never heard of" apart from "a host I recognize
/// sent me garbage for an event I do know" — the two cases call for
/// different diagnostics. The tailer never throws for either case.
/// </summary>
public sealed record MalformedStatusEvent : StatusEvent
{
public required string Error { get; init; }
}

View file

@ -11,23 +11,40 @@ namespace AcDream.Launcher.Core.Status;
/// "accountName":"...","slotCount":6,"characters":[...]}</c>.
///
/// <para>
/// Never throws: a line whose <c>e</c> is not one of the eight known
/// values, or whose payload doesn't match that event's expected shape,
/// or that isn't valid JSON at all, degrades to a typed
/// <see cref="UnknownStatusEvent"/> rather than an exception — a
/// launcher must keep tailing a session's status stream even against a
/// host running a newer/older wire version.
/// Never throws: a null/blank/malformed-JSON line, an unrecognized
/// <c>e</c> value, or a recognized <c>e</c> whose payload doesn't match
/// that event's expected shape, all degrade to a typed event
/// (<see cref="UnknownStatusEvent"/> or <see cref="MalformedStatusEvent"/>
/// — see each type's docs) rather than an exception — a launcher must
/// keep tailing a session's status stream even against a host running a
/// newer/older wire version, or a host that briefly writes a torn line.
/// </para>
/// </summary>
public static class StatusEventParser
{
public static StatusEvent Parse(string line)
{
ArgumentException.ThrowIfNullOrWhiteSpace(line);
if (string.IsNullOrWhiteSpace(line))
{
// Campaign LA plan §LA3 review finding F7: a blank/whitespace
// line is a normal "nothing complete here yet" degrade, not a
// caller error — the old ArgumentException.ThrowIfNullOrWhiteSpace
// guard ran BEFORE the try/catch below and escaped uncaught.
return UnknownEvent(line ?? string.Empty);
}
JsonDocument document;
try
{
using JsonDocument document = JsonDocument.Parse(line);
document = JsonDocument.Parse(line);
}
catch (JsonException)
{
return UnknownEvent(line);
}
using (document)
{
JsonElement root = document.RootElement;
int v = GetInt32OrDefault(root, "v");
@ -35,51 +52,70 @@ public static class StatusEventParser
DateTimeOffset t = GetDateTimeOffsetOrDefault(root, "t");
string sessionId = GetStringOrDefault(root, "sessionId");
return e switch
try
{
"started" =>
new StartedStatusEvent { V = v, E = e, T = t, SessionId = sessionId },
"connected" =>
new ConnectedStatusEvent { V = v, E = e, T = t, SessionId = sessionId },
"characterList" =>
ParseCharacterList(root, v, e, t, sessionId),
"enteredWorld" =>
ParseEnteredWorld(root, v, e, t, sessionId),
"pluginLoaded" =>
ParsePluginLoaded(root, v, e, t, sessionId),
"pluginFailed" =>
ParsePluginFailed(root, v, e, t, sessionId),
"disconnected" =>
ParseDisconnected(root, v, e, t, sessionId),
"exited" =>
ParseExited(root, v, e, t, sessionId),
_ =>
new UnknownStatusEvent
{
V = v,
E = e,
T = t,
SessionId = sessionId,
RawJson = line,
},
};
}
catch (Exception)
{
// JsonException (malformed JSON), FormatException (a
// required-field miss inside a Parse* helper) — all degrade
// the same way: never throw out of the tailer.
return new UnknownStatusEvent
return e switch
{
"started" =>
new StartedStatusEvent { V = v, E = e, T = t, SessionId = sessionId },
"connected" =>
new ConnectedStatusEvent { V = v, E = e, T = t, SessionId = sessionId },
"characterList" =>
ParseCharacterList(root, v, e, t, sessionId),
"enteredWorld" =>
ParseEnteredWorld(root, v, e, t, sessionId),
"pluginLoaded" =>
ParsePluginLoaded(root, v, e, t, sessionId),
"pluginFailed" =>
ParsePluginFailed(root, v, e, t, sessionId),
"disconnected" =>
ParseDisconnected(root, v, e, t, sessionId),
"exited" =>
ParseExited(root, v, e, t, sessionId),
_ =>
new UnknownStatusEvent
{
V = v,
E = e,
T = t,
SessionId = sessionId,
RawJson = line,
},
};
}
catch (Exception ex) when (ex is FormatException or InvalidOperationException)
{
V = 0,
E = string.Empty,
T = default,
SessionId = string.Empty,
RawJson = line,
};
// FormatException: a Require* helper found a missing
// field or a field of the wrong JSON kind (e.g.
// "secondsGreyedOut": true"). InvalidOperationException:
// a JsonElement API call (EnumerateArray, TryGetProperty)
// against an element of the wrong ValueKind (e.g.
// "characters" present but not an array). Both mean `e`
// WAS recognized but its payload wasn't — distinguished
// from UnknownStatusEvent (Campaign LA plan §LA3 review
// finding F12).
return new MalformedStatusEvent
{
V = v,
E = e,
T = t,
SessionId = sessionId,
Error = ex.Message,
};
}
}
}
private static UnknownStatusEvent UnknownEvent(string rawLine) =>
new()
{
V = 0,
E = string.Empty,
T = default,
SessionId = string.Empty,
RawJson = rawLine,
};
private static StatusEvent ParseCharacterList(
JsonElement root,
int v,
@ -96,7 +132,7 @@ public static class StatusEventParser
{
uint id = RequireUInt32(item, "id");
string name = RequireString(item, "name");
int secondsGreyedOut = RequireInt32(item, "secondsGreyedOut");
uint secondsGreyedOut = RequireUInt32(item, "secondsGreyedOut");
characters.Add(new StatusCharacterEntry(id, name, secondsGreyedOut));
}

View file

@ -33,10 +33,31 @@ public sealed class StatusFileTailer
/// <summary>
/// Reads and parses every complete line appended to the file since
/// the last call. Returns an empty list (never null, never throws)
/// when the file doesn't exist yet or nothing new/complete has
/// arrived since the last poll.
/// when the file doesn't exist yet, has been deleted/rotated between
/// the existence check and the open (a TOCTOU window — Campaign LA
/// plan §LA3 review finding F7), or nothing new/complete has arrived
/// since the last poll.
/// </summary>
public IReadOnlyList<StatusEvent> ReadNewEvents()
{
try
{
return ReadNewEventsCore();
}
catch (Exception ex) when (
ex is FileNotFoundException or DirectoryNotFoundException or IOException)
{
// The host process deleted/rotated the file (or its
// directory) between File.Exists and the open below, or
// another transient I/O condition hit mid-read — degrade to
// "nothing new this poll" rather than throwing out of a
// method documented never to throw; the next poll picks up
// wherever the file (or its replacement) actually is.
return [];
}
}
private IReadOnlyList<StatusEvent> ReadNewEventsCore()
{
if (!File.Exists(_path))
{