Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/launcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -1199,7 +1199,10 @@ write and gives it to the character in game.
- **Give item** gives the item to the character in game, into the main inventory, through the Waypoint Tools mod
(LocalExile-Mods' `waypoint-tools`, `WaypointToolsMod.cs`), the same on a source copy and a release; it needs no other
mod and no Frida. The mod counts as loaded when its `data/waypoint-tools/loaded.json` names a Gateway process that still
runs and lists `item_give`. Waypoint writes `data/waypoint-tools/requests/<id>.json` (as `.tmp`, then renamed) with the
runs and lists `item_give`. The Gateway's `commands` and `values` modes, which the Console and the lab layout ask,
load the mods too, so the mod writes that file with the question's process, which exits without unloading it: Waypoint
asks one question at a time, keeps the file a running Gateway wrote and puts it back when the question wrote over it
(`CommandCatalog.AskGateway`). Waypoint writes `data/waypoint-tools/requests/<id>.json` (as `.tmp`, then renamed) with the
item and no character, and the mod gives it to the one character in game on that connection's next tick, then answers
in `replies/<id>.json`, which Waypoint reads and deletes; the answer shows in the status line. Nothing goes over the
network and nothing limits the item's length. An answer not there in 35 seconds (the mod waits 30 for a character in
Expand Down
49 changes: 49 additions & 0 deletions src/Launcher.Core/WaypointToolsMod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,55 @@ public static bool Loaded(string root, string action, Func<int, bool>? running =
}
}

