RynthSuite/Plugins/Shared/ServerQuestGuideHost.cs

172 lines
7.6 KiB
C#

// ============================================================================
// RynthSuite - Plugins/Shared/ServerQuestGuideHost.cs
// A server plugin's side of "RynthServer.QuestGuide" (RynthServerQuestGuideApi.cs):
// the plugin builds its guide (QuestGuideData.cs) however its server's wiki needs
// and hands it here with Publish; readers (RynthOracle) take it through the table.
//
// How a server plugin uses it:
// - its RynthPluginQueryInterface answers RynthServerQuestGuideApiV1.InterfaceName
// with ServerQuestGuideHost.Query(version);
// - Publish(...) whenever its guide or status changes (pump thread);
// - in its tick, TryTakeCommand drains what readers asked for ("refresh", "settings");
// - Release() at shutdown.
// The table is allocated once per loaded copy and never freed; after Release it
// reports Version 0 and its functions answer 0. Everything handed out is a snapshot
// swapped in whole, so any thread may read while the pump publishes.
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace RynthCore.Plugin.Shared;
internal static unsafe class ServerQuestGuideHost
{
private sealed record Snapshot(string Info, string Guide, string[] Commands);
private static RynthServerQuestGuideApiV1* _table;
private static volatile bool _released;
private static Snapshot? _snap;
private static long _revision;
private static readonly ConcurrentQueue<string> _commands = new();
private const int MaxQueued = 16;
/// <summary>The revision of what was published last (goes up with every Publish).</summary>
public static long Revision => Interlocked.Read(ref _revision);
/// <summary>
/// Publishes the guide and its status. <paramref name="guide"/> null (or empty) is "no guide yet": readers
/// see the status and no quests. <paramref name="commands"/>: the GuideCommand words this plugin takes.
/// </summary>
public static void Publish(string tag, string plugin, QuestGuide? guide, string status, bool running, params string[] commands)
{
string json = guide == null || guide.IsEmpty ? string.Empty : guide.ToJson();
long rev = Interlocked.Increment(ref _revision);
string[] words = Array.ConvertAll(commands ?? Array.Empty<string>(), c => (c ?? string.Empty).Trim().ToLowerInvariant());
Volatile.Write(ref _snap, new Snapshot(InfoJson(tag, plugin, rev, json, guide?.Quests.Count ?? 0, running, status, words), json, words));
}
/// <summary>Takes nothing more: readers see no guide (a server whose wiki was turned off).</summary>
public static void Withdraw()
{
Interlocked.Increment(ref _revision);
Volatile.Write(ref _snap, null);
}
/// <summary>The table for a reader asking for <paramref name="version"/>, or 0 (released, or a version this doesn't have).</summary>
public static IntPtr Query(uint version)
{
if (version < 1 || version > RynthServerQuestGuideApiV1.InterfaceVersion || _released) return IntPtr.Zero;
if (_table == null)
{
var t = (RynthServerQuestGuideApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerQuestGuideApiV1));
t->StructSize = (uint)sizeof(RynthServerQuestGuideApiV1);
t->GetGuideInfoJson = &GetGuideInfoJson;
t->GetGuideJson = &GetGuideJson;
t->GuideCommand = &GuideCommand;
t->Version = RynthServerQuestGuideApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>A command a reader sent (oldest first); the plugin runs it on its own tick.</summary>
public static bool TryTakeCommand(out string word) => _commands.TryDequeue(out word!);
/// <summary>Plugin shutdown: readers see Version 0 and re-query; the functions answer 0.</summary>
public static void Release()
{
_released = true;
if (_table != null) _table->Version = 0;
while (_commands.TryDequeue(out _)) { }
}
/// <summary>The tests: a fresh start (a new "copy" of the plugin).</summary>
internal static void ResetForTests()
{
_released = false;
Volatile.Write(ref _snap, null);
while (_commands.TryDequeue(out _)) { }
if (_table != null) _table->Version = RynthServerQuestGuideApiV1.InterfaceVersion;
}
internal static string InfoJson(string tag, string plugin, long revision, string guideJson, int quests, bool running, string status, string[] commands)
{
var sb = new StringBuilder(256);
sb.Append("{\"schema\":").Append(RynthServerQuestGuide.Schema);
Field(sb, "tag", tag);
Field(sb, "plugin", plugin);
sb.Append(",\"revision\":").Append(revision);
sb.Append(",\"bytes\":").Append(Encoding.UTF8.GetByteCount(guideJson));
sb.Append(",\"quests\":").Append(quests);
sb.Append(",\"running\":").Append(running ? "true" : "false");
Field(sb, "status", status);
sb.Append(",\"commands\":[");
for (int i = 0; i < commands.Length; i++)
{
if (i > 0) sb.Append(',');
sb.Append('"').Append(Ascii(commands[i])).Append('"');
}
sb.Append("]}");
return sb.ToString();
}
private static void Field(StringBuilder sb, string name, string? value) =>
sb.Append(",\"").Append(name).Append("\":\"").Append(Ascii(value)).Append('"');
/// <summary>JSON string content in plain ASCII (the info JSON's rule).</summary>
private static string Ascii(string? value)
{
var sb = new StringBuilder((value ?? string.Empty).Length);
foreach (char c in value ?? string.Empty)
{
if (c == '"') sb.Append("\\\"");
else if (c == '\\') sb.Append("\\\\");
else if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4"));
else sb.Append(c);
}
return sb.ToString();
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetGuideInfoJson(byte* buffer, int capacity)
{
try { return _released || Volatile.Read(ref _snap) is not Snapshot s ? 0 : Write(s.Info, buffer, capacity); }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetGuideJson(byte* buffer, int capacity)
{
try { return _released || Volatile.Read(ref _snap) is not Snapshot s || s.Guide.Length == 0 ? 0 : Write(s.Guide, buffer, capacity); }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GuideCommand(byte* line)
{
try
{
if (_released || line == null || Volatile.Read(ref _snap) is not Snapshot s) return 0;
string word = (Marshal.PtrToStringUTF8((IntPtr)line) ?? string.Empty).Trim().ToLowerInvariant();
if (word.Length == 0 || Array.IndexOf(s.Commands, word) < 0 || _commands.Count >= MaxQueued) return 0;
_commands.Enqueue(word);
return 1;
}
catch { return 0; }
}
/// <summary>NUL-terminated UTF-8 into the caller's buffer when it fits; the byte length either way.</summary>
private static int Write(string text, byte* buffer, int capacity)
{
int length = Encoding.UTF8.GetByteCount(text);
if (buffer == null || capacity <= length) return length;
fixed (char* src = text) Encoding.UTF8.GetBytes(src, text.Length, buffer, capacity);
buffer[length] = 0;
return length;
}
}