using System.Net;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core;
using XFEWarframe.Core.Data;
using XFEWarframe.Core.Services;
using Xunit;
namespace XFEWarframe.Tests;
public sealed partial class EngineTests
{
private const string OfficialBuild = "2026.10.22.13.12/test-cache-hash";
private const string OfficialGoalId = "6ad0ea700000000000000000";
private const string OfficialAlertId = "6ad0d7390dfe89c5d8229436";
private const string Moonflesh = "/Lotus/Types/Gameplay/Events/RoadToTauEvent/RoadToTauEventResource";
private static JObject OfficialSample(long now)
{
var result = new JObject { ["Time"] = now / 1000, ["BuildLabel"] = OfficialBuild,
["Tmp"] = new JObject { ["eventPhase"] = 3, ["fbst"] = new JObject { ["a"] = now / 1000 - 60, ["e"] = now / 1000 + 7200 } }.ToString(Formatting.None) };
foreach (var field in OfficialEvents.Fields) result[field] = new JArray();
result["Goals"] = new JArray(new JObject { ["_id"] = Wire.Oid(OfficialGoalId), ["Tag"] = "RoadToTauEvent", ["Goal"] = 0,
["Activation"] = Wire.Date(now - 60000), ["Expiry"] = Wire.Date(now + WorldData.Day),
["Count"] = 53, ["HealthPct"] = .5300602962m, ["Community"] = true, ["ClanGoal"] = new JArray(72, 216, 648, 1944, 5832),
["RegionDrops"] = new JArray("/Lotus/Types/Gameplay/Events/RoadToTauEvent/RoadToTauEventPickup"), ["Regions"] = new JArray(10), ["ItemType"] = Moonflesh });
result["Alerts"] = new JArray(new JObject { ["_id"] = Wire.Oid(OfficialAlertId), ["Tag"] = "RoadToTauEvent", ["Activation"] = Wire.Date(now - 60000), ["Expiry"] = Wire.Date(now + 5400000),
["MissionInfo"] = new JObject { ["missionType"] = "MT_SURVIVAL", ["location"] = "SolNode173", ["minEnemyLevel"] = 50, ["maxEnemyLevel"] = 50,
["missionReward"] = new JObject { ["credits"] = 17000, ["countedItems"] = new JArray(new JObject { ["ItemType"] = Moonflesh, ["ItemCount"] = 50 }) } } });
result["Events"] = new JArray(new JObject { ["_id"] = Wire.Oid("6ad0ea700000000000000001"), ["Msg"] = "Official event", ["Date"] = Wire.Date(now) });
return result;
}
private sealed class OfficialHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> response) : HttpMessageHandler
{
public int Calls;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Calls++;
Assert.Equal(OfficialEvents.Source, request.RequestUri!.AbsoluteUri);
Assert.Equal(HttpMethod.Get, request.Method);
Assert.Null(request.Headers.Authorization);
return response(request, cancellationToken);
}
}
private static HttpResponseMessage OfficialResponse(JObject world) => new(HttpStatusCode.OK) { Content = new StringContent(world.ToString(Formatting.None), Encoding.UTF8, "application/json") };
private TestClock OfficialClock() => new(new DateTimeOffset(2026, 10, 27, 12, 0, 0, TimeSpan.Zero));
private void UseOfficialClient(TestClock time, HttpClient client)
{
options.FallbackBuildLabel = OfficialBuild;
engine = new(store, options, time, officialEventsClient: client);
}
[Fact] public async Task OfficialSyncRequiresAdminAndPreservesAccountsWhileMirroringEveryPhaseParameter()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
using var handler = new OfficialHandler((_, _) => Task.FromResult(OfficialResponse(official)));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
await Login();
var before = await store.Read(s => s["accounts"]!.DeepClone());
Assert.Equal(401, (await Call("/control/v1/events")).Status);
Assert.Equal(401, (await Call("/control/v1/events/sync", new { })).Status);
Assert.Equal(0, handler.Calls);
var sync = await Call("/control/v1/events/sync", new { }, admin: true);
Assert.True(sync.Status == 200, sync.Body); Assert.Equal(1, handler.Calls);
Assert.True(JToken.DeepEquals(before, await store.Read(s => s["accounts"]!.DeepClone())));
var world = JObject.Parse((await Call("/dynamic/worldState.php", query: new() { ["buildLabel"] = OfficialBuild })).Body);
foreach (var field in OfficialEvents.Fields)
foreach (var entry in official[field]!.OfType<JObject>())
Assert.True(JToken.DeepEquals(entry, world[field]!.OfType<JObject>().Single(x => Wire.Id(x["_id"]) == Wire.Id(entry["_id"]))), field);
Assert.Equal(.5300602962m, world["Goals"]![0]!.Value<decimal>("HealthPct"));
var flags = JObject.Parse(world.Value<string>("Tmp")!);
Assert.Equal(3, flags.Value<int>("eventPhase"));
Assert.True(JToken.DeepEquals(JObject.Parse(official.Value<string>("Tmp")!)["fbst"], flags["fbst"]));
Assert.NotNull(flags["lqo"]); Assert.NotNull(flags["hqo"]);
Assert.Equal(64, JObject.Parse(sync.Body).Value<string>("sha256")!.Length);
}
[Fact] public async Task OfficialSyncFollowsChangedStagesAndDoesNotEraseLocalActivitiesOrNews()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
using var handler = new OfficialHandler((_, _) => Task.FromResult(OfficialResponse(official)));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
var localId = Wire.NewId();
await store.Update(s => { s.Obj("worldState")["Goals"] = new JArray(new JObject { ["_id"] = Wire.Oid(localId), ["Tag"] = "LocalActivity", ["Expiry"] = Wire.Date(time.Now.AddDays(1).ToUnixTimeMilliseconds()) }); return 0; });
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
official["Goals"]![0]!["Count"] = 60; official["Goals"]![0]!["HealthPct"] = .6;
var updatedFlags = JObject.Parse(official.Value<string>("Tmp")!); updatedFlags["eventPhase"] = 4; official["Tmp"] = updatedFlags.ToString(Formatting.None);
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
var world = JObject.Parse((await Call("/dynamic/worldState.php", query: new() { ["buildLabel"] = OfficialBuild })).Body);
Assert.Equal(60, world["Goals"]!.Single(x => Wire.Id(x["_id"]) == OfficialGoalId).Value<int>("Count"));
Assert.Contains(world["Goals"]!, x => Wire.Id(x["_id"]) == localId);
Assert.Equal(4, JObject.Parse(world.Value<string>("Tmp")!).Value<int>("eventPhase"));
Assert.Contains(world["Events"]!, x => x.Value<string>("Msg")?.Contains("XFEWarframe", StringComparison.Ordinal) == true);
}
[Fact] public async Task FailedOfficialSyncKeepsTheLastSuccessfulSnapshotAndReportsStaleness()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds()); var fail = false;
using var handler = new OfficialHandler((_, _) => Task.FromResult(fail ? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) : OfficialResponse(official)));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
var before = await store.Read(s => s["officialEvents"]!["world"]!.DeepClone());
fail = true; time.Now = time.Now.AddMinutes(4);
Assert.Equal(502, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
Assert.True(JToken.DeepEquals(before, await store.Read(s => s["officialEvents"]!["world"]!.DeepClone())));
var status = JObject.Parse((await Call("/control/v1/events", admin: true)).Body);
Assert.True(status.Value<bool>("stale")); Assert.NotNull(status["lastError"]); Assert.True(status.Value<bool>("hasSnapshot"));
await store.DisposeAsync(); store = new(root); engine = new(store, options, time, officialEventsClient: http);
Assert.True(JToken.DeepEquals(before, await store.Read(s => s["officialEvents"]!["world"]!.DeepClone())));
}
[Theory] [InlineData("build")] [InlineData("clock")] [InlineData("collection")] [InlineData("flags")] [InlineData("duplicate")] [InlineData("deepFlags")] [InlineData("trailing")]
public async Task InvalidOfficialDocumentsCannotReplaceCachedActivities(string defect)
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
var broken = (JObject)official.DeepClone();
if (defect == "build") broken["BuildLabel"] = "invalid";
if (defect == "clock") broken["Time"] = time.Now.AddDays(-1).ToUnixTimeSeconds();
if (defect == "collection") broken["Goals"] = new JObject();
if (defect == "flags") broken["Tmp"] = "[]";
if (defect == "deepFlags") broken["Tmp"] = string.Concat(Enumerable.Repeat("{\"x\":", 60)) + "0" + new string('}', 60);
var json = broken.ToString(Formatting.None);
if (defect == "duplicate") json = json.Insert(1, "\"Time\":1,");
if (defect == "trailing") json += " {}";
using var handler = new OfficialHandler((_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json) }));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
await store.Update(s => { OfficialEvents.Store(s, official, time.Now.ToUnixTimeMilliseconds()); return 0; });
Assert.Equal(502, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
Assert.True(JToken.DeepEquals(official, await store.Read(s => s["officialEvents"]!["world"]!.DeepClone())));
}
[Fact] public async Task SettingsAndServerDefaultsDisableBothFetchingAndPublishingCachedEvents()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
using var handler = new OfficialHandler((_, _) => Task.FromResult(OfficialResponse(official)));
using var http = new HttpClient(handler); options.SyncOfficialEvents = false; UseOfficialClient(time, http);
await store.Update(s => { OfficialEvents.Store(s, official, time.Now.ToUnixTimeMilliseconds()); return 0; });
Assert.Equal(409, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
var world = JObject.Parse((await Call("/dynamic/worldState.php", query: new() { ["buildLabel"] = OfficialBuild })).Body);
Assert.DoesNotContain(world["Goals"]!, x => Wire.Id(x["_id"]) == OfficialGoalId); Assert.Equal(0, handler.Calls);
var settings = await ServerSettings();
Assert.False(settings["fields"]!.Single(x => x.Value<string>("key") == "worldState.officialEventsEnabled").Value<bool>("value"));
Assert.Equal(200, (await SetServer(settings, new JObject { ["worldState.officialEventsEnabled"] = true })).Status);
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
world = JObject.Parse((await Call("/dynamic/worldState.php", query: new() { ["buildLabel"] = OfficialBuild })).Body);
Assert.Contains(world["Goals"]!, x => Wire.Id(x["_id"]) == OfficialGoalId);
settings = await ServerSettings(); Assert.Equal(200, (await SetServer(settings, new JObject { ["worldState.officialEventsEnabled"] = false })).Status);
Assert.False(JObject.Parse((await Call("/control/v1/events", admin: true)).Body).Value<bool>("enabled"));
Assert.Equal(409, (await Call("/control/v1/events/sync", new { }, admin: true)).Status); Assert.Equal(1, handler.Calls);
}
[Fact] public async Task OfficialNetworkWaitDoesNotBlockPlayerSaveTransactions()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var handler = new OfficialHandler(async (_, token) => { entered.SetResult(); await release.Task.WaitAsync(token); return OfficialResponse(official); });
using var http = new HttpClient(handler); UseOfficialClient(time, http);
var q = await Login(); var pending = engine.OfficialEventSync.Synchronize();
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5));
try
{
var saved = await Call($"/control/v1/accounts/{q["accountId"]}/currency", new { currency = "RegularCredits", delta = 123 }, admin: true).WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(200, saved.Status); Assert.Equal(123, (await InventoryOf(q)).Value<int>("RegularCredits"));
}
finally { release.TrySetResult(); await pending; }
}
[Fact] public async Task OfficialGoalArraysAndAlertRewardsWorkWithLocalClanAndInventoryApis()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
using var handler = new OfficialHandler((_, _) => Task.FromResult(OfficialResponse(official)));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
var q = await Login(); await CreateClan(q, "OfficialActivityClan");
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
var progress = await Call("/api/goals.php", new { Progress = new[] { new { _id = Wire.Oid(OfficialGoalId), Count = 72, Best = 72 } } }, q);
Assert.True(progress.Status == 200, progress.Body);
var guild = JObject.Parse((await Call("/custom/getGuild", query: q)).Body);
Assert.Equal(72, guild["GoalProgress"]![0]!.Value<int>("Count"));
var mission = new { EndOfMatchUpload = true, Missions = new { Tag = "SolNode173", Tier = 0, Completes = 1 }, RewardInfo = new { alertId = OfficialAlertId, node = "SolNode173", rewardSeed = "1" } };
var finished = await Call("/api/missionInventoryUpdate.php", mission, q);
Assert.True(finished.Status == 200, finished.Body);
var inventory = await InventoryOf(q);
Assert.Equal(50, inventory["MiscItems"]!.Single(x => x.Value<string>("ItemType") == Moonflesh).Value<int>("ItemCount"));
Assert.Equal(200, (await Call("/api/missionInventoryUpdate.php", mission, q)).Status);
Assert.Equal(50, (await InventoryOf(q))["MiscItems"]!.Single(x => x.Value<string>("ItemType") == Moonflesh).Value<int>("ItemCount"));
}
[Fact] public void OfficialSnapshotsExpireEntriesProtectOlderBuildsAndIgnoreOlderCdnResponses()
{
var time = OfficialClock(); var now = time.Now.ToUnixTimeMilliseconds(); var official = OfficialSample(now); var state = new JObject();
OfficialEvents.Store(state, official, now);
var old = WorldApi.Generate(state, "2026.08.19.11.06", now);
Assert.DoesNotContain(old["Goals"]!, x => Wire.Id(x["_id"]) == OfficialGoalId);
var older = (JObject)official.DeepClone(); older["Time"] = now / 1000 - 1; older["Goals"]![0]!["Count"] = 1;
OfficialEvents.Store(state, older, now + 1000);
Assert.Equal(53, state["officialEvents"]!["world"]!["Goals"]![0]!.Value<int>("Count"));
var expired = WorldApi.Generate(state, OfficialBuild, now + 2 * WorldData.Day);
Assert.DoesNotContain(expired["Goals"]!, x => Wire.Id(x["_id"]) == OfficialGoalId);
Assert.DoesNotContain(expired["Alerts"]!, x => Wire.Id(x["_id"]) == OfficialAlertId);
}
[Fact] public void OfficialEventRewardPathsPreserveTheActualAvatarNamespace()
{
const string glyph = "/Lotus/Types/StoreItems/AvatarImages/TenYearAnniversaryWeek4Glyph";
var storePath = "/Lotus/StoreItems/Types/StoreItems/AvatarImages/TenYearAnniversaryWeek4Glyph";
Assert.Equal(glyph, GameData.ItemType(storePath)); Assert.Equal(glyph, GameData.ItemType(glyph)); Assert.Equal(storePath, GameData.StoreType(glyph));
var catalog = new ItemCatalog(); Assert.Equal("FlavourItems", catalog.Get(storePath).Category);
Assert.Equal("MiscItems", catalog.Get(Moonflesh).Category);
Assert.Equal("WeaponSkins", catalog.Get("/Lotus/StoreItems/Upgrades/Skins/MeleeDangles/PumpkinMeleeDangle").Category);
}
}
using System.Net;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core;
using XFEWarframe.Core.Data;
using XFEWarframe.Core.Services;
using Xunit;
namespace XFEWarframe.Tests;
public sealed partial class EngineTests
{
private const string OfficialBuild = "2026.10.22.13.12/test-cache-hash";
private const string OfficialGoalId = "6ad0ea700000000000000000";
private const string OfficialAlertId = "6ad0d7390dfe89c5d8229436";
private const string Moonflesh = "/Lotus/Types/Gameplay/Events/RoadToTauEvent/RoadToTauEventResource";
private static JObject OfficialSample(long now)
{
var result = new JObject { ["Time"] = now / 1000, ["BuildLabel"] = OfficialBuild,
["Tmp"] = new JObject { ["eventPhase"] = 3, ["fbst"] = new JObject { ["a"] = now / 1000 - 60, ["e"] = now / 1000 + 7200 } }.ToString(Formatting.None) };
foreach (var field in OfficialEvents.Fields) result[field] = new JArray();
result["Goals"] = new JArray(new JObject { ["_id"] = Wire.Oid(OfficialGoalId), ["Tag"] = "RoadToTauEvent", ["Goal"] = 0,
["Activation"] = Wire.Date(now - 60000), ["Expiry"] = Wire.Date(now + WorldData.Day),
["Count"] = 53, ["HealthPct"] = .5300602962m, ["Community"] = true, ["ClanGoal"] = new JArray(72, 216, 648, 1944, 5832),
["RegionDrops"] = new JArray("/Lotus/Types/Gameplay/Events/RoadToTauEvent/RoadToTauEventPickup"), ["Regions"] = new JArray(10), ["ItemType"] = Moonflesh });
result["Alerts"] = new JArray(new JObject { ["_id"] = Wire.Oid(OfficialAlertId), ["Tag"] = "RoadToTauEvent", ["Activation"] = Wire.Date(now - 60000), ["Expiry"] = Wire.Date(now + 5400000),
["MissionInfo"] = new JObject { ["missionType"] = "MT_SURVIVAL", ["location"] = "SolNode173", ["minEnemyLevel"] = 50, ["maxEnemyLevel"] = 50,
["missionReward"] = new JObject { ["credits"] = 17000, ["countedItems"] = new JArray(new JObject { ["ItemType"] = Moonflesh, ["ItemCount"] = 50 }) } } });
result["Events"] = new JArray(new JObject { ["_id"] = Wire.Oid("6ad0ea700000000000000001"), ["Msg"] = "Official event", ["Date"] = Wire.Date(now) });
return result;
}
private sealed class OfficialHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> response) : HttpMessageHandler
{
public int Calls;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Calls++;
Assert.Equal(OfficialEvents.Source, request.RequestUri!.AbsoluteUri);
Assert.Equal(HttpMethod.Get, request.Method);
Assert.Null(request.Headers.Authorization);
return response(request, cancellationToken);
}
}
private static HttpResponseMessage OfficialResponse(JObject world) => new(HttpStatusCode.OK) { Content = new StringContent(world.ToString(Formatting.None), Encoding.UTF8, "application/json") };
private TestClock OfficialClock() => new(new DateTimeOffset(2026, 10, 27, 12, 0, 0, TimeSpan.Zero));
private void UseOfficialClient(TestClock time, HttpClient client)
{
options.FallbackBuildLabel = OfficialBuild;
engine = new(store, options, time, officialEventsClient: client);
}
[Fact] public async Task OfficialSyncRequiresAdminAndPreservesAccountsWhileMirroringEveryPhaseParameter()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
using var handler = new OfficialHandler((_, _) => Task.FromResult(OfficialResponse(official)));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
await Login();
var before = await store.Read(s => s["accounts"]!.DeepClone());
Assert.Equal(401, (await Call("/control/v1/events")).Status);
Assert.Equal(401, (await Call("/control/v1/events/sync", new { })).Status);
Assert.Equal(0, handler.Calls);
var sync = await Call("/control/v1/events/sync", new { }, admin: true);
Assert.True(sync.Status == 200, sync.Body); Assert.Equal(1, handler.Calls);
Assert.True(JToken.DeepEquals(before, await store.Read(s => s["accounts"]!.DeepClone())));
var world = JObject.Parse((await Call("/dynamic/worldState.php", query: new() { ["buildLabel"] = OfficialBuild })).Body);
foreach (var field in OfficialEvents.Fields)
foreach (var entry in official[field]!.OfType<JObject>())
Assert.True(JToken.DeepEquals(entry, world[field]!.OfType<JObject>().Single(x => Wire.Id(x["_id"]) == Wire.Id(entry["_id"]))), field);
Assert.Equal(.5300602962m, world["Goals"]![0]!.Value<decimal>("HealthPct"));
var flags = JObject.Parse(world.Value<string>("Tmp")!);
Assert.Equal(3, flags.Value<int>("eventPhase"));
Assert.True(JToken.DeepEquals(JObject.Parse(official.Value<string>("Tmp")!)["fbst"], flags["fbst"]));
Assert.NotNull(flags["lqo"]); Assert.NotNull(flags["hqo"]);
Assert.Equal(64, JObject.Parse(sync.Body).Value<string>("sha256")!.Length);
}
[Fact] public async Task OfficialSyncFollowsChangedStagesAndDoesNotEraseLocalActivitiesOrNews()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
using var handler = new OfficialHandler((_, _) => Task.FromResult(OfficialResponse(official)));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
var localId = Wire.NewId();
await store.Update(s => { s.Obj("worldState")["Goals"] = new JArray(new JObject { ["_id"] = Wire.Oid(localId), ["Tag"] = "LocalActivity", ["Expiry"] = Wire.Date(time.Now.AddDays(1).ToUnixTimeMilliseconds()) }); return 0; });
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
official["Goals"]![0]!["Count"] = 60; official["Goals"]![0]!["HealthPct"] = .6;
var updatedFlags = JObject.Parse(official.Value<string>("Tmp")!); updatedFlags["eventPhase"] = 4; official["Tmp"] = updatedFlags.ToString(Formatting.None);
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
var world = JObject.Parse((await Call("/dynamic/worldState.php", query: new() { ["buildLabel"] = OfficialBuild })).Body);
Assert.Equal(60, world["Goals"]!.Single(x => Wire.Id(x["_id"]) == OfficialGoalId).Value<int>("Count"));
Assert.Contains(world["Goals"]!, x => Wire.Id(x["_id"]) == localId);
Assert.Equal(4, JObject.Parse(world.Value<string>("Tmp")!).Value<int>("eventPhase"));
Assert.Contains(world["Events"]!, x => x.Value<string>("Msg")?.Contains("XFEWarframe", StringComparison.Ordinal) == true);
}
[Fact] public async Task FailedOfficialSyncKeepsTheLastSuccessfulSnapshotAndReportsStaleness()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds()); var fail = false;
using var handler = new OfficialHandler((_, _) => Task.FromResult(fail ? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) : OfficialResponse(official)));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
var before = await store.Read(s => s["officialEvents"]!["world"]!.DeepClone());
fail = true; time.Now = time.Now.AddMinutes(4);
Assert.Equal(502, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
Assert.True(JToken.DeepEquals(before, await store.Read(s => s["officialEvents"]!["world"]!.DeepClone())));
var status = JObject.Parse((await Call("/control/v1/events", admin: true)).Body);
Assert.True(status.Value<bool>("stale")); Assert.NotNull(status["lastError"]); Assert.True(status.Value<bool>("hasSnapshot"));
await store.DisposeAsync(); store = new(root); engine = new(store, options, time, officialEventsClient: http);
Assert.True(JToken.DeepEquals(before, await store.Read(s => s["officialEvents"]!["world"]!.DeepClone())));
}
[Theory] [InlineData("build")] [InlineData("clock")] [InlineData("collection")] [InlineData("flags")] [InlineData("duplicate")] [InlineData("deepFlags")] [InlineData("trailing")]
public async Task InvalidOfficialDocumentsCannotReplaceCachedActivities(string defect)
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
var broken = (JObject)official.DeepClone();
if (defect == "build") broken["BuildLabel"] = "invalid";
if (defect == "clock") broken["Time"] = time.Now.AddDays(-1).ToUnixTimeSeconds();
if (defect == "collection") broken["Goals"] = new JObject();
if (defect == "flags") broken["Tmp"] = "[]";
if (defect == "deepFlags") broken["Tmp"] = string.Concat(Enumerable.Repeat("{\"x\":", 60)) + "0" + new string('}', 60);
var json = broken.ToString(Formatting.None);
if (defect == "duplicate") json = json.Insert(1, "\"Time\":1,");
if (defect == "trailing") json += " {}";
using var handler = new OfficialHandler((_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json) }));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
await store.Update(s => { OfficialEvents.Store(s, official, time.Now.ToUnixTimeMilliseconds()); return 0; });
Assert.Equal(502, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
Assert.True(JToken.DeepEquals(official, await store.Read(s => s["officialEvents"]!["world"]!.DeepClone())));
}
[Fact] public async Task SettingsAndServerDefaultsDisableBothFetchingAndPublishingCachedEvents()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
using var handler = new OfficialHandler((_, _) => Task.FromResult(OfficialResponse(official)));
using var http = new HttpClient(handler); options.SyncOfficialEvents = false; UseOfficialClient(time, http);
await store.Update(s => { OfficialEvents.Store(s, official, time.Now.ToUnixTimeMilliseconds()); return 0; });
Assert.Equal(409, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
var world = JObject.Parse((await Call("/dynamic/worldState.php", query: new() { ["buildLabel"] = OfficialBuild })).Body);
Assert.DoesNotContain(world["Goals"]!, x => Wire.Id(x["_id"]) == OfficialGoalId); Assert.Equal(0, handler.Calls);
var settings = await ServerSettings();
Assert.False(settings["fields"]!.Single(x => x.Value<string>("key") == "worldState.officialEventsEnabled").Value<bool>("value"));
Assert.Equal(200, (await SetServer(settings, new JObject { ["worldState.officialEventsEnabled"] = true })).Status);
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
world = JObject.Parse((await Call("/dynamic/worldState.php", query: new() { ["buildLabel"] = OfficialBuild })).Body);
Assert.Contains(world["Goals"]!, x => Wire.Id(x["_id"]) == OfficialGoalId);
settings = await ServerSettings(); Assert.Equal(200, (await SetServer(settings, new JObject { ["worldState.officialEventsEnabled"] = false })).Status);
Assert.False(JObject.Parse((await Call("/control/v1/events", admin: true)).Body).Value<bool>("enabled"));
Assert.Equal(409, (await Call("/control/v1/events/sync", new { }, admin: true)).Status); Assert.Equal(1, handler.Calls);
}
[Fact] public async Task OfficialNetworkWaitDoesNotBlockPlayerSaveTransactions()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var handler = new OfficialHandler(async (_, token) => { entered.SetResult(); await release.Task.WaitAsync(token); return OfficialResponse(official); });
using var http = new HttpClient(handler); UseOfficialClient(time, http);
var q = await Login(); var pending = engine.OfficialEventSync.Synchronize();
await entered.Task.WaitAsync(TimeSpan.FromSeconds(5));
try
{
var saved = await Call($"/control/v1/accounts/{q["accountId"]}/currency", new { currency = "RegularCredits", delta = 123 }, admin: true).WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(200, saved.Status); Assert.Equal(123, (await InventoryOf(q)).Value<int>("RegularCredits"));
}
finally { release.TrySetResult(); await pending; }
}
[Fact] public async Task OfficialGoalArraysAndAlertRewardsWorkWithLocalClanAndInventoryApis()
{
var time = OfficialClock(); var official = OfficialSample(time.Now.ToUnixTimeMilliseconds());
using var handler = new OfficialHandler((_, _) => Task.FromResult(OfficialResponse(official)));
using var http = new HttpClient(handler); UseOfficialClient(time, http);
var q = await Login(); await CreateClan(q, "OfficialActivityClan");
Assert.Equal(200, (await Call("/control/v1/events/sync", new { }, admin: true)).Status);
var progress = await Call("/api/goals.php", new { Progress = new[] { new { _id = Wire.Oid(OfficialGoalId), Count = 72, Best = 72 } } }, q);
Assert.True(progress.Status == 200, progress.Body);
var guild = JObject.Parse((await Call("/custom/getGuild", query: q)).Body);
Assert.Equal(72, guild["GoalProgress"]![0]!.Value<int>("Count"));
var mission = new { EndOfMatchUpload = true, Missions = new { Tag = "SolNode173", Tier = 0, Completes = 1 }, RewardInfo = new { alertId = OfficialAlertId, node = "SolNode173", rewardSeed = "1" } };
var finished = await Call("/api/missionInventoryUpdate.php", mission, q);
Assert.True(finished.Status == 200, finished.Body);
var inventory = await InventoryOf(q);
Assert.Equal(50, inventory["MiscItems"]!.Single(x => x.Value<string>("ItemType") == Moonflesh).Value<int>("ItemCount"));
Assert.Equal(200, (await Call("/api/missionInventoryUpdate.php", mission, q)).Status);
Assert.Equal(50, (await InventoryOf(q))["MiscItems"]!.Single(x => x.Value<string>("ItemType") == Moonflesh).Value<int>("ItemCount"));
}
[Fact] public void OfficialSnapshotsExpireEntriesProtectOlderBuildsAndIgnoreOlderCdnResponses()
{
var time = OfficialClock(); var now = time.Now.ToUnixTimeMilliseconds(); var official = OfficialSample(now); var state = new JObject();
OfficialEvents.Store(state, official, now);
var old = WorldApi.Generate(state, "2026.08.19.11.06", now);
Assert.DoesNotContain(old["Goals"]!, x => Wire.Id(x["_id"]) == OfficialGoalId);
var older = (JObject)official.DeepClone(); older["Time"] = now / 1000 - 1; older["Goals"]![0]!["Count"] = 1;
OfficialEvents.Store(state, older, now + 1000);
Assert.Equal(53, state["officialEvents"]!["world"]!["Goals"]![0]!.Value<int>("Count"));
var expired = WorldApi.Generate(state, OfficialBuild, now + 2 * WorldData.Day);
Assert.DoesNotContain(expired["Goals"]!, x => Wire.Id(x["_id"]) == OfficialGoalId);
Assert.DoesNotContain(expired["Alerts"]!, x => Wire.Id(x["_id"]) == OfficialAlertId);
}
[Fact] public void OfficialEventRewardPathsPreserveTheActualAvatarNamespace()
{
const string glyph = "/Lotus/Types/StoreItems/AvatarImages/TenYearAnniversaryWeek4Glyph";
var storePath = "/Lotus/StoreItems/Types/StoreItems/AvatarImages/TenYearAnniversaryWeek4Glyph";
Assert.Equal(glyph, GameData.ItemType(storePath)); Assert.Equal(glyph, GameData.ItemType(glyph)); Assert.Equal(storePath, GameData.StoreType(glyph));
var catalog = new ItemCatalog(); Assert.Equal("FlavourItems", catalog.Get(storePath).Category);
Assert.Equal("MiscItems", catalog.Get(Moonflesh).Category);
Assert.Equal("WeaponSkins", catalog.Get("/Lotus/StoreItems/Upgrades/Skins/MeleeDangles/PumpkinMeleeDangle").Category);
}
}