/// <summary><c>loaded.json</c> as a running Gateway wrote it, to put back after a question to the Gateway
/// (<see cref="PutBack"/>); null when no running process wrote it.</summary>
/// <remarks>The Gateway's <c>commands</c> and <c>values</c> modes load the mods to list theirs: this mod then writes its
/// <c>loaded.json</c> with the question's process, which exits without unloading it, and Give item would find no game
/// with the mod loaded until the mod loads again.</remarks>
public static string? KeepLoaded(string root, Func<int, bool>? running = null)
{
try
{
string file = Path.Combine(Root(root), "loaded.json");
if (!File.Exists(file)) return null;
string text = File.ReadAllText(file);
return Pid(text) is int pid && (running ?? Running)(pid) ? text : null;
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{
return null;
}
}

/// <summary>After the question to the Gateway that ran as process <paramref name="question"/>: puts back what
/// <see cref="KeepLoaded"/> kept, when the question wrote over it and the Gateway that wrote it still runs. Anything
/// else (the mod unloaded or loaded again meanwhile, that Gateway stopped) stays as it is.</summary>
public static void PutBack(string root, string? kept, int question, Func<int, bool>? running = null)
{
if (kept is null || Pid(kept) is not int pid) return;
try
{
string file = Path.Combine(Root(root), "loaded.json");
if (!File.Exists(file) || Pid(File.ReadAllText(file)) != question || !(running ?? Running)(pid)) return;
File.WriteAllText(file + ".tmp", kept);
File.Move(file + ".tmp", file, overwrite: true);
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
}

/// <summary>The process a <c>loaded.json</c> names, or null when it names none or is not JSON.</summary>
static int? Pid(string text)
{
try
{
return JsonNode.Parse(text) is JsonObject json ? (int?)json["pid"] : null;
}
catch (Exception e) when (e is JsonException or FormatException or InvalidOperationException)
{
return null;
}
}

static bool Running(int pid)
{
try
Expand Down
24 changes: 24 additions & 0 deletions src/Waypoint/CommandCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,35 @@ public static async Task<CommandCatalog> LoadAsync()
return new(Parse(await AskGateway(TimeSpan.FromSeconds(30), dll, "commands")), built);
}

// One question at a time: each one keeps the Waypoint Tools mod's loaded.json and puts it back, which another question
// running beside it would undo.
static readonly SemaphoreSlim Asking = new(1, 1);

/// <summary>Runs the built Gateway in one of its listing modes and returns what it printed. The process never outlives
/// the question, whatever it was doing.</summary>
internal static async Task<string> AskGateway(TimeSpan timeout, params string[] arguments)
{
if (!Repo.IsInstall && !Repo.HasLauncherHooks())
throw new InvalidOperationException(L.Text("This checkout is older than the launcher hooks, so its Gateway cannot list commands: pull the server's main branch."));
await Asking.WaitAsync();
// The commands and values modes load the mods too: Waypoint Tools would then name this question in loaded.json, and
// Give item would find no game with it loaded once the question exits (WaypointToolsMod.KeepLoaded).
string root = Environment.CurrentDirectory;
string? loaded = WaypointToolsMod.KeepLoaded(root);
int question = 0;
try
{
return await AskAsync(timeout, arguments, id => question = id);
}
finally
{
if (question != 0) WaypointToolsMod.PutBack(root, loaded, question);
Asking.Release();
}
}

static async Task<string> AskAsync(TimeSpan timeout, string[] arguments, Action<int> started)
{
// A release's Gateway is its own executable.
#if WINDOWS
bool program = arguments[0].EndsWith(".exe", StringComparison.OrdinalIgnoreCase);
Expand All @@ -56,6 +79,7 @@ internal static async Task<string> AskGateway(TimeSpan timeout, params string[]
info.Environment["TMPDIR"] = temp;
#endif
using var process = Process.Start(info)!;
started(process.Id);
try
{
string output = await process.StandardOutput.ReadToEndAsync().WaitAsync(timeout);
Expand Down
38 changes: 38 additions & 0 deletions tests/Waypoint.Tests/WaypointToolsModTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,44 @@ public void The_mod_counts_as_loaded_only_in_a_running_Gateway_with_the_action()
Assert.False(WaypointToolsMod.Loaded(_root, "item_give", _ => true));
}

[Fact]
public void A_Gateway_question_that_loaded_the_mod_gives_loaded_json_back_to_the_running_Gateway()
{
const string gateway = """{"protocol":1,"version":"1.0.0","pid":42,"actions":["item_give"]}""";
WriteLoaded(gateway);
string? kept = WaypointToolsMod.KeepLoaded(_root, pid => pid == 42);
Assert.Equal(gateway, kept);
// The `commands` question (process 7) loaded the mods, which wrote over it, and exited.
WriteLoaded("""{"protocol":1,"version":"1.0.0","pid":7,"actions":["item_give"]}""");
WaypointToolsMod.PutBack(_root, kept, question: 7, running: pid => pid == 42);
Assert.Equal(gateway, File.ReadAllText(Data("loaded.json")));
Assert.True(WaypointToolsMod.Loaded(_root, "item_give", pid => pid == 42));
Assert.Empty(Directory.GetFiles(Data(), "*.tmp"));
}

[Fact]
public void Loaded_json_is_put_back_only_over_the_question_and_for_a_Gateway_that_still_runs()
{
const string gateway = """{"protocol":1,"pid":42,"actions":["item_give"]}""";
// Nothing to keep when the process that wrote it has stopped.
WriteLoaded(gateway);
Assert.Null(WaypointToolsMod.KeepLoaded(_root, _ => false));
// The Gateway loaded the mod again meanwhile: what it wrote now stays.
const string reloaded = """{"protocol":1,"version":"1.0.1","pid":42,"actions":["item_give"]}""";
WriteLoaded(reloaded);
WaypointToolsMod.PutBack(_root, gateway, question: 7, running: _ => true);
Assert.Equal(reloaded, File.ReadAllText(Data("loaded.json")));
// The Gateway stopped while the question ran.
const string question = """{"protocol":1,"pid":7,"actions":["item_give"]}""";
WriteLoaded(question);
WaypointToolsMod.PutBack(_root, gateway, question: 7, running: _ => false);
Assert.Equal(question, File.ReadAllText(Data("loaded.json")));
// The mod unloaded: no file comes back.
File.Delete(Data("loaded.json"));
WaypointToolsMod.PutBack(_root, gateway, question: 7, running: _ => true);
Assert.False(File.Exists(Data("loaded.json")));
}

[Fact]
public void Installed_means_its_folder_has_a_manifest()
{
Expand Down
Loading