mirror of
https://github.com/soarqin/DSP_Mods.git
synced 2026-11-19 17:05:20 +08:00
fix(livestreamassist): migrate WebSocket API to Kestrel
Replace Fleck with pinned in-process Kestrel packages and explicit runtime packaging. Fix connection lifetimes, deadlines, admission accounting, and reflection validation. Add production transport regressions and update the migration guidance with remaining Unity/LAN acceptance gates.
This commit is contained in:
1 parent
94254b8c28
commit
e95c832e03
20 files changed
+3098
-480
No files matched your search
@@ -26,8 +26,8 @@ internal static class ApiLimits
|
||||
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 CloseProtocolError = 1002;
|
||||
public const int CloseUnsupportedData = 1003;
|
||||
public const int CloseInvalidPayload = 1007;
|
||||
public const int ClosePolicyViolation = 1008;
|
||||
@@ -214,14 +214,14 @@ internal static class ApiProtocol
|
||||
MethodRoots, MethodDescribe, MethodRead
|
||||
};
|
||||
|
||||
static readonly JsonSerializer Serializer = JsonSerializer.Create(new JsonSerializerSettings
|
||||
static readonly JsonSerializerSettings SerializerSettings = 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);
|
||||
@@ -327,7 +327,7 @@ internal static class ApiProtocol
|
||||
}
|
||||
|
||||
JObject parms;
|
||||
if (!obj.TryGetValue("params", out var paramsToken) || paramsToken == null || paramsToken.Type == JTokenType.Null)
|
||||
if (!obj.TryGetValue("params", out var paramsToken))
|
||||
parms = new JObject();
|
||||
else if (paramsToken is JObject p)
|
||||
parms = p;
|
||||
@@ -482,7 +482,7 @@ internal static class ApiProtocol
|
||||
using (var json = new JsonTextWriter(writer))
|
||||
{
|
||||
json.Formatting = Formatting.None;
|
||||
Serializer.Serialize(json, value);
|
||||
JsonSerializer.Create(SerializerSettings).Serialize(json, value);
|
||||
json.Flush();
|
||||
writer.Flush();
|
||||
return bounded.ToArray();
|
||||
@@ -521,7 +521,7 @@ internal static class ApiProtocol
|
||||
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 (parms.TryGetValue("requiredCapabilities", out var capToken))
|
||||
{
|
||||
if (!(capToken is JArray arr))
|
||||
return ApiErrors.InvalidParams("requiredCapabilities must be an array.");
|
||||
@@ -571,7 +571,7 @@ internal static class ApiProtocol
|
||||
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 (parms.TryGetValue("select", out var selectToken))
|
||||
{
|
||||
if (!(selectToken is JArray arr))
|
||||
{
|
||||
@@ -622,7 +622,7 @@ internal static class ApiProtocol
|
||||
options.Select = names;
|
||||
}
|
||||
|
||||
if (parms.TryGetValue("offset", out var offsetToken) && offsetToken != null && offsetToken.Type != JTokenType.Null)
|
||||
if (parms.TryGetValue("offset", out var offsetToken))
|
||||
{
|
||||
if (!TryGetInt32(offsetToken, out var offset) || offset < 0)
|
||||
{
|
||||
@@ -634,7 +634,7 @@ internal static class ApiProtocol
|
||||
options.Offset = offset;
|
||||
}
|
||||
|
||||
if (parms.TryGetValue("limit", out var limitToken) && limitToken != null && limitToken.Type != JTokenType.Null)
|
||||
if (parms.TryGetValue("limit", out var limitToken))
|
||||
{
|
||||
if (!TryGetInt32(limitToken, out var limit))
|
||||
{
|
||||
@@ -692,7 +692,7 @@ internal static class ApiProtocol
|
||||
{
|
||||
path = Array.Empty<PathSeg>();
|
||||
error = null;
|
||||
if (!parms.TryGetValue("path", out var token) || token == null || token.Type == JTokenType.Null)
|
||||
if (!parms.TryGetValue("path", out var token))
|
||||
return true;
|
||||
if (!(token is JArray arr))
|
||||
{
|
||||
|
||||
@@ -24,25 +24,31 @@ internal sealed class MainThreadDispatcher
|
||||
readonly Queue<GameWork> _queue = new Queue<GameWork>();
|
||||
readonly GameWorkExecutor _execute;
|
||||
readonly Func<long> _nowMs;
|
||||
readonly Func<int> _frameCount;
|
||||
readonly Timer _watchdog;
|
||||
GameWork _running;
|
||||
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)
|
||||
public MainThreadDispatcher(SynchronizationContext context, object token, GameWorkExecutor execute, Func<long> nowMs,
|
||||
Func<int> frameCount = null)
|
||||
{
|
||||
_context = context;
|
||||
_token = token;
|
||||
_execute = execute;
|
||||
_nowMs = nowMs;
|
||||
_frameCount = frameCount ?? (() => Time.frameCount);
|
||||
_watchdog = new Timer(_ => SweepTimeouts(), null, 250, 250);
|
||||
}
|
||||
|
||||
public bool TryEnqueue(GameWork work)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopped) return false;
|
||||
if (_stopped || _queue.Count >= ApiLimits.MaxPendingRequests) return false;
|
||||
_queue.Enqueue(work);
|
||||
ScheduleLocked();
|
||||
return true;
|
||||
@@ -51,17 +57,19 @@ internal sealed class MainThreadDispatcher
|
||||
|
||||
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());
|
||||
var count = _queue.Count;
|
||||
while (count-- > 0)
|
||||
{
|
||||
var work = _queue.Dequeue();
|
||||
var error = reason(work);
|
||||
if (error == null)
|
||||
_queue.Enqueue(work);
|
||||
else
|
||||
work.Pending.TryComplete(error);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var work in taken)
|
||||
work.Pending.Complete(reason(work));
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
@@ -69,11 +77,35 @@ internal sealed class MainThreadDispatcher
|
||||
lock (_gate)
|
||||
{
|
||||
_stopped = true;
|
||||
_running?.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
}
|
||||
|
||||
_watchdog.Dispose();
|
||||
CancelQueued(_ => ApiErrors.RequestTimeout());
|
||||
}
|
||||
|
||||
void SweepTimeouts()
|
||||
{
|
||||
var now = _nowMs();
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopped) return;
|
||||
if (_running != null && now >= _running.DeadlineMs)
|
||||
_running.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
var count = _queue.Count;
|
||||
while (count-- > 0)
|
||||
{
|
||||
var work = _queue.Dequeue();
|
||||
if (!work.Pending.IsActive)
|
||||
continue;
|
||||
if (now >= work.DeadlineMs)
|
||||
work.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
else
|
||||
_queue.Enqueue(work);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ScheduleLocked()
|
||||
{
|
||||
if (_pumpScheduled || _stopped) return;
|
||||
@@ -99,12 +131,12 @@ internal sealed class MainThreadDispatcher
|
||||
|
||||
void Drain()
|
||||
{
|
||||
var frame = Time.frameCount;
|
||||
var frame = _frameCount();
|
||||
if (frame != _frame)
|
||||
{
|
||||
_frame = frame;
|
||||
_startedThisFrame = 0;
|
||||
_budget.Restart();
|
||||
_budget.Reset();
|
||||
}
|
||||
|
||||
while (_startedThisFrame < ApiLimits.MaxRequestsPerFrame)
|
||||
@@ -116,10 +148,17 @@ internal sealed class MainThreadDispatcher
|
||||
{
|
||||
if (_stopped || _queue.Count == 0) return;
|
||||
work = _queue.Dequeue();
|
||||
_running = work;
|
||||
}
|
||||
|
||||
_startedThisFrame++;
|
||||
Run(work);
|
||||
_budget.Start();
|
||||
try { Run(work); }
|
||||
finally
|
||||
{
|
||||
_budget.Stop();
|
||||
lock (_gate) _running = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,9 +167,9 @@ internal sealed class MainThreadDispatcher
|
||||
if (!work.Pending.IsActive)
|
||||
return;
|
||||
var now = _nowMs();
|
||||
if (now > work.DeadlineMs)
|
||||
if (now >= work.DeadlineMs)
|
||||
{
|
||||
work.Pending.Complete(ApiErrors.RequestTimeout());
|
||||
work.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -142,21 +181,21 @@ internal sealed class MainThreadDispatcher
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogError($"API game-data request failed: {ex}");
|
||||
work.Pending.Complete(ApiErrors.InternalError());
|
||||
work.Pending.TryComplete(ApiErrors.InternalError());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!work.Pending.IsActive)
|
||||
return;
|
||||
if (_nowMs() > work.DeadlineMs)
|
||||
if (_nowMs() >= work.DeadlineMs)
|
||||
{
|
||||
work.Pending.Complete(ApiErrors.RequestTimeout());
|
||||
work.Pending.TryComplete(ApiErrors.RequestTimeout());
|
||||
return;
|
||||
}
|
||||
|
||||
if (result is ApiError err)
|
||||
work.Pending.Complete(err);
|
||||
work.Pending.TryComplete(err);
|
||||
else
|
||||
work.Pending.CompleteResult(result);
|
||||
work.Pending.TryCompleteResult(result);
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,8 @@ internal sealed class ReflectionReader
|
||||
Encoded = null
|
||||
};
|
||||
var effective = value == null ? declaredType : runtimeType ?? value.GetType();
|
||||
if (!IsAllowedType(effective))
|
||||
return Fail(ApiErrors.UnsupportedType());
|
||||
if (TryCollectionKind(effective, out var kind, out var elementType, out var keyType))
|
||||
{
|
||||
int? count = null;
|
||||
@@ -118,7 +120,6 @@ internal sealed class ReflectionReader
|
||||
(!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 };
|
||||
@@ -141,7 +142,7 @@ internal sealed class ReflectionReader
|
||||
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);
|
||||
var page = ReadPage(value, actual, options);
|
||||
if (page.Error != null) return page;
|
||||
page.TypeName = typeName;
|
||||
return page;
|
||||
@@ -186,6 +187,8 @@ internal sealed class ReflectionReader
|
||||
if (current == null)
|
||||
return new WalkStep { Error = ApiErrors.NullPath(i) };
|
||||
runtime = current.GetType();
|
||||
if (!IsAllowedType(runtime))
|
||||
return new WalkStep { Error = ApiErrors.UnsupportedType(i) };
|
||||
var seg = path[i];
|
||||
if (seg.Kind == PathKind.Member)
|
||||
{
|
||||
@@ -228,27 +231,11 @@ internal sealed class ReflectionReader
|
||||
return new WalkStep { Value = current, DeclaredType = declared, RuntimeType = current == null ? null : current.GetType() };
|
||||
}
|
||||
|
||||
WalkResult ReadPage(object collection, Type collectionType, Type elementType, ReadOptions options)
|
||||
WalkResult ReadPage(object collection, Type collectionType, 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)
|
||||
{
|
||||
@@ -301,6 +288,7 @@ internal sealed class ReflectionReader
|
||||
|
||||
WalkResult Project(object value, Type type, string[] select)
|
||||
{
|
||||
if (!IsAllowedType(type)) return Fail(ApiErrors.UnsupportedType());
|
||||
var map = new Dictionary<string, object>(select.Length);
|
||||
foreach (var name in select)
|
||||
{
|
||||
@@ -481,8 +469,11 @@ internal sealed class ReflectionReader
|
||||
CachedType BuildMembers(Type type)
|
||||
{
|
||||
var byName = new Dictionary<string, MemberSlot>(StringComparer.Ordinal);
|
||||
if (!IsAllowedType(type) || IsScalar(Unwrap(type)) || TryCollectionKind(type, out _, out _, out _))
|
||||
return new CachedType { ByName = byName, Exposed = Array.Empty<MemberInfoDto>() };
|
||||
for (var t = type; t != null && t != typeof(object); t = t.BaseType)
|
||||
{
|
||||
if (!IsAllowedType(t) || TryCollectionKind(t, out _, out _, out _)) break;
|
||||
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)
|
||||
@@ -546,7 +537,8 @@ internal sealed class ReflectionReader
|
||||
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.IsArray) return IsSupportedArray(type);
|
||||
if (IsSupportedList(type) || IsSupportedDictionary(type)) return true;
|
||||
if (type.Assembly == GameAssembly) return true;
|
||||
if (_extraAssemblies != null && _extraAssemblies.Contains(type.Assembly)) return true;
|
||||
return false;
|
||||
@@ -556,7 +548,7 @@ internal sealed class ReflectionReader
|
||||
{
|
||||
if (!type.IsArray || type.GetArrayRank() != 1) return false;
|
||||
var element = type.GetElementType();
|
||||
return element != null && !element.IsPointer && IsAllowedType(element);
|
||||
return element != null && type == element.MakeArrayType() && IsAllowedType(element);
|
||||
}
|
||||
|
||||
bool IsSupportedList(Type type)
|
||||
@@ -656,11 +648,10 @@ internal sealed class ReflectionReader
|
||||
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)
|
||||
["value"] = Enum.Format(type, value, "D")
|
||||
};
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BepInEx.Configuration;
|
||||
using UXAssist.Common.ModFeatures;
|
||||
using GameLogicProc = UXAssist.Common.GameLogic;
|
||||
@@ -30,8 +31,8 @@ internal static class WebSocketApiFeature
|
||||
static WebSocketApiServer _server;
|
||||
static MainThreadDispatcher _dispatcher;
|
||||
static ReflectionReader _reader;
|
||||
static GameVersionSnapshot _version = GameVersionSnapshot.Empty;
|
||||
static SessionSnapshot _session = new SessionSnapshot(0, null);
|
||||
static volatile GameVersionSnapshot _version = GameVersionSnapshot.Empty;
|
||||
static volatile SessionSnapshot _session = new SessionSnapshot(0, null);
|
||||
static bool _started;
|
||||
|
||||
public static void BindConfig(ConfigFile config)
|
||||
@@ -78,8 +79,11 @@ internal static class WebSocketApiFeature
|
||||
}
|
||||
|
||||
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);
|
||||
WebSocketApiServer server = null;
|
||||
var dispatcher = new MainThreadDispatcher(ctx, token,
|
||||
work => ReferenceEquals(_ownerToken, token) ? ExecuteWork(work) : ApiErrors.SessionChanged(),
|
||||
() => server?.NowMs ?? 0);
|
||||
server = new WebSocketApiServer(address, port, PluginInfo.PLUGIN_VERSION, GetVersion, GetSession, dispatcher);
|
||||
GameLogicProc.OnDataLoaded += OnDataLoaded;
|
||||
GameLogicProc.OnGameBegin += OnGameBegin;
|
||||
GameLogicProc.OnGameEnd += OnGameEnd;
|
||||
@@ -91,21 +95,29 @@ internal static class WebSocketApiFeature
|
||||
_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();
|
||||
_ = StartServerAsync();
|
||||
|
||||
async Task StartServerAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await server.StartAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LiveStreamAssist.Logger.LogError($"WebSocket API failed to start: {ex}");
|
||||
dispatcher.Stop();
|
||||
await server.StopAsync().ConfigureAwait(false);
|
||||
ctx.Post(_ =>
|
||||
{
|
||||
if (ReferenceEquals(_ownerToken, token)) Uninit();
|
||||
}, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void Uninit()
|
||||
@@ -179,7 +191,7 @@ internal static class WebSocketApiFeature
|
||||
dispatcher = _dispatcher;
|
||||
}
|
||||
|
||||
dispatcher?.CancelQueued(_ => ApiErrors.SessionChanged());
|
||||
dispatcher?.CancelQueued(work => work.Generation == _session.Generation ? null : ApiErrors.SessionChanged());
|
||||
}
|
||||
|
||||
static void EndSession()
|
||||
@@ -191,7 +203,7 @@ internal static class WebSocketApiFeature
|
||||
dispatcher = _dispatcher;
|
||||
}
|
||||
|
||||
dispatcher?.CancelQueued(_ => ApiErrors.SessionChanged());
|
||||
dispatcher?.CancelQueued(work => work.Generation == _session.Generation ? null : ApiErrors.SessionChanged());
|
||||
}
|
||||
|
||||
static bool IsGameReady()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user