feat(livestreamassist): add read-only WebSocket API

Add a Fleck/Newtonsoft.Json listener for local and LAN clients, with system methods, main-thread reflection reads, and ZipMod packaging of the two runtime DLLs. Ctrl+F8 statistics assist is unchanged. In-game and LAN acceptance remain pending.
This commit is contained in:
soarqin committed 2026-09-17 18:14:51 +08:00
1 parent ce9a4b73cd
commit 94254b8c28
16 files changed
+3300 -37

No files matched your search

+863
View File
@@ -0,0 +1,863 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace LiveStreamAssist.Api;
internal static class ApiLimits
{
public const string ApiVersion = "1.0.0";
public const string Path = "/api/v1";
public const int MaxConnections = 8;
public const int MaxPendingRequestsPerConnection = 8;
public const int MaxPendingRequests = 64;
public const int MaxRequestBytes = 65536;
public const int MaxResponseBytes = 262144;
public const int MaxJsonDepth = 32;
public const int MaxIdLength = 64;
public const int MaxPathSegments = 16;
public const int MaxSelectMembers = 32;
public const int DefaultPageSize = 64;
public const int MaxPageSize = 128;
public const int RequestTimeoutMs = 5000;
public const int MaxRequestsPerFrame = 8;
public const int MainThreadBudgetMs = 2;
public const int MaxIncomingSocketBytes = MaxRequestBytes + 8192;
public const int CloseGoingAway = 1001;
public const int CloseUnsupportedData = 1003;
public const int CloseInvalidPayload = 1007;
public const int ClosePolicyViolation = 1008;
public const int CloseMessageTooBig = 1009;
public const int CloseTryAgainLater = 1013;
}
internal sealed class ApiError
{
public int Code;
public string Kind;
public string Message;
public int? SegmentIndex;
public string Member;
public string Root;
public ApiError WithPath(int? segmentIndex = null, string member = null, string root = null)
{
SegmentIndex = segmentIndex;
Member = member;
Root = root;
return this;
}
}
internal sealed class ApiRequest
{
public string Id;
public string Method;
public JObject Params;
}
internal enum DataMethod
{
Roots,
Describe,
Read
}
internal struct ReadOptions
{
public bool HasSelect;
public string[] Select;
public bool HasOffset;
public int Offset;
public bool HasLimit;
public int Limit;
public int EffectiveOffset => HasOffset ? Offset : 0;
public int EffectiveLimit => HasLimit ? Limit : ApiLimits.DefaultPageSize;
}
internal sealed class DataCall
{
public DataMethod Method;
public string Root;
public PathSeg[] Path;
public ReadOptions Options;
}
internal enum PathKind
{
Member,
Index,
Key
}
internal readonly struct PathSeg
{
public readonly PathKind Kind;
public readonly string Name;
public readonly int Index;
public readonly object Key;
public PathSeg(string name)
{
Kind = PathKind.Member;
Name = name;
Index = 0;
Key = null;
}
public PathSeg(int index)
{
Kind = PathKind.Index;
Name = null;
Index = index;
Key = null;
}
public PathSeg(object key)
{
Kind = PathKind.Key;
Name = null;
Index = 0;
Key = key;
}
}
internal static class ApiErrors
{
public static ApiError ParseError() =>
New(-32700, "PARSE_ERROR", "Malformed JSON.");
public static ApiError InvalidRequest(string message = "Invalid request.") =>
New(-32600, "INVALID_REQUEST", message);
public static ApiError MethodNotFound() =>
New(-32601, "METHOD_NOT_FOUND", "Unknown method.");
public static ApiError InvalidParams(string message = "Invalid parameters.") =>
New(-32602, "INVALID_PARAMS", message);
public static ApiError InternalError() =>
New(-32603, "INTERNAL_ERROR", "Unexpected server failure.");
public static ApiError GameNotReady() =>
New(-32001, "GAME_NOT_READY", "Game data is unavailable.");
public static ApiError RootNotFound(string root) =>
New(-32002, "ROOT_NOT_FOUND", "Unknown root.").WithPath(root: root);
public static ApiError RootUnavailable(string root) =>
New(-32003, "ROOT_UNAVAILABLE", "Root is unavailable.").WithPath(root: root);
public static ApiError MemberNotFound(string member, int? segmentIndex = null) =>
New(-32004, "MEMBER_NOT_FOUND", "Requested member does not exist.").WithPath(segmentIndex, member);
public static ApiError MemberNotAllowed(string member, int? segmentIndex = null) =>
New(-32005, "MEMBER_NOT_ALLOWED", "Member is outside the read policy.").WithPath(segmentIndex, member);
public static ApiError NullPath(int segmentIndex) =>
New(-32006, "NULL_PATH", "Null encountered before completing the path.").WithPath(segmentIndex);
public static ApiError IndexOutOfRange(int segmentIndex) =>
New(-32007, "INDEX_OUT_OF_RANGE", "Element index is outside the current array or list.").WithPath(segmentIndex);
public static ApiError KeyNotFound(int segmentIndex) =>
New(-32008, "KEY_NOT_FOUND", "Dictionary has no matching key.").WithPath(segmentIndex);
public static ApiError UnsupportedType(int? segmentIndex = null, string member = null) =>
New(-32009, "UNSUPPORTED_TYPE", "Value type or traversal is unsupported.").WithPath(segmentIndex, member);
public static ApiError ReadFailed(int? segmentIndex = null, string member = null) =>
New(-32010, "READ_FAILED", "A permitted read failed.").WithPath(segmentIndex, member);
public static ApiError LimitExceeded(string message = "A documented resource limit would be exceeded.") =>
New(-32011, "LIMIT_EXCEEDED", message);
public static ApiError ServerBusy() =>
New(-32012, "SERVER_BUSY", "Admission capacity is exhausted.");
public static ApiError RequestTimeout() =>
New(-32013, "REQUEST_TIMEOUT", "Response production exceeded its deadline.");
public static ApiError SessionChanged() =>
New(-32014, "SESSION_CHANGED", "Session changed after admission.");
public static ApiError UnsupportedValue() =>
New(-32015, "UNSUPPORTED_VALUE", "Value cannot be represented under the scalar rules.");
static ApiError New(int code, string kind, string message) =>
new ApiError { Code = code, Kind = kind, Message = message };
}
internal static class ApiProtocol
{
public const string JsonRpc = "2.0";
public const string MethodPing = "system.ping";
public const string MethodInfo = "system.info";
public const string MethodValidate = "system.validate";
public const string MethodStats = "system.stats";
public const string MethodRoots = "data.roots";
public const string MethodDescribe = "data.describe";
public const string MethodRead = "data.read";
static readonly HashSet<string> SystemMethods = new HashSet<string>(StringComparer.Ordinal)
{
MethodPing, MethodInfo, MethodValidate, MethodStats
};
static readonly HashSet<string> DataMethods = new HashSet<string>(StringComparer.Ordinal)
{
MethodRoots, MethodDescribe, MethodRead
};
static readonly JsonSerializer Serializer = JsonSerializer.Create(new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.None,
DateParseHandling = DateParseHandling.None,
NullValueHandling = NullValueHandling.Include,
Formatting = Formatting.None,
MaxDepth = ApiLimits.MaxJsonDepth
});
public static bool IsSystemMethod(string method) => SystemMethods.Contains(method);
public static bool IsDataMethod(string method) => DataMethods.Contains(method);
public static bool TryParseMessage(string text, out ApiRequest request, out ApiError error, out object id)
{
request = null;
error = null;
id = null;
JToken token;
try
{
using (var sr = new StringReader(text))
using (var reader = new JsonTextReader(sr))
{
reader.DateParseHandling = DateParseHandling.None;
reader.MaxDepth = ApiLimits.MaxJsonDepth;
var load = new JsonLoadSettings
{
DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error,
LineInfoHandling = LineInfoHandling.Ignore
};
token = JToken.Load(reader, load);
if (reader.Read() && reader.TokenType != JsonToken.None)
{
error = ApiErrors.ParseError();
return false;
}
}
}
catch (Exception)
{
error = ApiErrors.ParseError();
return false;
}
if (token is JArray)
{
error = ApiErrors.InvalidRequest("Batch requests are not supported.");
return false;
}
if (!(token is JObject obj))
{
error = ApiErrors.InvalidRequest();
return false;
}
foreach (var prop in obj.Properties())
{
if (prop.Name != "jsonrpc" && prop.Name != "id" && prop.Name != "method" && prop.Name != "params")
{
error = ApiErrors.InvalidRequest("Unknown envelope field.");
return false;
}
}
var jsonrpc = obj["jsonrpc"];
if (jsonrpc == null || jsonrpc.Type != JTokenType.String || !string.Equals(jsonrpc.Value<string>(), JsonRpc, StringComparison.Ordinal))
{
error = ApiErrors.InvalidRequest("jsonrpc must be \"2.0\".");
return false;
}
if (!obj.TryGetValue("id", out var idToken) || idToken == null || idToken.Type == JTokenType.Null)
{
error = ApiErrors.InvalidRequest("id is required.");
return false;
}
if (idToken.Type != JTokenType.String)
{
error = ApiErrors.InvalidRequest("id must be a string.");
return false;
}
var idValue = idToken.Value<string>();
if (string.IsNullOrEmpty(idValue))
{
error = ApiErrors.InvalidRequest("id must be nonempty.");
return false;
}
if (idValue.Length > ApiLimits.MaxIdLength)
{
error = ApiErrors.InvalidRequest("id exceeds maxIdLength.");
return false;
}
id = idValue;
if (!obj.TryGetValue("method", out var methodToken) || methodToken == null || methodToken.Type != JTokenType.String)
{
error = ApiErrors.InvalidRequest("method is required.");
return false;
}
var method = methodToken.Value<string>();
if (string.IsNullOrEmpty(method))
{
error = ApiErrors.InvalidRequest("method is required.");
return false;
}
JObject parms;
if (!obj.TryGetValue("params", out var paramsToken) || paramsToken == null || paramsToken.Type == JTokenType.Null)
parms = new JObject();
else if (paramsToken is JObject p)
parms = p;
else
{
error = ApiErrors.InvalidParams("params must be an object.");
return false;
}
request = new ApiRequest { Id = idValue, Method = method, Params = parms };
return true;
}
public static bool TryParseDataCall(ApiRequest request, out DataCall call, out ApiError error)
{
call = null;
error = null;
switch (request.Method)
{
case MethodRoots:
error = RejectUnknownParams(request.Params);
if (error != null) return false;
call = new DataCall { Method = DataMethod.Roots, Path = Array.Empty<PathSeg>() };
return true;
case MethodDescribe:
return TryParseDescribe(request.Params, out call, out error);
case MethodRead:
return TryParseRead(request.Params, out call, out error);
default:
error = ApiErrors.MethodNotFound();
return false;
}
}
public static object HandleSystem(string method, JObject parms, GameVersionSnapshot version, string modVersion)
{
switch (method)
{
case MethodPing:
{
var err = RejectUnknownParams(parms);
if (err != null) return err;
return new Dictionary<string, object>
{
["serverTimeUtc"] = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture)
};
}
case MethodInfo:
{
var err = RejectUnknownParams(parms);
if (err != null) return err;
return BuildInfo(version, modVersion);
}
case MethodValidate:
return HandleValidate(parms);
case MethodStats:
{
var err = RejectUnknownParams(parms);
if (err != null) return err;
return new Dictionary<string, object>
{
["available"] = false,
["metrics"] = null
};
}
default:
return ApiErrors.MethodNotFound();
}
}
public static Dictionary<string, object> BuildInfo(GameVersionSnapshot version, string modVersion)
{
var ready = version != null && version.Ready;
return new Dictionary<string, object>
{
["apiVersion"] = ApiLimits.ApiVersion,
["modVersion"] = modVersion ?? "",
["gameVersionReady"] = ready,
["gameVersion"] = ready ? version.GameVersion : null,
["gameBuild"] = ready ? (object)version.GameBuild : null,
["capabilities"] = new Dictionary<string, object>
{
["reflection.read"] = true,
["reflection.describe"] = true,
["api.stats"] = false,
["subscriptions"] = false
},
["limits"] = new Dictionary<string, object>
{
["maxConnections"] = ApiLimits.MaxConnections,
["maxPendingRequestsPerConnection"] = ApiLimits.MaxPendingRequestsPerConnection,
["maxPendingRequests"] = ApiLimits.MaxPendingRequests,
["maxRequestBytes"] = ApiLimits.MaxRequestBytes,
["maxResponseBytes"] = ApiLimits.MaxResponseBytes,
["maxJsonDepth"] = ApiLimits.MaxJsonDepth,
["maxIdLength"] = ApiLimits.MaxIdLength,
["maxPathSegments"] = ApiLimits.MaxPathSegments,
["maxSelectMembers"] = ApiLimits.MaxSelectMembers,
["defaultPageSize"] = ApiLimits.DefaultPageSize,
["maxPageSize"] = ApiLimits.MaxPageSize,
["requestTimeoutMs"] = ApiLimits.RequestTimeoutMs,
["maxRequestsPerFrame"] = ApiLimits.MaxRequestsPerFrame,
["mainThreadBudgetMs"] = ApiLimits.MainThreadBudgetMs
}
};
}
public static bool CapabilityEnabled(string name)
{
switch (name)
{
case "reflection.read":
case "reflection.describe":
return true;
default:
return false;
}
}
public static byte[] SerializeEnvelope(object id, object result, ApiError error)
{
var envelope = new Dictionary<string, object>
{
["jsonrpc"] = JsonRpc,
["id"] = id
};
if (error != null)
envelope["error"] = ErrorBody(error);
else
envelope["result"] = result;
return SerializeBounded(envelope);
}
public static Dictionary<string, object> ErrorBody(ApiError error)
{
var data = new Dictionary<string, object> { ["kind"] = error.Kind };
if (error.SegmentIndex.HasValue) data["segmentIndex"] = error.SegmentIndex.Value;
if (error.Member != null) data["member"] = error.Member;
if (error.Root != null) data["root"] = error.Root;
return new Dictionary<string, object>
{
["code"] = error.Code,
["message"] = error.Message,
["data"] = data
};
}
public static byte[] SerializeBounded(object value)
{
using (var bounded = new BoundedStream(ApiLimits.MaxResponseBytes))
using (var writer = new StreamWriter(bounded, new UTF8Encoding(false), 1024, true))
using (var json = new JsonTextWriter(writer))
{
json.Formatting = Formatting.None;
Serializer.Serialize(json, value);
json.Flush();
writer.Flush();
return bounded.ToArray();
}
}
public static ApiError RejectUnknownParams(JObject parms, params string[] allowed)
{
if (parms == null) return null;
foreach (var prop in parms.Properties())
{
var known = false;
for (var i = 0; i < allowed.Length; i++)
{
if (string.Equals(prop.Name, allowed[i], StringComparison.Ordinal))
{
known = true;
break;
}
}
if (!known)
return ApiErrors.InvalidParams("Unknown parameter '" + prop.Name + "'.");
}
return null;
}
static object HandleValidate(JObject parms)
{
var err = RejectUnknownParams(parms, "apiMajor", "requiredCapabilities");
if (err != null) return err;
if (!parms.TryGetValue("apiMajor", out var majorToken) || majorToken == null || majorToken.Type == JTokenType.Null)
return ApiErrors.InvalidParams("apiMajor is required.");
if (!TryGetInt32(majorToken, out var apiMajor) || apiMajor < 1)
return ApiErrors.InvalidParams("apiMajor must be a positive 32-bit integer.");
var missing = new List<string>();
if (parms.TryGetValue("requiredCapabilities", out var capToken) && capToken != null && capToken.Type != JTokenType.Null)
{
if (!(capToken is JArray arr))
return ApiErrors.InvalidParams("requiredCapabilities must be an array.");
if (arr.Count > 32)
return ApiErrors.LimitExceeded("requiredCapabilities exceeds 32 entries.");
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var item in arr)
{
if (item == null || item.Type != JTokenType.String)
return ApiErrors.InvalidParams("Capability names must be nonempty strings.");
var name = item.Value<string>();
if (string.IsNullOrEmpty(name))
return ApiErrors.InvalidParams("Capability names must be nonempty strings.");
if (!seen.Add(name))
return ApiErrors.InvalidParams("requiredCapabilities must be distinct.");
if (!CapabilityEnabled(name))
missing.Add(name);
}
}
var majorOk = apiMajor == 1;
return new Dictionary<string, object>
{
["compatible"] = majorOk && missing.Count == 0,
["apiVersion"] = ApiLimits.ApiVersion,
["apiMajorCompatible"] = majorOk,
["missingCapabilities"] = missing
};
}
static bool TryParseDescribe(JObject parms, out DataCall call, out ApiError error)
{
call = null;
error = RejectUnknownParams(parms, "root", "path");
if (error != null) return false;
if (!TryParseRoot(parms, out var root, out error)) return false;
if (!TryParsePath(parms, out var path, out error)) return false;
call = new DataCall { Method = DataMethod.Describe, Root = root, Path = path };
return true;
}
static bool TryParseRead(JObject parms, out DataCall call, out ApiError error)
{
call = null;
error = RejectUnknownParams(parms, "root", "path", "select", "offset", "limit");
if (error != null) return false;
if (!TryParseRoot(parms, out var root, out error)) return false;
if (!TryParsePath(parms, out var path, out error)) return false;
var options = new ReadOptions();
if (parms.TryGetValue("select", out var selectToken) && selectToken != null && selectToken.Type != JTokenType.Null)
{
if (!(selectToken is JArray arr))
{
error = ApiErrors.InvalidParams("select must be an array of member names.");
return false;
}
if (arr.Count < 1)
{
error = ApiErrors.InvalidParams("select must contain at least one member.");
return false;
}
if (arr.Count > ApiLimits.MaxSelectMembers)
{
error = ApiErrors.LimitExceeded("select exceeds maxSelectMembers.");
return false;
}
var names = new string[arr.Count];
var seen = new HashSet<string>(StringComparer.Ordinal);
for (var i = 0; i < arr.Count; i++)
{
var item = arr[i];
if (item == null || item.Type != JTokenType.String)
{
error = ApiErrors.InvalidParams("select members must be nonempty strings.");
return false;
}
var name = item.Value<string>();
if (string.IsNullOrEmpty(name))
{
error = ApiErrors.InvalidParams("select members must be nonempty strings.");
return false;
}
if (!seen.Add(name))
{
error = ApiErrors.InvalidParams("select members must be distinct.");
return false;
}
names[i] = name;
}
options.HasSelect = true;
options.Select = names;
}
if (parms.TryGetValue("offset", out var offsetToken) && offsetToken != null && offsetToken.Type != JTokenType.Null)
{
if (!TryGetInt32(offsetToken, out var offset) || offset < 0)
{
error = ApiErrors.InvalidParams("offset must be a nonnegative 32-bit integer.");
return false;
}
options.HasOffset = true;
options.Offset = offset;
}
if (parms.TryGetValue("limit", out var limitToken) && limitToken != null && limitToken.Type != JTokenType.Null)
{
if (!TryGetInt32(limitToken, out var limit))
{
error = ApiErrors.InvalidParams("limit must be an integer.");
return false;
}
if (limit < 1)
{
error = ApiErrors.InvalidParams("limit must be at least 1.");
return false;
}
if (limit > ApiLimits.MaxPageSize)
{
error = ApiErrors.LimitExceeded("limit exceeds maxPageSize.");
return false;
}
options.HasLimit = true;
options.Limit = limit;
}
call = new DataCall { Method = DataMethod.Read, Root = root, Path = path, Options = options };
return true;
}
static bool TryParseRoot(JObject parms, out string root, out ApiError error)
{
root = null;
error = null;
if (!parms.TryGetValue("root", out var token) || token == null || token.Type == JTokenType.Null)
{
error = ApiErrors.InvalidParams("root is required.");
return false;
}
if (token.Type != JTokenType.String)
{
error = ApiErrors.InvalidParams("root must be a string.");
return false;
}
root = token.Value<string>();
if (string.IsNullOrEmpty(root))
{
error = ApiErrors.InvalidParams("root must be a nonempty string.");
return false;
}
return true;
}
static bool TryParsePath(JObject parms, out PathSeg[] path, out ApiError error)
{
path = Array.Empty<PathSeg>();
error = null;
if (!parms.TryGetValue("path", out var token) || token == null || token.Type == JTokenType.Null)
return true;
if (!(token is JArray arr))
{
error = ApiErrors.InvalidParams("path must be an array.");
return false;
}
if (arr.Count > ApiLimits.MaxPathSegments)
{
error = ApiErrors.LimitExceeded("path exceeds maxPathSegments.");
return false;
}
var segs = new PathSeg[arr.Count];
for (var i = 0; i < arr.Count; i++)
{
if (!TryParseSegment(arr[i], out segs[i], out error))
return false;
}
path = segs;
return true;
}
static bool TryParseSegment(JToken token, out PathSeg seg, out ApiError error)
{
seg = default;
error = null;
if (token == null || token.Type == JTokenType.Null)
{
error = ApiErrors.InvalidParams("path segments cannot be null.");
return false;
}
if (token.Type == JTokenType.String)
{
var name = token.Value<string>();
if (string.IsNullOrEmpty(name))
{
error = ApiErrors.InvalidParams("member names must be nonempty.");
return false;
}
seg = new PathSeg(name);
return true;
}
if (token.Type == JTokenType.Integer)
{
if (!TryGetInt32(token, out var index) || index < 0)
{
error = ApiErrors.InvalidParams("indexes must be nonnegative 32-bit integers.");
return false;
}
seg = new PathSeg(index);
return true;
}
if (token is JObject obj)
{
JProperty keyProp = null;
foreach (var prop in obj.Properties())
{
if (!string.Equals(prop.Name, "key", StringComparison.Ordinal))
{
error = ApiErrors.InvalidParams("key segments may only contain 'key'.");
return false;
}
keyProp = prop;
}
if (keyProp == null || keyProp.Value == null || keyProp.Value.Type == JTokenType.Null)
{
error = ApiErrors.InvalidParams("key is required.");
return false;
}
if (keyProp.Value.Type == JTokenType.String)
{
seg = new PathSeg((object)keyProp.Value.Value<string>());
return true;
}
if (keyProp.Value.Type == JTokenType.Integer && TryGetInt32(keyProp.Value, out var key))
{
seg = new PathSeg((object)key);
return true;
}
error = ApiErrors.InvalidParams("dictionary keys must be strings or 32-bit integers.");
return false;
}
error = ApiErrors.InvalidParams("unsupported path segment.");
return false;
}
public static bool TryGetInt32(JToken token, out int value)
{
value = 0;
if (token == null || token.Type != JTokenType.Integer) return false;
try
{
var n = token.Value<long>();
if (n < int.MinValue || n > int.MaxValue) return false;
value = (int)n;
return true;
}
catch
{
return false;
}
}
public static int ApiMajor => 1;
}
internal sealed class BoundedStream : MemoryStream
{
readonly int _max;
public BoundedStream(int max) => _max = max;
public override void Write(byte[] buffer, int offset, int count)
{
if (Length + count > _max)
throw new ResponseTooLargeException();
base.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
if (Length + 1 > _max)
throw new ResponseTooLargeException();
base.WriteByte(value);
}
}
internal sealed class ResponseTooLargeException : Exception;
internal sealed class GameVersionSnapshot
{
public readonly bool Ready;
public readonly string GameVersion;
public readonly int GameBuild;
public GameVersionSnapshot(bool ready, string gameVersion, int gameBuild)
{
Ready = ready;
GameVersion = gameVersion;
GameBuild = gameBuild;
}
public static readonly GameVersionSnapshot Empty = new GameVersionSnapshot(false, null, 0);
}
internal sealed class SessionSnapshot
{
public readonly int Generation;
public readonly string SessionId;
public SessionSnapshot(int generation, string sessionId)
{
Generation = generation;
SessionId = sessionId;
}
}
@@ -0,0 +1,162 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using UnityEngine;
namespace LiveStreamAssist.Api;
internal sealed class GameWork
{
public PendingRequest Pending;
public DataCall Call;
public int Generation;
public long DeadlineMs;
}
internal delegate object GameWorkExecutor(GameWork work);
internal sealed class MainThreadDispatcher
{
readonly SynchronizationContext _context;
readonly object _token;
readonly object _gate = new object();
readonly Queue<GameWork> _queue = new Queue<GameWork>();
readonly GameWorkExecutor _execute;
readonly Func<long> _nowMs;
bool _pumpScheduled;
bool _stopped;
int _frame = -1;
int _startedThisFrame;
readonly Stopwatch _budget = new Stopwatch();
public MainThreadDispatcher(SynchronizationContext context, object token, GameWorkExecutor execute, Func<long> nowMs)
{
_context = context;
_token = token;
_execute = execute;
_nowMs = nowMs;
}
public bool TryEnqueue(GameWork work)
{
lock (_gate)
{
if (_stopped) return false;
_queue.Enqueue(work);
ScheduleLocked();
return true;
}
}
public void CancelQueued(Func<GameWork, ApiError> reason)
{
List<GameWork> taken;
lock (_gate)
{
if (_queue.Count == 0) return;
taken = new List<GameWork>(_queue.Count);
while (_queue.Count > 0)
taken.Add(_queue.Dequeue());
}
foreach (var work in taken)
work.Pending.Complete(reason(work));
}
public void Stop()
{
lock (_gate)
{
_stopped = true;
}
CancelQueued(_ => ApiErrors.RequestTimeout());
}
void ScheduleLocked()
{
if (_pumpScheduled || _stopped) return;
_pumpScheduled = true;
_context.Post(Pump, _token);
}
void Pump(object state)
{
if (!ReferenceEquals(state, _token)) return;
Drain();
lock (_gate)
{
if (_stopped || _queue.Count == 0)
{
_pumpScheduled = false;
return;
}
}
_context.Post(Pump, _token);
}
void Drain()
{
var frame = Time.frameCount;
if (frame != _frame)
{
_frame = frame;
_startedThisFrame = 0;
_budget.Restart();
}
while (_startedThisFrame < ApiLimits.MaxRequestsPerFrame)
{
if (_startedThisFrame > 0 && _budget.ElapsedMilliseconds >= ApiLimits.MainThreadBudgetMs)
break;
GameWork work;
lock (_gate)
{
if (_stopped || _queue.Count == 0) return;
work = _queue.Dequeue();
}
_startedThisFrame++;
Run(work);
}
}
void Run(GameWork work)
{
if (!work.Pending.IsActive)
return;
var now = _nowMs();
if (now > work.DeadlineMs)
{
work.Pending.Complete(ApiErrors.RequestTimeout());
return;
}
object result;
try
{
result = _execute(work);
}
catch (Exception ex)
{
LiveStreamAssist.Logger.LogError($"API game-data request failed: {ex}");
work.Pending.Complete(ApiErrors.InternalError());
return;
}
if (!work.Pending.IsActive)
return;
if (_nowMs() > work.DeadlineMs)
{
work.Pending.Complete(ApiErrors.RequestTimeout());
return;
}
if (result is ApiError err)
work.Pending.Complete(err);
else
work.Pending.CompleteResult(result);
}
}
+836
View File
@@ -0,0 +1,836 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
namespace LiveStreamAssist.Api;
internal sealed class MemberInfoDto
{
public string Name;
public string Type;
public string Kind;
}
internal sealed class CollectionInfoDto
{
public string Kind;
public string ElementType;
public string KeyType;
public int? Count;
}
internal sealed class WalkResult
{
public object Encoded;
public string TypeName;
public bool IsNull;
public MemberInfoDto[] Members;
public CollectionInfoDto Collection;
public ApiError Error;
}
internal sealed class ReflectionReader
{
const int MaxCache = 1024;
static readonly Assembly GameAssembly = typeof(GameData).Assembly;
static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, false);
internal static Action<string> Warn;
readonly Dictionary<Type, CachedType> _cache = new Dictionary<Type, CachedType>();
readonly HashSet<Assembly> _extraAssemblies;
readonly object _cacheGate = new object();
public ReflectionReader(params Assembly[] extraAllowed)
{
if (extraAllowed != null && extraAllowed.Length > 0)
_extraAssemblies = new HashSet<Assembly>(extraAllowed);
}
public void ClearCache()
{
lock (_cacheGate) _cache.Clear();
}
public WalkResult Describe(object root, Type declaredType, PathSeg[] path)
{
var walked = Walk(root, declaredType, path);
if (walked.Error != null) return Fail(walked.Error);
return DescribeTerminal(walked.Value, walked.DeclaredType, walked.RuntimeType);
}
public WalkResult Read(object root, Type declaredType, PathSeg[] path, ReadOptions options)
{
var walked = Walk(root, declaredType, path);
if (walked.Error != null) return Fail(walked.Error);
return ReadTerminal(walked.Value, walked.DeclaredType, walked.RuntimeType, options);
}
public WalkResult DescribeTerminal(object value, Type declaredType, Type runtimeType)
{
var typeName = TypeName(value == null ? declaredType : runtimeType ?? value.GetType());
var result = new WalkResult
{
TypeName = typeName,
IsNull = value == null,
Members = Array.Empty<MemberInfoDto>(),
Encoded = null
};
var effective = value == null ? declaredType : runtimeType ?? value.GetType();
if (TryCollectionKind(effective, out var kind, out var elementType, out var keyType))
{
int? count = null;
if (value != null)
count = GetCount(value, effective);
result.Collection = new CollectionInfoDto
{
Kind = kind,
ElementType = TypeName(elementType),
KeyType = keyType == null ? null : TypeName(keyType),
Count = count
};
return result;
}
if (value != null && IsScalar(Unwrap(effective)))
return result;
if (effective != null && IsAllowedType(effective) && !IsScalar(Unwrap(effective)))
result.Members = GetExposedMembers(effective);
return result;
}
public WalkResult ReadTerminal(object value, Type declaredType, Type runtimeType, ReadOptions options)
{
var typeName = TypeName(value == null ? declaredType : runtimeType ?? value.GetType());
if (value == null)
{
if (options.HasOffset || options.HasLimit)
{
var declared = declaredType;
if (!TryCollectionKind(declared, out var nullKind, out _, out _) ||
(!string.Equals(nullKind, "array", StringComparison.Ordinal) &&
!string.Equals(nullKind, "list", StringComparison.Ordinal)))
return Fail(ApiErrors.InvalidParams("offset and limit are valid only for array or list terminals."));
return Fail(ApiErrors.InvalidParams("offset and limit require a non-null array or list."));
}
return new WalkResult { TypeName = typeName, IsNull = true, Encoded = null };
}
var actual = runtimeType ?? value.GetType();
if (TryCollectionKind(actual, out var kind, out var elementType, out _))
{
if (string.Equals(kind, "dictionary", StringComparison.Ordinal))
{
if (options.HasSelect)
return Fail(ApiErrors.InvalidParams("select is invalid for dictionary terminals."));
if (options.HasOffset || options.HasLimit)
return Fail(ApiErrors.InvalidParams("offset and limit are valid only for array or list terminals."));
return Ok(typeName, CollectionSummary(kind, actual, GetCount(value, actual)));
}
if (options.HasSelect && IsScalar(Unwrap(elementType)))
return Fail(ApiErrors.InvalidParams("select is invalid for scalar collection elements."));
if (options.HasSelect && TryCollectionKind(elementType, out _, out _, out _))
return Fail(ApiErrors.InvalidParams("select is invalid for collection elements."));
var page = ReadPage(value, actual, elementType, options);
if (page.Error != null) return page;
page.TypeName = typeName;
return page;
}
if (options.HasOffset || options.HasLimit)
return Fail(ApiErrors.InvalidParams("offset and limit are valid only for array or list terminals."));
if (IsScalar(Unwrap(actual)))
{
if (options.HasSelect)
return Fail(ApiErrors.InvalidParams("select is invalid for scalar terminals."));
if (!TryEncodeScalar(value, actual, out var encoded, out var err))
return Fail(err);
return Ok(typeName, encoded);
}
if (!IsAllowedType(actual))
return Fail(ApiErrors.UnsupportedType());
if (options.HasSelect)
{
var projected = Project(value, actual, options.Select);
if (projected.Error != null) return projected;
projected.TypeName = typeName;
return projected;
}
return Ok(typeName, ObjectSummary(actual));
}
WalkStep Walk(object root, Type declaredType, PathSeg[] path)
{
var current = root;
var declared = declaredType;
var runtime = current == null ? null : current.GetType();
if (path == null || path.Length == 0)
return new WalkStep { Value = current, DeclaredType = declared, RuntimeType = runtime };
for (var i = 0; i < path.Length; i++)
{
if (current == null)
return new WalkStep { Error = ApiErrors.NullPath(i) };
runtime = current.GetType();
var seg = path[i];
if (seg.Kind == PathKind.Member)
{
var slot = FindMember(runtime, seg.Name);
if (slot == null)
return new WalkStep { Error = ApiErrors.MemberNotFound(seg.Name, i) };
if (!slot.Allowed)
return new WalkStep { Error = ApiErrors.MemberNotAllowed(seg.Name, i) };
if (!TryGetMemberValue(current, slot, i, out current, out var err))
return new WalkStep { Error = err };
declared = slot.DeclaredType;
runtime = current == null ? null : current.GetType();
continue;
}
if (seg.Kind == PathKind.Index)
{
if (!TryCollectionKind(runtime, out var kind, out var elementType, out _) ||
!string.Equals(kind, "array", StringComparison.Ordinal) &&
!string.Equals(kind, "list", StringComparison.Ordinal))
return new WalkStep { Error = ApiErrors.UnsupportedType(i) };
if (!TryGetIndex(current, runtime, seg.Index, i, out current, out var err))
return new WalkStep { Error = err };
declared = elementType;
runtime = current == null ? null : current.GetType();
continue;
}
if (!TryCollectionKind(runtime, out var dkind, out var valueType, out var keyType) ||
!string.Equals(dkind, "dictionary", StringComparison.Ordinal))
return new WalkStep { Error = ApiErrors.UnsupportedType(i) };
if (!TryCoerceKey(seg.Key, keyType, out var key, out var keyErr))
return new WalkStep { Error = keyErr ?? ApiErrors.InvalidParams("dictionary key type mismatch.") };
if (!TryGetKey(current, key, i, out current, out var kerr))
return new WalkStep { Error = kerr };
declared = valueType;
runtime = current == null ? null : current.GetType();
}
return new WalkStep { Value = current, DeclaredType = declared, RuntimeType = current == null ? null : current.GetType() };
}
WalkResult ReadPage(object collection, Type collectionType, Type elementType, ReadOptions options)
{
var total = GetCount(collection, collectionType);
var offset = options.EffectiveOffset;
var limit = options.EffectiveLimit;
if (options.HasSelect)
{
var probe = GetCached(elementType);
if (options.Select != null)
{
foreach (var name in options.Select)
{
var slot = FindMember(elementType, name);
if (slot == null) return Fail(ApiErrors.MemberNotFound(name));
if (!slot.Allowed) return Fail(ApiErrors.MemberNotAllowed(name));
}
}
_ = probe;
}
var items = new List<object>();
if (offset < total)
{
var take = Math.Min(limit, total - offset);
for (var i = 0; i < take; i++)
{
if (!TryGetIndex(collection, collectionType, offset + i, null, out var item, out var err))
return Fail(err);
if (item == null)
{
items.Add(null);
continue;
}
var itemType = item.GetType();
if (options.HasSelect)
{
if (IsScalar(Unwrap(itemType)) || TryCollectionKind(itemType, out _, out _, out _))
return Fail(ApiErrors.InvalidParams("select is invalid for scalar or collection elements."));
var projected = Project(item, itemType, options.Select);
if (projected.Error != null) return projected;
items.Add(projected.Encoded);
}
else if (IsScalar(Unwrap(itemType)))
{
if (!TryEncodeScalar(item, itemType, out var encoded, out var encErr))
return Fail(encErr);
items.Add(encoded);
}
else if (TryCollectionKind(itemType, out var ikind, out _, out _))
items.Add(CollectionSummary(ikind, itemType, GetCount(item, itemType)));
else if (!IsAllowedType(itemType))
return Fail(ApiErrors.UnsupportedType());
else
items.Add(ObjectSummary(itemType));
}
}
return new WalkResult
{
Encoded = new Dictionary<string, object>
{
["items"] = items,
["offset"] = offset,
["totalCount"] = total,
["hasMore"] = offset + items.Count < total
}
};
}
WalkResult Project(object value, Type type, string[] select)
{
var map = new Dictionary<string, object>(select.Length);
foreach (var name in select)
{
var slot = FindMember(type, name);
if (slot == null) return Fail(ApiErrors.MemberNotFound(name));
if (!slot.Allowed) return Fail(ApiErrors.MemberNotAllowed(name));
if (!TryGetMemberValue(value, slot, null, out var memberValue, out var err))
return Fail(err);
if (memberValue == null)
{
map[name] = null;
continue;
}
var mt = memberValue.GetType();
if (IsScalar(Unwrap(mt)))
{
if (!TryEncodeScalar(memberValue, mt, out var encoded, out var encErr))
return Fail(encErr);
map[name] = encoded;
}
else if (TryCollectionKind(mt, out var kind, out _, out _))
map[name] = CollectionSummary(kind, mt, GetCount(memberValue, mt));
else if (!IsAllowedType(mt))
return Fail(ApiErrors.UnsupportedType(member: name));
else
map[name] = ObjectSummary(mt);
}
return new WalkResult { Encoded = map };
}
bool TryGetMemberValue(object instance, MemberSlot slot, int? segmentIndex, out object value, out ApiError error)
{
value = null;
error = null;
try
{
if (slot.Field != null)
{
value = slot.Field.GetValue(instance);
return true;
}
value = slot.Property.GetValue(instance, null);
return true;
}
catch (Exception ex)
{
Warn?.Invoke($"API read failed at {slot.Name}: {ex}");
error = ApiErrors.ReadFailed(segmentIndex, slot.Name);
return false;
}
}
bool TryGetIndex(object collection, Type collectionType, int index, int? segmentIndex, out object value, out ApiError error)
{
value = null;
error = null;
var count = GetCount(collection, collectionType);
if (index < 0 || index >= count)
{
error = ApiErrors.IndexOutOfRange(segmentIndex ?? 0);
return false;
}
try
{
if (collectionType.IsArray)
{
value = ((Array)collection).GetValue(index);
return true;
}
value = ((IList)collection)[index];
return true;
}
catch (Exception ex)
{
Warn?.Invoke($"API index read failed: {ex}");
error = ApiErrors.ReadFailed(segmentIndex);
return false;
}
}
static bool TryGetKey(object collection, object key, int segmentIndex, out object value, out ApiError error)
{
value = null;
error = null;
try
{
var dict = (IDictionary)collection;
if (!dict.Contains(key))
{
error = ApiErrors.KeyNotFound(segmentIndex);
return false;
}
value = dict[key];
return true;
}
catch (Exception ex)
{
Warn?.Invoke($"API key read failed: {ex}");
error = ApiErrors.ReadFailed(segmentIndex);
return false;
}
}
static bool TryCoerceKey(object raw, Type keyType, out object key, out ApiError error)
{
key = null;
error = null;
if (keyType == typeof(int))
{
if (raw is int i)
{
key = i;
return true;
}
error = ApiErrors.InvalidParams("dictionary key type mismatch.");
return false;
}
if (keyType == typeof(string))
{
if (raw is string s)
{
key = s;
return true;
}
error = ApiErrors.InvalidParams("dictionary key type mismatch.");
return false;
}
error = ApiErrors.UnsupportedType();
return false;
}
static int GetCount(object collection, Type type)
{
if (type.IsArray) return ((Array)collection).Length;
return ((ICollection)collection).Count;
}
MemberSlot FindMember(Type type, string name)
{
var cached = GetCached(type);
return cached.ByName.TryGetValue(name, out var slot) ? slot : null;
}
MemberInfoDto[] GetExposedMembers(Type type)
{
return GetCached(type).Exposed;
}
CachedType GetCached(Type type)
{
lock (_cacheGate)
{
if (_cache.TryGetValue(type, out var hit))
return hit;
}
var built = BuildMembers(type);
lock (_cacheGate)
{
if (_cache.TryGetValue(type, out var hit))
return hit;
if (_cache.Count < MaxCache)
_cache[type] = built;
return built;
}
}
CachedType BuildMembers(Type type)
{
var byName = new Dictionary<string, MemberSlot>(StringComparer.Ordinal);
for (var t = type; t != null && t != typeof(object); t = t.BaseType)
{
foreach (var field in t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
{
if (field.IsStatic || field.IsDefined(typeof(CompilerGeneratedAttribute), false) || field.Name.IndexOf('<') >= 0)
continue;
if (byName.ContainsKey(field.Name))
continue;
var ft = field.FieldType;
byName[field.Name] = new MemberSlot
{
Name = field.Name,
Kind = "field",
DeclaredType = ft,
Field = field,
Allowed = IsAllowedType(ft)
};
}
foreach (var prop in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
{
if (prop.GetIndexParameters().Length != 0)
continue;
if (byName.ContainsKey(prop.Name))
continue;
var allowed = IsAllowedProperty(prop) && IsAllowedType(prop.PropertyType) && prop.CanRead && prop.GetGetMethod(true) != null;
byName[prop.Name] = new MemberSlot
{
Name = prop.Name,
Kind = "property",
DeclaredType = prop.PropertyType,
Property = prop,
Allowed = allowed
};
}
}
var exposed = new List<MemberInfoDto>();
foreach (var pair in byName)
{
if (!pair.Value.Allowed) continue;
exposed.Add(new MemberInfoDto
{
Name = pair.Value.Name,
Type = TypeName(pair.Value.DeclaredType),
Kind = pair.Value.Kind
});
}
exposed.Sort((a, b) => string.CompareOrdinal(a.Name, b.Name));
return new CachedType { ByName = byName, Exposed = exposed.ToArray() };
}
static bool IsAllowedProperty(PropertyInfo prop)
{
return prop.DeclaringType == typeof(GameHistoryData) &&
string.Equals(prop.Name, "currentTech", StringComparison.Ordinal);
}
bool IsAllowedType(Type type)
{
if (type == null) return false;
type = Unwrap(type);
if (IsForbidden(type)) return false;
if (IsScalar(type) || IsUnityStruct(type)) return true;
if (IsSupportedArray(type) || IsSupportedList(type) || IsSupportedDictionary(type)) return true;
if (type.Assembly == GameAssembly) return true;
if (_extraAssemblies != null && _extraAssemblies.Contains(type.Assembly)) return true;
return false;
}
bool IsSupportedArray(Type type)
{
if (!type.IsArray || type.GetArrayRank() != 1) return false;
var element = type.GetElementType();
return element != null && !element.IsPointer && IsAllowedType(element);
}
bool IsSupportedList(Type type)
{
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(List<>)) return false;
return IsAllowedType(type.GetGenericArguments()[0]);
}
bool IsSupportedDictionary(Type type)
{
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Dictionary<,>)) return false;
var args = type.GetGenericArguments();
if (args[0] != typeof(int) && args[0] != typeof(string)) return false;
return IsAllowedType(args[1]);
}
bool TryCollectionKind(Type type, out string kind, out Type elementType, out Type keyType)
{
kind = null;
elementType = null;
keyType = null;
if (type == null) return false;
type = Unwrap(type);
if (IsSupportedArray(type))
{
kind = "array";
elementType = type.GetElementType();
return true;
}
if (IsSupportedList(type))
{
kind = "list";
elementType = type.GetGenericArguments()[0];
return true;
}
if (IsSupportedDictionary(type))
{
kind = "dictionary";
var args = type.GetGenericArguments();
keyType = args[0];
elementType = args[1];
return true;
}
return false;
}
static bool IsForbidden(Type t)
{
if (t.IsPointer || t.IsByRef || t.IsGenericParameter) return true;
if (t == typeof(IntPtr) || t == typeof(UIntPtr) || t == typeof(TypedReference)) return true;
if (typeof(Delegate).IsAssignableFrom(t)) return true;
if (typeof(Type).IsAssignableFrom(t) || typeof(MemberInfo).IsAssignableFrom(t) ||
typeof(Assembly).IsAssignableFrom(t) || typeof(Module).IsAssignableFrom(t))
return true;
if (typeof(System.IO.Stream).IsAssignableFrom(t) || typeof(System.IO.TextReader).IsAssignableFrom(t) ||
typeof(System.IO.TextWriter).IsAssignableFrom(t))
return true;
if (typeof(Task).IsAssignableFrom(t) || typeof(Thread).IsAssignableFrom(t) || typeof(WaitHandle).IsAssignableFrom(t))
return true;
if (t == typeof(SpinLock) || t == typeof(Mutex) || t == typeof(Semaphore) || t == typeof(ReaderWriterLock) ||
t == typeof(ReaderWriterLockSlim))
return true;
if (typeof(UnityEngine.Object).IsAssignableFrom(t)) return true;
return false;
}
static bool IsScalar(Type t)
{
if (t.IsEnum) return true;
return t == typeof(bool) || t == typeof(string) || t == typeof(char) ||
t == typeof(byte) || t == typeof(sbyte) || t == typeof(short) || t == typeof(ushort) ||
t == typeof(int) || t == typeof(uint) || t == typeof(long) || t == typeof(ulong) ||
t == typeof(float) || t == typeof(double) || t == typeof(decimal) ||
t == typeof(DateTime) || t == typeof(DateTimeOffset) || t == typeof(Guid);
}
static bool IsUnityStruct(Type t)
{
return t == typeof(Vector2) || t == typeof(Vector3) || t == typeof(Vector4) || t == typeof(Quaternion);
}
static Type Unwrap(Type t)
{
return Nullable.GetUnderlyingType(t) ?? t;
}
static bool TryEncodeScalar(object value, Type type, out object encoded, out ApiError error)
{
encoded = null;
error = null;
type = Unwrap(type);
if (value == null)
return true;
if (type.IsEnum)
{
var name = Enum.GetName(type, value);
var underlying = Convert.ToInt64(value, CultureInfo.InvariantCulture);
encoded = new Dictionary<string, object>
{
["name"] = name,
["value"] = underlying.ToString(CultureInfo.InvariantCulture)
};
return true;
}
if (type == typeof(bool))
{
encoded = (bool)value;
return true;
}
if (type == typeof(uint))
{
encoded = (uint)value;
return true;
}
if (type == typeof(int) || type == typeof(byte) || type == typeof(sbyte) || type == typeof(short) ||
type == typeof(ushort))
{
encoded = Convert.ToInt32(value, CultureInfo.InvariantCulture);
return true;
}
if (type == typeof(string))
{
var s = (string)value;
if (!CheckStringSize(s, out error)) return false;
encoded = s;
return true;
}
if (type == typeof(char))
{
encoded = ((char)value).ToString();
return true;
}
if (type == typeof(long))
{
encoded = ((long)value).ToString(CultureInfo.InvariantCulture);
return true;
}
if (type == typeof(ulong))
{
encoded = ((ulong)value).ToString(CultureInfo.InvariantCulture);
return true;
}
if (type == typeof(decimal))
{
encoded = ((decimal)value).ToString(CultureInfo.InvariantCulture);
return true;
}
if (type == typeof(float))
{
var f = (float)value;
if (float.IsNaN(f) || float.IsInfinity(f))
{
error = ApiErrors.UnsupportedValue();
return false;
}
encoded = f;
return true;
}
if (type == typeof(double))
{
var d = (double)value;
if (double.IsNaN(d) || double.IsInfinity(d))
{
error = ApiErrors.UnsupportedValue();
return false;
}
encoded = d;
return true;
}
if (type == typeof(DateTime))
{
encoded = ((DateTime)value).ToString("o", CultureInfo.InvariantCulture);
return true;
}
if (type == typeof(DateTimeOffset))
{
encoded = ((DateTimeOffset)value).ToString("o", CultureInfo.InvariantCulture);
return true;
}
if (type == typeof(Guid))
{
encoded = ((Guid)value).ToString("D");
return true;
}
error = ApiErrors.UnsupportedType();
return false;
}
static bool CheckStringSize(string s, out ApiError error)
{
error = null;
if (s == null) return true;
if (s.Length > ApiLimits.MaxResponseBytes || Utf8.GetByteCount(s) > ApiLimits.MaxResponseBytes)
{
error = ApiErrors.LimitExceeded("String value exceeds maxResponseBytes.");
return false;
}
return true;
}
static Dictionary<string, object> ObjectSummary(Type type)
{
return new Dictionary<string, object>
{
["$kind"] = "object",
["$type"] = TypeName(type)
};
}
static Dictionary<string, object> CollectionSummary(string kind, Type type, int count)
{
return new Dictionary<string, object>
{
["$kind"] = kind,
["$type"] = TypeName(type),
["count"] = count
};
}
internal static string TypeName(Type type)
{
if (type == null) return null;
type = Unwrap(type);
if (type.IsArray && type.GetArrayRank() == 1)
return TypeName(type.GetElementType()) + "[]";
return type.FullName ?? type.Name;
}
static WalkResult Fail(ApiError error) => new WalkResult { Error = error };
static WalkResult Ok(string typeName, object encoded) =>
new WalkResult { TypeName = typeName, Encoded = encoded, IsNull = encoded == null };
sealed class MemberSlot
{
public string Name;
public string Kind;
public Type DeclaredType;
public FieldInfo Field;
public PropertyInfo Property;
public bool Allowed;
}
sealed class CachedType
{
public Dictionary<string, MemberSlot> ByName;
public MemberInfoDto[] Exposed;
}
struct WalkStep
{
public object Value;
public Type DeclaredType;
public Type RuntimeType;
public ApiError Error;
}
}
+332
View File
@@ -0,0 +1,332 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Threading;
using BepInEx.Configuration;
using UXAssist.Common.ModFeatures;
using GameLogicProc = UXAssist.Common.GameLogic;
namespace LiveStreamAssist.Api;
[ModFeature("WebSocketApi", Order = 51)]
internal static class WebSocketApiFeature
{
internal static ConfigEntry<bool> Enabled;
internal static ConfigEntry<string> ListenAddress;
internal static ConfigEntry<int> Port;
static readonly string[] RootNames =
{ "game", "player", "history", "statistics", "galaxy", "localPlanet", "localStar" };
static readonly Type[] RootTypes =
{
typeof(GameData), typeof(Player), typeof(GameHistoryData), typeof(GameStatData),
typeof(GalaxyData), typeof(PlanetData), typeof(StarData)
};
static readonly object Gate = new object();
static object _ownerToken;
static WebSocketApiServer _server;
static MainThreadDispatcher _dispatcher;
static ReflectionReader _reader;
static GameVersionSnapshot _version = GameVersionSnapshot.Empty;
static SessionSnapshot _session = new SessionSnapshot(0, null);
static bool _started;
public static void BindConfig(ConfigFile config)
{
Enabled = config.Bind("WebSocketApi", "Enabled", false,
"Start the WebSocket API listener when the mod starts");
ListenAddress = config.Bind("WebSocketApi", "ListenAddress", "127.0.0.1",
"Bind address; use a specific LAN address or 0.0.0.0 for LAN access");
Port = config.Bind("WebSocketApi", "Port", 18080,
new ConfigDescription("Listening port", new AcceptableValueRange<int>(1, 65535)));
}
public static void Init()
{
_reader = new ReflectionReader();
ReflectionReader.Warn = msg => LiveStreamAssist.Logger.LogWarning(msg);
_version = GameVersionSnapshot.Empty;
_session = new SessionSnapshot(0, null);
}
public static void Start()
{
if (_started) return;
if (Enabled == null || !Enabled.Value) return;
var ctx = SynchronizationContext.Current;
if (ctx == null || ctx.GetType().FullName != "UnityEngine.UnitySynchronizationContext")
{
LiveStreamAssist.Logger.LogError(
"WebSocket API requires Unity's installed SynchronizationContext; startup aborted.");
return;
}
if (!IPAddress.TryParse(ListenAddress.Value, out var address))
{
LiveStreamAssist.Logger.LogError($"WebSocket API listen address is invalid: {ListenAddress.Value}");
return;
}
var port = Port.Value;
if (port < 1 || port > 65535)
{
LiveStreamAssist.Logger.LogError($"WebSocket API port is invalid: {port}");
return;
}
var token = new object();
var dispatcher = new MainThreadDispatcher(ctx, token, ExecuteWork, () => _server?.NowMs ?? 0);
var server = new WebSocketApiServer(address, port, PluginInfo.PLUGIN_VERSION, GetVersion, GetSession, dispatcher);
GameLogicProc.OnDataLoaded += OnDataLoaded;
GameLogicProc.OnGameBegin += OnGameBegin;
GameLogicProc.OnGameEnd += OnGameEnd;
lock (Gate)
{
_ownerToken = token;
_dispatcher = dispatcher;
_server = server;
_started = true;
}
try
{
server.Start();
}
catch (Exception ex)
{
LiveStreamAssist.Logger.LogError($"WebSocket API failed to start: {ex}");
Uninit();
return;
}
if (VFPreload.done || VFPreload.dbDone)
PublishVersion();
if (IsGameReady())
BeginSession();
}
public static void Uninit()
{
WebSocketApiServer server;
MainThreadDispatcher dispatcher;
lock (Gate)
{
if (!_started && _server == null) return;
_started = false;
_ownerToken = new object();
server = _server;
dispatcher = _dispatcher;
_server = null;
_dispatcher = null;
_session = new SessionSnapshot(_session.Generation + 1, null);
}
GameLogicProc.OnDataLoaded -= OnDataLoaded;
GameLogicProc.OnGameBegin -= OnGameBegin;
GameLogicProc.OnGameEnd -= OnGameEnd;
try { dispatcher?.Stop(); }
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"WebSocket API dispatcher stop failed: {ex.Message}"); }
try { server?.Stop(); }
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"WebSocket API server stop failed: {ex.Message}"); }
_reader?.ClearCache();
ReflectionReader.Warn = null;
}
public static bool IsKnownRoot(string name)
{
for (var i = 0; i < RootNames.Length; i++)
{
if (string.Equals(RootNames[i], name, StringComparison.Ordinal))
return true;
}
return false;
}
static GameVersionSnapshot GetVersion() => _version;
static SessionSnapshot GetSession() => _session;
static void OnDataLoaded() => PublishVersion();
static void PublishVersion()
{
var v = GameConfig.gameVersion;
_version = new GameVersionSnapshot(true, v.ToString(), GameConfig.build);
}
static void OnGameBegin()
{
if (IsGameReady())
BeginSession();
}
static void OnGameEnd()
{
EndSession();
}
static void BeginSession()
{
MainThreadDispatcher dispatcher;
int oldGeneration;
lock (Gate)
{
oldGeneration = _session.Generation;
_session = new SessionSnapshot(oldGeneration + 1, Guid.NewGuid().ToString("D"));
dispatcher = _dispatcher;
}
dispatcher?.CancelQueued(_ => ApiErrors.SessionChanged());
}
static void EndSession()
{
MainThreadDispatcher dispatcher;
lock (Gate)
{
_session = new SessionSnapshot(_session.Generation + 1, null);
dispatcher = _dispatcher;
}
dispatcher?.CancelQueued(_ => ApiErrors.SessionChanged());
}
static bool IsGameReady()
{
return GameMain.data != null && GameMain.isRunning && !GameMain.isLoading && !DSPGame.IsMenuDemo;
}
static object ResolveRoot(string name)
{
switch (name)
{
case "game": return GameMain.data;
case "player": return GameMain.mainPlayer;
case "history": return GameMain.history;
case "statistics": return GameMain.statistics;
case "galaxy": return GameMain.galaxy;
case "localPlanet": return GameMain.localPlanet;
case "localStar": return GameMain.localStar;
default: return null;
}
}
static Type DeclaredRootType(string name)
{
for (var i = 0; i < RootNames.Length; i++)
{
if (string.Equals(RootNames[i], name, StringComparison.Ordinal))
return RootTypes[i];
}
return null;
}
static object ExecuteWork(GameWork work)
{
var session = _session;
if (work.Generation != session.Generation)
return ApiErrors.SessionChanged();
var call = work.Call;
if (call.Method == DataMethod.Roots)
return BuildRoots(session);
if (!IsGameReady())
return ApiErrors.GameNotReady();
if (session.SessionId == null)
return ApiErrors.GameNotReady();
var instance = ResolveRoot(call.Root);
if (instance == null)
return ApiErrors.RootUnavailable(call.Root);
var declared = DeclaredRootType(call.Root);
WalkResult walked;
if (call.Method == DataMethod.Describe)
walked = _reader.Describe(instance, declared, call.Path);
else
walked = _reader.Read(instance, declared, call.Path, call.Options);
if (walked.Error != null)
return walked.Error;
if (_session.Generation != work.Generation)
return ApiErrors.SessionChanged();
var tick = GameMain.gameTick.ToString(CultureInfo.InvariantCulture);
if (call.Method == DataMethod.Describe)
return BuildDescribe(walked, session.SessionId, tick);
return BuildRead(walked, session.SessionId, tick);
}
static Dictionary<string, object> BuildRoots(SessionSnapshot session)
{
var ready = IsGameReady() && session.SessionId != null;
var roots = new List<object>(RootNames.Length);
for (var i = 0; i < RootNames.Length; i++)
{
var available = ready && ResolveRoot(RootNames[i]) != null;
roots.Add(new Dictionary<string, object>
{
["name"] = RootNames[i],
["type"] = ReflectionReader.TypeName(RootTypes[i]),
["available"] = available
});
}
return new Dictionary<string, object>
{
["gameReady"] = ready,
["sessionId"] = ready ? session.SessionId : null,
["gameTick"] = ready ? GameMain.gameTick.ToString(CultureInfo.InvariantCulture) : null,
["roots"] = roots
};
}
static Dictionary<string, object> BuildDescribe(WalkResult walked, string sessionId, string tick)
{
var members = new List<object>(walked.Members?.Length ?? 0);
if (walked.Members != null)
{
foreach (var m in walked.Members)
{
members.Add(new Dictionary<string, object>
{
["name"] = m.Name,
["type"] = m.Type,
["kind"] = m.Kind
});
}
}
object collection = null;
if (walked.Collection != null)
{
collection = new Dictionary<string, object>
{
["kind"] = walked.Collection.Kind,
["elementType"] = walked.Collection.ElementType,
["keyType"] = walked.Collection.KeyType,
["count"] = walked.Collection.Count
};
}
return new Dictionary<string, object>
{
["type"] = walked.TypeName,
["isNull"] = walked.IsNull,
["members"] = members,
["collection"] = collection,
["sessionId"] = sessionId,
["gameTick"] = tick
};
}
static Dictionary<string, object> BuildRead(WalkResult walked, string sessionId, string tick)
{
return new Dictionary<string, object>
{
["type"] = walked.TypeName,
["value"] = walked.Encoded,
["sessionId"] = sessionId,
["gameTick"] = tick
};
}
}
+544
View File
@@ -0,0 +1,544 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Fleck;
using Newtonsoft.Json.Linq;
namespace LiveStreamAssist.Api;
internal sealed class PendingRequest
{
int _done;
public ApiConnection Connection;
public string Id;
public bool IsActive => System.Threading.Volatile.Read(ref _done) == 0 && Connection != null && Connection.IsOpen;
public bool TryMarkDone() => System.Threading.Interlocked.Exchange(ref _done, 1) == 0;
public bool Complete(ApiError error)
{
if (error == null || !TryMarkDone()) return false;
Connection.Deliver(this, null, error);
return true;
}
public bool CompleteResult(object result)
{
if (!TryMarkDone()) return false;
Connection.Deliver(this, result, null);
return true;
}
}
internal sealed class ApiConnection
{
readonly WebSocketApiServer _server;
readonly IWebSocketConnection _socket;
readonly object _gate = new object();
readonly Dictionary<string, PendingRequest> _outstanding = new Dictionary<string, PendingRequest>(StringComparer.Ordinal);
readonly Queue<SendItem> _sendQueue = new Queue<SendItem>();
bool _sending;
bool _closed;
int _pending;
public ApiConnection(WebSocketApiServer server, IWebSocketConnection socket)
{
_server = server;
_socket = socket;
}
public bool IsOpen
{
get
{
lock (_gate) return !_closed && _socket.IsAvailable;
}
}
public int Pending
{
get
{
lock (_gate) return _pending;
}
}
public PendingRequest TryAdmit(string id, out bool duplicate, out bool busy)
{
duplicate = false;
busy = false;
lock (_gate)
{
if (_closed) return null;
if (_outstanding.ContainsKey(id))
{
duplicate = true;
return null;
}
if (_pending >= ApiLimits.MaxPendingRequestsPerConnection || !_server.TryIncrementPending())
{
busy = true;
return null;
}
var pending = new PendingRequest { Connection = this, Id = id };
_outstanding[id] = pending;
_pending++;
return pending;
}
}
public bool CanSendBusy()
{
lock (_gate)
return !_closed && _sendQueue.Count < ApiLimits.MaxPendingRequestsPerConnection;
}
public void EnqueueError(object id, ApiError error)
{
byte[] payload;
try
{
payload = ApiProtocol.SerializeEnvelope(id, null, error);
}
catch (ResponseTooLargeException)
{
Close(ApiLimits.CloseTryAgainLater);
return;
}
EnqueueSend(payload);
}
public void Deliver(PendingRequest pending, object result, ApiError error)
{
Release(pending.Id);
if (_closed) return;
byte[] payload;
try
{
payload = ApiProtocol.SerializeEnvelope(pending.Id, result, error);
}
catch (ResponseTooLargeException)
{
try
{
payload = ApiProtocol.SerializeEnvelope(pending.Id, null, ApiErrors.LimitExceeded("Response exceeds maxResponseBytes."));
}
catch (ResponseTooLargeException)
{
Close(ApiLimits.CloseTryAgainLater);
return;
}
}
EnqueueSend(payload);
}
public void Release(string id)
{
lock (_gate)
{
if (id != null)
_outstanding.Remove(id);
if (_pending > 0)
_pending--;
}
_server.DecrementPending();
}
public void EnqueueSend(byte[] payload)
{
lock (_gate)
{
if (_closed) return;
if (_sendQueue.Count >= ApiLimits.MaxPendingRequestsPerConnection)
{
CloseLocked(ApiLimits.CloseTryAgainLater);
return;
}
_sendQueue.Enqueue(new SendItem { Payload = payload, EnqueuedMs = _server.NowMs });
if (!_sending)
{
_sending = true;
DrainSend();
}
}
}
public void Close(int code)
{
lock (_gate) CloseLocked(code);
}
public void NotifyDisconnected()
{
FinishClose(null);
}
void CloseLocked(int code)
{
FinishClose(code);
}
void FinishClose(int? code)
{
PendingRequest[] pending;
lock (_gate)
{
if (_closed) return;
_closed = true;
_sendQueue.Clear();
_sending = false;
pending = new PendingRequest[_outstanding.Count];
if (_outstanding.Count > 0)
_outstanding.Values.CopyTo(pending, 0);
}
if (code.HasValue)
{
try
{
if (_socket.IsAvailable)
_socket.Close(code.Value);
}
catch (Exception ex)
{
LiveStreamAssist.Logger.LogWarning($"API close failed: {ex.Message}");
}
}
_server.OnConnectionClosed(this);
foreach (var item in pending)
item.Complete(ApiErrors.RequestTimeout());
}
void DrainSend()
{
SendItem item;
lock (_gate)
{
if (_closed || _sendQueue.Count == 0)
{
_sending = false;
return;
}
item = _sendQueue.Peek();
if (_server.NowMs - item.EnqueuedMs > ApiLimits.RequestTimeoutMs)
{
CloseLocked(ApiLimits.CloseTryAgainLater);
return;
}
_sendQueue.Dequeue();
}
Task task;
try
{
var text = Encoding.UTF8.GetString(item.Payload);
task = _socket.Send(text);
}
catch (Exception)
{
Close(ApiLimits.CloseTryAgainLater);
return;
}
if (task == null)
{
Close(ApiLimits.CloseTryAgainLater);
return;
}
task.ContinueWith(_ => DrainSend(), System.Threading.CancellationToken.None,
TaskContinuationOptions.None, TaskScheduler.Default);
}
struct SendItem
{
public byte[] Payload;
public long EnqueuedMs;
}
}
internal sealed class WebSocketApiServer
{
readonly IPAddress _address;
readonly int _port;
readonly string _modVersion;
readonly Func<GameVersionSnapshot> _version;
readonly Func<SessionSnapshot> _session;
readonly MainThreadDispatcher _dispatcher;
readonly object _gate = new object();
readonly List<ApiConnection> _connections = new List<ApiConnection>();
readonly System.Diagnostics.Stopwatch _clock = System.Diagnostics.Stopwatch.StartNew();
WebSocketServer _listener;
int _pending;
bool _alive;
public WebSocketApiServer(
IPAddress address,
int port,
string modVersion,
Func<GameVersionSnapshot> version,
Func<SessionSnapshot> session,
MainThreadDispatcher dispatcher)
{
_address = address;
_port = port;
_modVersion = modVersion;
_version = version;
_session = session;
_dispatcher = dispatcher;
}
public long NowMs => _clock.ElapsedMilliseconds;
public void Start()
{
var host = _address.Equals(IPAddress.Any) ? "0.0.0.0" : _address.ToString();
if (_address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
host = "[" + host + "]";
var location = "ws://" + host + ":" + _port;
FleckLog.Level = LogLevel.Error;
FleckLog.LogAction = (level, message, ex) =>
{
if (level == LogLevel.Error)
LiveStreamAssist.Logger.LogError(ex != null ? message + ": " + ex : message);
};
var server = new WebSocketServer(location, false);
server.RestartAfterListenError = false;
server.Start(OnSocket);
lock (_gate)
{
_listener = server;
_alive = true;
}
LiveStreamAssist.Logger.LogInfo($"WebSocket API listening on {location}{ApiLimits.Path}");
}
public void Stop()
{
ApiConnection[] conns;
WebSocketServer listener;
lock (_gate)
{
if (!_alive && _listener == null) return;
_alive = false;
listener = _listener;
_listener = null;
conns = _connections.ToArray();
_connections.Clear();
}
foreach (var conn in conns)
conn.Close(ApiLimits.CloseGoingAway);
try
{
listener?.Dispose();
}
catch (Exception ex)
{
LiveStreamAssist.Logger.LogWarning($"WebSocket API listener dispose failed: {ex.Message}");
}
}
public bool TryIncrementPending()
{
lock (_gate)
{
if (!_alive || _pending >= ApiLimits.MaxPendingRequests) return false;
_pending++;
return true;
}
}
public void DecrementPending()
{
lock (_gate)
{
if (_pending > 0) _pending--;
}
}
public void OnConnectionClosed(ApiConnection connection)
{
lock (_gate)
_connections.Remove(connection);
}
void OnSocket(IWebSocketConnection socket)
{
var conn = new ApiConnection(this, socket);
var bounded = socket as WebSocketConnection;
if (bounded != null && bounded.Handler != null)
bounded.Handler = new BoundedHandler(bounded.Handler, ApiLimits.MaxIncomingSocketBytes);
var path = socket.ConnectionInfo?.Path ?? "";
var q = path.IndexOf('?');
if (q >= 0) path = path.Substring(0, q);
socket.OnOpen = () =>
{
if (!string.Equals(path, ApiLimits.Path, StringComparison.Ordinal))
{
conn.Close(ApiLimits.ClosePolicyViolation);
return;
}
lock (_gate)
{
if (!_alive || _connections.Count >= ApiLimits.MaxConnections)
{
conn.Close(ApiLimits.CloseTryAgainLater);
return;
}
_connections.Add(conn);
}
};
socket.OnBinary = _ => conn.Close(ApiLimits.CloseUnsupportedData);
socket.OnMessage = message => OnMessage(conn, bounded, message);
socket.OnClose = () =>
{
if (bounded?.Handler is BoundedHandler)
((BoundedHandler)bounded.Handler).Reset();
conn.NotifyDisconnected();
};
socket.OnError = ex => LiveStreamAssist.Logger.LogWarning($"WebSocket API connection error: {ex.Message}");
var prevPing = socket.OnPing;
socket.OnPing = data =>
{
if (bounded?.Handler is BoundedHandler h) h.Reset();
prevPing?.Invoke(data);
};
}
void OnMessage(ApiConnection conn, WebSocketConnection raw, string message)
{
if (raw?.Handler is BoundedHandler bounded)
bounded.Reset();
bool alive;
lock (_gate) alive = _alive;
if (!alive || !conn.IsOpen) return;
if (message == null || Encoding.UTF8.GetByteCount(message) > ApiLimits.MaxRequestBytes)
{
conn.Close(ApiLimits.CloseMessageTooBig);
return;
}
if (!ApiProtocol.TryParseMessage(message, out var request, out var parseError, out var id))
{
conn.EnqueueError(id, parseError);
return;
}
var pending = conn.TryAdmit(request.Id, out var duplicate, out var busy);
if (pending == null)
{
if (duplicate)
{
conn.Close(ApiLimits.ClosePolicyViolation);
return;
}
if (busy)
{
if (conn.CanSendBusy())
conn.EnqueueError(request.Id, ApiErrors.ServerBusy());
else
conn.Close(ApiLimits.CloseTryAgainLater);
}
return;
}
try
{
if (!ApiProtocol.IsSystemMethod(request.Method) && !ApiProtocol.IsDataMethod(request.Method))
{
pending.Complete(ApiErrors.MethodNotFound());
return;
}
if (ApiProtocol.IsSystemMethod(request.Method))
{
var handled = ApiProtocol.HandleSystem(request.Method, request.Params, _version(), _modVersion);
if (handled is ApiError sysErr)
pending.Complete(sysErr);
else
pending.CompleteResult(handled);
return;
}
if (!ApiProtocol.TryParseDataCall(request, out var call, out var callErr))
{
pending.Complete(callErr);
return;
}
if (call.Method != DataMethod.Roots && !WebSocketApiFeature.IsKnownRoot(call.Root))
{
pending.Complete(ApiErrors.RootNotFound(call.Root));
return;
}
var session = _session();
var work = new GameWork
{
Pending = pending,
Call = call,
Generation = session.Generation,
DeadlineMs = NowMs + ApiLimits.RequestTimeoutMs
};
if (!_dispatcher.TryEnqueue(work))
pending.Complete(ApiErrors.RequestTimeout());
}
catch (Exception ex)
{
LiveStreamAssist.Logger.LogError($"API request handling failed: {ex}");
pending.Complete(ApiErrors.InternalError());
}
}
}
sealed class BoundedHandler : IHandler
{
readonly IHandler _inner;
readonly int _max;
int _consumed;
public BoundedHandler(IHandler inner, int max)
{
_inner = inner;
_max = max;
}
public void Reset() => _consumed = 0;
public byte[] CreateHandshake(string subProtocol = null) => _inner.CreateHandshake(subProtocol);
public void Receive(IEnumerable<byte> data)
{
var n = 0;
foreach (var _ in data)
n++;
if (_consumed > _max - n)
throw new WebSocketException(WebSocketStatusCodes.MessageTooBig);
_consumed += n;
_inner.Receive(data);
}
public byte[] FrameText(string text) => _inner.FrameText(text);
public byte[] FrameBinary(byte[] bytes) => _inner.FrameBinary(bytes);
public byte[] FramePing(byte[] bytes) => _inner.FramePing(bytes);
public byte[] FramePong(byte[] bytes) => _inner.FramePong(bytes);
public byte[] FrameClose(int code) => _inner.FrameClose(code);
}