Snapshot for release 2026.10.11.1 (internal 4eca83a)
This commit is contained in:
parent
194ea479a0
commit
08b80eed86
94 changed files with 11103 additions and 567 deletions
|
|
@ -3,7 +3,7 @@
|
|||
<!--
|
||||
Offline checks for src\RynthCore.Engine\Compatibility\AcMouseOverRules.cs (2026-10-08):
|
||||
a nameplate drawn under AC's windows may take a click only where AC's own mouse-over is
|
||||
the 3D world (the SmartBox wrapper, type 0x10000030) - never on one of AC's windows - and
|
||||
the 3D world (gmSmartBoxUI, type 0x10000014, or the SmartBox wrapper, 0x10000030) - never on one of AC's windows - and
|
||||
keeps today's behaviour (takes it) whenever AC's UI state can't be read.
|
||||
The AC-side facts (offsets, the type id) are checked against acclient.exe by
|
||||
tools\ui_hooks_check.py.
|
||||
|
|
|
|||
|
|
@ -41,12 +41,21 @@ internal static class Program
|
|||
AcMouseTarget t = AcMouseOverRules.Classify(true, false, SomeElement, true, SmartBox);
|
||||
Check(t == AcMouseTarget.World, $"SmartBox wrapper under the mouse = World (got {t})");
|
||||
Check(AcMouseOverRules.UnderUiOverlayMayTakeClick(t), "may take the click");
|
||||
|
||||
// 2026-10-10 client logs: over open ground AC reports gmSmartBoxUI (element 0x1000049A,
|
||||
// type 0x10000014), not the wrapper. Classed as a window, it kept every plate's click from the plate.
|
||||
Case("cursor on the 3D world as AC reports it in game: gmSmartBoxUI (0x10000014) takes the click");
|
||||
Check(AcMouseOverRules.UIElementTypeGmSmartBoxUI == 0x10000014, "gmSmartBoxUI::Register registers 0x10000014");
|
||||
AcMouseTarget g = AcMouseOverRules.Classify(true, false, 0x1000049A, true, AcMouseOverRules.UIElementTypeGmSmartBoxUI);
|
||||
Check(g == AcMouseTarget.World, $"gmSmartBoxUI under the mouse = World (got {g})");
|
||||
Check(AcMouseOverRules.UnderUiOverlayMayTakeClick(g), "gmSmartBoxUI: may take the click");
|
||||
}
|
||||
|
||||
private static void AcWindowsKeepTheClick()
|
||||
{
|
||||
Case("cursor on one of AC's windows: the click stays with AC");
|
||||
foreach (int type in new[] { ItemList, 0x10000001, 0x10000032, 0, -1, SmartBox + 1 })
|
||||
// 0x10000013 / 0x10000015: neighbours of gmSmartBoxUI's type stay windows.
|
||||
foreach (int type in new[] { ItemList, 0x10000001, 0x10000032, 0, -1, SmartBox + 1, 0x10000013, 0x10000015 })
|
||||
{
|
||||
AcMouseTarget t = AcMouseOverRules.Classify(true, false, SomeElement, true, type);
|
||||
Check(t == AcMouseTarget.AcWindow, $"type 0x{type:X8} = AcWindow (got {t})");
|
||||
|
|
|
|||
31
tools/ChatDiscordTests/ChatDiscordTests.csproj
Normal file
31
tools/ChatDiscordTests/ChatDiscordTests.csproj
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for RynthChat's Discord relay (src\RynthCore.Engine\UI\Data\Discord\, the
|
||||
engine-free parts compiled in): speech parsing, which routes take a line and under which
|
||||
label, the Discord text, scrollback detection, settings save / load, the request body and
|
||||
429 handling, a route's send queue, and DPAPI round trips. Nothing is sent.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>ChatDiscordTests</RootNamespace>
|
||||
<!-- DiscordRoute.Status is written by the engine's pump, which isn't compiled in here. -->
|
||||
<NoWarn>$(NoWarn);CS0649</NoWarn>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\ChatSpeech.cs" Link="Engine\ChatSpeech.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\ChatDiscordLogic.cs" Link="Engine\ChatDiscordLogic.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\ChatDiscordSettings.cs" Link="Engine\ChatDiscordSettings.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\DiscordFormat.cs" Link="Engine\DiscordFormat.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\DiscordClient.cs" Link="Engine\DiscordClient.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\DiscordSecrets.cs" Link="Engine\DiscordSecrets.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\Discord\DiscordRouteQueue.cs" Link="Engine\DiscordRouteQueue.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
704
tools/ChatDiscordTests/Program.cs
Normal file
704
tools/ChatDiscordTests/Program.cs
Normal file
|
|
@ -0,0 +1,704 @@
|
|||
using System.Text.Json;
|
||||
using RynthCore.Engine.UI.Data.Discord;
|
||||
|
||||
namespace ChatDiscordTests;
|
||||
|
||||
/// <summary>
|
||||
/// RynthChat's Discord relay, the parts that don't need the engine: what a chat line is, which
|
||||
/// routes take it, how it reads in Discord, scrollback, settings files, the request body and
|
||||
/// rate-limit waits, and the DPAPI wrapper. Fake webhook URLs and tokens are built at run time
|
||||
/// (no credential-shaped literals in the source).
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
|
||||
// A well-formed but fake webhook URL / bot token / channel id.
|
||||
private static readonly string FakeWebhook =
|
||||
"https://discord.com/api/webhooks/" + new string('1', 18) + "/" + new string('x', 68);
|
||||
private static readonly string FakeBotToken =
|
||||
string.Join(".", new string('A', 24), new string('b', 6), new string('c', 38));
|
||||
private static readonly string FakeChannel = new string('7', 19);
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
Speech();
|
||||
Classify();
|
||||
Routing();
|
||||
Formatting();
|
||||
Backlog();
|
||||
Packing();
|
||||
Validation();
|
||||
RequestBody();
|
||||
Settings();
|
||||
Secrets();
|
||||
Dedup();
|
||||
Characters();
|
||||
Queue();
|
||||
FaceText();
|
||||
ClientShutdown(); // last: it closes DiscordClient for good
|
||||
|
||||
Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks})");
|
||||
return _failed == 0 && _checks > 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
// ── Speech parsing ───────────────────────────────────────────────────
|
||||
|
||||
private static void Speech()
|
||||
{
|
||||
Said("Bob tells you, \"hi there\"", 0x03, SpeechChannel.Tell, "Bob", "hi there", own: false);
|
||||
Said("You tell Bob, \"yo\"", 0x03, SpeechChannel.Tell, "You", "yo", own: true);
|
||||
Said("Bob says on the General channel, \"wts pyreal\"", 0x1B, SpeechChannel.General, "Bob", "wts pyreal", own: false);
|
||||
Said("[Trade] Bob says, \"wtb mana stones\"", 0x00, SpeechChannel.Trade, "Bob", "wtb mana stones", own: false);
|
||||
Said("Bob says, \"hello\"", 0x02, SpeechChannel.Local, "Bob", "hello", own: false);
|
||||
Said("+Bob says to your fellowship, \"pull\"", 0x00, SpeechChannel.Fellowship, "Bob", "pull", own: false);
|
||||
Said("Bob says to your covassals, \"gz\"", 0x00, SpeechChannel.Covassals, "Bob", "gz", own: false);
|
||||
Said("Bob says to your vassals, \"hi\"", 0x00, SpeechChannel.Vassals, "Bob", "hi", own: false);
|
||||
Said("Bob says, \"caf<00e9> time\"", 0x12, SpeechChannel.Allegiance, "Bob", "caf\u00e9 time", own: false);
|
||||
Said("Bob says on the LFG channel, \"lf colo\"", 0x00, SpeechChannel.Lfg, "Bob", "lf colo", own: false);
|
||||
|
||||
NotSpeech("You say, \"Zojak Bor\"", ChatSpeech.ChatTypeSpellcasting); // spell words
|
||||
NotSpeech("You have gained 500 experience.", 0x00);
|
||||
NotSpeech("Bob says, \" \"", 0x02); // nothing said
|
||||
NotSpeech("", 0x02);
|
||||
NotSpeech(null, 0x02);
|
||||
NotSpeech("He says \"hi\"", 0x00); // no channel at all
|
||||
|
||||
Check(ChatSpeech.Name(SpeechChannel.Lfg) == "LFG", "LFG is shown upper case");
|
||||
Check(ChatSpeech.TryParseName("lfg", out var lfg) && lfg == SpeechChannel.Lfg, "LFG parses back");
|
||||
Check(ChatSpeech.TryParseName(" Fellow ", out var fel) && fel == SpeechChannel.Fellowship, "short names parse");
|
||||
Check(!ChatSpeech.TryParseName("guild", out _), "unknown names don't parse");
|
||||
foreach (var ch in ChatSpeech.All)
|
||||
Check(ChatSpeech.TryParseName(ChatSpeech.Name(ch), out var back) && back == ch, $"{ch} survives a save");
|
||||
Check(ChatSpeech.Decode("<zzzz> and <0041>") == "<zzzz> and A", "only hex escapes decode");
|
||||
}
|
||||
|
||||
private static void Said(string text, int chatType, SpeechChannel ch, string who, string msg, bool own)
|
||||
{
|
||||
bool ok = ChatSpeech.TryParse(text, chatType, out var c, out string s, out string m, out bool o);
|
||||
Check(ok, $"speech: {text}");
|
||||
if (!ok) return;
|
||||
Check(c == ch, $"{text} -> {ch} (got {c})");
|
||||
Check(s == who, $"{text} speaker {who} (got {s})");
|
||||
Check(m == msg, $"{text} message \"{msg}\" (got \"{m}\")");
|
||||
Check(o == own, $"{text} own={own}");
|
||||
}
|
||||
|
||||
private static void NotSpeech(string? text, int chatType)
|
||||
=> Check(!ChatSpeech.TryParse(text, chatType, out _, out _, out _, out _), $"not speech: {text ?? "(null)"}");
|
||||
|
||||
// ── Line classification ──────────────────────────────────────────────
|
||||
|
||||
private static void Classify()
|
||||
{
|
||||
Check(ChatDiscordLogic.TryClassify("You tell Bob, \"omw\"", 0x03, "Alice", out var mine), "own tell classifies");
|
||||
Check(mine.Own && mine.Speaker == "Alice" && mine.Speech == SpeechChannel.Tell, "own lines are shown as the character");
|
||||
Check(ChatDiscordLogic.TryClassify("You tell Bob, \"omw\"", 0x03, "", out var anon) && anon.Speaker == "You",
|
||||
"own lines before login keep \"You\"");
|
||||
|
||||
Check(ChatDiscordLogic.TryClassify("You gain 500 xp.", 0x00, "Alice", out var plain), "plain text classifies");
|
||||
Check(plain.Speech == null && plain.Speaker.Length == 0 && plain.Message == "You gain 500 xp.", "plain text has no channel");
|
||||
Check(plain.Haystack == "You gain 500 xp.", "plain haystack is the text");
|
||||
Check(ChatDiscordLogic.TryClassify("Bob tells you, \"rare drop\"", 0x03, "", out var tell) && tell.Haystack == "Bob rare drop",
|
||||
"speech haystack is speaker + message");
|
||||
|
||||
Check(!ChatDiscordLogic.TryClassify(" ", 0x00, "Alice", out _), "blank lines are skipped");
|
||||
Check(!ChatDiscordLogic.TryClassify(null, 0x00, "Alice", out _), "null lines are skipped");
|
||||
}
|
||||
|
||||
// ── Which routes take a line ─────────────────────────────────────────
|
||||
|
||||
private static void Routing()
|
||||
{
|
||||
var route = Route(DiscordRoute.DefaultSpeechMask(), "System");
|
||||
|
||||
Check(ChatDiscordLogic.Wants(route, SpeechChannel.Tell, _ => false, out string l1) && l1 == "Tell", "default routes take tells");
|
||||
Check(ChatDiscordLogic.Wants(route, SpeechChannel.Monarch, _ => false, out _), "default routes take the allegiance channels");
|
||||
Check(!ChatDiscordLogic.Wants(route, SpeechChannel.Local, _ => false, out _), "default routes skip local");
|
||||
Check(!ChatDiscordLogic.Wants(route, SpeechChannel.General, _ => false, out _), "default routes skip General");
|
||||
|
||||
Check(ChatDiscordLogic.Wants(route, null, t => t == "System", out string l2) && l2 == "System",
|
||||
"a line in a ticked tab is taken, labelled with the tab");
|
||||
Check(ChatDiscordLogic.Wants(route, SpeechChannel.Local, t => t == "System", out string l3) && l3 == "Local",
|
||||
"speech taken through a tab keeps its channel label");
|
||||
Check(!ChatDiscordLogic.Wants(route, null, t => t == "Combat", out _), "lines only in other tabs are skipped");
|
||||
|
||||
var none = Route(0);
|
||||
Check(!ChatDiscordLogic.Wants(none, SpeechChannel.Tell, _ => true, out _), "a route with nothing ticked takes nothing");
|
||||
|
||||
var all = Route(DiscordRoute.AllSpeechMask());
|
||||
foreach (var ch in ChatSpeech.All)
|
||||
Check(all.RelaysSpeech(ch), $"all-channels route relays {ch}");
|
||||
|
||||
Check(DiscordFormat.MatchesKeywords("Bob rare drop", DiscordFormat.SplitList("loot, RARE ,")), "keywords match case-insensitively");
|
||||
Check(!DiscordFormat.MatchesKeywords("Bob hi", DiscordFormat.SplitList("loot,rare")), "keywords filter");
|
||||
Check(DiscordFormat.MatchesKeywords("anything", DiscordFormat.SplitList(" , ")), "no keywords = everything");
|
||||
|
||||
|
||||
var s = new ChatDiscordSettings { BatchMs = 1500, MinIntervalMs = 2000 };
|
||||
var own = new DiscordRoute { CustomPace = true, BatchMs = 0, MinIntervalMs = 60_000 };
|
||||
Check(s.BatchFor(route) == 1500 && s.IntervalFor(route) == 2000, "routes use the relay's pacing by default");
|
||||
Check(s.BatchFor(own) == 0 && s.IntervalFor(own) == 60_000, "own pacing overrides it");
|
||||
|
||||
Check(!new DiscordRoute().HasSecret, "a new route has no secret");
|
||||
Check(new DiscordRoute { WebhookProtected = "blob" }.HasSecret, "webhook routes need the webhook");
|
||||
Check(!new DiscordRoute { Mode = DiscordRoute.ModeBot, BotTokenProtected = "blob" }.HasSecret, "bot routes need a channel too");
|
||||
Check(new DiscordRoute { Mode = DiscordRoute.ModeBot, BotTokenProtected = "blob", ChannelId = FakeChannel }.HasSecret, "bot route ready");
|
||||
}
|
||||
|
||||
private static DiscordRoute Route(uint speech, params string[] tabs)
|
||||
=> new() { SpeechMask = speech, Tabs = tabs };
|
||||
|
||||
// ── Discord text ─────────────────────────────────────────────────────
|
||||
|
||||
private static void Formatting()
|
||||
{
|
||||
var at = new DateTime(2026, 10, 11, 12, 34, 56);
|
||||
var s = new ChatDiscordSettings { IncludeTimestamp = true, TagCharacter = false };
|
||||
ChatDiscordLogic.TryClassify("Bob tells you, \"hi *there*\"", 0x03, "Alice", out var tell);
|
||||
Same(ChatDiscordLogic.Format(s, at, tell, "Tell", "Alice"), "`12:34:56` **\\[Tell\\] Bob:** hi \\*there\\*", "speech line");
|
||||
|
||||
s.IncludeTimestamp = false;
|
||||
s.TagCharacter = true;
|
||||
Same(ChatDiscordLogic.Format(s, at, tell, "Tell", "Alice"), "\\[Alice\\] **\\[Tell\\] Bob:** hi \\*there\\*", "character tag");
|
||||
Same(ChatDiscordLogic.Format(s, at, tell, "Tell", ""), "**\\[Tell\\] Bob:** hi \\*there\\*", "no tag before login");
|
||||
|
||||
s.TagCharacter = false;
|
||||
ChatDiscordLogic.TryClassify("# You found a rare!", 0x00, "Alice", out var plain);
|
||||
Same(ChatDiscordLogic.Format(s, at, plain, "", "Alice"), "\\# You found a rare!", "plain text can't become a heading");
|
||||
Same(ChatDiscordLogic.Format(s, at, plain, "System", "Alice"), "**\\[System\\]** # You found a rare!", "tab label");
|
||||
|
||||
string pinged = DiscordFormat.Escape("@everyone look <@123> [x](y)");
|
||||
Check(!pinged.Contains("@everyone"), "@everyone is defused");
|
||||
Check(pinged.Contains("\\<@123\\>") && pinged.Contains("\\[x\\]"), "mentions and links are escaped");
|
||||
Same(DiscordFormat.Escape("a\r\nb"), "a b", "newlines flatten");
|
||||
|
||||
string longLine = DiscordFormat.FormatLine(at, null, null, new string('z', 5000), false, null);
|
||||
Check(longLine.Length == DiscordFormat.MaxLine && longLine.EndsWith('\u2026'), "long lines are cut");
|
||||
string cut = DiscordFormat.Truncate(new string('a', 8) + "\\*", 10);
|
||||
Check(cut.Length <= 10 && !cut.TrimEnd('\u2026').EndsWith('\\'), "cuts don't strand an escape");
|
||||
|
||||
Same(DiscordFormat.SafeWebhookName("+Bob"), "Bob", "webhook name drops +");
|
||||
Same(DiscordFormat.SafeWebhookName("Discord Bob"), "", "Discord refuses names with 'discord'");
|
||||
Same(DiscordFormat.SafeWebhookName("everyone"), "", "no 'everyone' name");
|
||||
Check(DiscordFormat.SafeWebhookName(new string('n', 100)).Length == 80, "webhook names cap at 80");
|
||||
}
|
||||
|
||||
// ── Scrollback, by RynthChat's seq ───────────────────────────────────
|
||||
|
||||
private static void Backlog()
|
||||
{
|
||||
static ulong[] Seqs(ulong from, int count)
|
||||
{
|
||||
var a = new ulong[count];
|
||||
for (int i = 0; i < count; i++) a[i] = from + (ulong)i;
|
||||
return a;
|
||||
}
|
||||
static int Posted(bool[] post) => post.Count(p => p);
|
||||
|
||||
// Engine start or hot reload: the first read is RynthChat's whole ring (up to 500 lines).
|
||||
var g = new DiscordBacklogGate();
|
||||
Check(Posted(g.Admit(on: true, Seqs(1, 500))) == 0, "the first read after start is a baseline: 500 lines of scrollback, none posted");
|
||||
Check(g.Live, "after the baseline the relay is live");
|
||||
Check(Posted(g.Admit(on: true, Seqs(501, 3))) == 3, "lines after the baseline are posted");
|
||||
Check(Posted(g.Admit(on: true, Seqs(502, 2))) == 0, "a line seen already isn't posted twice");
|
||||
Check(Posted(g.Admit(on: true, new ulong[] { 503, 504, 505 })) == 2, "only the newer lines of a mixed read");
|
||||
|
||||
// An empty first read is still the baseline: the next line is news.
|
||||
g = new DiscordBacklogGate();
|
||||
Check(Posted(g.Admit(on: true, Array.Empty<ulong>())) == 0 && g.Live, "an empty first read is the baseline");
|
||||
Check(Posted(g.Admit(on: true, Seqs(1, 1))) == 1, "the line after an empty baseline is posted");
|
||||
|
||||
// Off, then on again: what arrived meanwhile is history.
|
||||
Check(Posted(g.Admit(on: false, Seqs(2, 10))) == 0 && !g.Live, "nothing is posted while off");
|
||||
Check(Posted(g.Admit(on: true, Seqs(12, 40))) == 0, "the first read after switching on is a baseline");
|
||||
Check(Posted(g.Admit(on: true, Seqs(52, 1))) == 1, "then new lines go");
|
||||
g.Off();
|
||||
Check(Posted(g.Admit(on: true, Seqs(53, 5))) == 0, "Off (the pump saw it off) re-baselines");
|
||||
|
||||
// RynthChat reloaded: its numbers start from 1 again.
|
||||
g.SourceReset();
|
||||
Check(Posted(g.Admit(on: true, Seqs(1, 4))) == 0, "after RynthChat restarts its numbering, its first read is a baseline");
|
||||
Check(Posted(g.Admit(on: true, Seqs(5, 2))) == 2, "and its new lines go, though their numbers are low");
|
||||
}
|
||||
|
||||
// ── Batching ─────────────────────────────────────────────────────────
|
||||
|
||||
private static void Packing()
|
||||
{
|
||||
var lines = new List<string> { new('a', 900), new('b', 900), new('c', 900) };
|
||||
string first = DiscordFormat.Pack(lines, out int taken);
|
||||
Check(taken == 2 && first.Length == 1801, $"two 900-char lines fit one message (took {taken}, {first.Length} chars)");
|
||||
|
||||
var huge = new List<string> { new('h', 2500), "next" };
|
||||
string one = DiscordFormat.Pack(huge, out int t2);
|
||||
Check(t2 == 1 && one.Length == DiscordFormat.MaxContent, "an oversized line still goes, cut to 2000");
|
||||
|
||||
Check(DiscordFormat.Pack(new List<string>(), out int t3) == string.Empty && t3 == 0, "nothing to pack");
|
||||
}
|
||||
|
||||
// ── Pasted values ────────────────────────────────────────────────────
|
||||
|
||||
private static void Validation()
|
||||
{
|
||||
Check(DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook, out string n1) && n1 == FakeWebhook, "webhook URL accepted");
|
||||
Check(DiscordFormat.TryNormalizeWebhookUrl(" " + FakeWebhook + "/?wait=true ", out string n2) && n2 == FakeWebhook,
|
||||
"query and trailing slash are dropped");
|
||||
Check(DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook.Replace("discord.com", "ptb.discordapp.com").Replace("/api/", "/api/v10/"), out _),
|
||||
"ptb / discordapp / versioned URLs accepted");
|
||||
Check(!DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook.Replace("https:", "http:"), out _), "plain http refused");
|
||||
Check(!DiscordFormat.TryNormalizeWebhookUrl(FakeWebhook.Replace("discord.com", "discord.com.example.net"), out _), "other hosts refused");
|
||||
Check(!DiscordFormat.TryNormalizeWebhookUrl("", out _), "blank refused");
|
||||
|
||||
Check(DiscordFormat.LooksLikeBotToken(FakeBotToken), "bot token shape accepted");
|
||||
Check(!DiscordFormat.LooksLikeBotToken("Bot " + FakeBotToken), "the 'Bot ' prefix isn't part of the token");
|
||||
Check(!DiscordFormat.LooksLikeBotToken("short.x.y"), "short tokens refused");
|
||||
Check(DiscordFormat.IsSnowflake(FakeChannel), "channel id accepted");
|
||||
Check(!DiscordFormat.IsSnowflake("#general"), "channel names refused");
|
||||
|
||||
string secret = new string('s', 40);
|
||||
Same(DiscordFormat.Redact("error near " + secret, secret), "error near ***", "secrets are redacted");
|
||||
Same(DiscordFormat.Redact("no secret here", ""), "no secret here", "nothing to redact");
|
||||
|
||||
string hookToken = FakeWebhook.Substring(FakeWebhook.LastIndexOf('/') + 1);
|
||||
Same(DiscordFormat.Redact("Invalid Webhook Token: " + hookToken, FakeWebhook), "Invalid Webhook Token: ***",
|
||||
"the webhook's bare token is redacted");
|
||||
string other = "https://discord.com/api/webhooks/" + new string('2', 18) + "/" + new string('y', 68);
|
||||
Check(!DiscordFormat.Redact("posting to " + other, FakeWebhook).Contains(new string('y', 68)), "any webhook URL's token is redacted");
|
||||
Same(DiscordFormat.Redact("Authorization: Bot " + FakeBotToken, null), "Authorization: Bot ***", "a bare bot token is redacted without being told");
|
||||
Same(DiscordFormat.Redact("401 for " + FakeBotToken + ".", FakeBotToken), "401 for ***.", "the bot token in use is redacted");
|
||||
Same(DiscordFormat.Redact("HTTP 404: Unknown Webhook (v1.2.3)", FakeWebhook), "HTTP 404: Unknown Webhook (v1.2.3)", "ordinary errors are left alone");
|
||||
}
|
||||
|
||||
// ── Request body and status handling ─────────────────────────────────
|
||||
|
||||
private static void RequestBody()
|
||||
{
|
||||
using (var doc = JsonDocument.Parse(DiscordClient.BuildBody("line \"one\"\nline two", "Alice")))
|
||||
{
|
||||
var root = doc.RootElement;
|
||||
Check(root.GetProperty("content").GetString() == "line \"one\"\nline two", "content round-trips");
|
||||
Check(root.GetProperty("username").GetString() == "Alice", "username sent");
|
||||
Check(root.GetProperty("allowed_mentions").GetProperty("parse").GetArrayLength() == 0, "no mentions can ping");
|
||||
Check(root.GetProperty("flags").GetInt32() == 4, "embeds suppressed");
|
||||
}
|
||||
using (var doc = JsonDocument.Parse(DiscordClient.BuildBody("x", "")))
|
||||
Check(!doc.RootElement.TryGetProperty("username", out _), "no username when blank (bot / webhook default)");
|
||||
|
||||
Check(DiscordClient.ParseRetryAfterMs("{\"retry_after\":1.5,\"global\":false}", null) == 1500, "retry_after from JSON");
|
||||
Check(DiscordClient.ParseRetryAfterMs(null, "3") == 3000, "Retry-After header");
|
||||
Check(DiscordClient.ParseRetryAfterMs("not json", null) == 5000, "unknown wait is 5 s");
|
||||
Check(DiscordClient.ParseRetryAfterMs("{\"retry_after\":0.01}", null) == 250, "waits at least 0.25 s");
|
||||
Check(DiscordClient.ParseRetryAfterMs("{\"retry_after\":99999}", null) == 600_000, "waits at most 10 min");
|
||||
|
||||
foreach (int st in new[] { 400, 401, 403, 404 }) Check(DiscordClient.IsPermanent(st), $"HTTP {st} pauses the route");
|
||||
foreach (int st in new[] { 429, 500, 502, 503 }) Check(!DiscordClient.IsPermanent(st), $"HTTP {st} is retried");
|
||||
}
|
||||
|
||||
// ── Settings file ────────────────────────────────────────────────────
|
||||
|
||||
private static void Settings()
|
||||
{
|
||||
string dir = TempDir();
|
||||
try
|
||||
{
|
||||
string path = Path.Combine(dir, "rynthchat_discord.json");
|
||||
|
||||
var fresh = ChatDiscordStore.Load(path, out string n0);
|
||||
Check(fresh.Characters.Length == 0 && fresh.Routes.Length == 0 && n0.Length == 0, "no file: defaults, off for everyone");
|
||||
|
||||
var s = new ChatDiscordSettings
|
||||
{
|
||||
Characters = new[] { DiscordCharacter.Of("Aelrynth", "Alice")! },
|
||||
SkipOwn = true,
|
||||
TagCharacter = true,
|
||||
BatchMs = 999_999, // clamped on load
|
||||
MinIntervalMs = 5, // clamped on load
|
||||
Routes = new[]
|
||||
{
|
||||
new DiscordRoute
|
||||
{
|
||||
Name = "Guild", Mode = DiscordRoute.ModeBot, ChannelId = FakeChannel, BotTokenProtected = "blob",
|
||||
SpeechMask = ChatSpeech.Bit(SpeechChannel.Tell) | ChatSpeech.Bit(SpeechChannel.Lfg),
|
||||
Tabs = new[] { "System", "Loot" }, Keywords = "rare", CustomPace = true, BatchMs = 0, MinIntervalMs = 30_000,
|
||||
},
|
||||
new DiscordRoute { Name = " ", SpeechMask = 0 },
|
||||
},
|
||||
};
|
||||
string json = ChatDiscordStore.Serialize(s);
|
||||
Check(json.Contains("\"speech\"") && json.Contains("\"LFG\""), "speech channels are saved by name");
|
||||
Check(!json.Contains("speechMask", StringComparison.OrdinalIgnoreCase), "the runtime mask isn't saved");
|
||||
Check(!json.Contains("hasSecret", StringComparison.OrdinalIgnoreCase) && !json.Contains("\"status\""), "runtime state isn't saved");
|
||||
ChatDiscordStore.Write(path, json);
|
||||
Check(Directory.GetFiles(dir, "*.tmp").Length == 0, "the temp file is swapped in");
|
||||
|
||||
var back = ChatDiscordStore.Load(path, out string n1);
|
||||
Check(n1.Length == 0, "clean load has no note");
|
||||
Check(back.SkipOwn && back.TagCharacter && back.Characters.Length == 1 && back.Characters[0].Name == "Alice" && back.Characters[0].Server == "Aelrynth", "switches round-trip");
|
||||
Check(back.BatchMs == ChatDiscordSettings.BatchMaxMs, "batch window clamped");
|
||||
Check(back.MinIntervalMs == ChatDiscordSettings.IntervalMinMs, "message spacing clamped");
|
||||
Check(back.Routes.Length == 2, "routes round-trip");
|
||||
var g = back.Routes[0];
|
||||
Check(g.Name == "Guild" && g.Mode == DiscordRoute.ModeBot && g.ChannelId == FakeChannel && g.BotTokenProtected == "blob",
|
||||
"route connection round-trips");
|
||||
Check(g.RelaysSpeech(SpeechChannel.Tell) && g.RelaysSpeech(SpeechChannel.Lfg) && !g.RelaysSpeech(SpeechChannel.Fellowship),
|
||||
"speech channels round-trip");
|
||||
Check(g.Tabs.SequenceEqual(new[] { "System", "Loot" }) && g.Keywords == "rare", "tabs and keywords round-trip");
|
||||
Check(g.CustomPace && g.BatchMs == 0 && g.MinIntervalMs == 30_000, "route pacing round-trips");
|
||||
Check(back.Routes[1].Name == "Discord", "blank route names get a name");
|
||||
Check(back.Routes[1].SpeechMask == 0, "a route with every channel unticked stays empty");
|
||||
|
||||
// Hand-edited file: no speech list means the defaults; bad values repaired.
|
||||
File.WriteAllText(path, "{ \"enabled\": true, \"routes\": [ { \"name\": \"x\", \"mode\": \"carrier pigeon\", " +
|
||||
"\"tabs\": [\"System\", \"system\", \" \", null] }, null ], \"maxQueue\": 1 }");
|
||||
var hand = ChatDiscordStore.Load(path, out _);
|
||||
Check(hand.Characters.Length == 0, "an old file's global \"enabled\" turns nobody on");
|
||||
Check(hand.Routes.Length == 1, "null routes dropped");
|
||||
Check(hand.Routes[0].Mode == DiscordRoute.ModeWebhook, "unknown modes become webhook");
|
||||
Check(hand.Routes[0].SpeechMask == DiscordRoute.DefaultSpeechMask(), "no speech list = the defaults");
|
||||
Check(hand.Routes[0].Tabs.Length == 1, $"tabs de-duplicated (got {hand.Routes[0].Tabs.Length})");
|
||||
Check(hand.MaxQueue == ChatDiscordSettings.QueueMin, "queue size clamped");
|
||||
|
||||
// A damaged file: defaults, a note for the log, and a copy kept for the user.
|
||||
File.WriteAllText(path, "{ not json");
|
||||
var bad = ChatDiscordStore.Load(path, out string n2);
|
||||
Check(bad.Characters.Length == 0 && bad.Routes.Length == 0, "damaged file: defaults");
|
||||
Check(n2.Contains("unreadable"), "damaged file is reported");
|
||||
Check(Directory.GetFiles(dir, "*.unreadable-*.json").Length == 1, "damaged file is kept aside");
|
||||
}
|
||||
finally { TryDelete(dir); }
|
||||
}
|
||||
|
||||
// ── DPAPI ────────────────────────────────────────────────────────────
|
||||
|
||||
private static void Secrets()
|
||||
{
|
||||
string blob = DiscordSecrets.Protect(FakeWebhook);
|
||||
Check(blob.Length > 0 && !blob.Contains(FakeWebhook) && !blob.Contains("webhooks"), "protected blobs hide the secret");
|
||||
Check(DiscordSecrets.TryUnprotect(blob, out string plain) && plain == FakeWebhook, "protect / unprotect round-trip");
|
||||
Check(DiscordSecrets.Protect(FakeWebhook) != blob, "each protect is salted");
|
||||
|
||||
byte[] raw = Convert.FromBase64String(blob);
|
||||
raw[raw.Length / 2] ^= 0x55;
|
||||
Check(!DiscordSecrets.TryUnprotect(Convert.ToBase64String(raw), out _), "damaged blobs don't open");
|
||||
Check(!DiscordSecrets.TryUnprotect("not base64 !!", out _), "garbage doesn't open");
|
||||
Check(!DiscordSecrets.TryUnprotect("", out _), "empty doesn't open");
|
||||
Check(DiscordSecrets.Protect("") == string.Empty && DiscordSecrets.Protect(null) == string.Empty, "empty in, empty out");
|
||||
}
|
||||
|
||||
// ── Repeat filter ────────────────────────────────────────────────────
|
||||
|
||||
private static void Dedup()
|
||||
{
|
||||
ChatDiscordLogic.TryClassify("Bob tells you, \"hi\"", 0x03, "", out var a);
|
||||
ChatDiscordLogic.TryClassify("Bob tells you, \"hi!\"", 0x03, "", out var b);
|
||||
Check(ChatDiscordLogic.DedupKey(a, "Tell") != ChatDiscordLogic.DedupKey(b, "Tell"), "different lines, different keys");
|
||||
Check(ChatDiscordLogic.DedupKey(a, "Tell") != ChatDiscordLogic.DedupKey(a, "General"), "the label is part of the key");
|
||||
|
||||
var recent = new Dictionary<string, long> { ["old"] = 1_000, ["new"] = 9_000 };
|
||||
ChatDiscordLogic.PruneRecent(recent, now: 10_000, windowMs: 5_000);
|
||||
Check(!recent.ContainsKey("old") && recent.ContainsKey("new"), "old repeat entries are pruned");
|
||||
}
|
||||
|
||||
// ── Per-character switch and merged saves ────────────────────────────
|
||||
|
||||
private static void Characters()
|
||||
{
|
||||
Check(DiscordCharacter.Of("Aelrynth", " ") == null && DiscordCharacter.Of("Aelrynth", null) == null, "no name, no character");
|
||||
var alice = DiscordCharacter.Of(" Aelrynth ", "+Alice ")!;
|
||||
Check(alice.Server == "Aelrynth" && alice.Name == "Alice", "names are trimmed (and lose AC's +)");
|
||||
Check(alice.Same(DiscordCharacter.Of("aelrynth", "ALICE")), "same character in any case");
|
||||
Check(!alice.Same(DiscordCharacter.Of("Other", "Alice")), "same name on another server is another character");
|
||||
Check(!alice.Same(null), "nobody is not Alice");
|
||||
var bob = DiscordCharacter.Of("Aelrynth", "Bob")!;
|
||||
var carol = DiscordCharacter.Of("Aelrynth", "Carol")!;
|
||||
|
||||
var s = new ChatDiscordSettings();
|
||||
Check(!s.IsOnFor(alice) && !s.IsOnFor(null), "off for everyone by default");
|
||||
s.Characters = new[] { alice };
|
||||
Check(s.IsOnFor(DiscordCharacter.Of("AELRYNTH", "alice")) && !s.IsOnFor(bob), "on only for the characters listed");
|
||||
|
||||
var list = ChatDiscordStore.ApplyCharacterOps(new[] { alice, alice, bob }, new[]
|
||||
{
|
||||
new DiscordCharacterOp(carol, true), new DiscordCharacterOp(bob, false), new DiscordCharacterOp(carol, true),
|
||||
});
|
||||
Check(list.Length == 2 && list[0].Same(alice) && list[1].Same(carol), "switches apply in order, without repeats");
|
||||
|
||||
// Two clients start from the same file; each switches its own character.
|
||||
string dir = TempDir();
|
||||
try
|
||||
{
|
||||
string path = Path.Combine(dir, "rynthchat_discord.json");
|
||||
var shared = new ChatDiscordSettings
|
||||
{
|
||||
Routes = new[] { new DiscordRoute { Name = "Guild", SpeechMask = ChatSpeech.Bit(SpeechChannel.Lfg), WebhookProtected = "blob" } },
|
||||
};
|
||||
ChatDiscordStore.Write(path, ChatDiscordStore.Serialize(shared));
|
||||
var clientA = ChatDiscordStore.Load(path, out _);
|
||||
var clientB = ChatDiscordStore.Load(path, out _);
|
||||
|
||||
string Save(ChatDiscordSettings mine, params DiscordCharacterOp[] ops)
|
||||
{
|
||||
string? disk = File.Exists(path) ? File.ReadAllText(path) : null;
|
||||
string json = ChatDiscordStore.MergeForSave(ChatDiscordStore.Serialize(mine), disk, ops, out var merged);
|
||||
ChatDiscordStore.Write(path, json);
|
||||
mine.Characters = merged;
|
||||
return json;
|
||||
}
|
||||
|
||||
Save(clientA, new DiscordCharacterOp(alice, true));
|
||||
Save(clientB, new DiscordCharacterOp(bob, true)); // B never saw Alice switched on
|
||||
var now = ChatDiscordStore.Load(path, out _);
|
||||
Check(now.IsOnFor(alice) && now.IsOnFor(bob), "B's save keeps A's switch");
|
||||
Check(clientB.IsOnFor(alice), "a save brings the other clients' switches back");
|
||||
|
||||
clientA.SkipOwn = true; // A, still not knowing Bob, saves an option
|
||||
Save(clientA);
|
||||
now = ChatDiscordStore.Load(path, out _);
|
||||
Check(now.IsOnFor(alice) && now.IsOnFor(bob) && now.SkipOwn, "a save with no switch keeps everyone's switch");
|
||||
Check(now.Routes.Length == 1 && now.Routes[0].RelaysSpeech(SpeechChannel.Lfg) && now.Routes[0].WebhookProtected == "blob",
|
||||
"routes survive the merge");
|
||||
|
||||
Save(clientB, new DiscordCharacterOp(bob, false));
|
||||
now = ChatDiscordStore.Load(path, out _);
|
||||
Check(now.IsOnFor(alice) && !now.IsOnFor(bob), "turning one character off leaves the others on");
|
||||
|
||||
// A switch another client turned off doesn't come back from a stale list.
|
||||
clientA.Characters = new[] { alice, bob };
|
||||
Save(clientA);
|
||||
Check(!ChatDiscordStore.Load(path, out _).IsOnFor(bob), "a stale in-memory list doesn't switch anyone back on");
|
||||
|
||||
File.WriteAllText(path, "{ damaged");
|
||||
clientA.Characters = new[] { alice, bob };
|
||||
string fromBad = ChatDiscordStore.MergeForSave(ChatDiscordStore.Serialize(clientA), File.ReadAllText(path),
|
||||
new[] { new DiscordCharacterOp(carol, true) }, out var m1);
|
||||
Check(m1.Length == 3 && fromBad.Contains("Carol"), "an unreadable file: our own list is the base");
|
||||
ChatDiscordStore.MergeForSave(ChatDiscordStore.Serialize(new ChatDiscordSettings()), null,
|
||||
Array.Empty<DiscordCharacterOp>(), out var m2);
|
||||
Check(m2.Length == 0, "no file and no switch: off for everyone");
|
||||
|
||||
Check(ChatDiscordStore.ReadCharacters("{ \"characters\": [ { \"server\": \"S\", \"name\": \"X\" }, { \"name\": \" \" } ] }") is { Length: 1 },
|
||||
"the list is read back without blanks");
|
||||
Check(ChatDiscordStore.ReadCharacters("nope") == null && ChatDiscordStore.ReadCharacters(null) == null, "unreadable lists are null");
|
||||
}
|
||||
finally { TryDelete(dir); }
|
||||
}
|
||||
|
||||
// ── A route's queue: off means off ───────────────────────────────────
|
||||
|
||||
private static void Queue()
|
||||
{
|
||||
const int Batch = 1500, Interval = 2000, Max = 200;
|
||||
var fail = DiscordSendResult.Fail("HTTP 502");
|
||||
var ok = new DiscordSendResult(true, 200, 0, false, string.Empty);
|
||||
|
||||
// Normal flow: the batch window, then one post.
|
||||
var q = new DiscordRouteQueue();
|
||||
q.Add("a", 1000, Max);
|
||||
q.Add("b", 1200, Max);
|
||||
Check(q.Next(2000, on: true, Batch, Interval) == null, "lines wait out the batch window");
|
||||
DiscordBatch? b1 = q.Next(2600, on: true, Batch, Interval);
|
||||
Check(b1 != null && b1.Content == "a\nb" && ReferenceEquals(q.InFlight, b1) && q.Pending.Count == 0, "the window's lines go as one message");
|
||||
Check(q.Next(9000, on: true, Batch, Interval) == null, "one post in flight at a time");
|
||||
Check(q.Apply(b1!, ok, 3000, Interval) == DiscordOutcome.Sent && q.MessagesSent == 1 && q.LinesSent == 2, "a sent batch counts");
|
||||
|
||||
// Pending lines, then the relay goes off.
|
||||
q = new DiscordRouteQueue();
|
||||
q.Add("x", 0, Max);
|
||||
q.Add("y", 0, Max);
|
||||
Check(q.Next(10_000, on: false, Batch, Interval) == null && q.Pending.Count == 0, "off drops pending lines");
|
||||
Check(q.Dropped == 2, "dropped lines are counted");
|
||||
q.Add("z", 20_000, Max);
|
||||
Check(q.Stop() == 1 && q.Queued == 0, "Stop drops pending lines");
|
||||
|
||||
// A batch waiting to retry must not go out once the relay or route is off.
|
||||
q = new DiscordRouteQueue();
|
||||
q.Add("retry me", 0, Max);
|
||||
DiscordBatch? b2 = q.Next(5000, on: true, Batch, Interval);
|
||||
Check(q.Apply(b2!, fail, 5100, Interval) == DiscordOutcome.Retrying && ReferenceEquals(q.Retry, b2), "a network error waits to retry");
|
||||
Check(q.Next(600_000, on: false, Batch, Interval) == null, "a waiting retry is not sent when off");
|
||||
Check(q.Retry == null && q.Queued == 0, "off drops the waiting retry");
|
||||
|
||||
// Same after a rate limit.
|
||||
q = new DiscordRouteQueue();
|
||||
q.Add("limited", 0, Max);
|
||||
DiscordBatch? b3 = q.Next(5000, on: true, Batch, Interval);
|
||||
Check(q.Apply(b3!, DiscordSendResult.Fail("rate limited", status: 429, retryAfterMs: 1000), 5100, Interval) == DiscordOutcome.RateLimited,
|
||||
"429 is a rate limit");
|
||||
Check(q.Next(600_000, on: false, Batch, Interval) == null && q.Retry == null, "a rate-limited batch is dropped when off");
|
||||
|
||||
// The post in flight when it goes off: cancelled, and its result can't come back as a retry.
|
||||
q = new DiscordRouteQueue();
|
||||
q.Add("flying", 0, Max);
|
||||
DiscordBatch? b4 = q.Next(5000, on: true, Batch, Interval);
|
||||
using (var cts = new CancellationTokenSource())
|
||||
{
|
||||
b4!.Cancel = cts;
|
||||
Check(q.Stop() == 1 && q.InFlight == null, "Stop drops the post in flight");
|
||||
Check(cts.IsCancellationRequested, "the request in flight is cancelled");
|
||||
}
|
||||
Check(q.Apply(b4, fail, 5200, Interval) == DiscordOutcome.Ignored && q.Retry == null, "a stopped post's failure isn't retried");
|
||||
Check(q.Apply(b4, ok, 5200, Interval) == DiscordOutcome.Ignored && q.MessagesSent == 0, "a stopped post's result is ignored");
|
||||
Check(q.Next(600_000, on: true, Batch, Interval) == null, "nothing comes back after a stop");
|
||||
|
||||
// Only an explicit test gets past the switches.
|
||||
q = new DiscordRouteQueue();
|
||||
q.Add("chat", 0, Max);
|
||||
q.QueueTest("test line");
|
||||
DiscordBatch? t1 = q.Next(10, on: false, Batch, Interval);
|
||||
Check(t1 != null && t1.IsTest && t1.Content == "test line", "a test goes while off");
|
||||
Check(q.Pending.Count == 0, "chat queued with it doesn't");
|
||||
Check(q.Stop() == 0 && ReferenceEquals(q.InFlight, t1), "Stop keeps a test in flight");
|
||||
Check(q.Apply(t1!, fail, 20, Interval) == DiscordOutcome.Retrying, "a failed test retries");
|
||||
Check(q.Next(600_000, on: false, Batch, Interval) is { IsTest: true }, "a test's retry goes while off");
|
||||
|
||||
q = new DiscordRouteQueue();
|
||||
q.Add("old", 0, Max);
|
||||
DiscordBatch? b5 = q.Next(5000, on: true, Batch, Interval);
|
||||
q.Apply(b5!, fail, 5100, Interval);
|
||||
q.QueueTest("test");
|
||||
Check(q.Retry is { IsTest: true } && q.Dropped == 1, "a test replaces a waiting retry");
|
||||
|
||||
// Permanent errors pause; give up after the retries.
|
||||
q = new DiscordRouteQueue();
|
||||
q.Add("p", 0, Max);
|
||||
DiscordBatch? b6 = q.Next(5000, on: true, Batch, Interval);
|
||||
q.Add("later", 5001, Max);
|
||||
Check(q.Apply(b6!, DiscordSendResult.Fail("HTTP 401", permanent: true, status: 401), 5100, Interval) == DiscordOutcome.Paused,
|
||||
"401 pauses");
|
||||
Check(q.Paused && q.Pending.Count == 0 && q.Next(600_000, on: true, Batch, Interval) == null, "a paused route sends nothing");
|
||||
q.Resume();
|
||||
Check(!q.Paused && q.LastError.Length == 0, "Resume clears a pause");
|
||||
|
||||
q = new DiscordRouteQueue();
|
||||
q.Add("doomed", 0, Max);
|
||||
long now = 5000;
|
||||
DiscordBatch? b7 = q.Next(now, on: true, Batch, Interval);
|
||||
DiscordOutcome last = DiscordOutcome.Ignored;
|
||||
for (int i = 0; i < DiscordRouteQueue.MaxTransientRetries && b7 != null; i++)
|
||||
{
|
||||
last = q.Apply(b7, fail, now, Interval);
|
||||
now += 120_000;
|
||||
b7 = q.Next(now, on: true, Batch, Interval);
|
||||
}
|
||||
Check(last == DiscordOutcome.GaveUp && q.Dropped == 1, "gives up after the retries");
|
||||
|
||||
q = new DiscordRouteQueue();
|
||||
for (int i = 0; i < 25; i++) q.Add("l" + i, 0, maxQueue: 20);
|
||||
Check(q.Pending.Count == 20 && q.Dropped == 5 && q.Pending[0] == "l5", "the oldest lines go past the queue limit");
|
||||
|
||||
Check(q.NoteFresh("k", 1000) && !q.NoteFresh("k", 2000) && q.NoteFresh("k", 1000 + DiscordRouteQueue.DedupWindowMs),
|
||||
"the repeat filter holds for its window");
|
||||
|
||||
// A new credential while a retry waits: the batch was for the old destination.
|
||||
const string Hook = DiscordRoute.ModeWebhook;
|
||||
q = new DiscordRouteQueue();
|
||||
Check(q.Retarget(Hook, "", "blobA") == 0, "the first destination drops nothing");
|
||||
q.Add("for A", 0, Max);
|
||||
DiscordBatch? a1 = q.Next(5000, on: true, Batch, Interval);
|
||||
Check(a1 != null && a1.Credential == q.Credential, "a batch remembers its destination");
|
||||
q.Apply(a1!, fail, 5100, Interval);
|
||||
q.Add("also for A", 5200, Max);
|
||||
Check(q.Retarget(Hook, "", "blobA") == 0 && ReferenceEquals(q.Retry, a1), "the same destination keeps the retry");
|
||||
Check(q.Retarget(Hook, "", new string("blobA".ToCharArray())) == 0, "an equal credential in a new string is the same destination");
|
||||
Check(q.Retarget(Hook, "", "blobB") == 2, "a new credential drops the waiting retry and pending lines");
|
||||
Check(q.Retry == null && q.Pending.Count == 0 && q.Next(600_000, on: true, Batch, Interval) == null,
|
||||
"nothing queued for A goes to B");
|
||||
q.Add("for B", 600_000, Max);
|
||||
Check(q.Next(700_000, on: true, Batch, Interval) is { Content: "for B" }, "new lines go to the new destination");
|
||||
|
||||
// A post in flight to the old destination fails after the change: dropped, not retried, no pause.
|
||||
q = new DiscordRouteQueue();
|
||||
q.Retarget(DiscordRoute.ModeBot, FakeChannel, "tokA");
|
||||
q.Add("to channel A", 0, Max);
|
||||
DiscordBatch? a2 = q.Next(5000, on: true, Batch, Interval);
|
||||
Check(q.Retarget(DiscordRoute.ModeBot, "8" + FakeChannel.Substring(1), "tokA") == 0, "a new channel with nothing waiting drops nothing");
|
||||
Check(q.Apply(a2!, fail, 5100, Interval) == DiscordOutcome.Retargeted && q.Retry == null, "a failed post to the old destination isn't retried");
|
||||
q.Add("x", 5200, Max);
|
||||
DiscordBatch? a3 = q.Next(600_000, on: true, Batch, Interval);
|
||||
q.Retarget(DiscordRoute.ModeWebhook, FakeChannel, "hook");
|
||||
Check(q.Apply(a3!, DiscordSendResult.Fail("HTTP 404", permanent: true, status: 404), 600_100, Interval) == DiscordOutcome.Retargeted
|
||||
&& !q.Paused, "the old destination's 404 doesn't pause the new one");
|
||||
|
||||
// A test follows the route to its new destination.
|
||||
q = new DiscordRouteQueue();
|
||||
q.Retarget(Hook, "", "old");
|
||||
q.QueueTest("t");
|
||||
q.Retarget(Hook, "", "new");
|
||||
Check(q.Retry is { IsTest: true } t2 && t2.Credential == q.Credential, "a waiting test goes to the new destination");
|
||||
}
|
||||
|
||||
// ── Engine shutdown closes the HTTP client ───────────────────────────
|
||||
|
||||
/// <summary>Last: after Shutdown no client is built again, so a post fails at once, sending nothing.</summary>
|
||||
private static void ClientShutdown()
|
||||
{
|
||||
DiscordClient.Shutdown();
|
||||
DiscordClient.Shutdown(); // twice is harmless
|
||||
var r = DiscordClient.PostWebhookAsync(FakeWebhook, "x", "", CancellationToken.None).GetAwaiter().GetResult();
|
||||
Check(!r.Ok && !r.Permanent && r.Error.Contains("ObjectDisposedException"), $"no posts after shutdown (got \"{r.Error}\")");
|
||||
Check(!r.Error.Contains(new string('x', 68)), "the refusal doesn't echo the webhook");
|
||||
}
|
||||
|
||||
// ── The panel never formats chat ─────────────────────────────────────
|
||||
|
||||
// ImGui.NET passes the string of these to ImGui as a printf format: "%s%s%s" in a relayed
|
||||
// tell crashed the client while the Discord panel's Log tab was open.
|
||||
private static readonly System.Text.RegularExpressions.Regex RxFormatCall = new(
|
||||
@"ImGui\.(?<fn>Text|TextWrapped|TextColored|TextDisabled|BulletText|LabelText|SetTooltip|SetItemTooltip|LogText)\(\s*(?<arg>[^\r\n]*)");
|
||||
|
||||
/// <summary>
|
||||
/// The face can't run here (it needs ImGui), so this reads its source: every call to an ImGui
|
||||
/// function that formats its text must be given a plain literal with no '%' conversions;
|
||||
/// anything else (chat, routes, Discord's errors) goes through TextUnformatted.
|
||||
/// </summary>
|
||||
private static void FaceText()
|
||||
{
|
||||
string face = Path.GetFullPath(Path.Combine(SourceDir(), "..", "..", "src", "RynthCore.Engine", "ImGui", "Panels", "ChatDiscordFace.cs"));
|
||||
Check(File.Exists(face), $"face source found ({face})");
|
||||
if (!File.Exists(face)) return;
|
||||
string src = File.ReadAllText(face);
|
||||
int calls = 0;
|
||||
foreach (System.Text.RegularExpressions.Match m in RxFormatCall.Matches(src))
|
||||
{
|
||||
calls++;
|
||||
string arg = m.Groups["arg"].Value;
|
||||
int line = src.Take(m.Index).Count(c => c == '\n') + 1;
|
||||
bool literal = arg.StartsWith('"');
|
||||
Check(literal, $"ChatDiscordFace.cs:{line}: ImGui.{m.Groups["fn"].Value} is given a non-literal (use TextUnformatted)");
|
||||
if (literal)
|
||||
Check(!arg.Replace("%%", "").Contains('%'), $"ChatDiscordFace.cs:{line}: '%' in a format string");
|
||||
}
|
||||
Check(calls > 0, "the face's tooltips are checked");
|
||||
Check(!src.Contains("TextWrapped("), "the face has no TextWrapped");
|
||||
Check(src.Contains("TextUnformatted("), "the face writes text with TextUnformatted");
|
||||
}
|
||||
|
||||
private static string SourceDir([System.Runtime.CompilerServices.CallerFilePath] string path = "")
|
||||
=> Path.GetDirectoryName(path)!;
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
private static string TempDir()
|
||||
{
|
||||
string dir = Path.Combine(Path.GetTempPath(), "ChatDiscordTests-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
private static void TryDelete(string dir)
|
||||
{
|
||||
try { Directory.Delete(dir, recursive: true); } catch { }
|
||||
}
|
||||
|
||||
private static void Same(string got, string want, string what)
|
||||
=> Check(got == want, $"{what}: want \"{want}\", got \"{got}\"");
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine("FAIL: " + what);
|
||||
}
|
||||
}
|
||||
28
tools/CreatureSizes/README.md
Normal file
28
tools/CreatureSizes/README.md
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# Creature sizes
|
||||
|
||||
The monster HUD anchors a plate above a creature's head, so it needs the creature's height. The client keeps
|
||||
that in memory (CPhysicsObj scale, CPartArray, CSetup height and selection sphere), but the engine does not map
|
||||
those layouts, so the HUD used to guess from the creature type and name. This builds the real numbers from data.
|
||||
|
||||
A creature's top = max(model height, selection sphere top) x its default scale. The model (Setup, 0x02xxxxxx)
|
||||
comes from `client_portal.dat`; the weenie's setup and default scale come from the ACE world database.
|
||||
|
||||
Output: `src/RynthCore.Engine/ImGui/MonsterHud/CreatureSizes.g.cs`, used through `CreatureSizes.TryGetTop(wcid)`.
|
||||
|
||||
## Regenerate
|
||||
|
||||
```powershell
|
||||
# 1. creature-like weenies with a setup (add the Aelrynth custom weenie .sql exports after the world dump)
|
||||
python parse_world.py C:\Projects\ACE-World-Database\ACE-World-Database-v0.9.293.sql -o out
|
||||
|
||||
# 2. each setup's height / radius / selection sphere / sorting sphere, from a folder holding client_portal.dat
|
||||
dotnet run --project SetupDims -c Release -- <dat dir> out\setups.json out\setups_dims.json
|
||||
|
||||
# 3. the table
|
||||
python gen_cs.py out\creatures.json out\setups_dims.json ..\..\src\RynthCore.Engine\ImGui\MonsterHud\CreatureSizes.g.cs
|
||||
```
|
||||
|
||||
Pass full Windows paths to step 2 (it is a Windows program). A creature with no row (a custom weenie that was not in
|
||||
the input, or a model with no height) falls back to the HUD's old estimate by creature type and name.
|
||||
|
||||
`tools/CreatureSizesTests` checks the lookup against the generated table.
|
||||
27
tools/CreatureSizes/SetupDims/Program.cs
Normal file
27
tools/CreatureSizes/SetupDims/Program.cs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
using System.Globalization;
|
||||
using System.Text;
|
||||
using ACE.DatLoader;
|
||||
using ACE.DatLoader.FileTypes;
|
||||
|
||||
// args: <dat dir> <setups.json> <out.json>
|
||||
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
|
||||
string datDir = args[0];
|
||||
string[] ids = System.Text.Json.JsonSerializer.Deserialize<string[]>(
|
||||
"[" + string.Join(",", System.Text.Json.JsonSerializer.Deserialize<uint[]>(File.ReadAllText(args[1]))!.Select(u => "\"" + u + "\"")) + "]")!;
|
||||
DatManager.Initialize(datDir, keepOpen: true, loadCell: false);
|
||||
var sb = new StringBuilder("{");
|
||||
int ok = 0, bad = 0; bool first = true;
|
||||
foreach (string s in ids)
|
||||
{
|
||||
uint id = uint.Parse(s);
|
||||
SetupModel m = DatManager.PortalDat.ReadFromDat<SetupModel>(id);
|
||||
if (m == null) { bad++; continue; }
|
||||
if (!first) sb.Append(',');
|
||||
first = false;
|
||||
string F(float v) => v.ToString("0.####", CultureInfo.InvariantCulture);
|
||||
sb.Append($"\"{id}\":[{F(m.Height)},{F(m.Radius)},{F(m.SelectionSphere.Origin.Z)},{F(m.SelectionSphere.Radius)},{F(m.SortingSphere.Origin.Z)},{F(m.SortingSphere.Radius)}]");
|
||||
ok++;
|
||||
}
|
||||
sb.Append('}');
|
||||
File.WriteAllText(args[2], sb.ToString());
|
||||
Console.WriteLine($"read {ok} setups, {bad} missing");
|
||||
18
tools/CreatureSizes/SetupDims/SetupDims.csproj
Normal file
18
tools/CreatureSizes/SetupDims/SetupDims.csproj
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- Step 2 of the creature size table (see ..\README.md): reads each Setup (model) from client_portal.dat
|
||||
with ACE's own dat reader. Needs a built ACE server; point AcBin at its bin folder if it is elsewhere. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>disable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<AcBin Condition="'$(AcBin)' == ''">C:\Projects\ACE\Source\ACE.Server\bin\x64\Release\net10.0</AcBin>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="ACE.DatLoader"><HintPath>$(AcBin)\ACE.DatLoader.dll</HintPath></Reference>
|
||||
<Reference Include="ACE.Common"><HintPath>$(AcBin)\ACE.Common.dll</HintPath></Reference>
|
||||
<Reference Include="ACE.Entity"><HintPath>$(AcBin)\ACE.Entity.dll</HintPath></Reference>
|
||||
<Reference Include="log4net"><HintPath>$(AcBin)\log4net.dll</HintPath></Reference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
50
tools/CreatureSizes/gen_cs.py
Normal file
50
tools/CreatureSizes/gen_cs.py
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
"""Step 3 of the creature size table (see README.md): writes CreatureSizes.g.cs.
|
||||
|
||||
usage: python gen_cs.py <creatures.json> <setups_dims.json> <out .cs>
|
||||
|
||||
A creature's top is max(model height, selection sphere top) x its default scale, in centimetres.
|
||||
Entries with no usable height (under 20 cm) are left out, so the HUD falls back to its estimate.
|
||||
A few creatures are scaled absurdly (a 400x "colossal" that is a trick, not a monster); tops
|
||||
over 120 m are capped.
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
creatures = json.load(open(sys.argv[1]))
|
||||
dims = json.load(open(sys.argv[2]))
|
||||
|
||||
rows = []
|
||||
for wcid, c in creatures.items():
|
||||
d = dims.get(str(c["setup"]))
|
||||
if not d:
|
||||
continue
|
||||
height, radius, sel_z, sel_r, sort_z, sort_r = d
|
||||
top = max(height, sel_z + sel_r) * c["scale"]
|
||||
if top < 0.2:
|
||||
continue
|
||||
rows.append((int(wcid), min(int(round(top * 100)), 12000)))
|
||||
rows.sort()
|
||||
|
||||
lines = [
|
||||
"// <auto-generated> by tools/CreatureSizes (gen_cs.py); do not edit. </auto-generated>",
|
||||
"// Weenie class id -> the creature's top in centimetres (model height x default scale).",
|
||||
"namespace RynthCore.Engine.ImGuiBackend.Hud;",
|
||||
"",
|
||||
"internal static partial class CreatureSizes",
|
||||
"{",
|
||||
" private static readonly int[] Wcids =",
|
||||
" {",
|
||||
]
|
||||
|
||||
|
||||
def chunk(values, per=12):
|
||||
for i in range(0, len(values), per):
|
||||
yield ", ".join(str(v) for v in values[i:i + per]) + ","
|
||||
|
||||
|
||||
lines += [" " + l for l in chunk([r[0] for r in rows])]
|
||||
lines += [" };", "", " private static readonly ushort[] TopCm =", " {"]
|
||||
lines += [" " + l for l in chunk([r[1] for r in rows], 16)]
|
||||
lines += [" };", "}", ""]
|
||||
open(sys.argv[3], "w", encoding="utf-8", newline="\n").write("\n".join(lines))
|
||||
print(len(rows), "creatures written to", sys.argv[3])
|
||||
62
tools/CreatureSizes/parse_world.py
Normal file
62
tools/CreatureSizes/parse_world.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
"""Step 1 of the creature size table (see README.md).
|
||||
|
||||
Reads the ACE world database dump and writes, to the output folder:
|
||||
creatures.json {weenie class id: {name, wtype, setup, scale}} for every creature-like weenie
|
||||
(creature, admin, vendor, cow, AI) that has a Setup (model) property
|
||||
setups.json the distinct setup ids, for SetupDims
|
||||
|
||||
usage: python parse_world.py <ACE-World-Database.sql> [<more weenie .sql files>] -o <out dir>
|
||||
|
||||
The extra files are weenie exports in the same INSERT format (the Aelrynth custom weenies).
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("sql", nargs="+")
|
||||
ap.add_argument("-o", "--out", default=".")
|
||||
args = ap.parse_args()
|
||||
|
||||
# weenie rows: (class_Id,'class_Name',type,'last_Modified')
|
||||
WEENIE_ROW = re.compile(r"\((\d+),'((?:[^'\\]|\\.|'')*)',(\d+),'[^']*'\)")
|
||||
PLAIN_ROW = re.compile(r"\(([^()]*)\)")
|
||||
|
||||
weenies, setup, scale = {}, {}, {}
|
||||
for path in args.sql:
|
||||
text = open(path, encoding="utf-8", errors="replace").read()
|
||||
|
||||
def inserts(table):
|
||||
for m in re.finditer(r"INSERT INTO `%s` VALUES (.*?);\n" % table, text, re.S):
|
||||
yield m.group(1)
|
||||
|
||||
for body in inserts("weenie"):
|
||||
for r in WEENIE_ROW.finditer(body):
|
||||
weenies[int(r.group(1))] = {"name": r.group(2), "wtype": int(r.group(3))}
|
||||
# property rows: (id, object_Id, type, value). Setup = DataId property 1, DefaultScale = float property 39.
|
||||
for body in inserts("weenie_properties_d_i_d"):
|
||||
for r in PLAIN_ROW.finditer(body):
|
||||
p = r.group(1).split(",")
|
||||
if len(p) == 4 and p[2] == "1":
|
||||
setup[int(p[1])] = int(p[3])
|
||||
for body in inserts("weenie_properties_float"):
|
||||
for r in PLAIN_ROW.finditer(body):
|
||||
p = r.group(1).split(",")
|
||||
if len(p) == 4 and p[2] == "39":
|
||||
scale[int(p[1])] = float(p[3])
|
||||
|
||||
out = {}
|
||||
for w, info in weenies.items():
|
||||
if info["wtype"] not in (10, 11, 12, 15, 16): # creature, admin, vendor, cow, AI
|
||||
continue
|
||||
if w not in setup:
|
||||
continue
|
||||
out[w] = {"name": info["name"], "wtype": info["wtype"], "setup": setup[w], "scale": scale.get(w, 1.0)}
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
json.dump(out, open(os.path.join(args.out, "creatures.json"), "w"))
|
||||
json.dump(sorted(set(v["setup"] for v in out.values())), open(os.path.join(args.out, "setups.json"), "w"))
|
||||
print(len(weenies), "weenies;", len(out), "creature-like with a setup;",
|
||||
len(set(v["setup"] for v in out.values())), "distinct setups;",
|
||||
sum(1 for v in out.values() if v["scale"] != 1.0), "with a default scale")
|
||||
12
tools/CreatureSizesTests/CreatureSizesTests.csproj
Normal file
12
tools/CreatureSizesTests/CreatureSizesTests.csproj
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\CreatureSizes.cs" Link="Engine\CreatureSizes.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\CreatureSizes.g.cs" Link="Engine\CreatureSizes.g.cs" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
31
tools/CreatureSizesTests/Program.cs
Normal file
31
tools/CreatureSizesTests/Program.cs
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
// Checks CreatureSizes (the lookup over the generated table) against creatures with known heights.
|
||||
using RynthCore.Engine.ImGuiBackend.Hud;
|
||||
|
||||
int pass = 0, fail = 0;
|
||||
void Check(string what, bool ok, string detail = "")
|
||||
{
|
||||
if (ok) pass++;
|
||||
else { fail++; Console.WriteLine($"FAIL {what} {detail}"); }
|
||||
}
|
||||
|
||||
void Top(uint wcid, string name, float expected)
|
||||
{
|
||||
bool found = CreatureSizes.TryGetTop(wcid, out float m);
|
||||
Check($"{name} ({wcid}) is in the table", found);
|
||||
Check($"{name} ({wcid}) top", found && MathF.Abs(m - expected) < 0.006f, $"got {m}, want {expected}");
|
||||
}
|
||||
|
||||
Check("the table is not empty", CreatureSizes.Count > 8000, $"count {CreatureSizes.Count}");
|
||||
|
||||
Top(1, "human", 1.84f);
|
||||
Top(5, "lugianlaigus", 2.08f);
|
||||
Top(185, "bandit", 1.84f);
|
||||
Top(1621, "olthoiqueen", 2.59f);
|
||||
Top(1756, "shadowchild", 0.92f); // a default scale of 0.5 halves its model
|
||||
|
||||
// Unknown ids fall through to the HUD's estimate.
|
||||
Check("wcid 0 is unknown", !CreatureSizes.TryGetTop(0, out _));
|
||||
Check("a huge id is unknown", !CreatureSizes.TryGetTop(uint.MaxValue, out _));
|
||||
|
||||
Console.WriteLine($"{(fail == 0 ? "PASS" : "FAIL")} {pass} checks, {fail} failed");
|
||||
return fail == 0 ? 0 : 1;
|
||||
|
|
@ -5,7 +5,10 @@
|
|||
compiled in): which registry view a Decal client reads its filter list from (per-user
|
||||
VirtualStore copy vs machine-wide HKLM) for non-elevated / elevated / UAC-off /
|
||||
manifest / run-as-administrator clients, and every check line, against a fake registry.
|
||||
Never touches the real registry.
|
||||
Plus DecalBridgeRegistration (register / unregister / Repair Decal, RegistrationTests.cs)
|
||||
against a scratch registry under HKCU\Software\RynthCoreTests\<run> and a temp folder,
|
||||
deleted after each scenario. The real Decal keys and VirtualStore copies are only read
|
||||
(before and after, to prove they did not change).
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ namespace DecalBridgeCheckTests;
|
|||
/// (2026-10-03, release 2026.10.3.1) is "elevated client, per-user registration only":
|
||||
/// Decal reads HKLM, the per-user entry is invisible, the bridge never loads.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
internal static partial class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
|
||||
|
|
@ -287,6 +287,8 @@ internal static class Program
|
|||
Check(RealDecalCheckHost.LevelIn("<assembly><description>x</description></assembly>") == null, "no element");
|
||||
});
|
||||
|
||||
RegistrationScenarios();
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(_failed == 0 ? $"PASS: {_checks} checks" : $"FAIL: {_failed} of {_checks} checks failed");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
|
|
|
|||
399
tools/DecalBridgeCheckTests/RegistrationTests.cs
Normal file
399
tools/DecalBridgeCheckTests/RegistrationTests.cs
Normal file
|
|
@ -0,0 +1,399 @@
|
|||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Win32;
|
||||
using RynthCore.App;
|
||||
|
||||
namespace DecalBridgeCheckTests;
|
||||
|
||||
/// <summary>
|
||||
/// DecalBridgeRegistration (register / unregister / Repair Decal) against a scratch registry:
|
||||
/// HKCU\Software\RynthCoreTests\<run>\Machine stands in for HKLM (32-bit view) and
|
||||
/// ...\User for HKCU (DecalRegistryRoots.ForTests), with a temp folder for %APPDATA%\RynthCore.
|
||||
/// Every scenario deletes its scratch key and folder. The real Decal keys and the real
|
||||
/// VirtualStore copies are only read, before and after, to prove nothing changed there.
|
||||
/// </summary>
|
||||
internal static partial class Program
|
||||
{
|
||||
private static readonly string VsNetworkFilters = DecalBridgeCheck.VirtualStoreDecalPath(true, "NetworkFilters");
|
||||
private const string VsDecalWow = @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\WOW6432Node\Decal";
|
||||
private const string VsDecalPlain = @"Software\Classes\VirtualStore\MACHINE\SOFTWARE\Decal";
|
||||
private const string MachineFilters = @"SOFTWARE\Decal\NetworkFilters";
|
||||
private const string ForeignId = "{AAAAAAAA-1111-2222-3333-444444444444}";
|
||||
private const string LateId = "{BBBBBBBB-1111-2222-3333-444444444444}"; // a filter installed for all users after the copy was made
|
||||
|
||||
private static void RegistrationScenarios()
|
||||
{
|
||||
string realBefore = RealDecalFingerprint();
|
||||
|
||||
RegScenario("ForTests refuses a root outside HKCU\\Software\\RynthCoreTests", _ =>
|
||||
{
|
||||
bool threw = false;
|
||||
try { DecalRegistryRoots.ForTests(@"Software\Classes\VirtualStore\X", Path.GetTempPath(), () => true); }
|
||||
catch (ArgumentException) { threw = true; }
|
||||
Check(threw, "ArgumentException");
|
||||
});
|
||||
|
||||
RegScenario("register, HKLM not writable: NeedsAdmin and NO per-user copy", t =>
|
||||
{
|
||||
t.MachineWritable = false;
|
||||
var log = new List<string>();
|
||||
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
|
||||
Check(o == DecalBridgeRegistration.Outcome.NeedsAdmin, $"NeedsAdmin (got {o}: {string.Join(" ", log)})");
|
||||
Check(!t.UserExists(VsNetworkFilters), "no per-user NetworkFilters copy created");
|
||||
Check(!t.UserExists(@"Software\Classes\VirtualStore"), "nothing written under the VirtualStore at all");
|
||||
Check(!t.MachineExists(MachineFilters + "\\" + Guid), "no machine entry");
|
||||
Check(t.StateFiles().Length == 0, "no record file written");
|
||||
});
|
||||
|
||||
RegScenario("register, HKLM writable (the elevated step): machine entry only", t =>
|
||||
{
|
||||
var log = new List<string>();
|
||||
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
|
||||
Check(o == DecalBridgeRegistration.Outcome.Registered, $"Registered ({string.Join(" ", log)})");
|
||||
using (RegistryKey? e = t.OpenMachine(MachineFilters + "\\" + Guid))
|
||||
{
|
||||
Check(e?.GetValue("Object") as string == DecalBridgeRegistration.FilterObject, "Object");
|
||||
Check(e?.GetValue("Path") as string == t.BridgeDir, "Path");
|
||||
Check(e?.GetValue("Enabled") is int en && en == 1, "Enabled=1");
|
||||
}
|
||||
Check(!t.UserExists(VsNetworkFilters), "no per-user copy");
|
||||
t.MachineWritable = false; // the non-elevated launcher afterwards
|
||||
log.Clear();
|
||||
o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
|
||||
Check(o == DecalBridgeRegistration.Outcome.Registered && log.Any(l => l.Contains("already")), "second call without rights: already registered, no prompt needed");
|
||||
Check(!t.UserExists(VsNetworkFilters), "still no per-user copy");
|
||||
});
|
||||
|
||||
RegScenario("a per-user copy Decal made itself: our entry goes in, the copy is never deleted", t =>
|
||||
{
|
||||
t.SetUser(VsNetworkFilters + "\\" + StockIds[0], new() { [""] = "World Object Filter", ["Enabled"] = 0 }); // Decal toggled it
|
||||
var log = new List<string>();
|
||||
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
|
||||
Check(o == DecalBridgeRegistration.Outcome.Registered, $"Registered ({string.Join(" ", log)})");
|
||||
Check(t.UserExists(VsNetworkFilters + "\\" + Guid), "bridge entry added to the existing copy");
|
||||
Check(DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "cleanup needed (our entry is there)");
|
||||
bool ok = DecalBridgeRegistration.UnregisterCore(t.Roots, out string report);
|
||||
Check(ok, "unregister ok: " + report);
|
||||
Check(!t.UserExists(VsNetworkFilters + "\\" + Guid), "bridge entry removed");
|
||||
Check(t.UserExists(VsNetworkFilters + "\\" + StockIds[0]), "Decal's own entry kept");
|
||||
Check(t.BackupFiles().Length == 0, "no backup needed (only our entry removed)");
|
||||
Check(!DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "nothing left to clean up");
|
||||
});
|
||||
|
||||
RegScenario("an earlier RynthCore's copy: left alone while HKLM can't be written, migrated once it can", t =>
|
||||
{
|
||||
t.MakeOldLauncherCopy();
|
||||
string before = t.UserFingerprint(VsNetworkFilters);
|
||||
t.MachineWritable = false;
|
||||
var log = new List<string>();
|
||||
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
|
||||
Check(o == DecalBridgeRegistration.Outcome.NeedsAdmin, "NeedsAdmin");
|
||||
Check(t.UserFingerprint(VsNetworkFilters) == before, "copy untouched until the machine entry exists");
|
||||
|
||||
t.MachineWritable = true;
|
||||
log.Clear();
|
||||
o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
|
||||
Check(o == DecalBridgeRegistration.Outcome.Registered, $"Registered ({string.Join(" ", log)})");
|
||||
Check(t.MachineExists(MachineFilters + "\\" + Guid), "machine entry");
|
||||
Check(!t.UserExists(VsNetworkFilters), "the old copy is gone (Decal reads HKLM again)");
|
||||
Check(t.StateFiles().Length == 0, "record file deleted");
|
||||
string[] backups = t.BackupFiles();
|
||||
Check(backups.Length == 1 && Path.GetFileName(backups[0]).StartsWith("decal-backup-"), "one decal-backup-<date>.reg");
|
||||
string text = backups.Length == 1 ? File.ReadAllText(backups[0]) : "";
|
||||
Check(text.StartsWith("Windows Registry Editor Version 5.00") && text.Contains(Guid) && text.Contains(StockIds[0]), "backup holds the copy (bridge + mirrors)");
|
||||
Check(log.Any(l => l.Contains("backup:")), "log names the backup");
|
||||
});
|
||||
|
||||
RegScenario("uninstall: an earlier RynthCore's copy goes, whatever is in it now", t =>
|
||||
{
|
||||
t.MakeOldLauncherCopy();
|
||||
// Changed since: Decal disabled a mirrored filter, and wrote a filter installed for
|
||||
// all users later (in HKLM, not in the record) into the copy.
|
||||
t.SetMachine(MachineFilters + "\\" + LateId, new() { [""] = "UtilityBelt Service", ["Enabled"] = 1 });
|
||||
t.SetUser(VsNetworkFilters + "\\" + StockIds[1], new() { [""] = "Echo Filter 2", ["Enabled"] = 0 });
|
||||
t.SetUser(VsNetworkFilters + "\\" + LateId, new() { [""] = "UtilityBelt Service", ["Enabled"] = 1 });
|
||||
string machineBefore = t.MachineFingerprint(MachineFilters);
|
||||
Check(DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "cleanup needed");
|
||||
bool ok = DecalBridgeRegistration.UnregisterCore(t.Roots, out string report);
|
||||
Check(ok, "unregister ok: " + report);
|
||||
Check(!t.UserExists(VsNetworkFilters), "copy removed (bridge, changed and unrecorded mirrors, key)");
|
||||
Check(t.StateFiles().Length == 0, "record deleted");
|
||||
Check(t.BackupFiles().Length == 1, "backed up first");
|
||||
Check(t.MachineFingerprint(MachineFilters) == machineBefore, "HKLM untouched");
|
||||
Check(!DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "nothing left");
|
||||
});
|
||||
|
||||
RegScenario("uninstall: entries that are neither ours nor in HKLM keep the copy", t =>
|
||||
{
|
||||
t.MakeOldLauncherCopy();
|
||||
t.SetUser(VsNetworkFilters + "\\" + ForeignId, new() { [""] = "Someone's Filter", ["Enabled"] = 1 });
|
||||
bool ok = DecalBridgeRegistration.UnregisterCore(t.Roots, out string report);
|
||||
Check(ok, "unregister ok: " + report);
|
||||
Check(t.UserExists(VsNetworkFilters + "\\" + ForeignId), "foreign entry kept");
|
||||
Check(!t.UserExists(VsNetworkFilters + "\\" + Guid), "our entry removed");
|
||||
Check(t.UserExists(VsNetworkFilters + "\\" + StockIds[0]), "mirrors kept with it (a copy of only the foreign entry would hide World Object Filter)");
|
||||
Check(report.Contains("Someone's Filter") && report.Contains("Repair Decal"), "logged, with the way out");
|
||||
Check(t.StateFiles().Length == 1, "record kept for a later cleanup");
|
||||
Check(t.BackupFiles().Length == 0, "no backup (nothing but our entry removed)");
|
||||
Check(!DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "not 'needed' again at every start");
|
||||
// Register with such a copy: the bridge must stay visible in it.
|
||||
var log = new List<string>();
|
||||
var o = DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
|
||||
Check(o == DecalBridgeRegistration.Outcome.Registered && t.UserExists(VsNetworkFilters + "\\" + Guid), "register: copy kept, our entry back in it");
|
||||
Check(t.UserExists(VsNetworkFilters + "\\" + ForeignId), "foreign entry still kept");
|
||||
});
|
||||
|
||||
RegScenario("no account uses Decal + RynthCore: machine entry removed (only this install's)", t =>
|
||||
{
|
||||
var log = new List<string>();
|
||||
DecalBridgeRegistration.RegisterCore(t.Roots, t.BridgeDir, log);
|
||||
Check(!DecalBridgeRegistration.PerUserCleanupNeededCore(t.Roots), "nothing per-user to remove (no prompt-free work to do)");
|
||||
Check(DecalBridgeRegistration.MachineEntryIsOursCore(t.Roots, t.BridgeDir), "entry is this install's");
|
||||
string other = Path.Combine(t.DataDir, "OtherInstall");
|
||||
Directory.CreateDirectory(other);
|
||||
File.WriteAllText(Path.Combine(other, DecalBridgeRegistration.AssemblyFile), "");
|
||||
Check(!DecalBridgeRegistration.MachineEntryIsOursCore(t.Roots, other), "another install's folder: not ours to remove");
|
||||
t.MachineWritable = false;
|
||||
log.Clear();
|
||||
Check(DecalBridgeRegistration.UnregisterMachineWideCore(t.Roots, t.BridgeDir, log) == DecalBridgeRegistration.Outcome.NeedsAdmin, "needs admin without rights");
|
||||
Check(t.MachineExists(MachineFilters + "\\" + Guid), "still there");
|
||||
t.MachineWritable = true;
|
||||
log.Clear();
|
||||
Check(DecalBridgeRegistration.UnregisterMachineWideCore(t.Roots, t.BridgeDir, log) == DecalBridgeRegistration.Outcome.Registered, "removed: " + string.Join(" ", log));
|
||||
Check(!t.MachineExists(MachineFilters + "\\" + Guid), "gone");
|
||||
Check(t.MachineExists(MachineFilters + "\\" + StockIds[0]), "other filters untouched");
|
||||
Check(!DecalBridgeRegistration.MachineEntryIsOursCore(t.Roots, t.BridgeDir), "nothing to ask about at the next start");
|
||||
t.MachineWritable = false;
|
||||
log.Clear();
|
||||
Check(DecalBridgeRegistration.UnregisterMachineWideCore(t.Roots, t.BridgeDir, log) == DecalBridgeRegistration.Outcome.Registered, "nothing to remove: no rights needed");
|
||||
});
|
||||
|
||||
RegScenario("dangling machine entry (DLL gone) counts as ours to remove", t =>
|
||||
{
|
||||
var gone = BridgeEntryAt(Path.Combine(t.DataDir, "Gone"));
|
||||
t.SetMachine(MachineFilters + "\\" + Guid, gone);
|
||||
Check(DecalBridgeRegistration.MachineEntryIsOursCore(t.Roots, t.BridgeDir), "dangling = ours");
|
||||
});
|
||||
|
||||
RegScenario("Repair Decal: backup, then delete both VirtualStore Decal keys; the backup restores", t =>
|
||||
{
|
||||
t.MakeOldLauncherCopy();
|
||||
t.SetUser(VsDecalWow + "\\Plugins\\{CCCCCCCC-1111-2222-3333-444444444444}", new() { [""] = "Some Plugin", ["Enabled"] = 1 });
|
||||
t.SetUser(VsDecalWow, new() { ["BarAlpha"] = 255, ["BarState"] = "1" });
|
||||
t.SetUser(VsDecalPlain + "\\Plugins", new() { ["X"] = "y" });
|
||||
string wowBefore = t.UserFingerprint(VsDecalWow), plainBefore = t.UserFingerprint(VsDecalPlain);
|
||||
List<string> found = DecalBridgeRegistration.FindVirtualStoreDecalKeysCore(t.Roots);
|
||||
Check(found.Count == 2, "both spellings found");
|
||||
|
||||
var r = DecalBridgeRegistration.RepairDecalCore(t.Roots);
|
||||
Check(r.Ok, "ok: " + r.Report);
|
||||
Check(r.Removed.Count == 2 && r.Removed.All(k => k.StartsWith(@"HKCU\Software\Classes\VirtualStore\")), "reports both keys as HKCU paths");
|
||||
Check(!t.UserExists(VsDecalWow) && !t.UserExists(VsDecalPlain), "both deleted");
|
||||
Check(r.BackupPath != null && File.Exists(r.BackupPath), "backup file exists");
|
||||
Check(t.StateFiles().Length == 0, "the earlier RynthCore's record goes with its copy");
|
||||
string text = r.BackupPath != null ? File.ReadAllText(r.BackupPath) : "";
|
||||
Check(text.Contains("BarAlpha") && text.Contains("Some Plugin") && text.Contains(Guid), "backup has values, plugins, filters");
|
||||
int headers = text.Split("Windows Registry Editor Version 5.00").Length - 1;
|
||||
Check(headers == 1, "one .reg header for both keys");
|
||||
|
||||
// Round trip, only into the scratch key: every section in the file must be under it.
|
||||
string root = @"[HKEY_CURRENT_USER\" + t.Key + @"\User\";
|
||||
bool allScratch = text.Split('\n').Where(l => l.StartsWith("[")).All(l => l.StartsWith(root, StringComparison.OrdinalIgnoreCase));
|
||||
Check(allScratch, "every key in the backup is under the scratch root");
|
||||
if (allScratch && r.BackupPath != null)
|
||||
{
|
||||
Check(RegImport(r.BackupPath), "reg import of the backup");
|
||||
Check(t.UserFingerprint(VsDecalWow) == wowBefore && t.UserFingerprint(VsDecalPlain) == plainBefore, "restored exactly");
|
||||
}
|
||||
});
|
||||
|
||||
RegScenario("Repair Decal with nothing to repair", t =>
|
||||
{
|
||||
var r = DecalBridgeRegistration.RepairDecalCore(t.Roots);
|
||||
Check(r.Ok && r.Removed.Count == 0 && r.BackupPath == null && t.BackupFiles().Length == 0, "nothing removed, no backup");
|
||||
});
|
||||
|
||||
RegScenario("Repair Decal: a failed backup deletes nothing", t =>
|
||||
{
|
||||
t.SetUser(VsDecalWow + "\\Plugins", new() { ["X"] = "y" });
|
||||
string blocker = Path.Combine(t.DataDir, "not-a-folder");
|
||||
File.WriteAllText(blocker, "");
|
||||
var roots = DecalRegistryRoots.ForTests(t.Key, Path.Combine(blocker, "sub"), () => true);
|
||||
var r = DecalBridgeRegistration.RepairDecalCore(roots);
|
||||
Check(!r.Ok && r.Removed.Count == 0 && r.Report.Contains("backup failed"), "stopped: " + r.Report);
|
||||
Check(t.UserExists(VsDecalWow + "\\Plugins"), "key still there");
|
||||
});
|
||||
|
||||
RegScenario("status reads the scratch registry", t =>
|
||||
{
|
||||
t.MakeOldLauncherCopy();
|
||||
t.SetMachine(MachineFilters + "\\" + LateId, new() { [""] = "UtilityBelt Service", ["Enabled"] = 1 });
|
||||
var s = DecalBridgeRegistration.GetStatusCore(t.Roots);
|
||||
Check(s.DecalInstalled && s.PerUserKeyExists && s.PerUserKeyCreatedByUs && s.RegisteredPerUser, "copy, ours, bridge in it");
|
||||
Check(s.HiddenMachineFilters.Contains("UtilityBelt Service"), "the later filter is hidden (the player's bug)");
|
||||
});
|
||||
|
||||
string realAfter = RealDecalFingerprint();
|
||||
Scenario("the real Decal keys and VirtualStore copies did not change", () =>
|
||||
Check(realAfter == realBefore, "real HKLM Decal + HKCU VirtualStore Decal fingerprints match"));
|
||||
Scenario("no scratch keys left", () =>
|
||||
{
|
||||
using RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
|
||||
using RegistryKey? left = hkcu.OpenSubKey(@"Software\RynthCoreTests");
|
||||
Check(left == null || left.SubKeyCount == 0, @"HKCU\Software\RynthCoreTests empty or gone");
|
||||
});
|
||||
}
|
||||
|
||||
private static readonly string[] StockIds = Stock.Select(s => s.Id).ToArray();
|
||||
|
||||
private static Dictionary<string, object> BridgeEntryAt(string dir) => new()
|
||||
{
|
||||
[""] = DecalBridgeRegistration.FilterName,
|
||||
["Enabled"] = 1,
|
||||
["Assembly"] = DecalBridgeRegistration.AssemblyFile,
|
||||
["Path"] = dir,
|
||||
["Object"] = DecalBridgeRegistration.FilterObject,
|
||||
["Surrogate"] = DecalBridgeCheck.SurrogateClsid,
|
||||
};
|
||||
|
||||
private static void RegScenario(string name, Action<RegTestBed> body)
|
||||
{
|
||||
Scenario(name, () =>
|
||||
{
|
||||
using var t = new RegTestBed();
|
||||
body(t);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Read only: the real HKLM Decal tree and the real VirtualStore Decal keys.</summary>
|
||||
private static string RealDecalFingerprint()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32))
|
||||
using (RegistryKey? d = hklm.OpenSubKey(@"SOFTWARE\Decal"))
|
||||
sb.Append("HKLM:").Append(d == null ? "<none>" : DecalBridgeRegistration.Fingerprint(d));
|
||||
using (RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64))
|
||||
{
|
||||
foreach (string k in DecalBridgeRegistration.VirtualStoreDecalKeys)
|
||||
{
|
||||
using RegistryKey? v = hkcu.OpenSubKey(k);
|
||||
sb.Append('|').Append(k).Append(':').Append(v == null ? "<none>" : DecalBridgeRegistration.Fingerprint(v));
|
||||
}
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
private static bool RegImport(string file)
|
||||
{
|
||||
var psi = new System.Diagnostics.ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "reg.exe"))
|
||||
{
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true,
|
||||
RedirectStandardError = true,
|
||||
RedirectStandardOutput = true,
|
||||
};
|
||||
psi.ArgumentList.Add("import");
|
||||
psi.ArgumentList.Add(file);
|
||||
psi.ArgumentList.Add("/reg:64");
|
||||
using var p = System.Diagnostics.Process.Start(psi)!;
|
||||
p.StandardOutput.ReadToEnd();
|
||||
string err = p.StandardError.ReadToEnd();
|
||||
p.WaitForExit(30_000);
|
||||
if (p.ExitCode != 0) Console.WriteLine(" reg import: " + err.Trim());
|
||||
return p.ExitCode == 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A scratch registry + folder for one scenario; deleted on Dispose.</summary>
|
||||
internal sealed class RegTestBed : IDisposable
|
||||
{
|
||||
public string Key { get; } = @"Software\RynthCoreTests\DecalBridge-" + Guid.NewGuid().ToString("N");
|
||||
public string DataDir { get; } = Path.Combine(Path.GetTempPath(), "RynthCoreTests", Guid.NewGuid().ToString("N"));
|
||||
public string BridgeDir { get; }
|
||||
public bool MachineWritable { get; set; } = true;
|
||||
public DecalRegistryRoots Roots { get; }
|
||||
|
||||
private static readonly (string Id, string Name)[] Stock =
|
||||
{
|
||||
("{53092D1B-F0B0-46FF-BF11-8F031EC9B137}", "World Object Filter"),
|
||||
("{34239EAD-6317-4c40-A405-193BA5232DD8}", "Echo Filter 2"),
|
||||
};
|
||||
|
||||
public RegTestBed()
|
||||
{
|
||||
Roots = DecalRegistryRoots.ForTests(Key, DataDir, () => MachineWritable);
|
||||
BridgeDir = Path.Combine(DataDir, "DecalBridge");
|
||||
Directory.CreateDirectory(BridgeDir);
|
||||
File.WriteAllText(Path.Combine(BridgeDir, DecalBridgeRegistration.AssemblyFile), "");
|
||||
// A machine with Decal and two stock filters (stands in for HKLM, 32-bit view).
|
||||
SetMachine(@"SOFTWARE\Decal\Agent", new() { ["AgentPath"] = @"C:\Program Files (x86)\Decal 3.0\" });
|
||||
SetMachine(@"SOFTWARE\Decal\NetworkFilters", new() { ["Version"] = "2.9.8.3" });
|
||||
foreach (var f in Stock)
|
||||
SetMachine(@"SOFTWARE\Decal\NetworkFilters\" + f.Id, new() { [""] = f.Name, ["Enabled"] = 1 });
|
||||
}
|
||||
|
||||
/// <summary>What a launcher before 2026-10-10 left: a full mirror + our entry + its record file.</summary>
|
||||
public void MakeOldLauncherCopy()
|
||||
{
|
||||
string vs = DecalBridgeCheck.VirtualStoreDecalPath(true, "NetworkFilters");
|
||||
SetUser(vs, new() { ["Version"] = "2.9.8.3" });
|
||||
foreach (var f in Stock)
|
||||
SetUser(vs + "\\" + f.Id, new() { [""] = f.Name, ["Enabled"] = 1 });
|
||||
SetUser(vs + "\\" + DecalBridgeRegistration.FilterGuid, new()
|
||||
{
|
||||
[""] = DecalBridgeRegistration.FilterName,
|
||||
["Enabled"] = 1,
|
||||
["Assembly"] = DecalBridgeRegistration.AssemblyFile,
|
||||
["Path"] = BridgeDir,
|
||||
["Object"] = DecalBridgeRegistration.FilterObject,
|
||||
["Surrogate"] = DecalBridgeCheck.SurrogateClsid,
|
||||
});
|
||||
var state = new
|
||||
{
|
||||
CreatedFiltersKey = true,
|
||||
BridgePath = BridgeDir,
|
||||
RegisteredUtc = new DateTime(2026, 9, 30, 0, 0, 0, DateTimeKind.Utc),
|
||||
MirroredKeys = Stock.ToDictionary(f => f.Id, f => "print"),
|
||||
MirroredValues = new Dictionary<string, string> { ["Version"] = "print" },
|
||||
};
|
||||
File.WriteAllText(Path.Combine(DataDir, DecalBridgeRegistration.StateFileName), JsonSerializer.Serialize(state));
|
||||
}
|
||||
|
||||
public void SetMachine(string path, Dictionary<string, object> values) => Set("Machine", path, values);
|
||||
public void SetUser(string path, Dictionary<string, object> values) => Set("User", path, values);
|
||||
public bool MachineExists(string path) { using var k = OpenMachine(path); return k != null; }
|
||||
public bool UserExists(string path) { using var k = Open("User", path); return k != null; }
|
||||
public RegistryKey? OpenMachine(string path) => Open("Machine", path);
|
||||
public string MachineFingerprint(string path) { using var k = Open("Machine", path); return k == null ? "<none>" : DecalBridgeRegistration.Fingerprint(k); }
|
||||
public string UserFingerprint(string path) { using var k = Open("User", path); return k == null ? "<none>" : DecalBridgeRegistration.Fingerprint(k); }
|
||||
public string[] StateFiles() => Directory.Exists(DataDir) ? Directory.GetFiles(DataDir, DecalBridgeRegistration.StateFileName) : Array.Empty<string>();
|
||||
public string[] BackupFiles() => Directory.Exists(DataDir) ? Directory.GetFiles(DataDir, "decal-backup-*.reg") : Array.Empty<string>();
|
||||
|
||||
private RegistryKey? Open(string part, string path)
|
||||
{
|
||||
using RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
|
||||
return hkcu.OpenSubKey(Key + "\\" + part + "\\" + path);
|
||||
}
|
||||
|
||||
private void Set(string part, string path, Dictionary<string, object> values)
|
||||
{
|
||||
using RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
|
||||
using RegistryKey k = hkcu.CreateSubKey(Key + "\\" + part + "\\" + path, writable: true);
|
||||
foreach (var kv in values)
|
||||
k.SetValue(kv.Key, kv.Value, kv.Value is int ? RegistryValueKind.DWord : RegistryValueKind.String);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
using RegistryKey hkcu = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64);
|
||||
try { hkcu.DeleteSubKeyTree(Key, throwOnMissingSubKey: false); } catch (Exception ex) { Console.WriteLine($" (cleanup of HKCU\\{Key} failed: {ex.Message})"); }
|
||||
try
|
||||
{
|
||||
using RegistryKey? parent = hkcu.OpenSubKey(@"Software\RynthCoreTests");
|
||||
if (parent != null && parent.SubKeyCount == 0 && parent.ValueCount == 0)
|
||||
hkcu.DeleteSubKey(@"Software\RynthCoreTests", throwOnMissingSubKey: false);
|
||||
}
|
||||
catch { }
|
||||
try { if (Directory.Exists(DataDir)) Directory.Delete(DataDir, recursive: true); } catch { }
|
||||
}
|
||||
}
|
||||
|
|
@ -22,6 +22,7 @@
|
|||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettings.cs" Link="Engine\EngineSettings.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Plugins\EngineSettingsFile.cs" Link="Engine\EngineSettingsFile.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\ReloadCapNotice.cs" Link="Engine\ReloadCapNotice.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -49,6 +49,7 @@ namespace EngineSettingsTests
|
|||
Run(nameof(SaveRoundTripsOwnedKeys), SaveRoundTripsOwnedKeys);
|
||||
Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys);
|
||||
Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone);
|
||||
Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -85,6 +86,7 @@ namespace EngineSettingsTests
|
|||
Console.WriteLine("DecalBridge=" + EngineSettings.DecalBridgeMode);
|
||||
Console.WriteLine("ImGuiBackend=" + EngineSettings.EnableImGuiBackend);
|
||||
Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream);
|
||||
Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads);
|
||||
break;
|
||||
default: throw new ArgumentException(args[0]);
|
||||
}
|
||||
|
|
@ -252,6 +254,52 @@ namespace EngineSettingsTests
|
|||
Eq(ReadJson(emptyPath).GetProperty("DisabledUiHooks")[0].GetString(), "StartTooltip", "empty: rewritten with the change");
|
||||
}
|
||||
|
||||
// engine.json "MaxHotReloads" (the loader's hot-reload cap): default 3, a hand-set value
|
||||
// (including -1 = no cap) is read and survives the engine's own saves, the default is
|
||||
// never written, and a value that isn't a whole number is ignored.
|
||||
private static void MaxHotReloadsReadAndKept()
|
||||
{
|
||||
string dir = NewDir("maxreloads");
|
||||
string path = Path.Combine(dir, "engine.json");
|
||||
|
||||
File.WriteAllText(path, LauncherFile);
|
||||
var (exit, output) = RunChild(path, "dump");
|
||||
Eq(exit, 0, "dump (missing)");
|
||||
Eq(DumpValue(output, "MaxHotReloads"), "3", "missing: the default");
|
||||
Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the default");
|
||||
Check(!ReadJson(path).TryGetProperty("MaxHotReloads", out _), "the default isn't written to the file");
|
||||
|
||||
foreach ((string json, string expected) in new[] { ("5", "5"), ("-1", "-1"), ("0", "0") })
|
||||
{
|
||||
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"MaxHotReloads\": {json}, \"LoggingLevel\""));
|
||||
(exit, output) = RunChild(path, "dump");
|
||||
Eq(exit, 0, $"{json}: dump");
|
||||
Eq(DumpValue(output, "MaxHotReloads"), expected, $"{json}: read back");
|
||||
Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, $"{json}: save");
|
||||
Eq(ReadJson(path).GetProperty("MaxHotReloads").GetRawText(), json, $"{json}: kept by the engine's save");
|
||||
Eq(DumpValue(RunChild(path, "dump").Out, "MaxHotReloads"), expected, $"{json}: still the same after the save");
|
||||
}
|
||||
|
||||
foreach (string bad in new[] { "\"lots\"", "2.5", "true", "null" })
|
||||
{
|
||||
File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"MaxHotReloads\": {bad}, \"LoggingLevel\""));
|
||||
(exit, output) = RunChild(path, "dump");
|
||||
Eq(exit, 0, $"{bad}: dump");
|
||||
Eq(DumpValue(output, "MaxHotReloads"), "3", $"{bad}: ignored, the default");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The value of a "Name=value" line of the child's dump output ("" if none).</summary>
|
||||
private static string DumpValue(string output, string name)
|
||||
{
|
||||
foreach (string line in output.Split('\n'))
|
||||
{
|
||||
string l = line.TrimEnd('\r');
|
||||
if (l.StartsWith(name + "=", StringComparison.Ordinal)) return l.Substring(name.Length + 1);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
// ── EngineSettingsFile, direct ──────────────────────────────────────────
|
||||
|
||||
private static byte[] Owned(string json) => Encoding.UTF8.GetBytes(json);
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
<RootNamespace>RynthCore.HookResolver.UI</RootNamespace>
|
||||
<AssemblyName>RynthCore.HookResolver.UI</AssemblyName>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<Version>1.0.1</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
@ -18,6 +19,8 @@
|
|||
<PackageReference Include="Avalonia.Desktop" Version="11.2.3" />
|
||||
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.3" />
|
||||
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.3" />
|
||||
<!-- Direct reference overrides Avalonia's transitive 0.20.x (NU1903 / GHSA-xrw6-gwf8-vvr9). -->
|
||||
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
24
tools/IltTests/IltTests.csproj
Normal file
24
tools/IltTests/IltTests.csproj
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the engine's Infinite Leaftide detection
|
||||
(src\RynthCore.Engine\Compatibility\IltDetect.cs, compiled in, with AelrynthWire.cs for the
|
||||
launch command line parser it shares): hosts, world names, the engine.json lists and the
|
||||
combined verdict. Nothing native: no AC, no engine state.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>IltTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\IltDetect.cs" Link="Engine\IltDetect.cs" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\AelrynthWire.cs" Link="Engine\AelrynthWire.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
140
tools/IltTests/Program.cs
Normal file
140
tools/IltTests/Program.cs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace IltTests;
|
||||
|
||||
/// <summary>
|
||||
/// Infinite Leaftide detection, offline. The host is the public AC server list's
|
||||
/// (acresources/serverslist Servers.xml: InfiniteLeaftide, game.infiniteleaftide.online:9000);
|
||||
/// the world name is the one UtilityBelt's Leaftide tools and the ILT Hub check for.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _case = "";
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
Hosts();
|
||||
WorldNames();
|
||||
Decisions();
|
||||
ConfiguredLists();
|
||||
FromCommandLines();
|
||||
Wildcards();
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
|
||||
if (_checks == 0) { Console.WriteLine("ABORT: no checks ran."); return 1; }
|
||||
Console.WriteLine(_failed == 0 ? "ALL ILT TESTS PASSED." : $"{_failed} FAILED.");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Hosts()
|
||||
{
|
||||
Case("hosts");
|
||||
var d = IltDetect.DefaultHosts;
|
||||
Check(IltDetect.HostMatches("game.infiniteleaftide.online", d, out string m) && m == "infiniteleaftide.online", "the server list's host");
|
||||
Check(IltDetect.HostMatches("infiniteleaftide.online", d, out _), "the bare domain");
|
||||
Check(IltDetect.HostMatches("GAME.InfiniteLeaftide.Online.", d, out _), "case and a trailing dot");
|
||||
Check(!IltDetect.HostMatches("notinfiniteleaftide.online", d, out _), "a look-alike domain");
|
||||
Check(!IltDetect.HostMatches("infiniteleaftide.online.evil.net", d, out _), "the domain as a prefix");
|
||||
Check(!IltDetect.HostMatches("leafdawning.duckdns.org", d, out _), "Leafdawning (another ACE server)");
|
||||
Check(!IltDetect.HostMatches("aelrynth.com", d, out _), "Aelrynth");
|
||||
Check(!IltDetect.HostMatches("", d, out _) && !IltDetect.HostMatches(null, d, out _), "no host");
|
||||
Check(!IltDetect.HostMatches("game.infiniteleaftide.online", null, out _), "no list");
|
||||
Check(IltDetect.HostMatches("10.0.0.5", new[] { "10.0.0.5" }, out _), "an IP listed matches itself");
|
||||
Check(!IltDetect.HostMatches("1.10.0.0.5", new[] { "10.0.0.5" }, out _), "an IP never matches as a suffix");
|
||||
}
|
||||
|
||||
private static void WorldNames()
|
||||
{
|
||||
Case("world names");
|
||||
var d = IltDetect.DefaultServerNames;
|
||||
Check(IltDetect.WorldNameMatches("InfiniteLeaftide", d, out string m) && m == "InfiniteLeaftide", "InfiniteLeaftide");
|
||||
Check(IltDetect.WorldNameMatches("infiniteleaftide", d, out _), "case-insensitive");
|
||||
Check(IltDetect.WorldNameMatches(" InfiniteLeaftide ", d, out _), "trimmed");
|
||||
Check(IltDetect.WorldNameMatches("Leaftide Test", d, out m) && m == "*Leaftide*", "anything with Leaftide in it");
|
||||
Check(!IltDetect.WorldNameMatches("Leafdawning", d, out _), "Leafdawning");
|
||||
Check(!IltDetect.WorldNameMatches("Infinite Frosthaven", d, out _), "another Infinite server");
|
||||
Check(!IltDetect.WorldNameMatches("ACEmulator", d, out _), "ACE's default name");
|
||||
Check(!IltDetect.WorldNameMatches("Aeshnidae", d, out _), "Aelrynth's world");
|
||||
Check(!IltDetect.WorldNameMatches("", d, out _) && !IltDetect.WorldNameMatches(null, d, out _), "no name");
|
||||
}
|
||||
|
||||
private static void Decisions()
|
||||
{
|
||||
Case("decisions (defaults)");
|
||||
IltVerdict v = IltDetect.Decide("game.infiniteleaftide.online", null, null, null);
|
||||
Check(v.IsIlt, "by host before the world name arrives: " + v.Reason);
|
||||
v = IltDetect.Decide("game.infiniteleaftide.online", "InfiniteLeaftide", null, null);
|
||||
Check(v.IsIlt && v.Reason.Contains("and"), "both signals: " + v.Reason);
|
||||
v = IltDetect.Decide("", "InfiniteLeaftide", null, null);
|
||||
Check(v.IsIlt, "by world name with no host (another launcher): " + v.Reason);
|
||||
v = IltDetect.Decide("localhost", "InfiniteLeaftide", null, null);
|
||||
Check(v.IsIlt, "a local ACECustom copy that calls itself InfiniteLeaftide");
|
||||
v = IltDetect.Decide("play.coldeve.ac", "Coldeve", null, null);
|
||||
Check(!v.IsIlt && v.Reason.StartsWith("not"), "someone else's server: " + v.Reason);
|
||||
v = IltDetect.Decide("aelrynth.com", "Aeshnidae", null, null);
|
||||
Check(!v.IsIlt, "Aelrynth is not ILT");
|
||||
v = IltDetect.Decide(null, null, null, null);
|
||||
Check(!v.IsIlt && v.Reason.Length > 0, "nothing known: " + v.Reason);
|
||||
Check(!IltVerdict.Unknown.IsIlt, "the starting verdict is not ILT");
|
||||
}
|
||||
|
||||
private static void ConfiguredLists()
|
||||
{
|
||||
Case("engine.json lists");
|
||||
IltVerdict v = IltDetect.Decide("ilt.example.net", "MyShard", new[] { "MyShard" }, Array.Empty<string>());
|
||||
Check(v.IsIlt, "a world name added in engine.json");
|
||||
v = IltDetect.Decide("game.infiniteleaftide.online", "InfiniteLeaftide", Array.Empty<string>(), Array.Empty<string>());
|
||||
Check(!v.IsIlt, "empty lists turn both signals off");
|
||||
v = IltDetect.Decide("ilt.example.net", null, Array.Empty<string>(), new[] { "example.net" });
|
||||
Check(v.IsIlt, "a host added in engine.json covers its subdomains");
|
||||
v = IltDetect.Decide("game.infiniteleaftide.online", null, null, new[] { "example.net" });
|
||||
Check(!v.IsIlt, "an IltHosts list replaces the default host");
|
||||
|
||||
var list = IltDetect.ParseList(new[] { " InfiniteLeaftide ", "infiniteleaftide", "*Leaftide*; Other", "", null });
|
||||
Check(list != null && list.Count == 3 && list[0] == "InfiniteLeaftide" && list[1] == "*Leaftide*" && list[2] == "Other",
|
||||
"lists are trimmed, split on ; and , and de-duplicated: " + (list == null ? "null" : string.Join("|", list)));
|
||||
Check(IltDetect.ParseList(null) == null, "no list stays null (the defaults apply)");
|
||||
}
|
||||
|
||||
private static void FromCommandLines()
|
||||
{
|
||||
Case("launch command lines");
|
||||
// The RynthCore launcher's ACE form and the GDLE form, as ServerInfo reads them.
|
||||
Check(ServerDetect.TryParseLaunchHost("acclient.exe -h game.infiniteleaftide.online:9000 -a tom -v secret", out string h, out int p)
|
||||
&& IltDetect.Decide(h, null, null, null).IsIlt && p == 9000, "-h host:port");
|
||||
Check(ServerDetect.TryParseLaunchHost("acclient.exe -h Game.InfiniteLeaftide.Online -p 9000", out h, out _)
|
||||
&& IltDetect.Decide(h, null, null, null).IsIlt, "-h host -p port, mixed case");
|
||||
Check(ServerDetect.TryParseLaunchHost("acclient.exe -h aelrynth.com:9020", out h, out _)
|
||||
&& !IltDetect.Decide(h, null, null, null).IsIlt, "Aelrynth's command line");
|
||||
}
|
||||
|
||||
private static void Wildcards()
|
||||
{
|
||||
Case("wildcards");
|
||||
Check(IltDetect.Matches("InfiniteLeaftide", "Infinite*"), "prefix");
|
||||
Check(IltDetect.Matches("InfiniteLeaftide", "*Leaftide"), "suffix");
|
||||
Check(IltDetect.Matches("InfiniteLeaftide", "I*Leaf*e"), "several stars");
|
||||
Check(!IltDetect.Matches("Leaftide", "Infinite*"), "missing prefix");
|
||||
Check(!IltDetect.Matches("Leaf", "*Leaftide*"), "too short");
|
||||
Check(!IltDetect.Matches("anything", ""), "empty pattern never matches");
|
||||
Check(IltDetect.HostMatches("eu.game.infiniteleaftide.online", new[] { "*.infiniteleaftide.online" }, out _), "host wildcard");
|
||||
}
|
||||
|
||||
// ── harness ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void Case(string name)
|
||||
{
|
||||
_case = name;
|
||||
Console.WriteLine($"-- {name}");
|
||||
}
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine($" FAIL [{_case}] {what}");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the large-address alignment fix
|
||||
(src\RynthCore.Engine\Compatibility\LargeAddressAlignmentScan.cs, compiled in): the site scan
|
||||
against the .text of a real acclient.exe read from disk, idempotence once patched, refusal of
|
||||
near-miss byte patterns, and the padding arithmetic above and below 2 GB. Nothing native: no
|
||||
AC process, no engine state.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail); after the usual separator, an AC folder or an acclient.exe.
|
||||
Default: C:\Turbine\Asheron's Call-ryn\acclient.exe.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>LargeAddressAlignmentTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Compatibility\LargeAddressAlignmentScan.cs" Link="Engine\LargeAddressAlignmentScan.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
154
tools/LargeAddressAlignmentTests/Program.cs
Normal file
154
tools/LargeAddressAlignmentTests/Program.cs
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
using System.Buffers.Binary;
|
||||
using RynthCore.Engine.Compatibility;
|
||||
|
||||
namespace LargeAddressAlignmentTests;
|
||||
|
||||
/// <summary>
|
||||
/// The large-address alignment fix, offline: which acclient code the scan picks, that a patched
|
||||
/// image rescans as fully patched, that look-alike bytes are refused, and that the patched
|
||||
/// remainder pads a cursor above 2 GB the same as below it.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
string exe = FindExe(args.Length > 0 ? args[0] : @"C:\Turbine\Asheron's Call-ryn");
|
||||
RealClient(exe);
|
||||
SyntheticPatterns();
|
||||
PaddingArithmetic();
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)");
|
||||
return _failed == 0 && _checks > 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static string FindExe(string arg) =>
|
||||
File.Exists(arg) ? arg : Path.Combine(arg, "acclient.exe");
|
||||
|
||||
private static void RealClient(string path)
|
||||
{
|
||||
Section("acclient .text from " + path);
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
Check(false, "acclient.exe exists");
|
||||
return;
|
||||
}
|
||||
|
||||
byte[] image = File.ReadAllBytes(path);
|
||||
Check(TryReadText(image, out int textVa, out byte[] text), ".text section read");
|
||||
if (text.Length == 0) return;
|
||||
|
||||
List<AlignmentSite> sites = LargeAddressAlignmentScan.Find(text, textVa);
|
||||
Console.WriteLine($" {sites.Count} site(s), first 0x{sites.FirstOrDefault().AndVa:X8}, last 0x{sites.LastOrDefault().AndVa:X8}");
|
||||
Check(sites.Count == 190, "retail client has 190 padding sites");
|
||||
Check(sites.All(s => !s.AlreadyPatched), "none patched on disk");
|
||||
|
||||
// MotionData::UnPack (kelpie's 0x09000009 corruption) and the setup unpack under the
|
||||
// 0x539153 crashes, plus the one site with a pop before its je.
|
||||
foreach (int va in new[] { 0x005271A6, 0x00534B48, 0x00534C96, 0x00532E78, 0x004FD1B6, 0x006B394E })
|
||||
Check(sites.Any(s => s.AndVa == va), $"0x{va:X8} found");
|
||||
// A 16-bit ring index (movzx, never negative), not cursor padding: no trailing je.
|
||||
Check(sites.All(s => s.AndVa != 0x00547029), "0x00547029 (ring index) left alone");
|
||||
|
||||
foreach (AlignmentSite s in sites)
|
||||
text[s.ImmHighByteVa - textVa] = LargeAddressAlignmentScan.PatchedHighByte;
|
||||
List<AlignmentSite> again = LargeAddressAlignmentScan.Find(text, textVa);
|
||||
Check(again.Count == sites.Count && again.All(s => s.AlreadyPatched), "patched image rescans as all already patched");
|
||||
Check(again.Select(s => s.AndVa).SequenceEqual(sites.Select(s => s.AndVa)), "same sites after patching");
|
||||
}
|
||||
|
||||
private static void SyntheticPatterns()
|
||||
{
|
||||
Section("synthetic byte patterns");
|
||||
// and eax, 0x80000003 ; jns +5 ; dec eax ; or eax, -4 ; inc eax ; je +0x18
|
||||
byte[] eax = { 0x25, 0x03, 0x00, 0x00, 0x80, 0x79, 0x05, 0x48, 0x83, 0xC8, 0xFC, 0x40, 0x74, 0x18 };
|
||||
Check(Scan(eax).Count == 1, "eax short form matches");
|
||||
Check(Scan(eax)[0].ImmHighByteVa == 0x1000 + 4, "immediate high byte located");
|
||||
|
||||
// and ecx, 0x80000003 ; mov [esp+0xC], eax ; jns ; dec ecx ; or ecx, -4 ; inc ecx ; pop ebx ; je
|
||||
byte[] ecxGap = { 0x81, 0xE1, 0x03, 0x00, 0x00, 0x80, 0x89, 0x44, 0x24, 0x0C, 0x79, 0x05, 0x49, 0x83, 0xC9, 0xFC, 0x41, 0x5B, 0x74, 0x10 };
|
||||
Check(Scan(ecxGap).Count == 1 && Scan(ecxGap)[0].Register == 1, "ecx long form with gap and pop matches");
|
||||
|
||||
byte[] noJe = (byte[])eax.Clone();
|
||||
noJe[12] = 0x66;
|
||||
Check(Scan(noJe).Count == 0, "no trailing je: refused");
|
||||
|
||||
byte[] wrongReg = (byte[])eax.Clone();
|
||||
wrongReg[7] = 0x49; // dec ecx after and eax
|
||||
Check(Scan(wrongReg).Count == 0, "fix-up on another register: refused");
|
||||
|
||||
byte[] otherMask = (byte[])eax.Clone();
|
||||
otherMask[1] = 0x07; // % 8
|
||||
Check(Scan(otherMask).Count == 0, "and 0x80000007: refused");
|
||||
|
||||
byte[] patched = (byte[])eax.Clone();
|
||||
patched[4] = 0x00;
|
||||
Check(Scan(patched) is [{ AlreadyPatched: true }], "and eax, 3 reported as already patched");
|
||||
}
|
||||
|
||||
private static void PaddingArithmetic()
|
||||
{
|
||||
Section("padding above and below 2 GB");
|
||||
foreach (uint cursor in new uint[] { 0x2FDC98E1, 0x2FDC98E3, 0x80438035, 0x80438036, 0x8043A4C3, 0xFFFFFFFD })
|
||||
{
|
||||
int stock = StockPad(cursor), fixedPad = FixedPad(cursor);
|
||||
Check((cursor + (uint)fixedPad) % 4 == 0 && fixedPad < 4, $"0x{cursor:X8}: patched pad {fixedPad} aligns");
|
||||
if (cursor < 0x80000000)
|
||||
Check(stock == fixedPad, $"0x{cursor:X8}: below 2 GB the patch changes nothing");
|
||||
else
|
||||
Check(stock == fixedPad + 4, $"0x{cursor:X8}: stock pad {stock} overshoots by 4");
|
||||
}
|
||||
}
|
||||
|
||||
// AC's code: r = and(ptr, 0x80000003) with the sign fix-up, pad = r == 0 ? 0 : 4 - r.
|
||||
private static int StockPad(uint cursor)
|
||||
{
|
||||
int r = (int)cursor % 4;
|
||||
return r == 0 ? 0 : 4 - r;
|
||||
}
|
||||
|
||||
private static int FixedPad(uint cursor)
|
||||
{
|
||||
int r = (int)(cursor & 3);
|
||||
return r == 0 ? 0 : 4 - r;
|
||||
}
|
||||
|
||||
private static List<AlignmentSite> Scan(byte[] code)
|
||||
{
|
||||
byte[] padded = new byte[code.Length + 64];
|
||||
code.CopyTo(padded, 0);
|
||||
return LargeAddressAlignmentScan.Find(padded, 0x1000);
|
||||
}
|
||||
|
||||
private static bool TryReadText(byte[] image, out int textVa, out byte[] text)
|
||||
{
|
||||
textVa = 0;
|
||||
text = Array.Empty<byte>();
|
||||
int pe = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(0x3C));
|
||||
int sections = BinaryPrimitives.ReadUInt16LittleEndian(image.AsSpan(pe + 6));
|
||||
int optSize = BinaryPrimitives.ReadUInt16LittleEndian(image.AsSpan(pe + 20));
|
||||
int imageBase = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(pe + 24 + 28));
|
||||
for (int i = 0; i < sections; i++)
|
||||
{
|
||||
int s = pe + 24 + optSize + i * 40;
|
||||
if (System.Text.Encoding.ASCII.GetString(image, s, 8).TrimEnd('\0') != ".text") continue;
|
||||
int virtualSize = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 8));
|
||||
int rva = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 12));
|
||||
int rawOffset = BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(s + 20));
|
||||
textVa = imageBase + rva;
|
||||
text = image.AsSpan(rawOffset, virtualSize).ToArray();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void Section(string name) => Console.WriteLine($"\n== {name}");
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (!ok) _failed++;
|
||||
Console.WriteLine($" {(ok ? "ok " : "FAIL")} {what}");
|
||||
}
|
||||
}
|
||||
30
tools/LoaderReloadCapTests/Run-Tests.ps1
Normal file
30
tools/LoaderReloadCapTests/Run-Tests.ps1
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Builds and runs the offline checks for the loader's reload cap and CoreCLR crash-dump setup
|
||||
# against the real native/Loader/Loader.c (x86, MSVC): a client that has hot reloaded MaxHotReloads
|
||||
# times refuses the next reload without shutting down, unloading or staging anything, and tells
|
||||
# the engine; the dump environment (DOTNET_DbgEnableMiniDump/Type/Name) is set unless already set;
|
||||
# only the newest 3 clr_*.dmp are kept. Builds and runs in %TEMP%\LoaderReloadCapTests; touches
|
||||
# nothing under C:\Games.
|
||||
$ErrorActionPreference = "Stop"
|
||||
$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
|
||||
$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name
|
||||
$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer"
|
||||
$cl = "$vcBase\bin\Hostx86\x86\cl.exe"
|
||||
$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name
|
||||
$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer"
|
||||
$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer"
|
||||
$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared"
|
||||
$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86"
|
||||
|
||||
$L = (Resolve-Path (Join-Path $PSScriptRoot "..\..\native\Loader")).Path
|
||||
$out = Join-Path $env:TEMP "LoaderReloadCapTests"
|
||||
New-Item -ItemType Directory -Force $out | Out-Null
|
||||
Push-Location $out
|
||||
try {
|
||||
foreach ($d in "work", "logs") { if (Test-Path $d) { Remove-Item $d -Recurse -Force } }
|
||||
# The exe plays the engine: its two fake exports, undecorated, as the engine's are.
|
||||
& $cl /nologo /O2 /MT /W4 /wd4100 /I $L (Join-Path $PSScriptRoot "test.c") "$L\Hooks.c" "$L\Clr.c" "$L\Services.c" user32.lib /Fe:test.exe `
|
||||
/link "/EXPORT:RynthCoreMaxHotReloads=_FakeMaxHotReloads@0" "/EXPORT:RynthCoreReloadCapped=_FakeReloadCapped@8"
|
||||
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
|
||||
& .\test.exe @args
|
||||
exit $LASTEXITCODE
|
||||
} finally { Pop-Location }
|
||||
211
tools/LoaderReloadCapTests/test.c
Normal file
211
tools/LoaderReloadCapTests/test.c
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
// Offline checks for Loader.c's reload cap and CoreCLR crash-dump setup. Built with the real
|
||||
// Loader.c included, so these are the shipped functions. Logs go to .\logs (LOG_DIR below),
|
||||
// never C:\Games. This exe stands in for the engine: it exports RynthCoreMaxHotReloads and
|
||||
// RynthCoreReloadCapped (Run-Tests.ps1 links them undecorated), and the loader finds them with
|
||||
// GetProcAddress, the NativeAOT-host path.
|
||||
#define LOG_DIR "logs"
|
||||
#include "Loader.c"
|
||||
|
||||
static int fails;
|
||||
#define CHECK(c, ...) do { if (c) printf("ok "); else { printf("FAIL "); fails++; } printf(__VA_ARGS__); printf("\n"); } while (0)
|
||||
|
||||
// --- the fake engine ---------------------------------------------------------------
|
||||
|
||||
static volatile LONG fakeCap = 3;
|
||||
static volatile LONG cappedCalls, cappedReloads = -99, cappedCap = -99;
|
||||
|
||||
int __stdcall FakeMaxHotReloads(void) { return fakeCap; }
|
||||
|
||||
unsigned int __stdcall FakeReloadCapped(int reloads, int cap)
|
||||
{
|
||||
cappedReloads = reloads;
|
||||
cappedCap = cap;
|
||||
InterlockedIncrement(&cappedCalls);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// --- helpers -------------------------------------------------------------------------
|
||||
|
||||
static void MakeFile(const char* dir, const char* name, int ageMinutes)
|
||||
{
|
||||
char p[MAX_PATH];
|
||||
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", dir, name);
|
||||
HANDLE h = CreateFileA(p, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
FILETIME now;
|
||||
GetSystemTimeAsFileTime(&now);
|
||||
ULARGE_INTEGER t;
|
||||
t.LowPart = now.dwLowDateTime;
|
||||
t.HighPart = now.dwHighDateTime;
|
||||
t.QuadPart -= (ULONGLONG)ageMinutes * 60 * 10000000ULL;
|
||||
FILETIME ft = { t.LowPart, t.HighPart };
|
||||
SetFileTime(h, NULL, NULL, &ft);
|
||||
CloseHandle(h);
|
||||
}
|
||||
|
||||
static int FileExists(const char* dir, const char* name)
|
||||
{
|
||||
char p[MAX_PATH];
|
||||
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", dir, name);
|
||||
return GetFileAttributesA(p) != INVALID_FILE_ATTRIBUTES;
|
||||
}
|
||||
|
||||
static int CountFiles(const char* dir, const char* pattern)
|
||||
{
|
||||
char p[MAX_PATH];
|
||||
_snprintf_s(p, sizeof p, _TRUNCATE, "%s\\%s", dir, pattern);
|
||||
WIN32_FIND_DATAA fd;
|
||||
HANDLE f = FindFirstFileA(p, &fd);
|
||||
if (f == INVALID_HANDLE_VALUE) return 0;
|
||||
int n = 0;
|
||||
do { if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) n++; } while (FindNextFileA(f, &fd));
|
||||
FindClose(f);
|
||||
return n;
|
||||
}
|
||||
|
||||
static void Env(const char* name, char* out, DWORD cap)
|
||||
{
|
||||
out[0] = 0;
|
||||
if (GetEnvironmentVariableA(name, out, cap) == 0) out[0] = 0;
|
||||
}
|
||||
|
||||
static int WaitForCalls(LONG want)
|
||||
{
|
||||
for (int i = 0; i < 200 && cappedCalls < want; i++) Sleep(10);
|
||||
return cappedCalls >= want;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
InitializeCriticalSection(&g_logLock);
|
||||
char root[MAX_PATH];
|
||||
GetFullPathNameA("work", sizeof root, root, NULL);
|
||||
CreateDirectoryA(root, NULL);
|
||||
CreateDirectoryA(LOG_DIR, NULL);
|
||||
DWORD self = GetCurrentProcessId();
|
||||
|
||||
// 1. The cap rule.
|
||||
CHECK(!ReloadCapReached(0, 3) && !ReloadCapReached(2, 3), "under the cap: 0 and 2 reloads of 3 allowed");
|
||||
CHECK(ReloadCapReached(3, 3) && ReloadCapReached(4, 3), "at/over the cap: the 4th reload (3 done, cap 3) refused");
|
||||
CHECK(ReloadCapReached(0, 0), "cap 0: no hot reloads at all");
|
||||
CHECK(!ReloadCapReached(0, -1) && !ReloadCapReached(1000, -1), "negative cap: no cap");
|
||||
|
||||
// 2. Where the cap comes from: the engine's export, else the default.
|
||||
g_engineIsManaged = 0;
|
||||
g_engineModule = NULL;
|
||||
CHECK(CurrentReloadCap() == DEFAULT_MAX_HOT_RELOADS && DEFAULT_MAX_HOT_RELOADS == 3,
|
||||
"no engine export: the default (%d)", CurrentReloadCap());
|
||||
g_engineModule = GetModuleHandleA(NULL);
|
||||
CHECK(EngineExport(ENGINE_MAXRELOADS_EXPORT) && EngineExport(ENGINE_CAPPED_EXPORT), "the fake engine's exports resolve");
|
||||
fakeCap = 7;
|
||||
CHECK(CurrentReloadCap() == 7, "the engine's MaxHotReloads is used (%d)", CurrentReloadCap());
|
||||
fakeCap = 3;
|
||||
|
||||
// 3. A refused reload, through the real ReloadWatcher: 3 reloads done (gen 4), cap 3.
|
||||
// Nothing may be shut down, unloaded or staged, and the engine is told each time.
|
||||
strcpy_s(g_loaderDir, sizeof g_loaderDir, root);
|
||||
_snprintf_s(g_enginePath, sizeof g_enginePath, _TRUNCATE, "%s\\" ENGINE_DLL_NAME, root);
|
||||
char staging[MAX_PATH];
|
||||
_snprintf_s(staging, sizeof staging, _TRUNCATE, "%s\\" STAGING_SUBDIR, root);
|
||||
CreateDirectoryA(staging, NULL);
|
||||
char gen4[96], gen5[96], gen3[96];
|
||||
_snprintf_s(gen3, sizeof gen3, _TRUNCATE, "RynthCore.Engine.p%lu.gen3.dll", self);
|
||||
_snprintf_s(gen4, sizeof gen4, _TRUNCATE, "RynthCore.Engine.p%lu.gen4.dll", self);
|
||||
_snprintf_s(gen5, sizeof gen5, _TRUNCATE, "RynthCore.Engine.p%lu.gen5.dll", self);
|
||||
MakeFile(staging, gen3, 5); // an older generation a real reload would clean up
|
||||
MakeFile(staging, gen4, 1); // the running generation
|
||||
g_initCount = 4;
|
||||
g_reloadEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
|
||||
HANDLE watcher = CreateThread(NULL, 0, ReloadWatcher, NULL, 0, NULL);
|
||||
|
||||
SetEvent(g_reloadEvent);
|
||||
int told = WaitForCalls(1);
|
||||
Sleep(50);
|
||||
CHECK(told && cappedReloads == 3 && cappedCap == 3, "refused: the engine is told (reloads=%ld, cap=%ld)", cappedReloads, cappedCap);
|
||||
CHECK(g_initCount == 4 && g_reloadInFlight == 0 && g_lastReloadDone == 0, "refused: still gen 4, no reload ran");
|
||||
CHECK(FileExists(staging, gen4) && FileExists(staging, gen3) && !FileExists(staging, gen5),
|
||||
"refused: staging untouched (gen 4 and gen 3 kept, no gen 5 staged)");
|
||||
|
||||
// A second publish: refused again, told again (the engine decides what goes to chat).
|
||||
SetEvent(g_reloadEvent);
|
||||
CHECK(WaitForCalls(2) && g_initCount == 4, "a second signal: refused again, told again (%ld calls)", cappedCalls);
|
||||
|
||||
// Cap 0 refuses the first reload too.
|
||||
g_initCount = 1;
|
||||
fakeCap = 0;
|
||||
SetEvent(g_reloadEvent);
|
||||
CHECK(WaitForCalls(3) && cappedReloads == 0 && cappedCap == 0 && g_initCount == 1, "cap 0: the first reload refused");
|
||||
fakeCap = 3;
|
||||
(void)watcher; // runs until the process exits
|
||||
|
||||
// 4. Dump type for the free space.
|
||||
CHECK(CrashDumpType(10ULL << 30) == 2, "10 GB free: dump with heap (type 2)");
|
||||
CHECK(CrashDumpType((unsigned long long)DUMP_HEAP_MIN_FREE_MB << 20) == 2, "exactly the floor: type 2");
|
||||
CHECK(CrashDumpType(((unsigned long long)DUMP_HEAP_MIN_FREE_MB << 20) - 1) == 1, "below the floor: normal dump (type 1)");
|
||||
CHECK(CrashDumpType(0) == 1, "unknown free space (0): type 1");
|
||||
|
||||
// 5. Pruning: the newest 3 clr_*.dmp stay; other dumps and folders are left alone.
|
||||
char dumps[MAX_PATH];
|
||||
_snprintf_s(dumps, sizeof dumps, _TRUNCATE, "%s\\dumps", root);
|
||||
CreateDirectoryA(dumps, NULL);
|
||||
MakeFile(dumps, "clr_100_1.dmp", 50);
|
||||
MakeFile(dumps, "clr_101_2.dmp", 40);
|
||||
MakeFile(dumps, "clr_102_3.dmp", 30);
|
||||
MakeFile(dumps, "clr_103_4.dmp", 20);
|
||||
MakeFile(dumps, "clr_104_5.dmp", 10);
|
||||
MakeFile(dumps, "hang_1_old.dmp", 500);
|
||||
MakeFile(dumps, "clr_notes.txt", 600);
|
||||
char sub[MAX_PATH];
|
||||
_snprintf_s(sub, sizeof sub, _TRUNCATE, "%s\\clr_folder.dmp", dumps);
|
||||
CreateDirectoryA(sub, NULL);
|
||||
int deleted = PruneCrashDumps(dumps, DUMP_KEEP);
|
||||
CHECK(deleted == 2 && !FileExists(dumps, "clr_100_1.dmp") && !FileExists(dumps, "clr_101_2.dmp"),
|
||||
"the 2 oldest clr dumps deleted (%d)", deleted);
|
||||
CHECK(FileExists(dumps, "clr_102_3.dmp") && FileExists(dumps, "clr_103_4.dmp") && FileExists(dumps, "clr_104_5.dmp"),
|
||||
"the newest 3 kept");
|
||||
CHECK(FileExists(dumps, "hang_1_old.dmp") && FileExists(dumps, "clr_notes.txt") &&
|
||||
GetFileAttributesA(sub) != INVALID_FILE_ATTRIBUTES, "hang dumps, other files and folders untouched");
|
||||
CHECK(PruneCrashDumps(dumps, DUMP_KEEP) == 0, "a second prune deletes nothing");
|
||||
char missing[MAX_PATH];
|
||||
_snprintf_s(missing, sizeof missing, _TRUNCATE, "%s\\nope", root);
|
||||
CHECK(PruneCrashDumps(missing, DUMP_KEEP) == 0, "a missing folder: nothing to do");
|
||||
|
||||
// 6. The environment CoreCLR reads at start.
|
||||
char v[MAX_PATH], want[MAX_PATH], runtimeDir[MAX_PATH], newDumps[MAX_PATH];
|
||||
SetEnvironmentVariableA("DOTNET_DbgEnableMiniDump", NULL);
|
||||
SetEnvironmentVariableA("COMPlus_DbgEnableMiniDump", NULL);
|
||||
SetEnvironmentVariableA("DOTNET_DbgMiniDumpType", NULL);
|
||||
SetEnvironmentVariableA("DOTNET_DbgMiniDumpName", NULL);
|
||||
_snprintf_s(runtimeDir, sizeof runtimeDir, _TRUNCATE, "%s\\dotnet", root); // no createdump.exe: warns
|
||||
_snprintf_s(newDumps, sizeof newDumps, _TRUNCATE, "%s\\newdumps", root); // created on demand
|
||||
MakeFile(dumps, "clr_105_6.dmp", 5);
|
||||
int type = ConfigureCrashDumps(dumps, runtimeDir);
|
||||
ULARGE_INTEGER freeBytes;
|
||||
GetDiskFreeSpaceExA(dumps, &freeBytes, NULL, NULL);
|
||||
CHECK(type == CrashDumpType(freeBytes.QuadPart), "dump type %d for %llu MB free", type, freeBytes.QuadPart >> 20);
|
||||
Env("DOTNET_DbgEnableMiniDump", v, sizeof v);
|
||||
CHECK(strcmp(v, "1") == 0, "DOTNET_DbgEnableMiniDump=%s", v);
|
||||
Env("DOTNET_DbgMiniDumpType", v, sizeof v);
|
||||
CHECK(atoi(v) == type, "DOTNET_DbgMiniDumpType=%s", v);
|
||||
Env("DOTNET_DbgMiniDumpName", v, sizeof v);
|
||||
_snprintf_s(want, sizeof want, _TRUNCATE, "%s\\clr_%lu_%%t.dmp", dumps, self);
|
||||
CHECK(strcmp(v, want) == 0, "DOTNET_DbgMiniDumpName=%s (pid in the name, createdump's %%t for the time)", v);
|
||||
CHECK(CountFiles(dumps, "clr_*.dmp") == 3 && !FileExists(dumps, "clr_102_3.dmp"), "pruned at startup to the newest 3");
|
||||
|
||||
// Already configured (a test client, or =0 to turn it off): left alone.
|
||||
SetEnvironmentVariableA("DOTNET_DbgEnableMiniDump", "0");
|
||||
SetEnvironmentVariableA("DOTNET_DbgMiniDumpName", "C:\\elsewhere\\x.dmp");
|
||||
CHECK(ConfigureCrashDumps(newDumps, runtimeDir) == 0, "DOTNET_DbgEnableMiniDump=0 already set: returns 0");
|
||||
Env("DOTNET_DbgEnableMiniDump", v, sizeof v);
|
||||
CHECK(strcmp(v, "0") == 0, "...and stays 0");
|
||||
Env("DOTNET_DbgMiniDumpName", v, sizeof v);
|
||||
CHECK(strcmp(v, "C:\\elsewhere\\x.dmp") == 0, "...name untouched");
|
||||
SetEnvironmentVariableA("DOTNET_DbgEnableMiniDump", NULL);
|
||||
SetEnvironmentVariableA("COMPlus_DbgEnableMiniDump", "1");
|
||||
CHECK(ConfigureCrashDumps(newDumps, runtimeDir) == 0, "the legacy COMPlus_ name counts too");
|
||||
SetEnvironmentVariableA("COMPlus_DbgEnableMiniDump", NULL);
|
||||
CHECK(ConfigureCrashDumps(newDumps, runtimeDir) > 0 && GetFileAttributesA(newDumps) != INVALID_FILE_ATTRIBUTES,
|
||||
"a missing dumps folder is created");
|
||||
|
||||
printf(fails ? "\n%d FAILED\n" : "\nALL PASSED\n", fails);
|
||||
return fails;
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
// Offline checks for Loader.c's staging: CleanStaleStagingFiles rules and CopyGuarded.
|
||||
// Built with the real Loader.c included, so these are the shipped functions.
|
||||
#define LOG_DIR "logs" // anything LoaderLog writes goes here, not C:\Games
|
||||
#include "Loader.c"
|
||||
|
||||
static int fails;
|
||||
|
|
|
|||
26
tools/PanelTextScaleTests/PanelTextScaleTests.csproj
Normal file
26
tools/PanelTextScaleTests/PanelTextScaleTests.csproj
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the toolbar's text size (the "chrome" row of PanelTextScale).
|
||||
src\RynthCore.Engine\UI\PanelTextScale.cs, compiled in, with a stub ImGuiFonts. The toolbar's
|
||||
row must survive a window being sized (SetForWindow's reset loop), be baked even when sizing
|
||||
per panel is off (StepsInUse), be left alone by All Panels changes, stay unbaked at 0, clamp,
|
||||
and round-trip through the file. PanelTextScale reads its file path once per process, so each
|
||||
case runs in a child process pointed at a temp file with RYNTHCORE_PANEL_TEXT_SIZE. Never
|
||||
touches %LOCALAPPDATA%\RynthCore.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>PanelTextScaleTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\PanelTextScale.cs" Link="Engine\PanelTextScale.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
174
tools/PanelTextScaleTests/Program.cs
Normal file
174
tools/PanelTextScaleTests/Program.cs
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
using System.Diagnostics;
|
||||
using RynthCore.Engine.UI;
|
||||
|
||||
namespace RynthCore.Engine.ImGuiBackend
|
||||
{
|
||||
/// <summary>Stub of the engine's fonts: counts the re-bake requests PanelTextScale makes.</summary>
|
||||
internal static class ImGuiFonts
|
||||
{
|
||||
internal static int Rebuilds;
|
||||
internal static void RequestRebuild(int delayMs = 0) => Rebuilds++;
|
||||
}
|
||||
}
|
||||
|
||||
namespace PanelTextScaleTests
|
||||
{
|
||||
// Offline tests for the toolbar text size. See the csproj.
|
||||
internal static class Program
|
||||
{
|
||||
private static int _fails, _asserts;
|
||||
private static void Check(bool cond, string msg)
|
||||
{
|
||||
_asserts++;
|
||||
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
|
||||
}
|
||||
private static void Eq<T>(T actual, T expected, string msg) =>
|
||||
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'");
|
||||
|
||||
// case name -> the file it starts from (null = no file)
|
||||
private static readonly (string Name, string? Seed, Action Body)[] Cases =
|
||||
{
|
||||
("ChromeSurvivesSetForWindow", "__all=2\n__chrome=3\n", ChromeSurvivesSetForWindow),
|
||||
("StepsInUseHasChromeWhenPerPanelOff", "__all=0\n__chrome=3\n", StepsInUseHasChromeWhenPerPanelOff),
|
||||
("UseForAllAndSetAllLeaveChromeAlone", "__chrome=3\n", UseForAllAndSetAllLeaveChromeAlone),
|
||||
("ChromeZeroIsNotBaked", "__all=0\n__chrome=0\n", ChromeZeroIsNotBaked),
|
||||
("ChromeDoesNotFallBackToAll", "__all=5\n", ChromeDoesNotFallBackToAll),
|
||||
("ChromeClamps", null, ChromeClamps),
|
||||
("RoundTripWrite", null, RoundTripWrite),
|
||||
("RoundTripRead", null, RoundTripRead),
|
||||
};
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
if (args.Length > 1 && args[0] == "--child")
|
||||
{
|
||||
foreach (var c in Cases)
|
||||
if (c.Name == args[1]) { c.Body(); return _fails == 0 && _asserts > 0 ? 0 : 1; }
|
||||
Console.WriteLine(" [FAIL] unknown case " + args[1]);
|
||||
return 1;
|
||||
}
|
||||
|
||||
string root = Path.Combine(Path.GetTempPath(), "rynth-panel-text-tests-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(root);
|
||||
int fails = 0;
|
||||
try
|
||||
{
|
||||
foreach (var c in Cases)
|
||||
{
|
||||
if (c.Name == "RoundTripRead") continue; // run right after RoundTripWrite, on its file
|
||||
string file = Path.Combine(root, c.Name + ".txt");
|
||||
if (c.Seed != null) File.WriteAllText(file, c.Seed);
|
||||
Console.WriteLine(c.Name);
|
||||
bool ok = RunChild(c.Name, file);
|
||||
if (ok && c.Name == "RoundTripWrite")
|
||||
{
|
||||
Console.WriteLine("RoundTripRead");
|
||||
ok = RunChild("RoundTripRead", file);
|
||||
}
|
||||
if (!ok) fails++;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(root, true); } catch { }
|
||||
}
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(fails == 0 ? "PASS" : $"FAIL ({fails} case(s) failed)");
|
||||
return fails == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static bool RunChild(string name, string file)
|
||||
{
|
||||
var psi = new ProcessStartInfo(Environment.ProcessPath!)
|
||||
{
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
};
|
||||
psi.ArgumentList.Add("--child");
|
||||
psi.ArgumentList.Add(name);
|
||||
psi.Environment["RYNTHCORE_PANEL_TEXT_SIZE"] = file;
|
||||
using Process p = Process.Start(psi)!;
|
||||
string output = p.StandardOutput.ReadToEnd() + p.StandardError.ReadToEnd();
|
||||
p.WaitForExit();
|
||||
if (output.Length > 0) Console.Write(output);
|
||||
return p.ExitCode == 0;
|
||||
}
|
||||
|
||||
private static string[] Lines(string? file = null) =>
|
||||
File.ReadAllLines(file ?? Environment.GetEnvironmentVariable("RYNTHCORE_PANEL_TEXT_SIZE")!);
|
||||
|
||||
// Sizing one window with per-panel off rewrites every other row to the All
|
||||
// Panels size; the toolbar's row is not a panel and must keep its own.
|
||||
private static void ChromeSurvivesSetForWindow()
|
||||
{
|
||||
PanelTextScale.SetForWindow("Radar", 4);
|
||||
Eq(PanelTextScale.GetChrome(), 3, "chrome after SetForWindow (per-panel off)");
|
||||
Check(Lines().Contains("__chrome=3"), "chrome row still 3 in the file");
|
||||
Eq(PanelTextScale.GetOwn("Radar"), 4, "the window itself did change");
|
||||
Check(PanelTextScale.PerPanel, "SetForWindow switched per-panel on");
|
||||
Eq(PanelTextScale.Get("Other"), 2, "other panels stay at All Panels");
|
||||
}
|
||||
|
||||
// Per-panel off: StepsInUse used to skip every non-All row, so the toolbar's
|
||||
// size would never have been baked.
|
||||
private static void StepsInUseHasChromeWhenPerPanelOff()
|
||||
{
|
||||
Check(!PanelTextScale.PerPanel, "per-panel is off");
|
||||
Eq(PanelTextScale.GetAll(), 0, "All Panels is 0");
|
||||
var steps = PanelTextScale.StepsInUse();
|
||||
Check(steps.Contains(3), "StepsInUse contains the chrome step 3 (got [" + string.Join(",", steps) + "])");
|
||||
Eq(steps.Count, 1, "and nothing else");
|
||||
}
|
||||
|
||||
private static void UseForAllAndSetAllLeaveChromeAlone()
|
||||
{
|
||||
PanelTextScale.UseForAll(5);
|
||||
Eq(PanelTextScale.GetChrome(), 3, "chrome after UseForAll(5)");
|
||||
PanelTextScale.SetAll(2);
|
||||
Eq(PanelTextScale.GetChrome(), 3, "chrome after SetAll(2)");
|
||||
Eq(PanelTextScale.GetAll(), 2, "All Panels did change");
|
||||
var steps = PanelTextScale.StepsInUse();
|
||||
Check(steps.Contains(3) && steps.Contains(2), "both steps baked (got [" + string.Join(",", steps) + "])");
|
||||
}
|
||||
|
||||
private static void ChromeZeroIsNotBaked()
|
||||
{
|
||||
Eq(PanelTextScale.StepsInUse().Count, 0, "nothing in use with chrome 0 and All 0");
|
||||
PanelTextScale.SetChrome(3);
|
||||
Check(PanelTextScale.StepsInUse().Contains(3), "chrome 3 baked");
|
||||
PanelTextScale.SetChrome(0);
|
||||
Eq(PanelTextScale.StepsInUse().Count, 0, "back to nothing after SetChrome(0)");
|
||||
}
|
||||
|
||||
private static void ChromeDoesNotFallBackToAll()
|
||||
{
|
||||
Eq(PanelTextScale.GetAll(), 5, "All Panels is 5");
|
||||
Eq(PanelTextScale.GetChrome(), 0, "toolbar without its own row is normal size");
|
||||
}
|
||||
|
||||
private static void ChromeClamps()
|
||||
{
|
||||
PanelTextScale.SetChrome(99);
|
||||
Eq(PanelTextScale.GetChrome(), PanelTextScale.SizeNames.Length - 1, "clamped to the top size");
|
||||
PanelTextScale.SetChrome(-4);
|
||||
Eq(PanelTextScale.GetChrome(), 0, "clamped to 0");
|
||||
}
|
||||
|
||||
private static void RoundTripWrite()
|
||||
{
|
||||
int before = RynthCore.Engine.ImGuiBackend.ImGuiFonts.Rebuilds;
|
||||
PanelTextScale.SetChrome(4);
|
||||
Eq(RynthCore.Engine.ImGuiBackend.ImGuiFonts.Rebuilds, before + 1, "SetChrome requested one re-bake");
|
||||
Check(Lines().Contains("__chrome=4"), "file has __chrome=4");
|
||||
PanelTextScale.SetChrome(4);
|
||||
Eq(RynthCore.Engine.ImGuiBackend.ImGuiFonts.Rebuilds, before + 1, "same size again requests nothing");
|
||||
}
|
||||
|
||||
// A fresh process reads what RoundTripWrite saved.
|
||||
private static void RoundTripRead()
|
||||
{
|
||||
Eq(PanelTextScale.GetChrome(), 4, "chrome read back from the file");
|
||||
}
|
||||
}
|
||||
}
|
||||
32
tools/ProblemReportTests/ProblemReportTests.csproj
Normal file
32
tools/ProblemReportTests/ProblemReportTests.csproj
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline tests for "Report a problem" (src\RynthCore.Engine\Report\ProblemReportCore.cs, compiled
|
||||
in; pure code, no engine state):
|
||||
- text cleaning and the UTF-8 byte limits (never cut inside a character);
|
||||
- the request body: exact keys and types the server's schema expects, limits applied,
|
||||
plugin names cleaned, the log gzipped + base64 and round-tripping, no log = null;
|
||||
- the log tail: last N lines, the byte cap (keeps the end, starts at a line), a last line
|
||||
still being written, CRLF, an empty / missing file, the rotated .old topping up a short
|
||||
current log, and reading while another thread keeps appending (as the engine does);
|
||||
- hiding the account (login) name, the Windows user name (profile paths) and the PC name;
|
||||
- the cooldown arithmetic, the endpoint override rules, and reading the server's answers.
|
||||
Optional: (double dash) server http://127.0.0.1:18097/report posts real bodies to a local copy
|
||||
of the endpoint (C:\Aeshnidae\ops\report-endpoint\test_local.py serve) to check both ends agree.
|
||||
Nothing native: no AC, no engine, no network unless asked.
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>ProblemReportTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\Report\ProblemReportCore.cs" Link="Engine\ProblemReportCore.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
473
tools/ProblemReportTests/Program.cs
Normal file
473
tools/ProblemReportTests/Program.cs
Normal file
|
|
@ -0,0 +1,473 @@
|
|||
using System.IO.Compression;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using RynthCore.Engine.Report;
|
||||
|
||||
namespace ProblemReportTests;
|
||||
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _case = "";
|
||||
private static string _tmp = "";
|
||||
|
||||
private static int Main(string[] args)
|
||||
{
|
||||
_tmp = Path.Combine(Path.GetTempPath(), "ProblemReportTests-" + Environment.ProcessId);
|
||||
Directory.CreateDirectory(_tmp);
|
||||
try
|
||||
{
|
||||
TextCleaning();
|
||||
Utf8Limits();
|
||||
Validation();
|
||||
PayloadShape();
|
||||
PayloadLimits();
|
||||
PayloadNoLog();
|
||||
TailLastLines();
|
||||
TailByteCap();
|
||||
TailPartialLastLine();
|
||||
TailCrlfAndEdges();
|
||||
TailTopsUpFromOld();
|
||||
TailWhileWriting();
|
||||
AccountHidden();
|
||||
Cooldown();
|
||||
Endpoint();
|
||||
Responses();
|
||||
Sizes();
|
||||
|
||||
int at = Array.IndexOf(args, "server");
|
||||
if (at >= 0 && at + 1 < args.Length) AgainstServer(args[at + 1]).GetAwaiter().GetResult();
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { Directory.Delete(_tmp, true); } catch { }
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
|
||||
Console.WriteLine(_failed == 0 ? "ALL PROBLEM REPORT TESTS PASSED." : $"{_failed} FAILED.");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Case(string name) { _case = name; Console.WriteLine("-- " + name); }
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine($"FAIL [{_case}] {what}");
|
||||
}
|
||||
|
||||
private static void Eq<T>(T actual, T expected, string what) =>
|
||||
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{what}: expected <{expected}>, got <{actual}>");
|
||||
|
||||
// ── Text ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void TextCleaning()
|
||||
{
|
||||
Case("text cleaning");
|
||||
Eq(ProblemReportCore.CleanText(" hello\r\nworld\r ", 100), "hello\nworld", "CRLF/CR to LF, trimmed");
|
||||
Eq(ProblemReportCore.CleanText("a\u0000b\u0007c\td", 100), "abc\td", "control chars dropped, tab kept");
|
||||
Eq(ProblemReportCore.CleanText(null, 100), "", "null");
|
||||
Eq(ProblemReportCore.CleanShort(" Tom\nthe\tGreat ", 64), "TomtheGreat", "one-line field drops newline and tab");
|
||||
Eq(ProblemReportCore.CleanShort(new string('x', 70), 64).Length, 64, "short field cut to 64");
|
||||
string emoji = new string('a', 63) + "\U0001F600";
|
||||
Check(!char.IsHighSurrogate(ProblemReportCore.CleanShort(emoji, 64)[^1]), "short field never ends on a lone high surrogate");
|
||||
Eq(ProblemReportCore.PluginName("Rynth<Ai>!"), "RynthAi", "plugin name cleaned");
|
||||
Eq(ProblemReportCore.PluginName(new string('p', 50)).Length, 40, "plugin name max 40");
|
||||
}
|
||||
|
||||
private static void Utf8Limits()
|
||||
{
|
||||
Case("UTF-8 limits");
|
||||
Eq(ProblemReportCore.TrimUtf8("abcdef", 4), "abcd", "ascii cut");
|
||||
Eq(ProblemReportCore.TrimUtf8("aé", 2), "a", "2-byte char not split");
|
||||
Eq(ProblemReportCore.TrimUtf8("a\U0001F600", 4), "a", "4-byte char not split");
|
||||
Eq(ProblemReportCore.TrimUtf8("a\U0001F600", 5), "a\U0001F600", "4-byte char fits");
|
||||
string big = string.Concat(Enumerable.Repeat("ü", 3000)); // 6000 bytes
|
||||
string cut = ProblemReportCore.CleanText(big, ProblemReportCore.MaxDescriptionBytes);
|
||||
Check(Encoding.UTF8.GetByteCount(cut) <= ProblemReportCore.MaxDescriptionBytes, "description <= 2500 bytes");
|
||||
Eq(cut.Length, 1250, "1250 two-byte chars");
|
||||
}
|
||||
|
||||
private static void Validation()
|
||||
{
|
||||
Case("validation");
|
||||
Check(ProblemReportCore.ValidateDescription("").Length > 0, "empty refused");
|
||||
Check(ProblemReportCore.ValidateDescription(" \r\n ").Length > 0, "blank refused");
|
||||
Check(ProblemReportCore.ValidateDescription("ab").Length > 0, "too short refused");
|
||||
Eq(ProblemReportCore.ValidateDescription("bot stuck"), "", "ok accepted");
|
||||
}
|
||||
|
||||
// ── Payload ──────────────────────────────────────────────────────────
|
||||
|
||||
private static ReportContext SampleContext() => new()
|
||||
{
|
||||
Character = "Drakkon",
|
||||
World = "Aelrynth",
|
||||
Connect = "aelrynth.com:9000",
|
||||
Aelrynth = true,
|
||||
RynthCoreVersion = "2026.10.9.3 (194ea47)",
|
||||
ApiVersion = 79,
|
||||
Generation = 2,
|
||||
RynthAiVersion = "2026.10.9.3 (e6fffb0)",
|
||||
Plugins = { ("RynthAi", "2026.10.9.3 (e6fffb0)"), ("RynthNav", "dev (abc1234)"), ("rynthai", "dupe") },
|
||||
Landcell = 0x12340105,
|
||||
Pid = 4242,
|
||||
};
|
||||
|
||||
private static readonly string[] TopKeys =
|
||||
{
|
||||
"schema", "description", "doing", "character", "world", "connect", "aelrynth", "rynthcore", "api",
|
||||
"generation", "rynthai", "plugins", "landcell", "pid", "clientTime", "log",
|
||||
};
|
||||
|
||||
private static void PayloadShape()
|
||||
{
|
||||
Case("payload shape");
|
||||
string logText = string.Join("\n", Enumerable.Range(1, 50).Select(i => $"[12:00:{i:00}.000] [pid:4242] [INF] [engine] line {i}")) + "\n";
|
||||
var tail = new LogTail { FileName = "RynthCore.4242.log", Text = Encoding.UTF8.GetBytes(logText), Lines = 50 };
|
||||
byte[] body = ProblemReportCore.BuildPayload("Bot <@everyone> stuck **here**", "hunting\r\nwith bot", SampleContext(), tail,
|
||||
new DateTime(2026, 10, 11, 12, 0, 0, DateTimeKind.Utc));
|
||||
using var doc = JsonDocument.Parse(body);
|
||||
JsonElement r = doc.RootElement;
|
||||
var keys = r.EnumerateObject().Select(p => p.Name).ToArray();
|
||||
Check(keys.OrderBy(k => k).SequenceEqual(TopKeys.OrderBy(k => k)), "exactly the schema's keys: " + string.Join(",", keys));
|
||||
Eq(r.GetProperty("schema").GetInt32(), 1, "schema");
|
||||
Eq(r.GetProperty("description").GetString(), "Bot <@everyone> stuck **here**", "description kept verbatim (the server escapes)");
|
||||
Eq(r.GetProperty("doing").GetString(), "hunting\nwith bot", "doing CRLF -> LF");
|
||||
Eq(r.GetProperty("character").GetString(), "Drakkon", "character");
|
||||
Eq(r.GetProperty("aelrynth").GetBoolean(), true, "aelrynth");
|
||||
Eq(r.GetProperty("api").GetInt32(), 79, "api");
|
||||
Eq(r.GetProperty("landcell").GetString(), "0x12340105", "landcell hex");
|
||||
Eq(r.GetProperty("pid").GetInt32(), 4242, "pid");
|
||||
Eq(r.GetProperty("clientTime").GetString(), "2026-10-11T12:00:00Z", "clientTime");
|
||||
Eq(r.GetProperty("plugins").GetArrayLength(), 2, "plugin dupes (any case) dropped");
|
||||
Eq(r.GetProperty("plugins")[1].GetProperty("name").GetString(), "RynthNav", "second plugin");
|
||||
JsonElement log = r.GetProperty("log");
|
||||
Eq(log.GetProperty("name").GetString(), "RynthCore.4242.log", "log name");
|
||||
Eq(log.GetProperty("lines").GetInt32(), 50, "log lines");
|
||||
Eq(log.GetProperty("bytes").GetInt32(), tail.Text.Length, "log bytes");
|
||||
byte[] gz = log.GetProperty("gzip").GetBytesFromBase64();
|
||||
using var unz = new GZipStream(new MemoryStream(gz), CompressionMode.Decompress);
|
||||
using var back = new MemoryStream();
|
||||
unz.CopyTo(back);
|
||||
Eq(Encoding.UTF8.GetString(back.ToArray()), logText, "log round-trips through gzip + base64");
|
||||
Check(gz.Length < tail.Text.Length, "gzip is smaller");
|
||||
}
|
||||
|
||||
private static void PayloadLimits()
|
||||
{
|
||||
Case("payload limits");
|
||||
var ctx = SampleContext();
|
||||
ctx.Character = new string('C', 200);
|
||||
ctx.Connect = new string('h', 300);
|
||||
ctx.Landcell = 0;
|
||||
ctx.Plugins.Clear();
|
||||
for (int i = 0; i < 50; i++) ctx.Plugins.Add(($"Plugin{i}", "1"));
|
||||
byte[] body = ProblemReportCore.BuildPayload(new string('d', 5000), new string('w', 5000), ctx, null, DateTime.UtcNow);
|
||||
using var doc = JsonDocument.Parse(body);
|
||||
JsonElement r = doc.RootElement;
|
||||
Eq(r.GetProperty("description").GetString()!.Length, ProblemReportCore.MaxDescriptionBytes, "description capped");
|
||||
Eq(r.GetProperty("doing").GetString()!.Length, ProblemReportCore.MaxDoingBytes, "doing capped");
|
||||
Eq(r.GetProperty("character").GetString()!.Length, ProblemReportCore.MaxShortField, "character capped");
|
||||
Eq(r.GetProperty("connect").GetString()!.Length, ProblemReportCore.MaxConnectField, "connect capped");
|
||||
Eq(r.GetProperty("plugins").GetArrayLength(), ProblemReportCore.MaxPlugins, "plugins capped at 32");
|
||||
Eq(r.GetProperty("landcell").GetString(), "", "no landcell = empty");
|
||||
Check(body.Length < 8192, $"no-log body small ({body.Length} bytes)");
|
||||
}
|
||||
|
||||
private static void PayloadNoLog()
|
||||
{
|
||||
Case("payload without log");
|
||||
byte[] body = ProblemReportCore.BuildPayload("x went wrong", "", SampleContext(), null, DateTime.UtcNow);
|
||||
using var doc = JsonDocument.Parse(body);
|
||||
Eq(doc.RootElement.GetProperty("log").ValueKind, JsonValueKind.Null, "log null when unticked");
|
||||
var empty = new LogTail { FileName = "a.log", Text = Array.Empty<byte>() };
|
||||
body = ProblemReportCore.BuildPayload("x went wrong", "", SampleContext(), empty, DateTime.UtcNow);
|
||||
using var doc2 = JsonDocument.Parse(body);
|
||||
Eq(doc2.RootElement.GetProperty("log").ValueKind, JsonValueKind.Null, "empty log sent as null");
|
||||
}
|
||||
|
||||
// ── Log tail ─────────────────────────────────────────────────────────
|
||||
|
||||
private static string WriteLines(string name, int count, string newline = "\n", bool trailing = true, int pad = 0)
|
||||
{
|
||||
string path = Path.Combine(_tmp, name);
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 1; i <= count; i++)
|
||||
{
|
||||
sb.Append("line ").Append(i).Append(new string('.', pad));
|
||||
if (i < count || trailing) sb.Append(newline);
|
||||
}
|
||||
File.WriteAllText(path, sb.ToString());
|
||||
return path;
|
||||
}
|
||||
|
||||
private static string[] LinesOf(LogTail t) =>
|
||||
Encoding.UTF8.GetString(t.Text).Split('\n', StringSplitOptions.None).Where(s => s.Length > 0).ToArray();
|
||||
|
||||
private static void TailLastLines()
|
||||
{
|
||||
Case("tail: last N lines");
|
||||
string path = WriteLines("a.log", 5000);
|
||||
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 10_000_000)!;
|
||||
string[] lines = LinesOf(t);
|
||||
Eq(t.Lines, 2000, "2000 lines");
|
||||
Eq(lines.Length, 2000, "2000 lines in text");
|
||||
Eq(lines[0], "line 3001", "first kept line");
|
||||
Eq(lines[^1], "line 5000", "last line");
|
||||
Check(t.Text[^1] == (byte)'\n', "ends with the newline");
|
||||
Eq(t.FileName, "a.log", "file name");
|
||||
|
||||
LogTail small = ProblemReportCore.ReadTail(WriteLines("b.log", 10), null, 2000, 10_000_000)!;
|
||||
Eq(small.Lines, 10, "short file: all lines");
|
||||
Eq(LinesOf(small)[0], "line 1", "short file from the start");
|
||||
|
||||
// Exactly the chunk size boundary: 64 KB lines.
|
||||
string big = WriteLines("c.log", 3000, pad: 60);
|
||||
LogTail tb = ProblemReportCore.ReadTail(big, null, 2000, 10_000_000)!;
|
||||
Eq(tb.Lines, 2000, "multi-chunk read: 2000 lines");
|
||||
Eq(LinesOf(tb)[0], "line 1001" + new string('.', 60), "multi-chunk first line whole");
|
||||
}
|
||||
|
||||
private static void TailByteCap()
|
||||
{
|
||||
Case("tail: byte cap keeps the end");
|
||||
string path = WriteLines("cap.log", 2000, pad: 90); // ~100 bytes a line, ~200 KB
|
||||
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 50_000)!;
|
||||
Check(t.Text.Length <= 50_000, $"<= cap ({t.Text.Length})");
|
||||
string[] lines = LinesOf(t);
|
||||
Check(lines[0].StartsWith("line ") && lines[0].EndsWith(new string('.', 90)), "first line whole: " + lines[0][..Math.Min(20, lines[0].Length)]);
|
||||
Eq(lines[^1], "line 2000" + new string('.', 90), "last line kept");
|
||||
Eq(t.Lines, lines.Length, "line count matches");
|
||||
Check(t.Lines < 2000 && t.Lines > 400, $"about 490 lines ({t.Lines})");
|
||||
}
|
||||
|
||||
private static void TailPartialLastLine()
|
||||
{
|
||||
Case("tail: last line still being written");
|
||||
string path = WriteLines("p.log", 3000, trailing: false);
|
||||
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 10_000_000)!;
|
||||
string[] lines = LinesOf(t);
|
||||
Eq(t.Lines, 2000, "2000 lines incl. the unfinished one");
|
||||
Eq(lines[^1], "line 3000", "unfinished last line kept");
|
||||
Eq(lines[0], "line 1001", "first");
|
||||
}
|
||||
|
||||
private static void TailCrlfAndEdges()
|
||||
{
|
||||
Case("tail: CRLF, empty, missing");
|
||||
string path = WriteLines("crlf.log", 2500, newline: "\r\n");
|
||||
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 10_000_000)!;
|
||||
Eq(t.Lines, 2000, "CRLF lines");
|
||||
Check(Encoding.UTF8.GetString(t.Text).StartsWith("line 501\r\n"), "CRLF first line whole");
|
||||
File.WriteAllText(Path.Combine(_tmp, "empty.log"), "");
|
||||
LogTail e = ProblemReportCore.ReadTail(Path.Combine(_tmp, "empty.log"), null)!;
|
||||
Eq(e.Lines, 0, "empty file: no lines");
|
||||
Eq(e.Text.Length, 0, "empty file: no bytes");
|
||||
Check(ProblemReportCore.ReadTail(Path.Combine(_tmp, "nope.log"), null) == null, "missing file: null");
|
||||
Eq(ProblemReportCore.CountLines("a\nb"u8), 2, "count: unfinished last line");
|
||||
Eq(ProblemReportCore.CountLines("a\nb\n"u8), 2, "count: trailing newline");
|
||||
Eq(ProblemReportCore.CountLines(""u8), 0, "count: empty");
|
||||
}
|
||||
|
||||
private static void TailTopsUpFromOld()
|
||||
{
|
||||
Case("tail: rotated .old tops up a short log");
|
||||
string old = WriteLines("r.log.old", 3000, trailing: false); // the old file's last line lacks a newline
|
||||
File.WriteAllText(Path.Combine(_tmp, "r.log"), "new 1\nnew 2\nnew 3\n");
|
||||
LogTail t = ProblemReportCore.ReadTail(Path.Combine(_tmp, "r.log"), old, 2000, 10_000_000)!;
|
||||
string[] lines = LinesOf(t);
|
||||
Eq(t.Lines, 2000, "2000 lines in all");
|
||||
Check(t.IncludesOld, "marked as including .old");
|
||||
Eq(lines[0], "line 1004", "old part starts 1997 lines back");
|
||||
Eq(lines[1996], "line 3000", "old part's last line");
|
||||
Eq(lines[1997], "new 1", "then the current log");
|
||||
Eq(lines[^1], "new 3", "ends with the current log");
|
||||
|
||||
LogTail full = ProblemReportCore.ReadTail(WriteLines("f.log", 2500), old, 2000, 10_000_000)!;
|
||||
Check(!full.IncludesOld, "a full current log doesn't touch .old");
|
||||
}
|
||||
|
||||
private static void TailWhileWriting()
|
||||
{
|
||||
Case("tail: file being appended to");
|
||||
string path = Path.Combine(_tmp, "live.log");
|
||||
using var stop = new CancellationTokenSource();
|
||||
long written = 0;
|
||||
// The engine's writer: open, append one line, close, with FileShare.ReadWrite (EntryPoint.AppendWithRetry).
|
||||
var writer = new Thread(() =>
|
||||
{
|
||||
int i = 0;
|
||||
while (!stop.IsCancellationRequested)
|
||||
{
|
||||
i++;
|
||||
string line = $"[12:00:00.000] [pid:1] [INF] [engine] hb #{i} up={i}s fps=60 plug=30/s ws=400MB login=1\r\n";
|
||||
for (int attempt = 0; attempt < 4; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
|
||||
byte[] b = Encoding.UTF8.GetBytes(line);
|
||||
// Two writes, so a reader can land between them (a half-written line).
|
||||
fs.Write(b, 0, b.Length / 2);
|
||||
fs.Flush();
|
||||
fs.Write(b, b.Length / 2, b.Length - b.Length / 2);
|
||||
Interlocked.Increment(ref written);
|
||||
break;
|
||||
}
|
||||
catch (IOException) { Thread.Sleep(1); }
|
||||
}
|
||||
}
|
||||
}) { IsBackground = true };
|
||||
writer.Start();
|
||||
while (Interlocked.Read(ref written) < 3000) Thread.Sleep(5);
|
||||
|
||||
int reads = 0, bad = 0;
|
||||
var until = DateTime.UtcNow.AddSeconds(2);
|
||||
while (DateTime.UtcNow < until)
|
||||
{
|
||||
LogTail t = ProblemReportCore.ReadTail(path, null, 2000, 10_000_000)!;
|
||||
reads++;
|
||||
string text = Encoding.UTF8.GetString(t.Text);
|
||||
string[] lines = text.Split("\r\n");
|
||||
// Whole lines, except possibly the very last one (being written now).
|
||||
for (int k = 0; k < lines.Length - 1; k++)
|
||||
if (!lines[k].StartsWith("[12:00:00.000]") || !lines[k].EndsWith("login=1")) { bad++; break; }
|
||||
if (t.Lines != 2000) bad++;
|
||||
}
|
||||
stop.Cancel();
|
||||
writer.Join();
|
||||
Check(reads > 5, $"read repeatedly while writing ({reads} reads)");
|
||||
Eq(bad, 0, "every read: 2000 lines, all whole but the last");
|
||||
}
|
||||
|
||||
private static void AccountHidden()
|
||||
{
|
||||
Case("tail: account, Windows user and PC names hidden");
|
||||
string path = Path.Combine(_tmp, "acct.log");
|
||||
File.WriteAllText(path,
|
||||
"[12:00:00.000] [pid:1] [INF] [engine] SessionState: recorded login session for PID 1 account='MyLogin42' character='Drakkon' (IsLoggedIn=true).\n" +
|
||||
"[12:00:01.000] [pid:1] [INF] [engine] launch context for mylogin42 read\n" +
|
||||
"[12:00:02.000] [pid:1] [INF] [engine] account='' (empty field)\n" +
|
||||
"[12:00:03.000] [pid:1] [INF] [engine] watching 'C:\\Users\\Jane Q. Doe\\AppData\\Roaming\\RynthCore\\dispatch.txt'.\n" +
|
||||
"[12:00:04.000] [pid:1] [INF] [engine] d:/users/jdoe/x.txt on JANES-PC as jdoe; Drakkon says hi\n");
|
||||
var hide = new[] { ("MyLogin42", ProblemReportCore.HiddenAccount), ("jdoe", ProblemReportCore.HiddenUser), ("JANES-PC", "<pc>") };
|
||||
LogTail t = ProblemReportCore.ReadTail(path, null, hide: hide)!;
|
||||
string text = Encoding.UTF8.GetString(t.Text);
|
||||
Check(!text.Contains("MyLogin42", StringComparison.OrdinalIgnoreCase), "login name gone (any case)");
|
||||
Check(text.Contains("account='<account>' character='Drakkon'"), "account field hidden, character kept");
|
||||
Check(text.Contains("launch context for <account> read"), "free-text mention hidden");
|
||||
Check(text.Contains("account='<account>' (empty field)"), "every account= field hidden");
|
||||
Check(text.Contains(@"'C:\Users\<user>\AppData\Roaming\RynthCore\dispatch.txt'"), "profile folder hidden (with spaces): " + text.Split('\n')[3]);
|
||||
Check(text.Contains("d:/users/<user>/x.txt on <pc> as <user>; Drakkon says hi"), "forward-slash path, user and PC names hidden: " + text.Split('\n')[4]);
|
||||
Check(!text.Contains("Jane") && !text.Contains("jdoe") && !text.Contains("JANES"), "nothing of the names left");
|
||||
Eq(t.Lines, 5, "line count unchanged");
|
||||
Check(t.Gzip.Length > 0 && t.Text.Length == Encoding.UTF8.GetByteCount(text), "size and gzip are of the hidden text");
|
||||
|
||||
LogTail noHide = ProblemReportCore.ReadTail(path, null, hide: new[] { ("", "<x>"), ("ab", "<x>") })!;
|
||||
Check(Encoding.UTF8.GetString(noHide.Text).Contains("for mylogin42 read"), "short/empty hide words ignored (only the field and paths are hidden)");
|
||||
byte[] plain = Encoding.UTF8.GetBytes("nothing to hide\n");
|
||||
Check(ReferenceEquals(ProblemReportCore.Redact(plain, hide), plain), "unchanged text is the same array");
|
||||
byte[] dollar = Encoding.UTF8.GetBytes("user bob here\n");
|
||||
Eq(Encoding.UTF8.GetString(ProblemReportCore.Redact(dollar, new[] { ("bob", "$1<x>") })), "user $1<x> here\n", "replacement text taken literally");
|
||||
}
|
||||
|
||||
// ── Cooldown, endpoint, answers ──────────────────────────────────────
|
||||
|
||||
private static void Cooldown()
|
||||
{
|
||||
Case("cooldown");
|
||||
long now = 1_000_000;
|
||||
long next = now + ProblemReportCore.CooldownMs;
|
||||
Eq(ProblemReportCore.CooldownLeft(now, 0), 0L, "never sent: now");
|
||||
Eq(ProblemReportCore.CooldownLeft(now, next), 60_000L, "just sent: 60 s");
|
||||
Eq(ProblemReportCore.CooldownLeft(now + 59_999, next), 1L, "1 ms left");
|
||||
Eq(ProblemReportCore.CooldownLeft(now + 60_000, next), 0L, "after 60 s: now");
|
||||
Eq(ProblemReportCore.CooldownLeft(now + 90_000, next), 0L, "long after: now");
|
||||
Eq(ProblemReportCore.FormatWait(42_000), "42 s", "42 s");
|
||||
Eq(ProblemReportCore.FormatWait(41_001), "42 s", "rounds up");
|
||||
Eq(ProblemReportCore.FormatWait(65_000), "1 min 5 s", "over a minute");
|
||||
Check(ProblemReportCore.RetryAfterFailureMs < ProblemReportCore.CooldownMs, "a failed send waits less");
|
||||
}
|
||||
|
||||
private static void Endpoint()
|
||||
{
|
||||
Case("endpoint override");
|
||||
Eq(ProblemReportCore.ResolveEndpoint(null, out var r0), ProblemReportCore.DefaultEndpoint, "none: default");
|
||||
Check(r0 == null, "none: nothing rejected");
|
||||
Eq(ProblemReportCore.ResolveEndpoint("https://staging.example.org/rynth/report", out _), "https://staging.example.org/rynth/report", "https ok");
|
||||
Eq(ProblemReportCore.ResolveEndpoint("http://127.0.0.1:18097/report", out _), "http://127.0.0.1:18097/report", "http loopback ok");
|
||||
Eq(ProblemReportCore.ResolveEndpoint("http://localhost:18097/report", out _), "http://localhost:18097/report", "http localhost ok");
|
||||
Eq(ProblemReportCore.ResolveEndpoint("http://evil.example.org/report", out var r1), ProblemReportCore.DefaultEndpoint, "plain http elsewhere refused");
|
||||
Check(r1 != null, "refusal reported");
|
||||
Eq(ProblemReportCore.ResolveEndpoint("https://user:pw@example.org/", out _), ProblemReportCore.DefaultEndpoint, "credentials in URL refused");
|
||||
Eq(ProblemReportCore.ResolveEndpoint("file:///c:/x", out _), ProblemReportCore.DefaultEndpoint, "file: refused");
|
||||
Eq(ProblemReportCore.ResolveEndpoint("not a url", out _), ProblemReportCore.DefaultEndpoint, "garbage refused");
|
||||
}
|
||||
|
||||
private static void Responses()
|
||||
{
|
||||
Case("server answers");
|
||||
Check(ProblemReportCore.ReadResponse(202, "{\"ok\":true,\"id\":\"R-20261011-ab12cd\"}", out string m, out string id), "202 ok");
|
||||
Eq(id, "R-20261011-ab12cd", "id read");
|
||||
Check(m.Contains("R-20261011-ab12cd") && m.StartsWith("Sent"), "message names the id: " + m);
|
||||
Check(ProblemReportCore.ReadResponse(200, "", out m, out id) && id == "", "200 without body ok");
|
||||
Check(!ProblemReportCore.ReadResponse(429, "{\"error\":\"Too many reports from this address; try again in 40 minutes.\"}", out m, out _), "429 fails");
|
||||
Check(m.Contains("40 minutes"), "429 shows the server's reason: " + m);
|
||||
Check(!ProblemReportCore.ReadResponse(429, "<html>nginx</html>", out m, out _) && m.Contains("Too many"), "nginx 429 page: generic text");
|
||||
Check(!ProblemReportCore.ReadResponse(400, "{\"error\":\"description\"}", out m, out _) && m.Contains("refused") && m.Contains("description"), "400 refusal: " + m);
|
||||
Check(!ProblemReportCore.ReadResponse(413, "", out m, out _) && m.Contains("Untick"), "413 suggests unticking the log");
|
||||
Check(!ProblemReportCore.ReadResponse(502, "<html>", out m, out _) && m.Contains("502"), "502 says so");
|
||||
Check(!ProblemReportCore.ReadResponse(404, "", out m, out _) && m.Contains("404"), "404 says so");
|
||||
Check(!ProblemReportCore.ReadResponse(400, "{not json", out m, out _), "bad json doesn't throw");
|
||||
string longErr = "{\"error\":\"" + new string('e', 500) + "\"}";
|
||||
ProblemReportCore.ReadResponse(400, longErr, out m, out _);
|
||||
Check(m.Length < 260, "server text capped");
|
||||
}
|
||||
|
||||
private static void Sizes()
|
||||
{
|
||||
Case("sizes");
|
||||
Eq(ProblemReportCore.FormatSize(812), "812 bytes", "bytes");
|
||||
Eq(ProblemReportCore.FormatSize(214_000), "209 KB", "KB");
|
||||
Eq(ProblemReportCore.FormatSize(1_468_006), "1.4 MB", "MB");
|
||||
var t = new LogTail { FileName = "RynthCore.1.log", Text = new byte[2048], Lines = 1987, TakenLocal = new DateTime(2026, 10, 11, 14, 2, 11) };
|
||||
string d = ProblemReportCore.DescribeTail(t);
|
||||
Check(d.StartsWith("RynthCore.1.log: 1,987 lines, 2 KB (") && d.EndsWith("compressed), taken 14:02:11"), d);
|
||||
}
|
||||
|
||||
// ── Optional: against a local copy of the server ─────────────────────
|
||||
|
||||
private static async Task AgainstServer(string url)
|
||||
{
|
||||
Case("against " + url);
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
|
||||
string logPath = WriteLines("server.log", 2600, pad: 30);
|
||||
LogTail tail = ProblemReportCore.ReadTail(logPath, null)!;
|
||||
var ctx = SampleContext();
|
||||
ctx.Character = "Test Character " + Environment.ProcessId; // its own per-character bucket
|
||||
async Task<(int, string)> Post(byte[] body)
|
||||
{
|
||||
using var content = new ByteArrayContent(body);
|
||||
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
|
||||
using var resp = await http.PostAsync(url, content);
|
||||
return ((int)resp.StatusCode, await resp.Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
var (s1, b1) = await Post(ProblemReportCore.BuildPayload("Bot stuck at the portal @everyone **bold** `code`", "hunting", ctx, tail, DateTime.UtcNow));
|
||||
Check(ProblemReportCore.ReadResponse(s1, b1, out string m1, out string id1), $"with log taken: {s1} {b1}");
|
||||
Check(id1.StartsWith("R-"), "id returned: " + id1);
|
||||
Console.WriteLine(" " + m1);
|
||||
|
||||
var (s2, b2) = await Post(ProblemReportCore.BuildPayload("No log this time", "", ctx, null, DateTime.UtcNow));
|
||||
Check(ProblemReportCore.ReadResponse(s2, b2, out _, out _), $"without log taken: {s2} {b2}");
|
||||
|
||||
// A body the client would never build: refused.
|
||||
var (s3, _) = await Post(Encoding.UTF8.GetBytes("{\"schema\":1}"));
|
||||
Eq(s3, 400, "malformed refused");
|
||||
}
|
||||
}
|
||||
84
tools/ReloadCapTests/Program.cs
Normal file
84
tools/ReloadCapTests/Program.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
using RynthCore.Engine;
|
||||
|
||||
namespace ReloadCapTests;
|
||||
|
||||
/// <summary>
|
||||
/// The engine's side of the hot-reload cap (ReloadCapNotice.cs). After 4+ engine hot reloads in
|
||||
/// one client, clients died with CoreCLR fatal error 0x80131506; the loader now refuses reloads
|
||||
/// past engine.json MaxHotReloads and the engine tells the player.
|
||||
/// </summary>
|
||||
internal static class Program
|
||||
{
|
||||
private static int _checks, _failed;
|
||||
private static string _case = "";
|
||||
|
||||
private static int Main()
|
||||
{
|
||||
ChatTextIsThePlainSentence();
|
||||
ToldOnceThenOnlyWhenAskedByHand();
|
||||
AskedByHandFirstStillCountsAsTheOnce();
|
||||
ManualWindow();
|
||||
LogLineSaysWhy();
|
||||
|
||||
Console.WriteLine($"{_checks} check(s), {_failed} failed.");
|
||||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
private static void Check(bool ok, string what)
|
||||
{
|
||||
_checks++;
|
||||
if (ok) return;
|
||||
_failed++;
|
||||
Console.WriteLine($"[FAIL] {_case}: {what}");
|
||||
}
|
||||
|
||||
private static void ChatTextIsThePlainSentence()
|
||||
{
|
||||
_case = "chat text";
|
||||
Check(ReloadCapNotice.ChatText(3) == "RynthCore: this client has hot reloaded 3 times; restart the client to pick up the new engine.",
|
||||
$"3: {ReloadCapNotice.ChatText(3)}");
|
||||
Check(ReloadCapNotice.ChatText(1) == "RynthCore: this client has hot reloaded 1 time; restart the client to pick up the new engine.",
|
||||
$"1: {ReloadCapNotice.ChatText(1)}");
|
||||
Check(ReloadCapNotice.ChatText(0).Contains("hot reloaded 0 times"), $"0 (MaxHotReloads 0): {ReloadCapNotice.ChatText(0)}");
|
||||
Check(ReloadCapNotice.DefaultMaxHotReloads == 3, "the default cap is 3 (Loader.c DEFAULT_MAX_HOT_RELOADS)");
|
||||
}
|
||||
|
||||
private static void ToldOnceThenOnlyWhenAskedByHand()
|
||||
{
|
||||
_case = "once";
|
||||
var n = new ReloadCapNotice();
|
||||
Check(n.ShouldChat(askedByHand: false), "the first refusal (an engine publish) goes to chat");
|
||||
Check(!n.ShouldChat(askedByHand: false), "the second automatic one is logged only");
|
||||
Check(!n.ShouldChat(askedByHand: false), "and the third");
|
||||
Check(n.ShouldChat(askedByHand: true), "a press of RL is answered");
|
||||
Check(n.ShouldChat(askedByHand: true), "every time");
|
||||
Check(!n.ShouldChat(askedByHand: false), "automatic ones stay quiet after that");
|
||||
}
|
||||
|
||||
private static void AskedByHandFirstStillCountsAsTheOnce()
|
||||
{
|
||||
_case = "by hand first";
|
||||
var n = new ReloadCapNotice();
|
||||
Check(n.ShouldChat(askedByHand: true), "the first refusal, asked by hand, goes to chat");
|
||||
Check(!n.ShouldChat(askedByHand: false), "the next automatic one doesn't repeat it");
|
||||
}
|
||||
|
||||
private static void ManualWindow()
|
||||
{
|
||||
_case = "manual window";
|
||||
Check(!ReloadCapNotice.IsRecentManualSignal(0, 50_000), "never signalled: not by hand");
|
||||
Check(ReloadCapNotice.IsRecentManualSignal(100_000, 100_250), "250 ms after RL: by hand");
|
||||
Check(ReloadCapNotice.IsRecentManualSignal(100_000, 100_000 + ReloadCapNotice.ManualWindowMs - 1), "just inside the window");
|
||||
Check(!ReloadCapNotice.IsRecentManualSignal(100_000, 100_000 + ReloadCapNotice.ManualWindowMs), "at the window's end: not");
|
||||
Check(!ReloadCapNotice.IsRecentManualSignal(100_000, 99_000), "a signal 'in the future' (clock oddity): not");
|
||||
}
|
||||
|
||||
private static void LogLineSaysWhy()
|
||||
{
|
||||
_case = "log";
|
||||
string auto = ReloadCapNotice.LogText(3, 3, askedByHand: false);
|
||||
string hand = ReloadCapNotice.LogText(3, 3, askedByHand: true);
|
||||
Check(auto.Contains("hot reloaded 3 time(s)") && auto.Contains("MaxHotReloads is 3") && auto.Contains("restart"), auto);
|
||||
Check(!auto.Contains("by hand") && hand.Contains("(asked for by hand)"), hand);
|
||||
}
|
||||
}
|
||||
25
tools/ReloadCapTests/ReloadCapTests.csproj
Normal file
25
tools/ReloadCapTests/ReloadCapTests.csproj
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Offline checks for the engine's side of the hot-reload cap (2026-10-11):
|
||||
src\RynthCore.Engine\ReloadCapNotice.cs, compiled in. When the loader refuses a hot reload
|
||||
(engine.json MaxHotReloads, default 3), the player hears about it in chat once, and again only
|
||||
when they asked for the reload by hand (RL, /rc rl) within the last 10 s; the chat line is the
|
||||
plain sentence agreed for it. The loader's own rule (refuse once reloads >= cap, negative = no
|
||||
cap; nothing staged on a refusal) is checked in tools\LoaderReloadCapTests (C).
|
||||
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>ReloadCapTests</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.Engine\ReloadCapNotice.cs" Link="Engine\ReloadCapNotice.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -32,6 +32,7 @@ internal static class Program
|
|||
RaiseCommand();
|
||||
StatusFileReads();
|
||||
MoveProtocol();
|
||||
LogRollover();
|
||||
if (Arg(args, "--atlas") is { } atlas) RealAtlas(atlas);
|
||||
if (portal != null) RealSpellTable(portal);
|
||||
if (cell != null) RealWorldMap(cell, outFile);
|
||||
|
|
@ -41,6 +42,33 @@ internal static class Program
|
|||
return _failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
// ── log rollover ────────────────────────────────────────────────────────
|
||||
|
||||
private static void LogRollover()
|
||||
{
|
||||
Section("StatusAgent.log rolls over past its cap");
|
||||
string dir = Path.Combine(Path.GetTempPath(), "sa-logroll-" + Environment.ProcessId);
|
||||
Directory.CreateDirectory(dir);
|
||||
try
|
||||
{
|
||||
string f = Path.Combine(dir, "StatusAgent.log");
|
||||
File.WriteAllText(f, new string('x', 2000));
|
||||
File.WriteAllText(f + ".old", "older");
|
||||
AgentLog.RollIfBig(f, maxBytes: 1000);
|
||||
Check(!File.Exists(f), "the first write checks at once (a big log from before starts over)");
|
||||
Check(File.Exists(f + ".old") && new FileInfo(f + ".old").Length == 2000, "to .old, replacing the older copy");
|
||||
File.WriteAllText(f, new string('y', 3000));
|
||||
for (int i = 0; i < 199; i++) AgentLog.RollIfBig(f, maxBytes: 1000);
|
||||
Check(File.Exists(f), "then only every 200th write checks the size");
|
||||
AgentLog.RollIfBig(f, maxBytes: 1000);
|
||||
Check(!File.Exists(f) && new FileInfo(f + ".old").Length == 3000, "the 200th rolls it over");
|
||||
File.WriteAllText(f, "small");
|
||||
for (int i = 0; i < 400; i++) AgentLog.RollIfBig(f, maxBytes: 1000);
|
||||
Check(File.Exists(f), "under the cap it stays");
|
||||
}
|
||||
finally { try { Directory.Delete(dir, true); } catch { } }
|
||||
}
|
||||
|
||||
// ── landblocks ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void Landblocks()
|
||||
|
|
|
|||
|
|
@ -173,6 +173,9 @@ def main():
|
|||
# 8a. the 3D view's element class (Compatibility/AcMouseOver.cs)
|
||||
smartbox = [t for t in tables if at(u32(t + 0x98), 6) == bytes([0xB8, 0x30, 0x00, 0x00, 0x10, 0xC3])]
|
||||
check(len(smartbox) == 1, f"UIElement_SmartBoxWrapper: one UIElement vtable whose GetUIElementType returns 0x10000030 ({len(smartbox)})")
|
||||
# gmSmartBoxUI: what AC actually reports over open ground (element 0x1000049A)
|
||||
gmsbox = [t for t in tables if at(u32(t + 0x98), 6) == bytes([0xB8, 0x14, 0x00, 0x00, 0x10, 0xC3])]
|
||||
check(len(gmsbox) == 1, f"gmSmartBoxUI: one UIElement vtable whose GetUIElementType returns 0x10000014 ({len(gmsbox)})")
|
||||
|
||||
# 8. AC's mouse-over element (Compatibility/AcMouseOver.cs): UIElementManager +0x244
|
||||
switch = find([0x53, 0x8B, 0x5C, 0x24, 0x08, 0x56, 0x8B, 0xF1, 0x8B, 0x86, 0x44, 0x02, 0x00, 0x00, 0x57, 0x33, 0xFF,
|
||||
|
|
@ -215,6 +218,9 @@ def main():
|
|||
check("MgrMouseOver = 0x244" in mo and "MgrMouseOutside = 0x2D4" in mo and "VtGetUIElementType = 0x98" in mo,
|
||||
"AcMouseOver.cs reads +0x244, +0x2D4 and vtable +0x98")
|
||||
check("UIElementTypeSmartBoxWrapper = 0x10000030" in rules, "AcMouseOverRules.cs: the 3D view is type 0x10000030")
|
||||
check("UIElementTypeGmSmartBoxUI = 0x10000014" in rules, "AcMouseOverRules.cs: gmSmartBoxUI (0x10000014) is the 3D view too")
|
||||
check(len(matches(W, [0x68, 0x14, 0x00, 0x00, 0x10], limit=8)) >= 1,
|
||||
"push 10000014h present (gmSmartBoxUI::Register registers the type)")
|
||||
|
||||
print("=" * 60)
|
||||
print("PASS - the UI hooks' facts hold on this client." if fails == 0 else f"FAIL - {fails} check(s) failed.")
|
||||
|
|
|
|||
Loading…
Reference in a new issue