From e95c832e033bb869f6eae056b688aa5af1f8ddde Mon Sep 17 00:00:00 2001 From: Soar Qin Date: Thu, 17 Sep 2026 20:53:05 +0800 Subject: [PATCH] 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. --- AGENTS.md | 2 +- LiveStreamAssist/Api/ApiProtocol.cs | 20 +- LiveStreamAssist/Api/MainThreadDispatcher.cs | 79 +- LiveStreamAssist/Api/ReflectionReader.cs | 37 +- LiveStreamAssist/Api/WebSocketApiFeature.cs | 46 +- LiveStreamAssist/Api/WebSocketApiServer.cs | 803 ++++++++++++------ LiveStreamAssist/LiveStreamAssist.csproj | 65 +- .../Properties/InternalsVisibleTo.cs | 1 + LiveStreamAssist/README.md | 4 +- LiveStreamAssist/docs/WebSocketApi.md | 23 +- LiveStreamAssist/docs/WebSocketDesign.md | 276 ++++-- LiveStreamAssist/packages.lock.json | 620 ++++++++++++++ .../Copy-GameFacades.ps1 | 2 +- .../tools/ReflectionReaderCheck/Program.cs | 66 +- LiveStreamAssist/tools/Test-WebSocketApi.ps1 | 152 ++-- .../tools/WebSocketTransportCheck/App.config | 12 + .../ProductionChecks.cs | 532 ++++++++++++ .../tools/WebSocketTransportCheck/Program.cs | 157 ++++ .../WebSocketTransportCheck.csproj | 26 + .../packages.lock.json | 655 ++++++++++++++ 20 files changed, 3098 insertions(+), 480 deletions(-) create mode 100644 LiveStreamAssist/packages.lock.json create mode 100644 LiveStreamAssist/tools/WebSocketTransportCheck/App.config create mode 100644 LiveStreamAssist/tools/WebSocketTransportCheck/ProductionChecks.cs create mode 100644 LiveStreamAssist/tools/WebSocketTransportCheck/Program.cs create mode 100644 LiveStreamAssist/tools/WebSocketTransportCheck/WebSocketTransportCheck.csproj create mode 100644 LiveStreamAssist/tools/WebSocketTransportCheck/packages.lock.json diff --git a/AGENTS.md b/AGENTS.md index 46db71e..500b307 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ - This repository contains independent BepInEx 5.x C# mods for Dyson Sphere Program. HarmonyLib patches game methods at runtime; `UXAssist` is the shared library used directly by `CheatEnabler` and `UniverseGenTweaks`. - Projects target `net472` or `netstandard2.1` with SDK-style `.csproj` files. Compile-time game references live in `AssemblyFromGame/`. - `DustbinPreloader` and `LabOptPreloader` are Mono.Cecil preloaders; their main mods consume the injected fields without reflection. -- LiveStreamAssist: [project design and implementation plan](LiveStreamAssist/docs/WebSocketDesign.md). The WebSocket API packages `Fleck.dll` and `Newtonsoft.Json.dll` through a project-local `ZipMod` `BeforeTargets` item; do not rely on other mods for those DLLs. +- LiveStreamAssist: [WebSocket architecture, transport migration, and validation](LiveStreamAssist/docs/WebSocketDesign.md). ## Build diff --git a/LiveStreamAssist/Api/ApiProtocol.cs b/LiveStreamAssist/Api/ApiProtocol.cs index 1a9ef37..da1aef2 100644 --- a/LiveStreamAssist/Api/ApiProtocol.cs +++ b/LiveStreamAssist/Api/ApiProtocol.cs @@ -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(); - 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(); 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)) { diff --git a/LiveStreamAssist/Api/MainThreadDispatcher.cs b/LiveStreamAssist/Api/MainThreadDispatcher.cs index 6b7d009..36a65d0 100644 --- a/LiveStreamAssist/Api/MainThreadDispatcher.cs +++ b/LiveStreamAssist/Api/MainThreadDispatcher.cs @@ -24,25 +24,31 @@ internal sealed class MainThreadDispatcher readonly Queue _queue = new Queue(); readonly GameWorkExecutor _execute; readonly Func _nowMs; + readonly Func _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 nowMs) + public MainThreadDispatcher(SynchronizationContext context, object token, GameWorkExecutor execute, Func nowMs, + Func 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 reason) { - List taken; lock (_gate) { - if (_queue.Count == 0) return; - taken = new List(_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); } } diff --git a/LiveStreamAssist/Api/ReflectionReader.cs b/LiveStreamAssist/Api/ReflectionReader.cs index e7a3c04..5c975a5 100644 --- a/LiveStreamAssist/Api/ReflectionReader.cs +++ b/LiveStreamAssist/Api/ReflectionReader.cs @@ -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(); 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(select.Length); foreach (var name in select) { @@ -481,8 +469,11 @@ internal sealed class ReflectionReader CachedType BuildMembers(Type type) { var byName = new Dictionary(StringComparer.Ordinal); + if (!IsAllowedType(type) || IsScalar(Unwrap(type)) || TryCollectionKind(type, out _, out _, out _)) + return new CachedType { ByName = byName, Exposed = Array.Empty() }; 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 { ["name"] = name, - ["value"] = underlying.ToString(CultureInfo.InvariantCulture) + ["value"] = Enum.Format(type, value, "D") }; return true; } diff --git a/LiveStreamAssist/Api/WebSocketApiFeature.cs b/LiveStreamAssist/Api/WebSocketApiFeature.cs index 7c6ff94..9ece335 100644 --- a/LiveStreamAssist/Api/WebSocketApiFeature.cs +++ b/LiveStreamAssist/Api/WebSocketApiFeature.cs @@ -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() diff --git a/LiveStreamAssist/Api/WebSocketApiServer.cs b/LiveStreamAssist/Api/WebSocketApiServer.cs index 15bbb05..0e1164b 100644 --- a/LiveStreamAssist/Api/WebSocketApiServer.cs +++ b/LiveStreamAssist/Api/WebSocketApiServer.cs @@ -1,67 +1,97 @@ using System; using System.Collections.Generic; +using System.IO; using System.Net; +using System.Net.WebSockets; using System.Text; +using System.Threading; using System.Threading.Tasks; -using Fleck; -using Newtonsoft.Json.Linq; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; namespace LiveStreamAssist.Api; +internal sealed class ProducedResponse +{ + public object Result; + public ApiError Error; +} + 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; + readonly TaskCompletionSource _tcs = + new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - public bool TryMarkDone() => System.Threading.Interlocked.Exchange(ref _done, 1) == 0; + public Task Completion => _tcs.Task; + public bool IsActive => Volatile.Read(ref _done) == 0 && Connection != null && Connection.IsOpen; - public bool Complete(ApiError error) + public bool TryComplete(ApiError error) { - if (error == null || !TryMarkDone()) return false; - Connection.Deliver(this, null, error); - return true; + if (error == null || Interlocked.Exchange(ref _done, 1) != 0) return false; + return _tcs.TrySetResult(new ProducedResponse { Error = error }); } - public bool CompleteResult(object result) + public bool TryCompleteResult(object result) { - if (!TryMarkDone()) return false; - Connection.Deliver(this, result, null); + if (Interlocked.Exchange(ref _done, 1) != 0) return false; + return _tcs.TrySetResult(new ProducedResponse { Result = result }); + } + + public bool TryCancel() + { + if (Interlocked.Exchange(ref _done, 1) != 0) return false; + _tcs.TrySetCanceled(); return true; } } -internal sealed class ApiConnection +internal sealed class ApiConnection : IDisposable { readonly WebSocketApiServer _server; - readonly IWebSocketConnection _socket; readonly object _gate = new object(); readonly Dictionary _outstanding = new Dictionary(StringComparer.Ordinal); readonly Queue _sendQueue = new Queue(); - bool _sending; + readonly SemaphoreSlim _sendSignal = new SemaphoreSlim(0); + readonly SemaphoreSlim _sendGate = new SemaphoreSlim(1, 1); + readonly CancellationTokenSource _cancellation = new CancellationTokenSource(); + WebSocket _socket; + Task _closeTask; + bool _closing; bool _closed; - int _pending; + bool _sending; - public ApiConnection(WebSocketApiServer server, IWebSocketConnection socket) + public ApiConnection(WebSocketApiServer server) { _server = server; - _socket = socket; + } + + public void Attach(WebSocket socket) + { + lock (_gate) + { + _socket = socket; + if (!_closed) return; + } + socket.Abort(); + } + + public CancellationToken Cancellation => _cancellation.Token; + + public Task CloseCompletion + { + get { lock (_gate) return _closeTask ?? Task.CompletedTask; } } public bool IsOpen { get { - lock (_gate) return !_closed && _socket.IsAvailable; - } - } - - public int Pending - { - get - { - lock (_gate) return _pending; + lock (_gate) return !_closed && !_closing; } } @@ -71,14 +101,14 @@ internal sealed class ApiConnection busy = false; lock (_gate) { - if (_closed) return null; + if (_closed || _closing) return null; if (_outstanding.ContainsKey(id)) { duplicate = true; return null; } - if (_pending >= ApiLimits.MaxPendingRequestsPerConnection || !_server.TryIncrementPending()) + if (_outstanding.Count >= ApiLimits.MaxPendingRequestsPerConnection || !_server.TryIncrementPending()) { busy = true; return null; @@ -86,7 +116,7 @@ internal sealed class ApiConnection var pending = new PendingRequest { Connection = this, Id = id }; _outstanding[id] = pending; - _pending++; + _ = DeliverAsync(pending); return pending; } } @@ -94,7 +124,7 @@ internal sealed class ApiConnection public bool CanSendBusy() { lock (_gate) - return !_closed && _sendQueue.Count < ApiLimits.MaxPendingRequestsPerConnection; + return !_closed && !_closing && _sendQueue.Count + (_sending ? 1 : 0) < ApiLimits.MaxPendingRequestsPerConnection; } public void EnqueueError(object id, ApiError error) @@ -110,166 +140,229 @@ internal sealed class ApiConnection 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); + EnqueueSend(new SendItem { Payload = payload, EnqueuedMs = _server.NowMs }); } public void Release(string id) { + var released = false; lock (_gate) { - if (id != null) - _outstanding.Remove(id); - if (_pending > 0) - _pending--; + if (id != null && _outstanding.Remove(id)) + { + released = true; + } } - _server.DecrementPending(); + if (released) _server.DecrementPending(); } - public void EnqueueSend(byte[] payload) + public void Close(int code) => _ = CloseAsync(code); + + public Task CloseAsync(int code) { lock (_gate) { - if (_closed) return; - if (_sendQueue.Count >= ApiLimits.MaxPendingRequestsPerConnection) - { - CloseLocked(ApiLimits.CloseTryAgainLater); - return; - } + if (_closeTask != null) return _closeTask; + if (_closed) return Task.CompletedTask; + _closing = true; + _sendQueue.Clear(); + _cancellation.CancelAfter(ApiLimits.RequestTimeoutMs); + _sendSignal.Release(); + return _closeTask = Task.Run(SendCloseAsync); + } - _sendQueue.Enqueue(new SendItem { Payload = payload, EnqueuedMs = _server.NowMs }); - if (!_sending) + async Task SendCloseAsync() + { + var entered = false; + try { - _sending = true; - DrainSend(); + await _sendGate.WaitAsync(Cancellation).ConfigureAwait(false); + entered = true; + var ws = _socket; + if (ws == null) + { + NotifyDisconnected(); + return; + } + if (ws.State == WebSocketState.Open || ws.State == WebSocketState.CloseReceived) + await ws.CloseOutputAsync((WebSocketCloseStatus)code, "", Cancellation).ConfigureAwait(false); + } + catch (Exception ex) + { + LiveStreamAssist.Logger.LogWarning($"API close failed: {ex.Message}"); + AbortSend(_socket); + } + finally + { + if (entered) _sendGate.Release(); } } } - 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; + pending = SnapshotPending(); + _outstanding.Clear(); _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()); + { + item.TryCancel(); + _server.DecrementPending(); + } + _cancellation.Cancel(); } - void DrainSend() + public async Task RunSendLoop(WebSocket ws, CancellationToken ct) { - 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; + using var disconnected = ct.Register(NotifyDisconnected); try { - var text = Encoding.UTF8.GetString(item.Payload); - task = _socket.Send(text); + while (!Cancellation.IsCancellationRequested && IsOpen) + { + await _sendSignal.WaitAsync(Cancellation).ConfigureAwait(false); + SendItem item; + lock (_gate) + { + if (_closed || _closing) return; + if (_sendQueue.Count == 0) continue; + item = _sendQueue.Dequeue(); + _sending = true; + } + + var remaining = ApiLimits.RequestTimeoutMs - (_server.NowMs - item.EnqueuedMs); + if (remaining <= 0) + { + AbortSend(ws); + return; + } + + using (var timeout = CancellationTokenSource.CreateLinkedTokenSource(Cancellation)) + { + timeout.CancelAfter((int)remaining); + var entered = false; + try + { + await _sendGate.WaitAsync(timeout.Token).ConfigureAwait(false); + entered = true; + if (!IsOpen) return; + await ws.SendAsync(new ArraySegment(item.Payload), WebSocketMessageType.Text, true, + timeout.Token).ConfigureAwait(false); + } + catch (Exception ex) + { + LiveStreamAssist.Logger.LogWarning($"API send failed: {ex.Message}"); + AbortSend(ws); + return; + } + finally + { + if (entered) _sendGate.Release(); + lock (_gate) _sending = false; + } + } + + if (item.Id != null) + Release(item.Id); + } } - catch (Exception) + catch (OperationCanceledException) { + } + catch (Exception ex) + { + LiveStreamAssist.Logger.LogWarning($"API send loop failed: {ex.Message}"); + AbortSend(ws); + } + } + + async Task DeliverAsync(PendingRequest pending) + { + try + { + var produced = await pending.Completion.ConfigureAwait(false); + if (!IsOpen) return; + byte[] payload; + try + { + payload = ApiProtocol.SerializeEnvelope(pending.Id, produced.Result, produced.Error); + } + catch (ResponseTooLargeException) + { + payload = ApiProtocol.SerializeEnvelope(pending.Id, null, + ApiErrors.LimitExceeded("Response exceeds maxResponseBytes.")); + } + + EnqueueSend(new SendItem { Payload = payload, Id = pending.Id, EnqueuedMs = _server.NowMs }); + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + LiveStreamAssist.Logger.LogError($"API response serialization failed: {ex}"); Close(ApiLimits.CloseTryAgainLater); - return; + } + } + + void EnqueueSend(SendItem item) + { + lock (_gate) + { + if (_closed || _closing) return; + if (_sendQueue.Count + (_sending ? 1 : 0) < ApiLimits.MaxPendingRequestsPerConnection) + { + _sendQueue.Enqueue(item); + _sendSignal.Release(); + return; + } } - if (task == null) - { - Close(ApiLimits.CloseTryAgainLater); - return; - } + Close(ApiLimits.CloseTryAgainLater); + } - task.ContinueWith(_ => DrainSend(), System.Threading.CancellationToken.None, - TaskContinuationOptions.None, TaskScheduler.Default); + void AbortSend(WebSocket ws) + { + try { ws?.Abort(); } + catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"API abort failed: {ex.Message}"); } + NotifyDisconnected(); + } + + public void Dispose() + { + NotifyDisconnected(); + _cancellation.Dispose(); + _sendSignal.Dispose(); + _sendGate.Dispose(); + } + + PendingRequest[] SnapshotPending() + { + var pending = new PendingRequest[_outstanding.Count]; + if (_outstanding.Count > 0) + _outstanding.Values.CopyTo(pending, 0); + return pending; } struct SendItem { public byte[] Payload; + public string Id; public long EnqueuedMs; } } internal sealed class WebSocketApiServer { + static readonly UTF8Encoding Utf8Throw = new UTF8Encoding(false, true); readonly IPAddress _address; readonly int _port; readonly string _modVersion; @@ -279,9 +372,13 @@ internal sealed class WebSocketApiServer readonly object _gate = new object(); readonly List _connections = new List(); readonly System.Diagnostics.Stopwatch _clock = System.Diagnostics.Stopwatch.StartNew(); - WebSocketServer _listener; + readonly CancellationTokenSource _cts = new CancellationTokenSource(); + IWebHost _host; + Task _startTask; + Task _stopTask; int _pending; bool _alive; + bool _stopped; public WebSocketApiServer( IPAddress address, @@ -301,53 +398,101 @@ internal sealed class WebSocketApiServer public long NowMs => _clock.ElapsedMilliseconds; - public void Start() + public void Start() => StartAsync().GetAwaiter().GetResult(); + + public Task StartAsync() { - 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; + if (_stopped) return Task.CompletedTask; + return _startTask ?? (_startTask = Task.Run(StartHostAsync)); } - - LiveStreamAssist.Logger.LogInfo($"WebSocket API listening on {location}{ApiLimits.Path}"); } - public void Stop() + async Task StartHostAsync() { - 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(); + _cts.Token.ThrowIfCancellationRequested(); + await StartHostCoreAsync().ConfigureAwait(false); } - catch (Exception ex) + catch { - LiveStreamAssist.Logger.LogWarning($"WebSocket API listener dispose failed: {ex.Message}"); + _ = StopAsync(); + throw; + } + } + + async Task StartHostCoreAsync() + { + var host = new WebHostBuilder() + .UseSetting(WebHostDefaults.PreventHostingStartupKey, "true") + .UseContentRoot(Path.GetDirectoryName(typeof(WebSocketApiServer).Assembly.Location) ?? ".") + .ConfigureLogging(logging => logging.ClearProviders().AddProvider(new HostLogger())) + .UseKestrel(options => + { + options.Listen(_address, _port); + options.AddServerHeader = false; + options.Limits.MaxConcurrentConnections = ApiLimits.MaxConnections + 2; + options.Limits.MaxConcurrentUpgradedConnections = ApiLimits.MaxConnections; + options.Limits.MaxRequestHeadersTotalSize = 16 * 1024; + options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(5); + options.Limits.MaxRequestBodySize = 1024; + }) + .UseSockets() + .Configure(app => + { + app.UseWebSockets(new WebSocketOptions { ReceiveBufferSize = 4096 }); + app.Run(HandleHttp); + }) + .Build(); + lock (_gate) + { + _host = host; + _alive = !_stopped; + } + + await host.StartAsync(_cts.Token).ConfigureAwait(false); + lock (_gate) + { + if (_stopped) return; + } + var displayed = _address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6 + ? "[" + _address + "]" : _address.ToString(); + LiveStreamAssist.Logger.LogInfo($"WebSocket API listening on ws://{displayed}:{_port}{ApiLimits.Path}"); + } + + public void Stop() => _ = StopAsync(); + + public Task StopAsync() + { + lock (_gate) + { + if (_stopTask != null) return _stopTask; + _stopped = true; + _alive = false; + var conns = _connections.ToArray(); + var startup = _startTask; + return _stopTask = Task.Run(async () => + { + try { _cts.Cancel(); } + catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"API cancel failed: {ex.Message}"); } + foreach (var conn in conns) + conn.Close(ApiLimits.CloseGoingAway); + if (startup != null) + { + try { await startup.ConfigureAwait(false); } + catch (Exception) { /* Startup failures are reported by the feature owner. */ } + } + IWebHost host; + lock (_gate) + { + host = _host; + _host = null; + } + DisposeHost(host); + _cts.Dispose(); + }); } } @@ -375,73 +520,181 @@ internal sealed class WebSocketApiServer _connections.Remove(connection); } - void OnSocket(IWebSocketConnection socket) + async Task HandleHttp(HttpContext context) { - 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) + if (!alive) { - conn.Close(ApiLimits.CloseMessageTooBig); + context.Response.StatusCode = 503; return; } - if (!ApiProtocol.TryParseMessage(message, out var request, out var parseError, out var id)) + var path = context.Request.Path.Value ?? ""; + if (!string.Equals(path, ApiLimits.Path, StringComparison.Ordinal)) + { + context.Response.StatusCode = 404; + return; + } + + if (!context.WebSockets.IsWebSocketRequest) + { + context.Response.StatusCode = 400; + return; + } + + ApiConnection conn; + lock (_gate) + { + if (!_alive || _connections.Count >= ApiLimits.MaxConnections) + { + context.Response.StatusCode = 503; + return; + } + + conn = new ApiConnection(this); + _connections.Add(conn); + } + + try + { + WebSocket ws; + using (_cts.Token.Register(context.Abort)) + ws = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false); + conn.Attach(ws); + await RunConnection(ws, conn, context.RequestAborted).ConfigureAwait(false); + } + finally + { + conn.NotifyDisconnected(); + await conn.CloseCompletion.ConfigureAwait(false); + conn.Dispose(); + } + } + + async Task RunConnection(WebSocket ws, ApiConnection conn, CancellationToken aborted) + { + using (ws) + { + var send = conn.RunSendLoop(ws, aborted); + try + { + await ReceiveLoop(ws, conn).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + catch (WebSocketException ex) + { + LiveStreamAssist.Logger.LogWarning($"API websocket error: {ex.Message}"); + } + catch (Exception ex) + { + LiveStreamAssist.Logger.LogWarning($"API connection failed: {ex.Message}"); + } + finally + { + conn.NotifyDisconnected(); + try { ws.Abort(); } + catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"API abort failed: {ex.Message}"); } + try { await send.ConfigureAwait(false); } + catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"API send join failed: {ex.Message}"); } + } + } + } + + async Task ReceiveLoop(WebSocket ws, ApiConnection conn) + { + var buffer = new byte[4096]; + var payload = new byte[ApiLimits.MaxRequestBytes]; + var used = 0; + long? messageDeadlineMs = null; + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(conn.Cancellation); + while ((ws.State == WebSocketState.Open || ws.State == WebSocketState.CloseSent) && !conn.Cancellation.IsCancellationRequested) + { + var remaining = messageDeadlineMs.HasValue && conn.IsOpen ? messageDeadlineMs.Value - NowMs : Timeout.Infinite; + if (messageDeadlineMs.HasValue && conn.IsOpen && remaining <= 0) + { + await conn.CloseAsync(ApiLimits.CloseTryAgainLater).ConfigureAwait(false); + continue; + } + timeout.CancelAfter((int)remaining); + WebSocketReceiveResult result; + try + { + result = await ws.ReceiveAsync(new ArraySegment(buffer), timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + + if (result.MessageType == WebSocketMessageType.Close) + { + var status = result.CloseStatus.GetValueOrDefault(WebSocketCloseStatus.NormalClosure); + if (status == WebSocketCloseStatus.Empty) status = WebSocketCloseStatus.NormalClosure; + await conn.CloseAsync((int)status).ConfigureAwait(false); + return; + } + + if (!conn.IsOpen) continue; + if (result.MessageType == WebSocketMessageType.Binary) + { + await conn.CloseAsync(ApiLimits.CloseUnsupportedData).ConfigureAwait(false); + continue; + } + + if (messageDeadlineMs.HasValue && NowMs >= messageDeadlineMs.Value) + { + await conn.CloseAsync(ApiLimits.CloseTryAgainLater).ConfigureAwait(false); + continue; + } + + if (used > ApiLimits.MaxRequestBytes - result.Count) + { + await conn.CloseAsync(ApiLimits.CloseMessageTooBig).ConfigureAwait(false); + continue; + } + + Buffer.BlockCopy(buffer, 0, payload, used, result.Count); + used += result.Count; + if (!result.EndOfMessage) + { + if (!messageDeadlineMs.HasValue) messageDeadlineMs = NowMs + ApiLimits.RequestTimeoutMs; + continue; + } + timeout.CancelAfter(Timeout.Infinite); + + string text; + try + { + text = used == 0 ? "" : Utf8Throw.GetString(payload, 0, used); + } + catch (ArgumentException) + { + await conn.CloseAsync(ApiLimits.CloseInvalidPayload).ConfigureAwait(false); + continue; + } + + used = 0; + messageDeadlineMs = null; + HandleMessage(conn, text); + } + } + + void HandleMessage(ApiConnection conn, string message) + { + if (!conn.IsOpen) return; + var parsed = ApiProtocol.TryParseMessage(message, out var request, out var parseError, out var id); + if (!parsed && !(id is string)) { conn.EnqueueError(id, parseError); return; } - var pending = conn.TryAdmit(request.Id, out var duplicate, out var busy); + var requestId = parsed ? request.Id : (string)id; + var admittedMs = NowMs; + var pending = conn.TryAdmit(requestId, out var duplicate, out var busy); if (pending == null) { if (duplicate) @@ -453,18 +706,24 @@ internal sealed class WebSocketApiServer if (busy) { if (conn.CanSendBusy()) - conn.EnqueueError(request.Id, ApiErrors.ServerBusy()); + conn.EnqueueError(requestId, ApiErrors.ServerBusy()); else conn.Close(ApiLimits.CloseTryAgainLater); } return; } + try { + if (!parsed) + { + pending.TryComplete(parseError); + return; + } if (!ApiProtocol.IsSystemMethod(request.Method) && !ApiProtocol.IsDataMethod(request.Method)) { - pending.Complete(ApiErrors.MethodNotFound()); + pending.TryComplete(ApiErrors.MethodNotFound()); return; } @@ -472,21 +731,21 @@ internal sealed class WebSocketApiServer { var handled = ApiProtocol.HandleSystem(request.Method, request.Params, _version(), _modVersion); if (handled is ApiError sysErr) - pending.Complete(sysErr); + pending.TryComplete(sysErr); else - pending.CompleteResult(handled); + pending.TryCompleteResult(handled); return; } if (!ApiProtocol.TryParseDataCall(request, out var call, out var callErr)) { - pending.Complete(callErr); + pending.TryComplete(callErr); return; } if (call.Method != DataMethod.Roots && !WebSocketApiFeature.IsKnownRoot(call.Root)) { - pending.Complete(ApiErrors.RootNotFound(call.Root)); + pending.TryComplete(ApiErrors.RootNotFound(call.Root)); return; } @@ -496,49 +755,49 @@ internal sealed class WebSocketApiServer Pending = pending, Call = call, Generation = session.Generation, - DeadlineMs = NowMs + ApiLimits.RequestTimeoutMs + DeadlineMs = admittedMs + ApiLimits.RequestTimeoutMs }; if (!_dispatcher.TryEnqueue(work)) - pending.Complete(ApiErrors.RequestTimeout()); + pending.TryComplete(ApiErrors.ServerBusy()); } catch (Exception ex) { LiveStreamAssist.Logger.LogError($"API request handling failed: {ex}"); - pending.Complete(ApiErrors.InternalError()); + pending.TryComplete(ApiErrors.InternalError()); + } + } + + static void DisposeHost(IWebHost host) + { + if (host == null) return; + try + { + host.StopAsync(TimeSpan.FromMilliseconds(ApiLimits.RequestTimeoutMs)).GetAwaiter().GetResult(); + } + catch (Exception ex) + { + LiveStreamAssist.Logger.LogWarning($"WebSocket API host stop failed: {ex.Message}"); + } + + try { host.Dispose(); } + catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"WebSocket API host dispose failed: {ex.Message}"); } + } + + sealed class HostLogger : ILoggerProvider, ILogger + { + public ILogger CreateLogger(string categoryName) => this; + public IDisposable BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel level) => level >= LogLevel.Warning && level != LogLevel.None; + public void Dispose() { } + + public void Log(LogLevel level, EventId eventId, TState state, Exception exception, + Func formatter) + { + if (!IsEnabled(level)) return; + var message = "WebSocket host: " + formatter(state, exception); + if (exception != null) message += "\n" + exception; + if (level >= LogLevel.Error) LiveStreamAssist.Logger.LogError(message); + else LiveStreamAssist.Logger.LogWarning(message); } } } - -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 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); -} diff --git a/LiveStreamAssist/LiveStreamAssist.csproj b/LiveStreamAssist/LiveStreamAssist.csproj index 6d70c2b..c169e87 100644 --- a/LiveStreamAssist/LiveStreamAssist.csproj +++ b/LiveStreamAssist/LiveStreamAssist.csproj @@ -6,18 +6,77 @@ 1.0.0 LiveStreamAssist LiveStreamAssist + true - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - <_PackRootFiles Include="$(TargetDir)Fleck.dll" Condition="Exists('$(TargetDir)Fleck.dll')" /> - <_PackRootFiles Include="$(TargetDir)Newtonsoft.Json.dll" Condition="Exists('$(TargetDir)Newtonsoft.Json.dll')" /> + <_PackRootFiles Include="@(WebSocketRuntimeDll)" /> diff --git a/LiveStreamAssist/Properties/InternalsVisibleTo.cs b/LiveStreamAssist/Properties/InternalsVisibleTo.cs index a0361ba..7e92d2a 100644 --- a/LiveStreamAssist/Properties/InternalsVisibleTo.cs +++ b/LiveStreamAssist/Properties/InternalsVisibleTo.cs @@ -1,3 +1,4 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("ReflectionReaderCheck")] +[assembly: InternalsVisibleTo("WebSocketTransportCheck")] diff --git a/LiveStreamAssist/README.md b/LiveStreamAssist/README.md index 28793d5..dae0648 100644 --- a/LiveStreamAssist/README.md +++ b/LiveStreamAssist/README.md @@ -13,6 +13,8 @@ The mod requires UXAssist. ## WebSocket API +The in-tree listener uses in-process ASP.NET Core 2.3 Kestrel (managed sockets). Unity 2022/Mono and LAN acceptance remain pending. The design document below defines the remaining gates. + Disabled by default. In the BepInEx config file, set: ```text @@ -25,4 +27,4 @@ Port = 18080 Then connect to `ws://:18080/api/v1`. There is no authentication. Use a LAN bind address or `0.0.0.0` only on trusted networks. Configuration changes require a game restart. - [WebSocket API reference](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketApi.md) -- [WebSocket design and implementation plan](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketDesign.md) +- [WebSocket design and transport migration plan](https://github.com/soarqin/DSP_Mods/blob/master/LiveStreamAssist/docs/WebSocketDesign.md) diff --git a/LiveStreamAssist/docs/WebSocketApi.md b/LiveStreamAssist/docs/WebSocketApi.md index 41b509a..403ee82 100644 --- a/LiveStreamAssist/docs/WebSocketApi.md +++ b/LiveStreamAssist/docs/WebSocketApi.md @@ -1,8 +1,8 @@ # LiveStreamAssist WebSocket API -Status: implemented contract for API `1.0.0`. Enable the listener with BepInEx setting `WebSocketApi.Enabled`. Real-game and LAN acceptance still need a DSP run; see the [design and implementation plan](WebSocketDesign.md). +Status: API `1.0.0` compatibility contract. The in-tree transport is in-process ASP.NET Core 2.3 Kestrel; Unity/LAN acceptance is still pending. Enable the listener with BepInEx setting `WebSocketApi.Enabled`; see the [design and transport migration plan](WebSocketDesign.md). -Audience: developers of live-stream overlays, OBS integrations, and other clients. Server architecture and implementation tasks are documented separately in the [design and implementation plan](WebSocketDesign.md). +Audience: developers of live-stream overlays, OBS integrations, and other clients. Server architecture and implementation tasks are documented separately in the [design and transport migration plan](WebSocketDesign.md). ## Connection @@ -12,7 +12,7 @@ ws://:18080/api/v1 The service supports local and LAN clients without authentication. No token, login request, or application-level handshake is required. The client sends requests after the WebSocket connection opens. Other URL paths are rejected and must not execute API requests. -The planned BepInEx configuration section is `WebSocketApi`: +The BepInEx configuration section is `WebSocketApi`: | Setting | Type | Default | Meaning | | --- | --- | --- | --- | @@ -31,6 +31,18 @@ Suggested client sequence: There are no subscriptions or unsolicited application messages. Normal WebSocket control frames, including ping/pong and close frames, are transport operations rather than application notifications. +## WebSocket interoperability + +The required transport profile is [RFC 6455](https://www.rfc-editor.org/rfc/rfc6455) over HTTP/1.1 Upgrade, using WebSocket version `13`. It is intended to interoperate with current browsers, OBS browser sources, and standard WebSocket clients. The migration does not change the JSON-RPC contract or require a new client SDK. + +- Client frames must be masked; server frames must not be masked. Invalid framing, reserved opcodes, and unnegotiated RSV bits are protocol errors (`1002`). +- Fragmentation must preserve message boundaries and UTF-8 decoder state. Interleaved control frames do not restart or relax the complete-message byte limit. +- Ping/pong and close handshakes follow RFC 6455. A pong responding to a ping carries the same payload. Invalid text or close-reason UTF-8 produces `1007`. +- `permessage-deflate` and other extensions are not negotiated in v1. An extension offer can be declined while accepting an ordinary uncompressed WebSocket connection. HTTP/2 and HTTP/3 WebSocket transports are not advertised by this profile. +- Invalid paths, invalid opening handshakes, and connection-capacity rejection may be rejected at the HTTP layer before upgrade. A client must not assume every unsuccessful connection produces a WebSocket close frame. + +These are acceptance requirements for the transport. Passing desktop checks does not imply full conformance or Unity/LAN acceptance; see the linked implementation status. + ## Message format The API uses a restricted JSON-RPC 2.0 request/response format. It does not implement the full JSON-RPC feature set: batches and notification requests are deliberately rejected. @@ -123,7 +135,7 @@ These are the initial v1 defaults. `system.info.limits` is the authoritative sou | `maxRequestsPerFrame` | 8 | Maximum game-data requests started in one Unity frame. | | `mainThreadBudgetMs` | 2 | Soft main-thread scheduling budget per Unity frame. | -Outstanding requests include queued reads, executing reads, and responses waiting to be sent. System methods also consume outstanding-request capacity, but do not consume the game-data execution budget. A saturated server returns `SERVER_BUSY` when it can deliver an error without growing the send queue; otherwise it closes the connection with `1013`. +Outstanding requests include queued reads, executing reads, and responses waiting to be sent, including an active send. System methods also consume outstanding-request capacity, but do not consume the game-data execution budget. A saturated server returns `SERVER_BUSY` when it can deliver an error within the bounded send queue; otherwise it attempts to close the connection with `1013`. A stalled or broken transport is aborted if a close frame cannot be delivered within the send deadline. The main-thread budget does not preempt a running read. Deadlines are independent of game ticks and pause state. A timed-out request cannot later produce a success response. If a response cannot be delivered to a stalled client within the bounded send deadline, the connection closes instead of retaining output indefinitely. @@ -486,10 +498,13 @@ Transport closure codes relevant to clients: | Code | Meaning | | --- | --- | | `1001` | Server is stopping. | +| `1002` | WebSocket framing or protocol violation. | | `1003` | Binary application message is unsupported. | | `1007` | Invalid UTF-8 payload. | | `1008` | Protocol violation such as reuse of an outstanding ID. | | `1009` | Incoming message is too large. | | `1013` | Overload or inability to drain a bounded send queue. | +Reserved status values such as `1005`, `1006`, and `1015` are not sent in close frames. A client may locally report `1006` when a transport is lost or aborted without a completed close handshake. + Do not retry invalid paths unchanged in a tight loop. Game-state errors can be retried after discovery; overload and timeouts require client-side backoff. Reconnection creates a new request-ID namespace but does not restore any requests from the old connection. diff --git a/LiveStreamAssist/docs/WebSocketDesign.md b/LiveStreamAssist/docs/WebSocketDesign.md index 1e0223a..120e38a 100644 --- a/LiveStreamAssist/docs/WebSocketDesign.md +++ b/LiveStreamAssist/docs/WebSocketDesign.md @@ -1,6 +1,8 @@ -# LiveStreamAssist WebSocket Design and Implementation Plan +# LiveStreamAssist WebSocket Design and Transport Migration Plan -Status: code is in tree; real-game/LAN acceptance is still blocked. Transport is Fleck **1.2.0** plus Newtonsoft.Json **13.0.3**. Fixture checks pass via `dotnet build LiveStreamAssist/tools/ReflectionReaderCheck/ReflectionReaderCheck.csproj -c Release` then `LiveStreamAssist/tools/ReflectionReaderCheck/bin/Release/net472/ReflectionReaderCheck.exe`. Enable the listener with BepInEx `WebSocketApi.Enabled` and rerun `LiveStreamAssist/tools/Test-WebSocketApi.ps1` in DSP. +Status: **in-process Kestrel transport implemented; desktop regressions pass; Unity/LAN and full conformance acceptance pending**. Production code explicitly pins ASP.NET Core **2.3.13** hosting, HTTP, Kestrel Core, Sockets, and WebSockets, `System.Net.WebSockets.WebSocketProtocol` **5.1.3**, and Newtonsoft.Json **13.0.3**. Fleck is removed. The desktop probe verifies a fragmented echo round trip; production-code checks cover connection cleanup, admission, deadlines, shutdown, and loopback requests. DSP/Unity Mono, Autobahn, and LAN checks have not passed. + +The next remaining work is an actual DSP run of the probe/mod, then M3 conformance. Keep the mod on `net472`. A standalone gateway is a last-resort fallback after concrete in-process failures, not the default design. The [API reference](WebSocketApi.md) defines the client-visible contract. This document defines the scope, implementation constraints, source references, work order, and acceptance checks. Keep API usage documentation separate from implementation investigation and progress notes. @@ -16,8 +18,11 @@ The following decisions were confirmed with the user and must survive a session - Reserve API statistics through `system.stats`, returning `available: false` and `metrics: null`; advertise `api.stats: false`. - Do not implement subscriptions, application notifications, batch requests, game writes, arbitrary method invocation, or script evaluation. - Preserve the existing Ctrl+F8 statistics-window feature and its independent state. +- The game uses Unity 2022. Standard-library APIs, selected NuGet assets, and the entire runtime dependency graph must work in its actual Mono player. +- Prefer an in-process implementation. Consider a standalone gateway only when maintained, compatible in-process options cannot satisfy the compatibility and conformance gates. +- Retire Fleck and its internal-handler workaround. Do not carry them forward as the normal transport or as an automatic runtime fallback. -Keep the implementation small: one listener, a fixed method switch, fixed root providers, a bounded main-thread dispatcher, and shallow result projection. No RPC framework, general-purpose reflection service, dependency-injection container, external server process, HTTP REST API, web dashboard, or custom WebSocket framing implementation is required. +Keep the implementation small: one listener, a fixed method switch, fixed root providers, a bounded main-thread dispatcher, and shallow result projection. Use only the hosting services required by Kestrel; do not refactor the mod's feature architecture into a dependency-injection framework. No MVC, SignalR, REST API, web dashboard, general-purpose reflection service, or custom WebSocket framing implementation is required. The initial listener configuration and all wire limits are defined in [API connection settings](WebSocketApi.md#connection) and [API limits](WebSocketApi.md#limits). Keep those tables as the single documentation source for their values. Configuration is startup-only in v1; do not introduce live configuration reload as part of this work. @@ -27,10 +32,48 @@ The initial listener configuration and all wire limits are defined in [API conne 2. Inspect `git status` and the current diff. Treat existing changes as user work. Check whether some phases have already been implemented rather than assuming this document's initial status still describes the checkout. 3. Read the source entry points in the next section. Preserve the host-owned feature lifecycle and existing keyboard handling. 4. Recheck runtime-specific assumptions against the installed game's original assemblies if DSP or Unity has changed. Do not use stripped reference DLL method bodies as evidence. -5. Complete phases in dependency order. Mark a phase complete only after its acceptance checks pass; identify unavailable real-game or LAN checks as blocked, not passed. +5. Complete the migration phases in dependency order. M0 must pass before adopting a replacement in production code. Mark checks complete only after running them; an unavailable DSP or LAN test is blocked, not passed and not proof that an in-process solution is impossible. 6. If pausing between sessions, update this document's current status, remaining phase checks, selected dependency versions, and concrete blockers. Replace stale notes instead of appending a chronological transcript. Keep project-specific guidance here; `AGENTS.md` should contain only a link to this document. -The API reference is the source of truth for method names, message shapes, numeric error codes, null behavior, and capability names. Resolve any conflict with this plan before implementing it. The transport package/version is intentionally provisional until Phase 0; that is not permission to redesign the protocol or expand the confirmed scope. +The API reference is the source of truth for method names, message shapes, numeric error codes, null behavior, and capability names. Resolve any conflict with this plan before implementing it. The migration replaces transport and repairs its integration; it does not restart the reflection feature from scratch or expand the API scope. Do not preserve an implementation bug by weakening the documented contract. + +## Transport decision and evidence + +Research baseline: **2026-09-17**. The preferred candidate is the **serviced ASP.NET Core 2.3 package line for .NET Framework**, using Kestrel's managed socket transport and its WebSocket middleware in the game process. This is a package-based `netstandard2.0` route, not a requirement to load a modern .NET runtime into Unity. + +Microsoft explicitly lists Kestrel, its socket transport, and WebSocket middleware in the [supported 2.3 package set][aspnet-support]. Its [servicing advisory][aspnet-advisory] distinguishes this line from unsupported ASP.NET Core 2.1/2.2 packages and from running old .NET Core runtimes. The reviewed [WebSockets 2.3.13][websockets-package] and [Sockets transport 2.3.13][sockets-package] packages publish `netstandard2.0` assets and September 2026 servicing releases. Recheck the latest supported patch when implementing; patch numbers need not be identical across all packages. + +The [reviewed middleware source][middleware-source] obtains an opaque stream through Kestrel's `IHttpUpgradeFeature` and constructs the WebSocket through the protocol dependency. The [socket transport source][sockets-source] uses the managed socket transport. This avoids the game's unimplemented `HttpListenerContext.AcceptWebSocketAsync` path. + +Important qualifications: + +- Microsoft's support statement concerns ASP.NET Core on .NET Framework; it is **not a certification of Unity's Mono player**. M0 still requires an actual DSP run. +- This is a serviced compatibility line, not the current ASP.NET Core feature line. The required standard is the [API's RFC 6455/HTTP/1.1 profile](WebSocketApi.md#websocket-interoperability), not a claim of HTTP/2, HTTP/3, compression, or future extension support. +- The transitive [WebSocketProtocol package][protocol-package] labels its standalone factory API obsolete. Do not build a new handshake stack around that API. Use the maintained middleware's existing integration, review the exact resolved protocol package and advisories, and verify which concrete WebSocket implementation is loaded. A package's Microsoft ownership alone is not sufficient acceptance evidence. + +### Candidate disposition + +| Candidate | Disposition and evidence | +| --- | --- | +| ASP.NET Core 2.3 + managed Kestrel Sockets + WebSockets | First candidate for M0: serviced packages and a compatible declared API surface. Actual Mono loading, protocol behavior, and resource bounds remain to be tested. | +| Fleck 1.2.0 | Retired by the user's requirement. The reviewed [repository head][fleck-source] is a 2021 core commit; do not imply the repository is formally archived. The retired handler wrapper did not enforce a message-level limit. | +| TouchSocket.Http 4.3.x | Maintained and publishes compatible targets, but not an approved drop-in. The [reviewed 4.3.6 frame parser][touch-frame] allocates from the advertised payload length before an application callback; the [framework-target project][touch-project] also references `System.Web`. The [4.3.7 package][touch-package] is newer than the reviewed source snapshot. Reconsider only with matching released source and passing gates, without a private framing fork. | +| SuperSocket.WebSocket.Server 2.1.0 | The [current package][supersocket-package] requires .NET 6 or later, so it is not a compatible in-process replacement for this `net472` mod. Do not select an old preview merely to obtain a different TFM. | +| A separate supported .NET LTS gateway | Conditional fallback only; see [Fallback boundary](#fallback-boundary). It adds packaging, IPC, and process-lifetime responsibilities and must not be introduced just because game testing is unavailable. | + +### Unity and dependency compatibility rules + +The [Unity 2022.3 documentation][unity-profile] describes .NET Standard 2.1 and .NET Framework API compatibility profiles and explicitly excludes .NET Core-targeted managed plugins. The installed player, not a Unity Editor setting in a different project, is the runtime to validate. + +1. Keep `LiveStreamAssist.csproj` and its UXAssist reference on the existing `net472` path. For the replacement, select actual `netstandard2.0` or compatible .NET Framework assets, including transitive dependencies. Unity's support for Standard 2.1 does not make a Standard-2.1-only package a valid SDK project reference from `net472`. +2. Do not reference `net6.0`, `net8.0`, or `net10.0` implementation DLLs in the mod. Do not add a `Microsoft.AspNetCore.App` framework reference, switch to `Microsoft.NET.Sdk.Web`, or retarget shared mods to make an incompatible package restore. +3. Package version and target framework are different facts. A dependency such as `System.IO.Pipelines` or `Microsoft.Extensions.Options` can have an 8.x version and still supply a compatible asset; inspect the selected asset path and its APIs instead of deciding from its version number. +4. Inspect `project.assets.json`, resolved runtime copy items, assembly references, and the actual game load results. Pay particular attention to `System.Memory`, `System.Buffers`, `System.Threading.Tasks.Extensions`, `System.Runtime.CompilerServices.Unsafe`, `System.IO.Pipelines`, and `Microsoft.Extensions.*`, including conflicts with other installed mods. +5. Never replace the game's `mscorlib`, `System`, `System.Core`, `netstandard`, Unity assemblies, or framework facades to make the host start. Do not ship reference assemblies from a package's `ref` directory. Conversely, do not discard every `System.*` DLL: reviewed package implementations such as `System.Net.WebSockets.WebSocketProtocol.dll` may be required runtime dependencies. +6. Use the classic `WebHostBuilder`/`IWebHost` hosting surface and `WebSocket` array-segment/task APIs available to the selected target. Avoid APIs copied from modern examples, such as `WebApplication.CreateBuilder`, `Task.WaitAsync`, or memory-based WebSocket overloads absent from the compile/runtime surface. Use ordinary task cancellation/timeouts where necessary. +7. A successful desktop .NET Framework build or console run is only an early check. `MissingMethodException`, `TypeLoadException`, `NotImplementedException`, or unsupported socket behavior in the actual player fails M0. Do not conceal such failures with warning suppression, private-reflection patches, or global assembly-resolution hooks. + +Prospective direct dependencies are the supported 2.3.x hosting/Kestrel components, `Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets`, and `Microsoft.AspNetCore.WebSockets`, plus the existing Newtonsoft.Json dependency. Prefer explicit components if a convenience package brings unused transports. Select the latest compatible serviced protocol dependency as well; do not let a minimum transitive constraint silently pin an obsolete patch. Record and lock the exact approved graph after M0. ## Repository entry points @@ -41,6 +84,10 @@ Paths in this table are relative to the repository root. | `LiveStreamAssist/LiveStreamAssist.cs` / `LiveStreamAssist.Awake` | BepInEx plugin startup; performs localization setup and feature discovery. Bind API configuration before discovery. | | `LiveStreamAssist/LiveStreamAssist.cs` / `LiveStreamAssistFeature` | Existing feature, order 50; owns Ctrl+F8 and statistics-window switching. Its `_enabled` flag is not the server-enabled flag. | | `LiveStreamAssist/LiveStreamAssist.csproj` | Inherits `net472`, currently references UXAssist, and owns the mod version. Add only the server's required dependencies and project-scoped packaging customization here. | +| `LiveStreamAssist/Api/WebSocketApiServer.cs` | Kestrel host, `ApiConnection`, and `PendingRequest`; owns transport lifetime, admission, bounded I/O, and host-error logging. | +| `LiveStreamAssist/Api/MainThreadDispatcher.cs` | Current game-work queue and completion path; inspect physical queue bounds and timeout behavior as well as frame budgets. | +| `LiveStreamAssist/Api/ApiProtocol.cs` | Reuse the JSON-RPC contract and system methods; review serializer concurrency and remove transport-specific raw-socket limits. | +| `LiveStreamAssist/tools/ReflectionReaderCheck/` | Existing fixture runner. Preserve its coverage; it does not prove WebSocket conformance or game-runtime compatibility. | | `UXAssist/Common/ModFeatures/ModFeatureRegistry.cs` | Initializes discovered features eagerly. UXAssist alone drives `StartAll`, `UninitAll`, and update dispatchers. | | `UXAssist/UXAssist.cs` / `Update` | Skips feature updates while `VFInput.inputing` or `DSPGame.IsMenuDemo` is true. This is unsuitable as the sole server request pump. | | `UXAssist/Common/GameLogic.cs` | Supplies `OnDataLoaded`, `OnGameBegin`, and `OnGameEnd` callbacks. Use the fully qualified UXAssist type or the existing `GameLogicProc` alias to avoid DSP's own `GameLogic` type. | @@ -78,22 +125,39 @@ ilspycmd --disable-updatecheck -t System.Net.HttpListenerContext /Syste Replace placeholders and quote paths containing spaces. Do not depend on this session's temporary decompilation output or a hard-coded Steam drive letter. Do not commit game DLLs or decompiled game source. -## Intended code organization +### Transport integration invariants + +Keep these rules when changing the transport. The desktop harness exercises the production classes with controlled work scheduling and sockets; it does not replace the Unity acceptance gate. + +| Code path | Required behavior | +| --- | --- | +| `ReceiveLoop` | Bound complete-message payloads, preserve fragmentation state across empty fragments, and cancel stalled partial reads independently of the next receive completion. | +| `ApiConnection.NotifyDisconnected` / `Dispose` | Cancel I/O and wake an idle sender, clear queued output, and release every admission exactly once. Overflow must use this cleanup path rather than setting the terminal flag early. | +| `TryAdmit` / `DeliverAsync` / `RunSendLoop` | Retain IDs and admission slots through delivery. Include active sends in output capacity, and deduct queued time from the send deadline. Invalid requests with a reliable ID still participate in duplicate-ID checks. | +| `CloseAsync` / `ReceiveLoop` | Serialize close output with application sends; leave peer-close reception to the single receive loop. Bound the handshake and abort stalled I/O. | +| `MainThreadDispatcher` | Watch queued and executing work, bound the physical queue, and remove canceled entries. Completion continuations must not serialize inline in the game-work producer. | +| `StartAsync` / `StopAsync` / `HandleHttp` | One startup/shutdown task per owner, no resurrection after stop, no disposal racing startup, and concrete connection reservations that can be canceled during upgrade. | +| `WebSocketApiFeature` | Bind clocks and failure callbacks to their originating owner, publish immutable snapshots with cross-thread visibility, and invalidate only old-session work. | +| `ApiProtocol` / `ReflectionReader` | Use per-operation serializers, reject explicitly null typed parameters, and apply runtime/declaration type boundaries consistently to reads, descriptions, and projections. | +| `tools/Test-WebSocketApi.ps1` | Use per-operation deadlines, strict-mode-safe optional access, bounded reads, and cleanup after failed upgrades. Require an actual HTTP rejection rather than treating every connection failure as a passed route test. | + +## Code organization Use these responsibilities as the starting layout; keep small private helpers with their owner rather than creating an interface or service for each step. -| Planned file | Responsibility | +| File | Responsibility after migration | | --- | --- | -| `LiveStreamAssist/Api/WebSocketApiFeature.cs` | Configuration references, feature lifecycle, version publication, game-session tracking, and root providers. Suggested feature order: 51. | -| `LiveStreamAssist/Api/WebSocketApiServer.cs` | Listener, connections, message admission, serialized sends, and connection cleanup. | +| `LiveStreamAssist/Api/WebSocketApiFeature.cs` | Preserve configuration, feature order 51, Unity-context capture, version publication, sessions, and root providers; coordinate asynchronous host lifetime. | +| `LiveStreamAssist/Api/WebSocketApiServer.cs` | Private Kestrel host and `System.Net.WebSockets.WebSocket` connection loops, bounded admission, serialized sends, and cleanup. Keep framework-specific types here. | | `LiveStreamAssist/Api/ApiProtocol.cs` | DTOs, error constants, validation, fixed method dispatch, system methods, and the API version constant. | | `LiveStreamAssist/Api/ReflectionReader.cs` | Shared path resolution, allowed-member discovery, value projection, and detached result construction. | -| `LiveStreamAssist/Api/MainThreadDispatcher.cs` | Bounded request queue, one scheduled pump, cancellation, and deadline/session checks. | +| `LiveStreamAssist/Api/MainThreadDispatcher.cs` | Physically bounded game-work queue, one scheduled pump, cancellation, and detached completion; no JSON serialization or socket work. | | `LiveStreamAssist/tools/Test-WebSocketApi.ps1` | Runnable WebSocket integration checks using PowerShell 7 and `System.Net.WebSockets.ClientWebSocket`. | +| `LiveStreamAssist/tools/WebSocketTransportCheck/` | Desktop `net472` echo probe and production transport/dispatcher regression checks. Keep test-only echo behavior out of the production API. | Bind the three API settings in plugin startup before `ModFeatureRegistry.Discover`. Use a separate `[ModFeature]` class for the server. Do not have LiveStreamAssist call registry dispatchers, add a second shared update driver, relax UXAssist's menu/typing guards, or attach server activation to Ctrl+F8. -Keep `net472`. Prefer one managed Mono-compatible WebSocket server dependency, initially evaluate Fleck, and explicitly reference Newtonsoft.Json. LuaScriptEngine's transitive Newtonsoft.Json reference does not make that DLL a guaranteed runtime dependency of LiveStreamAssist. Pin versions only after compatibility verification; record the chosen versions in this document and the project file. +Keep Newtonsoft.Json for the existing API encoding. Do not migrate the JSON contract to SignalR or a different serializer as part of replacing Fleck. No new general-purpose transport factory or public abstraction is needed; isolate the selected framework at the existing server boundary. ## Runtime design @@ -101,12 +165,25 @@ Keep `net472`. Prefer one managed Mono-compatible WebSocket server dependency, i - `Init`: prepare configuration references and non-network state. Keep initialization safe if the API is disabled. - `Start`: if enabled, capture `SynchronizationContext.Current` on Unity's main thread, initialize a server owner instance, subscribe to game lifecycle events, and start the listener without blocking the game loop. If the current context is null or is not Unity's installed context, fail startup with a useful log; a newly constructed generic `SynchronizationContext` is not a main-thread dispatcher. +- Build/start the private `IWebHost` on a worker and observe its startup task. Initialize owner/admission state before requests can arrive. Use explicit configuration from the mod rather than process-global URL settings, console lifetime, or unrelated hosting-startup discovery. Do not call `Run()` or terminate the game process when the host stops. - Publish version data from `GameLogicProc.OnDataLoaded`. If starting after preload, use the original preload completion flags to populate it immediately. Publish an immutable snapshot; network callbacks never read `GameConfig` or Unity state directly. Preserve this snapshot across save changes. - Source `modVersion` from generated `PluginInfo.PLUGIN_VERSION`. Keep `apiVersion` independent, initially `1.0.0`. Use the explicit `System.Version` name if parsing the API version to avoid DSP's global `Version` type. - Subscribe to `OnGameBegin` and `OnGameEnd` for session transitions. Account for starting after a game has already begun. - `Uninit`: stop admitting work, invalidate the owner/session, cancel requests, unsubscribe events, close the listener, and close connections. Clear metadata caches owned by the server. Posted callbacks must check their old owner token so they cannot run against a restarted instance. - Startup errors, including an occupied port or invalid settings, disable only this server instance and are logged. Do not silently bind a different address/port or let an exception escape into other features' startup/shutdown. - Start/stop and cleanup must be idempotent. Never synchronously wait on a task whose completion needs the Unity thread during shutdown. +- Bound and observe `StopAsync`; dispose the host off the Unity thread, including startup-failure paths. A stopped or superseded owner cannot resume startup and leave a listener behind. Keep lifecycle/event-state transitions coordinated with the existing main-thread feature owner. +- Forward Kestrel warnings/errors to the mod logger so runtime failures before the API handler are visible. The host must not require process-global logging configuration. + +### Kestrel connection and receive loop + +- Explicitly select the managed socket transport and the configured IP endpoint. Do not use `HttpListener`, HTTP.sys, IIS integration, or Libuv. Use the supported WebSocket middleware for handshake validation and the opaque-stream upgrade; do not recreate handshake or frame parsing in mod code. +- Restrict the route to `/api/v1` before upgrade. Return an HTTP rejection for other paths, invalid handshakes, or exhausted upgrade capacity. Bound ordinary HTTP connections, upgraded connections, request-header size, and header-read time using supported host options. A Kestrel HTTP request-body limit is not a WebSocket message limit. +- Await the connection handler for the lifetime of the WebSocket so the HTTP request pipeline does not dispose the upgraded stream prematurely. Each connection owns one receive loop, one serialized application send loop, and cancellation linked to server shutdown and client disconnect. +- Read through the target-compatible `ReceiveAsync(ArraySegment, CancellationToken)` API. Accumulate at most `maxRequestBytes`, checking before each append; deliver one complete text message only when `EndOfMessage` is true. Handle an empty message as a JSON parse failure, not as a disconnect. Give an incomplete message an operation deadline once it starts, while allowing an otherwise idle connection to remain open. +- Let the maintained protocol implementation handle masking, RSV/opcode validation, fragmentation state, ping/pong, and close parsing. Use strict UTF-8 decoding for the bounded completed text. Do not install another private-handler hook or write a frame parser to compensate for failed conformance. +- Keep compression/extensions disabled for the v1 profile. Preserve binary-message rejection (`1003`), invalid UTF-8 (`1007`), invalid framing (`1002`), oversized messages (`1009`), and application policy errors (`1008`) as distinct outcomes. +- Await and observe sends. Apply a deadline covering both queued time and the active send; use a bounded close attempt followed by `Abort`/disposal if the peer cannot drain. Do not send reserved close status values, swallow a failed send and continue, or launch overlapping application sends. ### Root providers and readiness @@ -138,15 +215,20 @@ WebSocket callback -> one Unity SynchronizationContext.Post pump -> recheck connection, deadline, session, and readiness -> resolve root/path and build detached result - -> serialize and send off the Unity thread + -> asynchronous completion signal only + -> worker serializes within the output cap + -> serialized send; release admission only after delivery/cancellation ``` - Network receive, JSON parsing, serialization, and socket sends stay off the Unity thread. Avoid accidentally capturing Unity's context in network async continuations. - Only one pump callback may be scheduled per server owner at a time. Process work within the API's per-frame count and soft-time budget, then repost remaining work. Do not busy-wait, spin, or post one unbounded callback per request. Track the Unity frame for the budget if the context is pumped more than once in a frame. - Use a standard queue with a small lock or `ConcurrentQueue` with correct admission accounting. A custom scheduler or lock-free queue is unnecessary. If using task completions, run continuations asynchronously so response work does not execute inline in the pump. - A request owns one admission slot until response delivery or cancellation. Capacity includes outgoing responses. Serialize sends per connection, bound the send queue, and close slow consumers rather than retaining unlimited output. -- Expiry is based on monotonic elapsed time, not `Time.time` or game ticks. Check expiry before reading. Once timed out, work cannot later emit success. A deadline does not abort a getter halfway through; the read policy must keep getters short and bounded. -- Cancellation and session invalidation must remove or cheaply skip queued work and release its slot. Use one completion path so timeout, disconnect, and successful reads cannot double-complete or leak admission counts. +- Distinguish response production from terminal delivery: `admitted -> result/error produced -> response sent or connection canceled`. Keep the ID reserved through the last step. A task completion source with asynchronous continuations is sufficient; do not serialize or release the slot inside its main-thread producer. +- Expiry is based on monotonic elapsed time, not `Time.time` or game ticks. A worker-enforced production deadline must fire even when Unity stops pumping. Check expiry before reading as well. Once timed out, work cannot later emit success. A deadline does not abort a getter halfway through; the read policy must keep getters short and bounded. +- Reuse the documented timeout duration for a separate bounded send deadline beginning at response enqueue, including the active send. A send timeout closes/aborts the connection; it must not interleave a second error envelope into a partly transmitted response. +- Connection cancellation removes or cheaply skips queued work and releases its slot exactly once. Session invalidation and production timeout instead produce the documented error; retain the ID and slot until that error is sent or the connection is canceled. Use one terminal cleanup path so competing outcomes cannot double-complete or leak admission counts. +- Enforce a physical game-work queue bound even after canceled requests release network admission. A queue full of stale entries is not permission to allocate another unbounded queue or task list. Bound unslotted parse/busy-error responses as well. - The only mutable game references exist during main-thread execution. Return scalar values, strings, copied arrays/pages, and plain snapshot dictionaries/DTOs; never pass a live DSP object, boxed game struct with nested references, `MemberInfo`, or `UnityEngine.Object` to the background JSON serializer. ### Session transitions @@ -180,102 +262,131 @@ Use one resolver/member-policy path for `data.read`, `data.describe`, and projec Catch reflection/getter failures at the request boundary and map them to the API errors. Retain diagnostic exceptions in local logs, not response bodies. System methods and generic game-data methods must share envelope/error handling; do not introduce parallel protocol implementations. -## Implementation phases +## Migration phases -### Phase 0: runtime transport verification +Checkmarks describe the completed work below; stated desktop results do not close the separate Unity/LAN gates. Keep evidence for the tested package graph and actual game runtime with the current phase status. -- [x] Inspect the current project state and original runtime assumptions listed above. -- [x] Evaluate Fleck first as a single managed WebSocket server dependency, plus an explicit Newtonsoft.Json dependency, while retaining `net472`. -- [ ] Verify the server inside actual DSP/BepInEx/Mono using a standard WebSocket client. A standalone .NET console server is not evidence of game-runtime compatibility. **Blocked: DSP was not launched in the implementation session.** -- [x] Verify text-message fragmentation, invalid UTF-8 handling, binary rejection, connection closure, and request-size enforcement before unbounded message accumulation. Check the library's behavior before promising a limit that its callbacks cannot enforce. -- [ ] Verify path rejection, clean listener disposal, occupied-port failure, and a bounded serialized send path. **Code is present; in-game confirmation blocked.** -- [x] Record the selected package versions and any necessary runtime dependency DLLs here; pin them in `LiveStreamAssist.csproj`. +### M0: prove the in-process compatibility path -Selected packages: Fleck **1.2.0**, Newtonsoft.Json **13.0.3**. Packaged runtime DLLs: `Fleck.dll`, `Newtonsoft.Json.dll`. Fleck 1.2.0 has no max-message API; incoming size is capped by wrapping `IHandler.Receive` at `maxRequestBytes + 8KiB` socket bytes, then checking UTF-8 payload length in `OnMessage`. Invalid UTF-8 uses Fleck's thrower `UTF8Encoding` and close `1007`. Binary frames close `1003`. +- [x] Build a small `net472` probe with the latest serviced ASP.NET Core 2.3 hosting, managed socket transport, and WebSocket packages. The researched transport/middleware baseline is 2.3.13; resolve compatible current versions for the other components and the protocol dependency instead of assuming all version numbers match. +- [x] Inspect and record the selected compile/runtime assets and transitive closure, including the concrete protocol assembly. Check advisories and the upstream support statement, not just the package title or a computed NuGet compatibility list. +- [x] Prove that the probe uses managed Kestrel Sockets and the maintained middleware upgrade path, with no fallback to the game's `HttpListener` implementation, Libuv, HTTP.sys, or a hand-written handshake/parser. +- [ ] Run the same candidate in actual DSP/Unity 2022 Mono. Record game/Unity versions, architecture, loaded assembly identities/locations, and the WebSocket implementation type. Test both a clean supported installation and coexistence with the normal mod set. **Blocked: DSP was not launched.** +- [ ] Verify a real opening handshake, fragmented text with interleaved ping, exact ping/pong payload behavior, a bounded oversized input, and closing/releasing the listener. An advertised huge frame length must not trigger an allocation proportional to that length before the application can enforce its limit. **Desktop checks cover handshake, fragmented round trips, payload limits, and listener release. Interleaved ping/pong and huge advertised lengths remain unverified.** +- [ ] Confirm an idle API, startup failure, and normal shutdown do not disturb Ctrl+F8 or the shared feature lifecycle. Verify a port already in use fails softly. **Blocked: DSP.** +- [x] Record a go/no-go decision and the exact graph to adopt. If a compatible package asset is missing or an actual Mono API fails, record the concrete failing call/assembly rather than suppressing it. -If Fleck cannot meet the runtime or bounded-buffer requirements, evaluate one other small managed Mono-compatible server library and document the reason. Do not write a new framing stack, switch to an ASP.NET host, change the target framework, or add multiple competing transports to hide an unresolved compatibility problem. Treat missing real-game verification as a blocker. - -Exit condition: the selected transport can actually listen, exchange bounded messages, and release its resources in the game's runtime. Reuse the verified code in the implementation rather than leaving a second prototype server in the tree. - -### Phase 1: lifecycle, protocol, and system methods - -- [x] Add the separate API feature and startup-only configuration; preserve the existing feature's registration and state. -- [x] Implement request validation, ID tracking, fixed dispatch, response/error envelopes, capacity accounting, and serial sends. -- [x] Implement `system.ping`, `system.info`, and `system.validate` with the specified state-independent semantics. -- [x] Implement only the `system.stats` placeholder. Keep `api.stats` and `subscriptions` false; advertise reflection capabilities only when their implementations are ready. -- [x] Publish runtime version metadata through main-thread initialization/lifecycle code and handle late feature startup. -- [x] Add the integration script's no-save mode for system methods, malformed messages, invalid IDs, unknown methods, incompatible majors/capabilities, and the statistics placeholder. - -Exit condition: system methods work from local and LAN clients without authentication, including at the main menu. Version fields match the running game after preload. Startup/stop failures do not interrupt other features. Invalid requests produce the documented response or transport closure. - -### Phase 2: main-thread queries and reflection - -- [x] Add the bounded synchronization-context pump and current-session admission state. -- [x] Add the seven fixed root providers and readiness checks, including the menu-demo exclusion and paused-game allowance. -- [x] Implement the shared member policy, exact getter allowlist, typed path traversal, null handling, and deterministic metadata listing. -- [x] Implement scalar encoding, summaries, explicit projections, and array/list pages exactly as the API reference specifies. -- [x] Attach `sessionId` and `gameTick` to game-data results; ensure returned snapshots contain no live game references. -- [x] Extend the integration script with `-RequireGame` checks that discover roots, read `history.currentTech`, read `history.techQueue`, and inspect/read a research state using an ID obtained from the game. -- [x] Leave one small runnable set of fixture-based checks for the production reflection/projection code, covering inherited private fields, blocked getters, null intermediates/terminals, dictionary key types, indexes, shallow cyclic references, 64-bit precision, and non-finite values. - -Fixture run command (repository root; copies `netstandard.dll` and Unity core modules from the installed game): +Desktop probe (repository root): ```powershell -dotnet build LiveStreamAssist/tools/ReflectionReaderCheck/ReflectionReaderCheck.csproj -c Release -& LiveStreamAssist/tools/ReflectionReaderCheck/bin/Release/net472/ReflectionReaderCheck.exe +dotnet build LiveStreamAssist/tools/WebSocketTransportCheck/WebSocketTransportCheck.csproj -c Release +& LiveStreamAssist/tools/WebSocketTransportCheck/bin/Release/net472/WebSocketTransportCheck.exe +& LiveStreamAssist/tools/WebSocketTransportCheck/bin/Release/net472/WebSocketTransportCheck.exe --regression ``` -Keep fixture checks outside the shipped plugin and out of the remote root catalog. Use the smallest repository-compatible harness; no new testing framework or abstraction is required solely for these checks. Exercise the production reader, not a reimplementation of it, and record the exact run command here once its layout is chosen. +Observed desktop identities: Kestrel.Core **2.3.13**, Transport.Sockets **2.3.13**, WebSockets middleware **2.3.13**, protocol type `System.Net.WebSockets.ManagedWebSocket` from `System.Net.WebSockets.WebSocketProtocol` **5.1.3**. Microsoft.Extensions.* **8.x** assets selected as `lib/net462`. Newtonsoft.Json **13.0.3**. No Libuv package. The harness references the production project, and all 34 transport/hosting package versions match its lock file. Unity/Mono adoption remains unconfirmed. -Exit condition: returned research values match the in-game data, precision is preserved beyond `2^53`, rejected members cannot be reached through alternate read/describe/projection paths, and queries execute on Unity's main thread while typing or paused. +The desktop regression harness loads Unity type metadata but runs on the Windows CLR. Its test-only `App.config` binds `netstandard` to the desktop 2.0 facade; Unity's Mono 2.1 type forwarders are not interchangeable with CLR forwarders. This configuration and the copied test host/game assemblies are not mod package contents and do not establish Mono compatibility. -### Phase 3: lifecycle races, resource bounds, and recovery +Exit condition: the candidate actually starts, exchanges bounded messages, and disposes under the game's runtime using the intended managed assemblies. Desktop-only tests or an unavailable DSP launch leave M0 blocked. Investigate supported in-process alternatives before crossing the fallback boundary. -- [ ] Verify a queued read cannot run against a different save after loading, unloading, or reloading a session. **Blocked: needs a running save.** -- [ ] Verify timeout/disconnect/session-change races release admission capacity once and cannot emit late or duplicate success responses. **Single completion path is implemented; in-game race verification blocked.** -- [ ] Verify menu, loading, pause, space-travel root absence, and game-end behavior match the documented error distinctions. **Blocked: needs DSP.** -- [ ] Exercise capacity and payload limits with multiple clients, fragmented oversized input, slow readers, and large projections/pages. Output must stay bounded during serialization, not merely fail after allocation. **Bounded send/receive/serialize is implemented; multi-client DSP run blocked.** -- [ ] Verify an ordinary query still succeeds after malformed requests, busy responses, and other recoverable errors. **Covered by Test-WebSocketApi.ps1; needs DSP.** -- [ ] Verify idempotent stop, released listener ports, ignored callbacks after disposal, and fail-soft behavior when another process owns the configured port. **Blocked: needs DSP / occupied-port check.** -- [ ] Regress Ctrl+F8 startup/stop, window closure, and the existing randomized tab switching. **Blocked: needs DSP.** +### M1: replace the Fleck transport -Exit condition: the server remains usable after recoverable failures, old sessions cannot leak through queued work, and overload cannot create unbounded queues or main-thread network work. Report actual observations rather than asserting an unmeasured FPS or latency guarantee. +- [x] Replace the listener and connection implementation at `WebSocketApiServer.cs` using the M0-approved graph. Keep framework-specific hosting types at this boundary. +- [x] Implement explicit endpoint/path handling, bounded pre-upgrade and upgraded connection admission, and a correctly awaited WebSocket connection lifetime. +- [x] Implement the single receive loop and bounded complete-message assembly using the standard WebSocket API. Remove all Fleck references, `BoundedHandler`, handler casts/reflection, and `MaxIncomingSocketBytes`. +- [x] Coordinate asynchronous host startup/stop with the existing feature owner and cancellation token. Dispose partial startup instances and prevent late callbacks from resurrecting stopped state. +- [x] Retain API version `1.0.0`, the existing configuration keys/defaults, seven methods, root providers, reflection policy, game-session identifiers, numeric encoding, and statistics placeholder. Do not add authentication or subscriptions. -### Phase 4: packaging and final handoff +Exit condition: the production request path no longer uses Fleck or a private frame implementation, and the original API requests work through the new host. This does not yet establish all race/resource guarantees. -- [x] Add the selected runtime dependencies to LiveStreamAssist's package, scoped to this project. -- [ ] Build, run the fixture checks and integration script, and complete the manual real-game/LAN acceptance matrix below. **Fixture checks passed; integration script and LAN matrix blocked without DSP.** -- [ ] Inspect the resulting ZIP and test a clean install with only the manifest-declared dependencies and packaged runtime DLLs. Do not rely on DLLs provided incidentally by LuaScriptEngine or the development environment. -- [x] Update the API reference and project README to describe verified implemented behavior. Remove the planned-only status only when the implementation is actually ready. -- [x] Update this design document's current status, dependency selection, verified environment, and any remaining blockers. Keep `AGENTS.md` as a documentation pointer instead of copying this plan into it. -- [x] Run `git diff --check` and review the final diff for unrelated changes. +### M2: repair completion, accounting, and deadlines -The existing `ZipMod` target does not gather dependency DLLs automatically. Prefer a project-local target with `BeforeTargets="ZipMod"` that adds the explicitly selected runtime DLLs to `_PackRootFiles`; the shared target will then stage them along with the plugin. Confirm the ordering and actual resolved filenames in the build output. Do not copy the entire output directory: that can include game references, Unity assemblies, BepInEx assemblies, and UXAssist itself. No shared packaging redesign is needed. +- [x] Separate detached result production from delivery. No Unity-thread completion path may serialize JSON or enter a socket send. Verify thread affinity rather than assuming an async method automatically moves work to another thread. +- [x] Keep request IDs and per-connection/global slots until the response is sent or the connection is canceled. Test success, error, timeout, disconnect, and stop races for exactly-once slot release. **Desktop held-send, overflow, timeout, and disconnect checks pass; in-game transitions remain pending.** +- [x] Enforce response-production deadlines on a worker while the Unity pump is intentionally blocked. Do not cancel the receive loop merely because one game-data request times out. +- [x] Enforce queued and active-send deadlines, observe failed tasks, and bound close attempts before aborting failed transports. Include the active send in queue/memory accounting. +- [x] Put a hard bound on the physical game-work queue and remove/prune canceled entries. Repeated timeouts while the game loop is stopped must not accumulate stale work without limit. +- [x] Make response serialization safe under concurrency while preserving the byte cap and existing JSON encoding. +- [x] Preserve session-generation checks and invalidate queued old-save work. Already produced/in-transit snapshots remain tagged with the sampling session; never claim they can be recalled. +- [x] Retain and rerun the reflection fixture checks. Add focused deterministic checks for these transport-integration defects using held completions/fake work scheduling, not production-only debug endpoints. **Reflection fixtures and the production `--regression` harness pass.** -The project README can link to source-hosted developer documentation so its links also work when the README is distributed without the repository's `docs` folder. +Exit condition: a blocked Unity frame does not block system methods or timeout responses; all queues remain bounded; slots and IDs survive until terminal delivery/cancellation; no late success follows a timeout. + +### M3: conformance and game integration + +- [ ] Run a pinned [Autobahn Testsuite][autobahn] configuration in `fuzzingclient` mode against a test-only echo host using the same approved transport packages and configuration path. Use its isolated toolchain image and record the image digest, case results, and justified exclusions. Do not expose an echo method on the production JSON-RPC endpoint. Probe `--echo` exists; Autobahn was not run. +- [ ] Test opening-handshake validation separately: HTTP method/version, required Upgrade/Connection tokens, WebSocket version/key, invalid paths, capacity rejection, and oversized or stalled headers. Autobahn's documented opening-handshake coverage is incomplete. +- [ ] Cover masking direction, RSV/reserved opcodes, continuation ordering, interleaved control frames, control-frame FIN/size rules, invalid length encodings, UTF-8 across fragments, close status/reason validation, and ping/pong payload equality. +- [ ] Test application limits separately with the real v1 settings: exact boundary and boundary-plus-one payloads, byte-by-byte fragmentation, multiple messages in one socket read, interleaved pings, and huge advertised lengths. Do not mistake an Autobahn echo expectation for a requirement to accept application payloads above 64 KiB. +- [ ] Use a raw-socket/fuzzing test tool for invalid frames; `ClientWebSocket` intentionally does not generate many malformed frame cases. Keep malformed-frame generation in test tooling, not production transport code. +- [x] Repair the PowerShell smoke harness: per-operation cancellation, response-ID matching, optional-field checks under strict mode, buffer/socket cleanup, and HTTP handshake-rejection handling. Move duplicate-outstanding-ID checks to a held-request harness so a legitimately completed first request does not create a timing-dependent failure. +- [ ] Run no-save and active-save API checks, then real-game pause/text-input, loading, space travel, save switch/reload, and Ctrl+F8 regressions. Run a LAN client from a second machine and a current browser/OBS browser source. **Blocked: DSP.** +- [ ] Exercise multiple clients and slow/non-reading consumers, blocked game work, malformed input followed by valid input, port conflicts, repeated start/stop, and shutdown during startup/read/send. + +Desktop production checks pass for fragmented JSON, binary/invalid-UTF-8/oversized rejection (`1003`/`1007`/`1009`), duplicate IDs (`1008`), shutdown (`1001`), blocked-pump timeout delivery, stalled fragments, occupied ports, and startup/stop races. Full framing conformance, multi-client stress, and actual game/LAN scenarios remain open. + +Autobahn proves the covered transport behavior, not the reflection API or Unity scheduling. Compression/other unsupported extensions and application size limits must be accounted for explicitly. A partial run, waived core-protocol failure, or test against a different runtime/package build is not a full pass. Seek an upstream fix for a required protocol defect; do not reconstruct a private frame layer to turn the report green. + +Exit condition: the applicable RFC 6455 cases and application/resource tests pass with recorded evidence, and the actual Unity/Mono plus LAN integration matrix passes. No unmeasured FPS, latency, or future-standard guarantee is implied. + +### M4: packaging and maintained delivery + +- [x] Replace the two-DLL Fleck packaging list with the audited runtime closure of the approved host, while retaining project-local packaging customization. +- [x] Pin the approved package versions and record the resolved graph, selected TFMs, and source/support references. Use a project-local package lock and locked restore for repeatable validation once the graph is approved; do not change dependency policy for unrelated mods. +- [x] Fail packaging when a required runtime dependency is absent. Do not silently drop mandatory files behind `Exists` conditions, copy the entire build output, or ship reference/game/framework assemblies. +- [x] Verify the final assembly references and ZIP contain no Fleck dependency or leftover handler shim. Remove stale Fleck files only from LiveStreamAssist-owned staging/install locations; other mods may legitimately use their own copies. +- [ ] Test the packaged mod on a clean installation containing the declared BepInEx/UXAssist dependencies, then with the ordinary mod set. Do not depend on a developer machine's shared .NET runtime or incidental plugin DLLs. **Blocked: DSP.** +- [x] Update API/README status only after the documented gates pass. Record the approved graph, exact probe/conformance commands, runtime evidence, and any remaining blocker in this document. Keep `AGENTS.md` as a link only. **Status records remaining Unity/LAN blockers; do not treat this as a full gate pass.** +- [ ] Run the narrow build/fixture/smoke checks and `git diff --check`; review the diff for unrelated changes. **Release builds, fixtures, desktop transport checks, and ZipMod pass. The PowerShell script parses successfully; its game/LAN run is still pending.** + +Use the existing project-local `BeforeTargets="ZipMod"` extension point and `_PackRootFiles`, driven by an audited dependency list or filtered resolved-runtime items. Include required supporting implementations such as the approved protocol/buffer packages, while excluding game references, Unity/BepInEx assemblies, and UXAssist itself. Record why each packaged assembly is needed; a `System.*` filename alone neither includes nor excludes it. + +### Maintenance policy + +- Review upstream support, servicing releases, and package advisories before a mod release and when an advisory affects shipped dependencies. Old release dates alone do not prove abandonment, and frequent releases alone do not prove conformance. +- Review updates within the supported compatibility line. Do not automatically upgrade package majors or switch to a `net6.0+` asset because it has a higher version number. Avoid floating transport versions in a released build. +- For every runtime-dependency update, inspect the graph/TFM diff, run the transport/protocol regressions and Unity smoke tests, and retain the conformance configuration/results. Rerun the wider game/LAN matrix when runtime behavior or hosting changes. +- Prefer upstream fixes and serviced packages over local protocol patches. Track a discovered defect with a minimal reproducer and regression case. If a necessary fix cannot be obtained on a supported compatible line, reopen the selection decision instead of permanently freezing an unmaintained fork. +- Keep compiler/audit policy intact. Document an actual compatibility limitation rather than suppressing it to obtain a green build. This process reduces maintenance risk; it does not promise bug-free dependencies. + +## Fallback boundary + +The user requested in-process investigation first. A standalone gateway becomes an option only after recording concrete failures of the preferred route and reasonable maintained in-process alternatives: unavailable Mono APIs, an unresolvable assembly-identity conflict, required protocol defects without a supported fix, or loss of upstream support. Missing access to DSP, a failed search, or extra package DLLs is not such evidence. + +If this boundary is reached, revise the architecture before implementation: a supported .NET LTS process can own Kestrel/WebSockets while the Unity `net472` mod continues to own reflection and main-thread snapshots. The public API should remain compatible. Specify bounded local IPC, connection/request routing, deadlines, session invalidation, startup failure, parent/child exit cleanup, packaging, and runtime servicing in that revision. Modern .NET assemblies must remain in the separate process, never loaded into Unity. Do not scaffold or ship this fallback alongside a working in-process host. ## Validation commands and acceptance matrix -Run commands from the repository root. These are implementation-time commands; their inclusion here does not mean the server, scripts, or runtime checks already exist or have passed. +Run commands from the repository root. These target the existing mod and tools; their inclusion does not mean the replacement or runtime checks have passed. When adding the M0 probe and M3 conformance harness, record their exact build/run commands, test configuration path, and pinned toolchain version here. Before the integration commands, install the built mod and its required DLLs, set `WebSocketApi.Enabled` to true, and restart DSP. Run no-save checks at the main menu, then open a save for `-RequireGame`. For the LAN check, configure the actual LAN bind address or `0.0.0.0` before restarting and connect from the second machine to the server's real LAN address, not to `0.0.0.0`. ```powershell -dotnet restore LiveStreamAssist/LiveStreamAssist.csproj +dotnet restore LiveStreamAssist/LiveStreamAssist.csproj --locked-mode dotnet build LiveStreamAssist/LiveStreamAssist.csproj -c Release --no-restore +dotnet build LiveStreamAssist/tools/WebSocketTransportCheck/WebSocketTransportCheck.csproj -c Release +& LiveStreamAssist/tools/WebSocketTransportCheck/bin/Release/net472/WebSocketTransportCheck.exe +& LiveStreamAssist/tools/WebSocketTransportCheck/bin/Release/net472/WebSocketTransportCheck.exe --regression +dotnet build LiveStreamAssist/tools/ReflectionReaderCheck/ReflectionReaderCheck.csproj -c Release +& LiveStreamAssist/tools/ReflectionReaderCheck/bin/Release/net472/ReflectionReaderCheck.exe pwsh -NoProfile -File LiveStreamAssist/tools/Test-WebSocketApi.ps1 -ServerUri ws://127.0.0.1:18080/api/v1 pwsh -NoProfile -File LiveStreamAssist/tools/Test-WebSocketApi.ps1 -ServerUri ws://127.0.0.1:18080/api/v1 -RequireGame dotnet build LiveStreamAssist/LiveStreamAssist.csproj -t:ZipMod -c Release --no-restore git diff --check ``` +The fixture tools copy Unity metadata/facades from the installed game; the transport harness also copies BepInEx for desktop type loading. These copies are test-only. Use locked restore for repeatable validation; dependency updates require an explicit graph review and lock update. The packaged ZIP contains 49 declared runtime dependencies plus the plugin, manifest, README, and icon. Neither tool binaries/configuration nor game/core-framework/host assemblies belong in it. + The smoke script must accept those parameters, require no WebSocket client package, close its sockets in cleanup, and exit nonzero when an assertion fails. `-RequireGame` fails clearly if a save is not ready; no-save mode skips only game-dependent assertions, not protocol/system checks. Repeat the relevant script from a second machine with the actual LAN address. A loopback-only run does not establish LAN acceptance. Do not use game-mutating debug endpoints to make checks pass. If a particular research ID is needed, discover it from current research, the research queue, or known game data; do not assume the API example's `1001` is always active. | Scenario | Required observation | | --- | --- | +| Unity/Mono dependency loading | The reviewed runtime assets load from the intended locations without missing APIs, assembly conflicts, or framework replacement. | | Default configuration | API disabled, no listener, existing assist still works. | +| Opening handshake / RFC 6455 | Valid clients connect; invalid handshakes and framing fail as specified; applicable conformance cases pass with recorded results. | | Preload / main menu | Ping works; version readiness is explicit; menu demo is not an available player root. | | Active save | Roots, metadata, research reads, projections, and pages are correct. | | Pause / text input | Data reads still complete through the Unity context. | @@ -285,8 +396,12 @@ Do not use game-mutating debug endpoints to make checks pass. If a particular re | Cyclic object fixture | Shallow summaries and bounded explicit paths terminate without recursive graph export. | | Save switch / reload | Old queued requests fail; new queries carry a new session identifier. | | Invalid / oversized input | Documented JSON error or WebSocket close; no unlimited fragment buffer. | +| Fragmentation / control frames | Payload accounting survives interleaved pings and TCP chunking; huge declared lengths cannot force proportional allocation. | | Multiple clients / slow consumer | Bounded admission and output; normal clients recover after pressure is removed. | +| Blocked Unity pump | System methods and production deadlines still work; stale game-work entries remain bounded. | +| Active send / ID reuse | IDs and slots stay reserved through delivery; send failure or timeout aborts without a second response or leaked capacity. | | Timeout / disconnect / stop | No double completion, leaked slots, stale game references, or Unity-thread wait deadlock. | +| Startup / shutdown races | Occupied-port failure is isolated; stopping during startup leaves no orphan listener or late owner callbacks. | | Clean installation | All required third-party DLLs resolve without an incidental mod installation. | | Existing statistics assist | Ctrl+F8 and automatic tab switching retain their behavior. | @@ -297,3 +412,18 @@ Normal validation remains the narrow LiveStreamAssist build, with warnings treat `system.stats` deliberately stops at the placeholder. When statistics are requested, define a concrete schema before enabling `api.stats`; likely candidates are current connections, completed/failed requests, bytes sent/received, and durations in milliseconds since server start. V1 admission counters are resource controls, not an excuse to expose an undocumented metrics schema. Subscriptions, writes, method invocation, authentication, additional root catalogs, aggregated gameplay endpoints, dictionary enumeration, and recursive object export require separate scope decisions. Do not implement extension scaffolding for them now. + +[aspnet-support]: https://dotnet.microsoft.com/en-us/platform/support/policy/aspnet/2.3-packages +[aspnet-advisory]: https://devblogs.microsoft.com/dotnet/servicing-release-advisory-aspnetcore-23/ +[websockets-package]: https://www.nuget.org/packages/Microsoft.AspNetCore.WebSockets/2.3.13 +[sockets-package]: https://www.nuget.org/packages/Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets/2.3.13 +[middleware-source]: https://github.com/dotnet/aspnetcore/blob/1db07eda0330bfc87e383d1d65a50e9f0d43c6e9/src/Middleware/WebSockets/src/WebSocketMiddleware.cs +[sockets-source]: https://github.com/dotnet/aspnetcore/blob/1db07eda0330bfc87e383d1d65a50e9f0d43c6e9/src/Servers/Kestrel/Transport.Sockets/src/SocketTransportFactory.cs +[protocol-package]: https://www.nuget.org/packages/System.Net.WebSockets.WebSocketProtocol +[fleck-source]: https://github.com/statianzo/Fleck/commit/45672e0781974bb04dbad1b94320756a33c60a6d +[touch-frame]: https://github.com/RRQM/TouchSocket/blob/bf377c2a1363576e8b0ecb0924e9718f0093f0dc/src/TouchSocket.Http/WebSockets/Common/WSDataFrame.cs +[touch-project]: https://github.com/RRQM/TouchSocket/blob/bf377c2a1363576e8b0ecb0924e9718f0093f0dc/src/TouchSocket.Http/TouchSocket.Http.csproj +[touch-package]: https://www.nuget.org/packages/TouchSocket.Http/4.3.7 +[supersocket-package]: https://www.nuget.org/packages/SuperSocket.WebSocket.Server/2.1.0 +[unity-profile]: https://docs.unity3d.com/2022.3/Documentation/Manual/dotnetProfileSupport.html +[autobahn]: https://github.com/crossbario/autobahn-testsuite diff --git a/LiveStreamAssist/packages.lock.json b/LiveStreamAssist/packages.lock.json new file mode 100644 index 0000000..10ff688 --- /dev/null +++ b/LiveStreamAssist/packages.lock.json @@ -0,0 +1,620 @@ +{ + "version": 1, + "dependencies": { + ".NETFramework,Version=v4.7.2": { + "BepInEx.Core": { + "type": "Direct", + "requested": "[5.*, )", + "resolved": "5.4.21", + "contentHash": "NMUPlbHTTfJ+qIQCI90uIvjuUQ4wnwt4cpRsK3ItBh1DhsWFzAHXNiZjBxZkPysljEKQ2iu89sxMTga4bxBXVQ==", + "dependencies": { + "BepInEx.BaseLib": "5.4.20", + "HarmonyX": "2.7.0" + } + }, + "BepInEx.PluginInfoProps": { + "type": "Direct", + "requested": "[1.*, )", + "resolved": "1.1.0", + "contentHash": "RqM3aaGs8Hc2m0D+8aSt9mv09rCMYNIF35NB3D6KA2zSpcXJh/9ZVWrPlIUJfA8KYzodSWcCMUexEW24fjwR3w==" + }, + "Microsoft.AspNetCore.Hosting": { + "type": "Direct", + "requested": "[2.3.13, )", + "resolved": "2.3.13", + "contentHash": "hNB7B9mtUzrJ9T8qZe8Dvm9DqSSLIASCihVqHDbq2gWGKkF6bQ3qw1Oo2PLqMCsTzf9F2sAPo9V3LO8cMP3ZNg==", + "dependencies": { + "Microsoft.AspNetCore.Hosting.Abstractions": "2.3.12", + "Microsoft.AspNetCore.Http": "2.3.12", + "Microsoft.AspNetCore.Http.Extensions": "2.3.12", + "Microsoft.Extensions.Configuration": "8.0.0", + "Microsoft.Extensions.Configuration.EnvironmentVariables": "8.0.0", + "Microsoft.Extensions.Configuration.FileExtensions": "8.0.1", + "Microsoft.Extensions.DependencyInjection": "8.0.1", + "Microsoft.Extensions.FileProviders.Physical": "8.0.0", + "Microsoft.Extensions.Hosting.Abstractions": "8.0.1", + "Microsoft.Extensions.Logging": "8.0.1", + "Microsoft.Extensions.Logging.Debug": "8.0.1", + "Microsoft.Extensions.Options": "8.0.2", + "System.Diagnostics.DiagnosticSource": "8.0.1", + "System.Reflection.Metadata": "8.0.1" + } + }, + "Microsoft.AspNetCore.Http": { + "type": "Direct", + "requested": "[2.3.13, )", + "resolved": "2.3.13", + "contentHash": "6dSurGknKDspLgtKkqGw5SlDp8qpeaZ31P9RWiDsdT+CnecbNP8HgXPrAQthsIuV25FIKzfwF7VCC0JTRHtRqA==", + "dependencies": { + "Microsoft.AspNetCore.Http.Abstractions": "2.3.12", + "Microsoft.AspNetCore.WebUtilities": "2.3.12", + "Microsoft.Extensions.ObjectPool": "8.0.11", + "Microsoft.Extensions.Options": "8.0.2", + "Microsoft.Net.Http.Headers": "2.3.12" + } + }, + "Microsoft.AspNetCore.Server.Kestrel": { + "type": "Direct", + "requested": "[2.3.13, )", + "resolved": "2.3.13", + "contentHash": "E39NfUxxS6EGfKdUmRUU8789BDxX3Au675HaKLs3Z+EP0R6cn3iUEqYt9msHQJ0JFTJwmqt8i25GeYc8/m7w9Q==", + "dependencies": { + "Microsoft.AspNetCore.Hosting": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Core": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Https": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets": "2.3.13", + "System.IO.Pipelines": "8.0.0" + } + }, + "Microsoft.AspNetCore.Server.Kestrel.Core": { + "type": "Direct", + "requested": "[2.3.13, )", + "resolved": "2.3.13", + "contentHash": "mSxCuFfUJfDT+dGiXaLPT+fRsfxwIrlS1HlAIVjGEDBbxqLk/QQbI9r29xv32Yyw6tUejNAFBh/bGcEkw2Y0UA==", + "dependencies": { + "Microsoft.AspNetCore.Hosting.Abstractions": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions": "2.3.12", + "Microsoft.AspNetCore.WebUtilities": "2.3.12", + "Microsoft.Extensions.Configuration": "8.0.0", + "Microsoft.Extensions.Configuration.Binder": "8.0.2", + "Microsoft.Extensions.Logging.Abstractions": "8.0.2", + "Microsoft.Extensions.Options": "8.0.2", + "Microsoft.Net.Http.Headers": "2.3.12", + "System.Memory": "4.6.0", + "System.Numerics.Vectors": "4.6.0", + "System.Runtime.CompilerServices.Unsafe": "6.1.0", + "System.Security.Cryptography.Cng": "5.0.0", + "System.Threading.Tasks.Extensions": "4.6.0" + } + }, + "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets": { + "type": "Direct", + "requested": "[2.3.13, )", + "resolved": "2.3.13", + "contentHash": "l3URJm6IoIczXezQ1UgzCeFgak3fK781uovNKkS3Qrh9hQbsHDx0wMt3Qf9NuKyOVwkEreIB5oF/NLIb/k0N9A==", + "dependencies": { + "Microsoft.AspNetCore.Hosting.Abstractions": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions": "2.3.12", + "Microsoft.Extensions.Options": "8.0.2" + } + }, + "Microsoft.AspNetCore.WebSockets": { + "type": "Direct", + "requested": "[2.3.13, )", + "resolved": "2.3.13", + "contentHash": "9NRfb/pnNMffdqQC+AJiseOmum+Y7guPekFGJjO921EMsr/S9e0ZZ3ouoO10tlZPiJBhMHrHe6pqcUcZddFKww==", + "dependencies": { + "Microsoft.AspNetCore.Http.Extensions": "2.3.12", + "Microsoft.Extensions.Options": "8.0.2", + "System.Net.WebSockets.WebSocketProtocol": "5.1.0" + } + }, + "Microsoft.NETFramework.ReferenceAssemblies": { + "type": "Direct", + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", + "dependencies": { + "Microsoft.NETFramework.ReferenceAssemblies.net472": "1.0.3" + } + }, + "Newtonsoft.Json": { + "type": "Direct", + "requested": "[13.0.3, )", + "resolved": "13.0.3", + "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" + }, + "System.Net.WebSockets.WebSocketProtocol": { + "type": "Direct", + "requested": "[5.1.3, )", + "resolved": "5.1.3", + "contentHash": "n236SAZz8HzZe1BEessCoAFh+QhAXq6jgc7qkQ5hi0iEcTra21Q5o4Utm5Ln92SOWcn/Sz+YdMGJQteb/7SISg==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2", + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "UnityEngine.Modules": { + "type": "Direct", + "requested": "[2022.3.62, )", + "resolved": "2022.3.62", + "contentHash": "zpu5dELUCFt7Rvvzp50iTrfVusJg+2gmlcaytGEoHYuIP+AOv57X272czjp+sA8N1onPo/IiHFnOEFtT9rLJBA==" + }, + "BepInEx.BaseLib": { + "type": "Transitive", + "resolved": "5.4.20", + "contentHash": "0bXgYxbCEN2Ixp3kiFEhyw+RASeFQeg/ww+lbMt7if6XMeVS60eg6epNsMA8Jbx57dmNOzNevkKKw8mP8SUMqw==" + }, + "DysonSphereProgram.Modding.CommonAPI": { + "type": "Transitive", + "resolved": "1.6.5", + "contentHash": "1VJ3hNzvmmk6aekCF0RtmOl4vbaDtQscDNNDhIvpmMQEh3j1wESezWPPVyrQB4/+0uVlDgRoqTOJo6RS74XpIQ==", + "dependencies": { + "DysonSphereProgram.Modding.DSPModSave": "1.2.0", + "DysonSphereProgram.Modding.LDBTool": "3.0.0", + "DysonSphereProgram.Modding.NebulaMultiplayerModApi": "2.0.0" + } + }, + "DysonSphereProgram.Modding.DSPModSave": { + "type": "Transitive", + "resolved": "1.2.0", + "contentHash": "i70jjFTXtvE0UfD2PLqlkkLhF317KrcVl1W/PFoza9nWsAZuz12pyVaUS6h35hkqVN4k8ZODkVn2UpFiVr07aw==" + }, + "DysonSphereProgram.Modding.LDBTool": { + "type": "Transitive", + "resolved": "3.0.0", + "contentHash": "RY9gnVs6X6RQ5pdOrtEIYFuKijQXYZG8kcAeUEjZz+WvkmqI23igUhHFYrmTz25WGbtGzsle06fbG0K4bA0rZQ==" + }, + "DysonSphereProgram.Modding.NebulaMultiplayerModApi": { + "type": "Transitive", + "resolved": "2.0.0", + "contentHash": "ExoBArVwtbUpn2r1tTSE12sPQVxeBzmzC3MqDMxuhZTz8wgEl2RLT/USLy7DDaoK7XMAjXi29DBjopxSmsYPMA==" + }, + "HarmonyX": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "lec/SkduQspMa3Pi/nM/NSvA84Za8HCCWA8ybdToKiTqnBZa+JC5g6rxoFQCg/1vNuYcvjy77edePZzIEsRmvw==", + "dependencies": { + "MonoMod.RuntimeDetour": "21.12.13.1" + } + }, + "Microsoft.AspNetCore.Connections.Abstractions": { + "type": "Transitive", + "resolved": "2.3.11", + "contentHash": "lS3+85IKCaoJLqyep27kE6qd9VUB5VVGqCl4xl+gVwoidN/qH29kT7UTSncUvV2bHyc62erOHprTwVqjZb+0Aw==", + "dependencies": { + "Microsoft.AspNetCore.Http.Features": "2.3.10", + "System.IO.Pipelines": "8.0.0" + } + }, + "Microsoft.AspNetCore.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "jSEvM9Ot0ok4VIT8R5JNOSiLTay+sFBp1vCwiqWPqaY3HuvK0EAr8YfqOkxDnWw5nqyC5Z3asJ2NuddLNVzXGA==", + "dependencies": { + "Microsoft.AspNetCore.Hosting.Server.Abstractions": "2.3.11", + "Microsoft.AspNetCore.Http.Abstractions": "2.3.11", + "Microsoft.Extensions.Hosting.Abstractions": "8.0.1" + } + }, + "Microsoft.AspNetCore.Hosting.Server.Abstractions": { + "type": "Transitive", + "resolved": "2.3.11", + "contentHash": "LMp90i+SDiogwqOybUn8T6uZ0E3wmfKxZpUUMUWo/mWkaxTFtzFPTj/VU0G5ZEgYQdz6oPSwSpkoV6pzikt9Qg==", + "dependencies": { + "Microsoft.AspNetCore.Http.Features": "2.3.10", + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0" + } + }, + "Microsoft.AspNetCore.Http.Abstractions": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "Mc1UKKSU8PmOWqpNdfpRYmqotmoQlsL1SAYwLHIIlTDayjyKng3UVn5+b+mPAEp31vU4ozy0CYeRYvCPqzdxZw==", + "dependencies": { + "Microsoft.AspNetCore.Http.Features": "2.3.11", + "System.Text.Encodings.Web": "8.0.0" + } + }, + "Microsoft.AspNetCore.Http.Extensions": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "qMK/Q25fj2R97RNNnbK2WmQTBN6wAa1t0sWSyOb3XA8JYkZTGxWjoVJ3P7ntdmEdV8EVfTrV1DCQl390GAOeXg==", + "dependencies": { + "Microsoft.AspNetCore.Http.Abstractions": "2.3.11", + "Microsoft.Extensions.FileProviders.Abstractions": "8.0.0", + "Microsoft.Net.Http.Headers": "2.3.11", + "System.Buffers": "4.6.0" + } + }, + "Microsoft.AspNetCore.Http.Features": { + "type": "Transitive", + "resolved": "2.3.11", + "contentHash": "TRQWR0vHBUUAEynbgCI3/MRf4+xRj8TsljoUPYxqiombhYhoEYHnr1sowozU1L/OyJHkPdm2IscJ9JBa0kcgbw==", + "dependencies": { + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.AspNetCore.Server.Kestrel.Https": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "WYgEPYGQStLbv8mDjM5vZ4G42inArjFQlfqZfHXLWTDabn7dFoCJMtArFITQO0ufXBnhLxT/mzpLTaBD63jI1Q==", + "dependencies": { + "Microsoft.AspNetCore.Http.Abstractions": "2.3.11", + "Microsoft.AspNetCore.Server.Kestrel.Core": "2.3.11" + } + }, + "Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "JMmL1DrpgaeEHE3jCavNFShBS1q9zt3u0PzdUSSqWHBep5MXnidbPyuHW+fIOeWVwEnN5GwXj8VINx+qyjFSAg==", + "dependencies": { + "Microsoft.AspNetCore.Connections.Abstractions": "2.3.11", + "System.IO.Pipelines": "8.0.0" + } + }, + "Microsoft.AspNetCore.WebUtilities": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "wzbAsF9N+9Eftg7+daZwPbfuT8wFQlD1duV/OPHNw5twVVgWkSjjens9QQ4ZrXSY6sd1nRYE6RZGUtZt5NaENA==", + "dependencies": { + "Microsoft.Net.Http.Headers": "2.3.11", + "System.Text.Encodings.Web": "8.0.0" + } + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "3WA9q9yVqJp222P3x1wYIGDAkpjAku0TMUaaQV22g6L67AI0LdOIrVS7Ht2vJfLHGSPVuqN94vIr15qn+HEkHw==", + "dependencies": { + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "0J/9YNXTMWSZP2p2+nvl8p71zpSwokZXZuJW+VjdErkegAnFdO1XlqtA62SJtgVYHdKu3uPxJHcMR/r35HwFBA==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0", + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "3lE/iLSutpgX1CC0NOW70FJoGARRHbyKmG7dc0klnUZ9Dd9hS6N/POPWhKhMLCEuNN5nXEY5agmlFtH562vqhQ==", + "dependencies": { + "Microsoft.Extensions.Primitives": "8.0.0", + "System.ValueTuple": "4.5.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "7IQhGK+wjyGrNsPBjJcZwWAr+Wf6D4+TwOptUt77bWtgNkiV8tDEbhFS+dDamtQFZ2X7kWG9m71iZQRj2x3zgQ==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0" + } + }, + "Microsoft.Extensions.Configuration.EnvironmentVariables": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "plvZ0ZIpq+97gdPNNvhwvrEZ92kNml9hd1pe3idMA7svR0PztdzVLkoWLcRFgySYXUJc3kSM3Xw3mNFMo/bxRA==", + "dependencies": { + "Microsoft.Extensions.Configuration": "8.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0" + } + }, + "Microsoft.Extensions.Configuration.FileExtensions": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "EJzSNO9oaAXnTdtdNO6npPRsIIeZCBSNmdQ091VDO7fBiOtJAAeEq6dtrVXIi3ZyjC5XRSAtVvF8SzcneRHqKQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "8.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0", + "Microsoft.Extensions.FileProviders.Abstractions": "8.0.0", + "Microsoft.Extensions.FileProviders.Physical": "8.0.0", + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "BmANAnR5Xd4Oqw7yQ75xOAYODybZQRzdeNucg7kS5wWKd2PNnMdYtJ2Vciy0QLylRmv42DGl5+AFL9izA6F1Rw==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "8.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "3iE7UF7MQkCv1cxzCahz+Y/guQbTqieyxyaWKhrRO91itI9cOKO76OHeQDahqG4MmW5umr3CcCvGmK92lWNlbg==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "8.0.0", + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "elH2vmwNmsXuKmUeMQ4YW9ldXiF+gSGDgg1vORksob5POnpaI6caj1Hu8zaYbEuibhqCoWg0YRWDazBY3zjBfg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "Microsoft.Extensions.Options": "8.0.2", + "System.Buffers": "4.5.1", + "System.Diagnostics.DiagnosticSource": "8.0.1", + "System.Memory": "4.5.5" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "ZbaMlhJlpisjuWbvXr4LdAst/1XxH3vZ6A0BsgTphZ2L4PGuxRLz7Jr/S7mkAAnOn78Vu0fKhEgNF5JO3zfjqQ==", + "dependencies": { + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.Extensions.FileProviders.Physical": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "UboiXxpPUpwulHvIAVE36Knq0VSHaAmfrFkegLyBZeaADuKezJ/AIXYAW8F5GBlGk/VaibN2k/Zn1ca8YAfVdA==", + "dependencies": { + "Microsoft.Extensions.FileProviders.Abstractions": "8.0.0", + "Microsoft.Extensions.FileSystemGlobbing": "8.0.0", + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.Extensions.FileSystemGlobbing": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "OK+670i7esqlQrPjdIKRbsyMCe9g5kSLpRRQGSr4Q58AOYEe/hCnfLZprh7viNisSUUQZmMrbbuDaIrP+V1ebQ==" + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "nHwq9aPBdBPYXPti6wYEEfgXddfBrYC+CQLn+qISiwQq5tpfaqDZSKOJNxoe9rfQxGf1c+2wC/qWFe1QYJPYqw==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "8.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "Microsoft.Extensions.Diagnostics.Abstractions": "8.0.1", + "Microsoft.Extensions.FileProviders.Abstractions": "8.0.0", + "Microsoft.Extensions.Logging.Abstractions": "8.0.2", + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "4x+pzsQEbqxhNf1QYRr5TDkLP9UsLT3A6MdRKDDEgrW7h1ljiEPgTNhKYUhNCCAaVpQECVQ+onA91PTPnIp6Lw==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "8.0.0", + "Microsoft.Extensions.DependencyInjection": "8.0.1", + "Microsoft.Extensions.Logging.Abstractions": "8.0.2", + "Microsoft.Extensions.Options": "8.0.2", + "System.Diagnostics.DiagnosticSource": "8.0.1", + "System.ValueTuple": "4.5.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "nroMDjS7hNBPtkZqVBbSiQaQjWRDxITI8Y7XnDs97rqG3EbzVTNLZQf7bIeUJcaHOV8bca47s1Uxq94+2oGdxA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "System.Buffers": "4.5.1", + "System.Diagnostics.DiagnosticSource": "8.0.1", + "System.Memory": "4.5.5" + } + }, + "Microsoft.Extensions.Logging.Debug": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "B8hqNuYudC2RB+L/DI33uO4rf5by41fZVdcVL2oZj0UyoAZqnwTwYHp1KafoH4nkl1/23piNeybFFASaV2HkFg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "Microsoft.Extensions.Logging": "8.0.1", + "Microsoft.Extensions.Logging.Abstractions": "8.0.2" + } + }, + "Microsoft.Extensions.ObjectPool": { + "type": "Transitive", + "resolved": "8.0.11", + "contentHash": "6ApKcHNJigXBfZa6XlDQ8feJpq7SG1ogZXg6M4FiNzgd6irs3LUAzo0Pfn4F2ZI9liGnH1XIBR/OtSbZmJAV5w==" + }, + "Microsoft.Extensions.Options": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "dWGKvhFybsaZpGmzkGCbNNwBD1rVlWzrZKANLW/CcbFJpCEceMCGzT7zZwHOGBCbwM0SzBuceMj5HN1LKV1QqA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0", + "Microsoft.Extensions.Primitives": "8.0.0", + "System.ValueTuple": "4.5.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "bXJEZrW9ny8vjMF1JV253WeLhpEVzFo1lyaZu1vQ4ZxWUlVvknZ/+ftFgVheLubb4eZPSwwxBeqS1JkCOjxd8g==", + "dependencies": { + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "Microsoft.Net.Http.Headers": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "lh9agX9zEuQy69kxwPTT2+OmK2Y49OA8r7qdwZNWNKGug45V050HLH3xhPF23y4sr5Nl6JKXo0AofCwxkNd6zw==", + "dependencies": { + "Microsoft.Extensions.Primitives": "8.0.0", + "System.Buffers": "4.6.0" + } + }, + "Microsoft.NETFramework.ReferenceAssemblies.net472": { + "type": "Transitive", + "resolved": "1.0.3", + "contentHash": "0E7evZXHXaDYYiLRfpyXvCh+yzM2rNTyuZDI+ZO7UUqSc6GfjePiXTdqJGtgIKUwdI81tzQKmaWprnUiPj9hAw==" + }, + "Mono.Cecil": { + "type": "Transitive", + "resolved": "0.11.4", + "contentHash": "IC1h5g0NeJGHIUgzM1P82ld57knhP0IcQfrYITDPXlNpMYGUrsG5TxuaWTjaeqDNQMBDNZkB8L0rBnwsY6JHuQ==" + }, + "MonoMod.RuntimeDetour": { + "type": "Transitive", + "resolved": "21.12.13.1", + "contentHash": "65mB+bHjT6UCGCgO+/pYhpuGPf96rQ1Whwkut/x7cqVIW0DTndDFyWc/3bngzhnY/Y6IYtBMlXsU2ATq+CxpHg==", + "dependencies": { + "Mono.Cecil": "0.11.4", + "MonoMod.Utils": "21.12.13.1" + } + }, + "MonoMod.Utils": { + "type": "Transitive", + "resolved": "21.12.13.1", + "contentHash": "/H+0RMWqx/D1/fSuY5jhY6GFvqhdYdlnI7J3IfL8P6y4nJkoZDxqts6+RxWWOz4pbnJdWnxSjS8XG+Lq6rUi7w==", + "dependencies": { + "Mono.Cecil": "0.11.4" + } + }, + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" + }, + "System.Collections.Immutable": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "AurL6Y5BA1WotzlEvVaIDpqzpIPvYnnldxru8oXJU2yFxFUy3+pNXjXd1ymO+RA0rq0+590Q8gaz2l3Sr7fmqg==", + "dependencies": { + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "vaoWjvkG1aenR2XdjaVivlCV9fADfgyhW5bZtXT23qaEea0lWiUljdQuze4E31vKM7ZWJaSUsbYIKE3rnzfZUg==", + "dependencies": { + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "System.IO": { + "type": "Transitive", + "resolved": "4.3.0", + "contentHash": "3qjaHvxQPDpSOYICjUoTsmoq5u6QJAFRUITgeT/4gqkF1bajbSmb1kwSxEA8AHlofqgcKJcM8udgieRNhaJ5Cg==" + }, + "System.IO.Pipelines": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "FHNOatmUq0sqJOkTx+UF/9YK1f180cnW5FVqnQMvYUN0elp6wFzbtPSiqbo1/ru8ICp43JM1i7kKkk6GsNGHlA==", + "dependencies": { + "System.Buffers": "4.5.1", + "System.Memory": "4.5.5", + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "System.Memory": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Numerics.Vectors": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" + }, + "System.Reflection.Metadata": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "+4sz5vGHPlo+5NpAxf2IlABnqVvOHOxv17b4dONv4hVwyNeFAeBevT14DIn7X3YWQ+eQFYO3YeTBNCleAblOKA==", + "dependencies": { + "System.Collections.Immutable": "8.0.0", + "System.Memory": "4.5.5" + } + }, + "System.Runtime": { + "type": "Transitive", + "resolved": "4.3.0", + "contentHash": "JufQi0vPQ0xGnAczR13AUFglDyVYt4Kqnz1AZaiKZ5+GICq0/1MH/mO/eAJHt/mHW1zjKBJd7kV26SrxddAhiw==" + }, + "System.Runtime.CompilerServices.Unsafe": { + "type": "Transitive", + "resolved": "6.1.2", + "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" + }, + "System.Security.Cryptography.Algorithms": { + "type": "Transitive", + "resolved": "4.3.1", + "contentHash": "DVUblnRfnarrI5olEC2B/OCsJQd0anjVaObQMndHSc43efbc88/RMOlDyg/EyY0ix5ecyZMXS8zMksb5ukebZA==", + "dependencies": { + "System.IO": "4.3.0", + "System.Runtime": "4.3.0", + "System.Security.Cryptography.Encoding": "4.3.0", + "System.Security.Cryptography.Primitives": "4.3.0" + } + }, + "System.Security.Cryptography.Cng": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "jIMXsKn94T9JY7PvPq/tMfqa6GAaHpElRDpmG+SuL+D3+sTw2M8VhnibKnN8Tq+4JqbPJ/f+BwtLeDMEnzAvRg==", + "dependencies": { + "System.Security.Cryptography.Algorithms": "4.3.1" + } + }, + "System.Security.Cryptography.Encoding": { + "type": "Transitive", + "resolved": "4.3.0", + "contentHash": "1DEWjZZly9ae9C79vFwqaO5kaOlI5q+3/55ohmq/7dpDyDfc8lYe7YVxJUZ5MF/NtbkRjwFRo14yM4OEo9EmDw==" + }, + "System.Security.Cryptography.Primitives": { + "type": "Transitive", + "resolved": "4.3.0", + "contentHash": "7bDIyVFNL/xKeFHjhobUAQqSpJq9YTOpbEs6mR233Et01STBMXNAc/V+BM6dwYGc95gVh/Zf+iVXWzj3mE8DWg==" + }, + "System.Text.Encodings.Web": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "yev/k9GHAEGx2Rg3/tU6MQh4HGBXJs70y7j1LaM1i/ER9po+6nnQ6RRqTJn1E7Xu0fbIFK80Nh5EoODxrbxwBQ==", + "dependencies": { + "System.Buffers": "4.5.1", + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "System.Threading.Tasks.Extensions": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", + "dependencies": { + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ValueTuple": { + "type": "Transitive", + "resolved": "4.5.0", + "contentHash": "okurQJO6NRE/apDIP23ajJ0hpiNmJ+f0BwOlB/cSqTLQlw5upkf+5+96+iG2Jw40G1fCVCyPz/FhIABUjMR+RQ==" + }, + "uxassist": { + "type": "Project", + "dependencies": { + "BepInEx.Core": "[5.*, )", + "BepInEx.PluginInfoProps": "[1.*, )", + "DysonSphereProgram.Modding.CommonAPI": "[1.*, )", + "DysonSphereProgram.Modding.DSPModSave": "[1.*, )", + "UnityEngine.Modules": "[2022.3.62, )" + } + } + } + } +} \ No newline at end of file diff --git a/LiveStreamAssist/tools/ReflectionReaderCheck/Copy-GameFacades.ps1 b/LiveStreamAssist/tools/ReflectionReaderCheck/Copy-GameFacades.ps1 index 34e78d5..cadb8e5 100644 --- a/LiveStreamAssist/tools/ReflectionReaderCheck/Copy-GameFacades.ps1 +++ b/LiveStreamAssist/tools/ReflectionReaderCheck/Copy-GameFacades.ps1 @@ -37,7 +37,7 @@ foreach ($block in [regex]::Matches($vdfContent, $blockPattern, 'Singleline')) { if (-not $managed) { throw 'DSP Managed directory not found; cannot copy game facades for ReflectionReaderCheck.' } -foreach ($name in @('netstandard.dll', 'UnityEngine.CoreModule.dll', 'UnityEngine.SharedInternalsModule.dll')) { +foreach ($name in @('netstandard.dll', 'UnityEngine.dll', 'UnityEngine.CoreModule.dll', 'UnityEngine.SharedInternalsModule.dll')) { $src = Join-Path $managed $name if (-not (Test-Path $src)) { throw "Missing $src" } Copy-Item -LiteralPath $src -Destination (Join-Path $TargetDir $name) -Force diff --git a/LiveStreamAssist/tools/ReflectionReaderCheck/Program.cs b/LiveStreamAssist/tools/ReflectionReaderCheck/Program.cs index cb996ef..78e351a 100644 --- a/LiveStreamAssist/tools/ReflectionReaderCheck/Program.cs +++ b/LiveStreamAssist/tools/ReflectionReaderCheck/Program.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Reflection; +using System.Reflection.Emit; using LiveStreamAssist.Api; using UnityEngine; @@ -25,6 +27,11 @@ static class Program Int64Precision(reader); NonFinite(reader); UnityAndStreamBlocked(reader); + NullCollectionPaging(reader); + RuntimeProjectionMembers(reader); + UnsignedEnum(reader); + RuntimeTypeBoundary(reader); + FrameworkInternals(reader); } finally { @@ -170,6 +177,59 @@ static class Program return false; } + static void NullCollectionPaging(ReflectionReader reader) + { + var result = reader.Read(new DerivedFixture(), typeof(DerivedFixture), new[] { new PathSeg("Arr") }, + new ReadOptions { HasLimit = true, Limit = 1 }); + Check(result.Error == null && result.IsNull, "null array with paging remains null"); + } + + static void RuntimeProjectionMembers(ReflectionReader reader) + { + var values = new BaseFixture[] { new DerivedFixture { Visible = 42 } }; + var options = new ReadOptions { HasSelect = true, Select = new[] { "Visible" } }; + var result = reader.Read(values, values.GetType(), Array.Empty(), options); + Check(result.Error == null, "page projection resolves members on actual derived objects"); + var empty = reader.Read(Array.Empty(), typeof(BaseFixture[]), Array.Empty(), options); + Check(empty.Error == null, "empty page does not resolve unread member names"); + } + + static void UnsignedEnum(ReflectionReader reader) + { + try + { + var result = reader.Read(WideEnum.Max, typeof(WideEnum), Array.Empty(), default); + Check(result.Error == null && result.Encoded is Dictionary value && + Equals(value["value"], "18446744073709551615"), "ulong enum preserves its full range"); + } + catch (OverflowException) + { + Check(false, "ulong enum preserves its full range"); + } + } + + static void RuntimeTypeBoundary(ReflectionReader reader) + { + var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("UnlistedFixture"), AssemblyBuilderAccess.Run); + var type = assembly.DefineDynamicModule("main").DefineType("ForeignFixture", TypeAttributes.Public, typeof(BaseFixture)); + type.DefineField("Secret", typeof(int), FieldAttributes.Public); + var foreign = (BaseFixture)Activator.CreateInstance(type.CreateType()); + var result = reader.Read(foreign, typeof(BaseFixture), new[] { new PathSeg("Secret") }, default); + Check(result.Error?.Kind == "UNSUPPORTED_TYPE", "runtime type cannot bypass the allowed assembly boundary"); + var described = reader.Describe(foreign, typeof(BaseFixture), Array.Empty()); + Check(described.Error?.Kind == "UNSUPPORTED_TYPE", "describe enforces the runtime type boundary"); + } + + static void FrameworkInternals(ReflectionReader reader) + { + var list = new GameListFixture(); + var result = reader.Read(list, list.GetType(), new[] { new PathSeg("_items") }, default); + Check(result.Error?.Kind == "MEMBER_NOT_FOUND", "game-defined subclasses do not expose BCL container internals"); + var array = Array.CreateInstance(typeof(BaseFixture), new[] { 1 }, new[] { 5 }); + result = reader.Read(array, array.GetType(), Array.Empty(), default); + Check(result.Error?.Kind == "UNSUPPORTED_TYPE", "nonzero-based game arrays are rejected"); + } + static void Check(bool cond, string name) { if (cond) @@ -183,13 +243,17 @@ static class Program } } -class BaseFixture +public class BaseFixture { int baseSecret; public void SetBaseSecret(int value) => baseSecret = value; } +enum WideEnum : ulong { Max = ulong.MaxValue } + +class GameListFixture : List; + class DerivedFixture : BaseFixture { public int Visible; diff --git a/LiveStreamAssist/tools/Test-WebSocketApi.ps1 b/LiveStreamAssist/tools/Test-WebSocketApi.ps1 index edb81db..29b2f58 100644 --- a/LiveStreamAssist/tools/Test-WebSocketApi.ps1 +++ b/LiveStreamAssist/tools/Test-WebSocketApi.ps1 @@ -17,46 +17,71 @@ function New-Id { "t-$script:seq" } +function New-OpCts { + [Threading.CancellationTokenSource]::new([TimeSpan]::FromSeconds($TimeoutSec)) +} + function Connect-Api { param([string] $Uri) $ws = [Net.WebSockets.ClientWebSocket]::new() - $cts = [Threading.CancellationTokenSource]::new([TimeSpan]::FromSeconds($TimeoutSec)) - $ws.ConnectAsync([Uri]$Uri, $cts.Token).GetAwaiter().GetResult() - return @{ Ws = $ws; Cts = $cts } + $cts = New-OpCts + try { + $ws.ConnectAsync([Uri]$Uri, $cts.Token).GetAwaiter().GetResult() + } catch { + $ws.Dispose() + throw + } finally { + $cts.Dispose() + } + return @{ Ws = $ws } } function Close-Api { param($Conn) if (-not $Conn) { return } + $cts = New-OpCts try { - if ($Conn.Ws.State -eq [Net.WebSockets.WebSocketState]::Open) { - $Conn.Ws.CloseAsync([Net.WebSockets.WebSocketCloseStatus]::NormalClosure, '', $Conn.Cts.Token).GetAwaiter().GetResult() + if ($Conn.Ws.State -eq [Net.WebSockets.WebSocketState]::Open -or + $Conn.Ws.State -eq [Net.WebSockets.WebSocketState]::CloseReceived) { + $Conn.Ws.CloseAsync([Net.WebSockets.WebSocketCloseStatus]::NormalClosure, '', $cts.Token).GetAwaiter().GetResult() } } catch { } + finally { $cts.Dispose() } try { $Conn.Ws.Dispose() } catch { } - try { $Conn.Cts.Dispose() } catch { } } function Send-Text { param($Conn, [string] $Text, [bool] $End = $true) $bytes = $utf8.GetBytes($Text) $seg = [ArraySegment[byte]]::new($bytes) - $Conn.Ws.SendAsync($seg, [Net.WebSockets.WebSocketMessageType]::Text, $End, $Conn.Cts.Token).GetAwaiter().GetResult() + $cts = New-OpCts + try { + $Conn.Ws.SendAsync($seg, [Net.WebSockets.WebSocketMessageType]::Text, $End, $cts.Token).GetAwaiter().GetResult() + } finally { $cts.Dispose() } } function Receive-Message { param($Conn) $buffer = [byte[]]::new(65536) $ms = [IO.MemoryStream]::new() - do { - $seg = [ArraySegment[byte]]::new($buffer) - $result = $Conn.Ws.ReceiveAsync($seg, $Conn.Cts.Token).GetAwaiter().GetResult() - if ($result.MessageType -eq [Net.WebSockets.WebSocketMessageType]::Close) { - return @{ Closed = $true; CloseStatus = [int]$Conn.Ws.CloseStatus; Text = $null } - } - $ms.Write($buffer, 0, $result.Count) - } while (-not $result.EndOfMessage) - return @{ Closed = $false; Text = $utf8.GetString($ms.ToArray()) } + $cts = New-OpCts + try { + do { + $seg = [ArraySegment[byte]]::new($buffer) + $result = $Conn.Ws.ReceiveAsync($seg, $cts.Token).GetAwaiter().GetResult() + if ($result.MessageType -eq [Net.WebSockets.WebSocketMessageType]::Close) { + return @{ Closed = $true; CloseStatus = [int]$Conn.Ws.CloseStatus; Text = $null } + } + if ($result.MessageType -ne [Net.WebSockets.WebSocketMessageType]::Text -or $ms.Length + $result.Count -gt 262144) { + throw 'Expected a text response within maxResponseBytes' + } + $ms.Write($buffer, 0, $result.Count) + } while (-not $result.EndOfMessage) + return @{ Closed = $false; Text = $utf8.GetString($ms.ToArray()) } + } finally { + $ms.Dispose() + $cts.Dispose() + } } function Invoke-Rpc { @@ -65,7 +90,16 @@ function Invoke-Rpc { Send-Text $Conn ($body | ConvertTo-Json -Compress -Depth 16) $msg = Receive-Message $Conn if ($msg.Closed) { throw "Connection closed while waiting for $Method (close $($msg.CloseStatus))" } - return ($msg.Text | ConvertFrom-Json) + $resp = $msg.Text | ConvertFrom-Json + $respId = $null + if ($resp.PSObject.Properties.Name -contains 'id') { $respId = [string]$resp.id } + if ($respId -ne $Id) { throw "Response id '$respId' did not match '$Id'" } + return $resp +} + +function Has-Prop { + param($Obj, [string] $Name) + return $null -ne $Obj -and $Obj.PSObject.Properties.Name -contains $Name } function Assert-True { @@ -77,7 +111,9 @@ function Assert-True { function Assert-Kind { param($Resp, [string] $Kind, [string] $Name) $actual = $null - if ($Resp.error -and $Resp.error.data) { $actual = [string]$Resp.error.data.kind } + if ((Has-Prop $Resp 'error') -and $Resp.error -and (Has-Prop $Resp.error 'data') -and $Resp.error.data -and (Has-Prop $Resp.error.data 'kind')) { + $actual = [string]$Resp.error.data.kind + } Assert-True ($actual -eq $Kind) "$Name (kind=$actual)" } @@ -86,14 +122,14 @@ try { $conn = Connect-Api $ServerUri $ping = Invoke-Rpc $conn 'system.ping' - Assert-True ($null -ne $ping.result.serverTimeUtc) 'system.ping' + Assert-True ((Has-Prop $ping 'result') -and (Has-Prop $ping.result 'serverTimeUtc') -and $null -ne $ping.result.serverTimeUtc) 'system.ping' $info = Invoke-Rpc $conn 'system.info' Assert-True ($info.result.apiVersion -eq '1.0.0') 'system.info apiVersion' Assert-True ($info.result.limits.maxRequestBytes -eq 65536) 'system.info limits' Assert-True ($info.result.capabilities.'api.stats' -eq $false) 'api.stats false' Assert-True ($info.result.capabilities.subscriptions -eq $false) 'subscriptions false' - Assert-True ($info.result.PSObject.Properties.Name -contains 'gameVersionReady') 'gameVersionReady present' + Assert-True ((Has-Prop $info.result 'gameVersionReady')) 'gameVersionReady present' $ok = Invoke-Rpc $conn 'system.validate' @{ apiMajor = 1; requiredCapabilities = @('reflection.read') } Assert-True ($ok.result.compatible -eq $true) 'validate compatible' @@ -129,25 +165,14 @@ try { $batch = (Receive-Message $conn).Text | ConvertFrom-Json Assert-Kind $batch 'INVALID_REQUEST' 'batch array' - Send-Text $conn '{"jsonrpc":"2.0","id":"dup","method":"data.read","params":{"root":"history","path":["currentTech"]}}' - Send-Text $conn '{"jsonrpc":"2.0","id":"dup","method":"data.read","params":{"root":"history","path":["currentTech"]}}' - $dup = Receive-Message $conn - if ($dup.Closed) { - Assert-True ($dup.CloseStatus -eq 1008) "duplicate outstanding id close $($dup.CloseStatus)" - } else { - Assert-True $false 'duplicate outstanding id should close' - } - - Close-Api $conn - $conn = Connect-Api $ServerUri - $ping2 = Invoke-Rpc $conn 'system.ping' - Assert-True ($null -ne $ping2.result.serverTimeUtc) 'recover after duplicate-id close' - - $conn.Ws.SendAsync( - [ArraySegment[byte]]::new([byte[]](1, 2, 3)), - [Net.WebSockets.WebSocketMessageType]::Binary, - $true, - $conn.Cts.Token).GetAwaiter().GetResult() + $cts = New-OpCts + try { + $conn.Ws.SendAsync( + [ArraySegment[byte]]::new([byte[]](1, 2, 3)), + [Net.WebSockets.WebSocketMessageType]::Binary, + $true, + $cts.Token).GetAwaiter().GetResult() + } finally { $cts.Dispose() } $bin = Receive-Message $conn Assert-True ($bin.Closed -and $bin.CloseStatus -eq 1003) "binary rejected $($bin.CloseStatus)" @@ -159,11 +184,27 @@ try { Assert-True ($over.Closed -and $over.CloseStatus -eq 1009) "oversized close $($over.CloseStatus)" Close-Api $conn - $uri = [Uri]$ServerUri - $badPath = Connect-Api "$($uri.Scheme)://$($uri.Authority)/nope" - $bad = Receive-Message $badPath - Assert-True ($bad.Closed -and $bad.CloseStatus -eq 1008) "wrong path close $($bad.CloseStatus)" - Close-Api $badPath + $wrong = [UriBuilder]::new($ServerUri) + $wrong.Scheme = if ($wrong.Scheme -eq 'wss') { 'https' } else { 'http' } + $wrong.Path = '/nope' + $wrong.Query = '' + $http = [Net.Http.HttpClient]::new() + $request = [Net.Http.HttpRequestMessage]::new([Net.Http.HttpMethod]::Get, $wrong.Uri) + $request.Headers.Connection.Add('Upgrade') + $request.Headers.Upgrade.Add([Net.Http.Headers.ProductHeaderValue]::new('websocket')) + [void]$request.Headers.TryAddWithoutValidation('Sec-WebSocket-Version', '13') + [void]$request.Headers.TryAddWithoutValidation('Sec-WebSocket-Key', 'dGhlIHNhbXBsZSBub25jZQ==') + $cts = New-OpCts + $response = $null + try { + $response = $http.SendAsync($request, [Net.Http.HttpCompletionOption]::ResponseHeadersRead, $cts.Token).GetAwaiter().GetResult() + Assert-True ([int]$response.StatusCode -eq 404) 'wrong path HTTP rejection' + } finally { + if ($null -ne $response) { $response.Dispose() } + $request.Dispose() + $http.Dispose() + $cts.Dispose() + } $conn = Connect-Api $ServerUri $part1 = '{"jsonrpc":"2.0","id":"frag","method":' @@ -171,21 +212,24 @@ try { Send-Text $conn $part1 $false Send-Text $conn $part2 $frag = (Receive-Message $conn).Text | ConvertFrom-Json - Assert-True ($null -ne $frag.result.serverTimeUtc) 'fragmented text message' + Assert-True ((Has-Prop $frag 'result') -and (Has-Prop $frag.result 'serverTimeUtc')) 'fragmented text message' $unknownRoot = Invoke-Rpc $conn 'data.read' @{ root = 'no-such-root' } Assert-Kind $unknownRoot 'ROOT_NOT_FOUND' 'unknown root' if ($RequireGame) { $roots = Invoke-Rpc $conn 'data.roots' + if (-not (Has-Prop $roots 'result') -or -not $roots.result.gameReady) { + throw '-RequireGame needs a ready player save' + } Assert-True ($roots.result.gameReady -eq $true) 'data.roots gameReady' - Assert-True ($null -ne $roots.result.sessionId) 'sessionId' + Assert-True ((Has-Prop $roots.result 'sessionId') -and $null -ne $roots.result.sessionId) 'sessionId' $tech = Invoke-Rpc $conn 'data.read' @{ root = 'history'; path = @('currentTech') } - Assert-True ($null -eq $tech.error) 'read history.currentTech' + Assert-True (-not (Has-Prop $tech 'error') -or $null -eq $tech.error) 'read history.currentTech' $queue = Invoke-Rpc $conn 'data.read' @{ root = 'history'; path = @('techQueue'); offset = 0; limit = 8 } - Assert-True ($null -eq $queue.error) 'read history.techQueue' + Assert-True (-not (Has-Prop $queue 'error') -or $null -eq $queue.error) 'read history.techQueue' $techId = [int]$tech.result.value - if ($techId -eq 0 -and $queue.result.value.items) { + if ($techId -eq 0 -and (Has-Prop $queue.result.value 'items') -and $queue.result.value.items) { foreach ($item in @($queue.result.value.items)) { if ([int]$item -ne 0) { $techId = [int]$item; break } } @@ -198,18 +242,18 @@ try { path = @('techStates', @{ key = $techId }) select = @('curLevel', 'hashUploaded', 'hashNeeded') } - Assert-True ($null -eq $state.error) "read techStates[$techId]" - Assert-True ($null -ne $state.result.value.curLevel) 'research curLevel' + Assert-True (-not (Has-Prop $state 'error') -or $null -eq $state.error) "read techStates[$techId]" + Assert-True ((Has-Prop $state.result.value 'curLevel') -and $null -ne $state.result.value.curLevel) 'research curLevel' } else { $roots = Invoke-Rpc $conn 'data.roots' - Assert-True ($roots.result.PSObject.Properties.Name -contains 'gameReady') 'data.roots without save' - if ($roots.result.gameReady -eq $true) { + Assert-True ((Has-Prop $roots.result 'gameReady')) 'data.roots without save' + if ((Has-Prop $roots.result 'gameReady') -and $roots.result.gameReady -eq $true) { Write-Host 'note game is ready; -RequireGame would exercise research reads' } } $still = Invoke-Rpc $conn 'system.ping' - Assert-True ($null -ne $still.result.serverTimeUtc) 'ping after protocol errors' + Assert-True ((Has-Prop $still.result 'serverTimeUtc') -and $null -ne $still.result.serverTimeUtc) 'ping after protocol errors' } finally { Close-Api $conn diff --git a/LiveStreamAssist/tools/WebSocketTransportCheck/App.config b/LiveStreamAssist/tools/WebSocketTransportCheck/App.config new file mode 100644 index 0000000..fac5ca3 --- /dev/null +++ b/LiveStreamAssist/tools/WebSocketTransportCheck/App.config @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/LiveStreamAssist/tools/WebSocketTransportCheck/ProductionChecks.cs b/LiveStreamAssist/tools/WebSocketTransportCheck/ProductionChecks.cs new file mode 100644 index 0000000..b7f5e35 --- /dev/null +++ b/LiveStreamAssist/tools/WebSocketTransportCheck/ProductionChecks.cs @@ -0,0 +1,532 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using LiveStreamAssist.Api; +using Newtonsoft.Json.Linq; + +namespace WebSocketTransportCheck; + +static class ProductionChecks +{ + static int _failed; + [ThreadStatic] static bool _producing; + + public static async Task Run() + { + global::LiveStreamAssist.LiveStreamAssist.Logger.LogEvent += (_, entry) => Console.WriteLine(entry.Data); + await DisconnectWakesSender(); + await QueueOverflowReleasesAdmission(); + await StopBeforeStart(); + NullParameters(); + await ActiveSendRetainsAdmission(); + await SendDeadlineIncludesQueueTime(); + await ExecutingWorkTimesOut(); + await SessionCancellationKeepsNewWork(); + await PhysicalQueueRemainsBounded(); + await OversizedResult(); + await NetworkLifetime(); + await StartupRaces(); + Console.WriteLine(_failed == 0 ? "OK production checks" : $"FAILED {_failed} production checks"); + return _failed == 0 ? 0 : 1; + } + + static WebSocketApiServer CreateServer() => new WebSocketApiServer(IPAddress.Loopback, 0, "test", + () => GameVersionSnapshot.Empty, () => new SessionSnapshot(0, null), null); + + static async Task DisconnectWakesSender() + { + var server = CreateServer(); + using var connection = new ApiConnection(server); + using (var socket = new TestSocket()) + using (var cancel = new CancellationTokenSource()) + { + connection.Attach(socket); + var sending = connection.RunSendLoop(socket, cancel.Token); + connection.NotifyDisconnected(); + Check(await Task.WhenAny(sending, Task.Delay(500)) == sending, "disconnect wakes idle sender"); + cancel.Cancel(); + await sending; + } + await server.StopAsync(); + } + + static async Task QueueOverflowReleasesAdmission() + { + var server = CreateServer(); + server.Start(); + using var connection = new ApiConnection(server); + using (var socket = new TestSocket()) + { + connection.Attach(socket); + for (var i = 0; i < ApiLimits.MaxPendingRequestsPerConnection; i++) + Check(connection.TryAdmit("held-" + i, out _, out _) != null, "admit held request " + i); + for (var i = 0; i <= ApiLimits.MaxPendingRequestsPerConnection; i++) + connection.EnqueueError(null, ApiErrors.ParseError()); + connection.NotifyDisconnected(); + var available = 0; + while (server.TryIncrementPending()) available++; + Check(available == ApiLimits.MaxPendingRequests, "overflow releases every global admission slot"); + while (available-- > 0) server.DecrementPending(); + await connection.CloseCompletion; + } + await server.StopAsync(); + } + + static async Task StopBeforeStart() + { + var server = CreateServer(); + await server.StopAsync(); + server.Start(); + var admitted = server.TryIncrementPending(); + Check(!admitted, "stopped owner cannot start a listener later"); + if (admitted) server.DecrementPending(); + await server.StopAsync(); + } + + static void NullParameters() + { + var parsed = ApiProtocol.TryParseMessage( + "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"method\":\"system.ping\",\"params\":null}", + out _, out var error, out _); + Check(!parsed && error?.Kind == "INVALID_PARAMS", "explicit null params is not omission"); + foreach (var name in new[] { "path", "select", "offset", "limit" }) + { + var request = new ApiRequest + { + Method = ApiProtocol.MethodRead, + Params = new JObject { ["root"] = "history", [name] = JValue.CreateNull() } + }; + Check(!ApiProtocol.TryParseDataCall(request, out _, out error) && error.Kind == "INVALID_PARAMS", + "explicit null " + name + " is rejected"); + } + } + + static async Task ActiveSendRetainsAdmission() + { + var server = CreateServer(); + await server.StartAsync(); + using var connection = new ApiConnection(server); + using var socket = new TestSocket(); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + socket.Sending = _ => release.Task; + connection.Attach(socket); + var sending = connection.RunSendLoop(socket, CancellationToken.None); + try + { + var pending = connection.TryAdmit("held", out _, out _); + _producing = true; + try { pending.TryCompleteResult(new SerializationProbe()); } + finally { _producing = false; } + await Bounded(socket.SendStarted.Task); + Check(JObject.Parse(Encoding.UTF8.GetString(socket.Payload))["result"]?["Value"]?.Value() == 42, + "serialization does not run inline in the producer"); + Check(connection.TryAdmit("held", out var duplicate, out _) == null && duplicate, + "active send retains the request ID"); + for (var i = 0; i < ApiLimits.MaxPendingRequestsPerConnection - 1; i++) + connection.EnqueueError(null, ApiErrors.ParseError()); + Check(!connection.CanSendBusy(), "active send counts against the bounded output queue"); + connection.EnqueueError(null, ApiErrors.ParseError()); + Check(!connection.IsOpen, "output overflow starts connection closure"); + } + finally + { + release.TrySetResult(true); + connection.NotifyDisconnected(); + await Bounded(sending); + await connection.CloseCompletion; + await server.StopAsync(); + } + } + + static async Task SendDeadlineIncludesQueueTime() + { + var server = CreateServer(); + using var connection = new ApiConnection(server); + using var socket = new TestSocket(); + var first = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var second = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var calls = 0; + socket.Sending = token => + { + if (Interlocked.Increment(ref calls) == 1) return first.Task; + second.TrySetResult(true); + return Task.Delay(Timeout.Infinite, token); + }; + connection.Attach(socket); + var sending = connection.RunSendLoop(socket, CancellationToken.None); + try + { + connection.EnqueueError(null, ApiErrors.ParseError()); + await Bounded(socket.SendStarted.Task); + connection.EnqueueError(null, ApiErrors.ParseError()); + await Task.Delay(ApiLimits.RequestTimeoutMs - 750); + first.TrySetResult(true); + await Bounded(second.Task); + Check(await Task.WhenAny(sending, Task.Delay(2000)) == sending, + "queued time is deducted from the active-send deadline"); + } + finally + { + first.TrySetResult(true); + connection.NotifyDisconnected(); + await Bounded(sending); + await server.StopAsync(); + } + } + + static async Task ExecutingWorkTimesOut() + { + var server = CreateServer(); + using var connection = new ApiConnection(server); + using var entered = new ManualResetEventSlim(); + using var release = new ManualResetEventSlim(); + var context = new QueuedContext(); + long now = 0; + var dispatcher = new MainThreadDispatcher(context, new object(), _ => + { + entered.Set(); + if (!release.Wait(5000)) throw new TimeoutException("Held executor was not released."); + return "late result"; + }, () => Interlocked.Read(ref now), () => 1); + var pending = new PendingRequest { Connection = connection, Id = "running" }; + dispatcher.TryEnqueue(new GameWork { Pending = pending, DeadlineMs = 10 }); + var execution = Task.Run(context.RunOne); + try + { + Check(entered.Wait(2000), "game-work executor entered"); + Interlocked.Exchange(ref now, 10); + var completed = await Task.WhenAny(pending.Completion, Task.Delay(1500)) == pending.Completion; + Check(completed && pending.Completion.Result.Error?.Kind == "REQUEST_TIMEOUT", + "watchdog completes a request while its executor is blocked"); + } + finally + { + release.Set(); + await Bounded(execution); + dispatcher.Stop(); + await server.StopAsync(); + } + Check(pending.Completion.Result.Error?.Kind == "REQUEST_TIMEOUT", "late executor result cannot replace timeout"); + } + + static async Task SessionCancellationKeepsNewWork() + { + var server = CreateServer(); + using var connection = new ApiConnection(server); + var context = new QueuedContext(); + var dispatcher = new MainThreadDispatcher(context, new object(), _ => "current", () => 0, () => 1); + try + { + var old = new PendingRequest { Connection = connection }; + var current = new PendingRequest { Connection = connection }; + dispatcher.TryEnqueue(new GameWork { Pending = old, Generation = 1, DeadlineMs = 10 }); + dispatcher.TryEnqueue(new GameWork { Pending = current, Generation = 2, DeadlineMs = 10 }); + dispatcher.CancelQueued(work => work.Generation == 2 ? null : ApiErrors.SessionChanged()); + context.RunOne(); + Check(old.Completion.Result.Error?.Kind == "SESSION_CHANGED" && Equals(current.Completion.Result.Result, "current"), + "session invalidation preserves work admitted into the new session"); + } + finally + { + dispatcher.Stop(); + await server.StopAsync(); + } + } + + static async Task PhysicalQueueRemainsBounded() + { + var server = CreateServer(); + using var connection = new ApiConnection(server); + var dispatcher = new MainThreadDispatcher(new QueuedContext(), new object(), _ => null, () => 0, () => 1); + try + { + for (var i = 0; i < ApiLimits.MaxPendingRequests; i++) + if (!dispatcher.TryEnqueue(new GameWork { Pending = new PendingRequest { Connection = connection }, DeadlineMs = 1 })) + throw new InvalidOperationException("Physical queue rejected work before its limit."); + Check(!dispatcher.TryEnqueue(new GameWork()), "physical game-work queue rejects overflow"); + connection.NotifyDisconnected(); + await Task.Delay(750); + using var next = new ApiConnection(server); + Check(dispatcher.TryEnqueue(new GameWork { Pending = new PendingRequest { Connection = next }, DeadlineMs = 1 }), + "watchdog reclaims canceled physical queue entries without pumping Unity"); + } + finally + { + dispatcher.Stop(); + await server.StopAsync(); + } + } + + static async Task OversizedResult() + { + var server = CreateServer(); + await server.StartAsync(); + using var connection = new ApiConnection(server); + using var socket = new TestSocket(); + connection.Attach(socket); + var sending = connection.RunSendLoop(socket, CancellationToken.None); + try + { + connection.TryAdmit("large", out _, out _).TryCompleteResult(new string('x', ApiLimits.MaxResponseBytes)); + await Bounded(socket.SendStarted.Task); + var response = JObject.Parse(Encoding.UTF8.GetString(socket.Payload)); + Check(response["error"]?["data"]?["kind"]?.Value() == "LIMIT_EXCEEDED", + "bounded serialization returns LIMIT_EXCEEDED"); + } + finally + { + connection.NotifyDisconnected(); + await Bounded(sending); + await connection.CloseCompletion; + await server.StopAsync(); + } + } + + static async Task NetworkLifetime() + { + var port = FreePort(); + WebSocketApiServer server = null; + var dispatcher = new MainThreadDispatcher(new QueuedContext(), new object(), _ => ApiErrors.GameNotReady(), + () => server.NowMs, () => 1); + server = new WebSocketApiServer(IPAddress.Loopback, port, "test", () => GameVersionSnapshot.Empty, + () => new SessionSnapshot(0, null), dispatcher); + var uri = new Uri("ws://127.0.0.1:" + port + ApiLimits.Path); + await server.StartAsync(); + try + { + using (var http = new HttpClient()) + using (var cancel = new CancellationTokenSource(5000)) + using (var response = await http.GetAsync("http://127.0.0.1:" + port + "/nope", cancel.Token)) + Check(response.StatusCode == HttpStatusCode.NotFound, "wrong route is rejected before upgrade"); + using (var client = await Connect(uri)) + { + await Send(client, "{\"jsonrpc\":\"2.0\",\"id\":\"fragment\",", false); + await Send(client, "\"method\":\"system.ping\"}"); + var response = await ReceiveJson(client); + Check(response["id"]?.Value() == "fragment" && response["result"]?["serverTimeUtc"] != null, + "production transport reassembles fragmented JSON"); + await Close(client); + } + using (var client = await Connect(uri)) + { + using var cancel = new CancellationTokenSource(5000); + await client.SendAsync(new ArraySegment(new byte[] { 1 }), WebSocketMessageType.Binary, true, cancel.Token); + await ExpectClose(client, ApiLimits.CloseUnsupportedData); + } + using (var client = await Connect(uri)) + { + using var cancel = new CancellationTokenSource(5000); + await client.SendAsync(new ArraySegment(new byte[] { 0xff }), WebSocketMessageType.Text, true, cancel.Token); + await ExpectClose(client, ApiLimits.CloseInvalidPayload); + } + using (var client = await Connect(uri)) + { + await Send(client, new string('x', ApiLimits.MaxRequestBytes + 1)); + await ExpectClose(client, ApiLimits.CloseMessageTooBig); + } + using (var client = await Connect(uri)) + { + await Send(client, "{\"jsonrpc\":\"2.0\",\"id\":\"held\",\"method\":\"data.roots\"}"); + await Send(client, "{\"jsonrpc\":\"2.0\",\"id\":\"held\",\"method\":\"system.ping\",\"params\":[]}"); + await ExpectClose(client, ApiLimits.ClosePolicyViolation); + } + using (var client = await Connect(uri)) + { + await Send(client, "{\"jsonrpc\":\"2.0\",\"id\":\"blocked\",\"method\":\"data.roots\"}"); + await Send(client, "{\"jsonrpc\":\"2.0\",\"id\":\"ping\",\"method\":\"system.ping\"}"); + Check((await ReceiveJson(client))["id"]?.Value() == "ping", "system ping bypasses blocked game work"); + var timeout = await ReceiveJson(client); + Check(timeout["id"]?.Value() == "blocked" && + timeout["error"]?["data"]?["kind"]?.Value() == "REQUEST_TIMEOUT", + "blocked pump returns a network timeout response"); + await Close(client); + } + using (var client = await Connect(uri)) + using (var cancel = new CancellationTokenSource(ApiLimits.RequestTimeoutMs + 2500)) + { + await Send(client, "", false); + await Send(client, "{", false); + var closed = false; + try + { + var result = await client.ReceiveAsync(new ArraySegment(new byte[1024]), cancel.Token); + closed = result.MessageType == WebSocketMessageType.Close; + } + catch (WebSocketException) { closed = !cancel.IsCancellationRequested; } + catch (OperationCanceledException) { } + Check(closed, "stalled fragmented message expires without another receive completing"); + } + using (var client = await Connect(uri)) + { + var stopped = server.StopAsync(); + await ExpectClose(client, ApiLimits.CloseGoingAway); + await Bounded(stopped, 7000); + } + } + finally + { + dispatcher.Stop(); + await server.StopAsync(); + } + var rebound = new TcpListener(IPAddress.Loopback, port); + rebound.Start(); + rebound.Stop(); + Check(true, "shutdown releases the listener port"); + } + + static async Task StartupRaces() + { + for (var i = 0; i < 4; i++) + { + var server = CreateServer(); + var startup = server.StartAsync(); + var stopped = server.StopAsync(); + try { await startup; } + catch (OperationCanceledException) { } + await Bounded(stopped, 7000); + Check(!server.TryIncrementPending(), "stop during startup leaves no live owner " + i); + } + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var occupied = new WebSocketApiServer(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port, "test", + () => GameVersionSnapshot.Empty, () => new SessionSnapshot(0, null), null); + try + { + try + { + await occupied.StartAsync(); + Check(false, "occupied port rejects startup"); + } + catch (IOException) { Check(true, "occupied port rejects startup"); } + await Bounded(occupied.StopAsync(), 7000); + } + finally { listener.Stop(); } + } + + static int FreePort() + { + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } + + static async Task Bounded(Task task, int milliseconds = 2000) + { + if (await Task.WhenAny(task, Task.Delay(milliseconds)) != task) + throw new TimeoutException("Production check did not complete within its deadline."); + await task; + } + + static async Task Connect(Uri uri) + { + var client = new ClientWebSocket(); + using var cancel = new CancellationTokenSource(5000); + try { await client.ConnectAsync(uri, cancel.Token); } + catch { client.Dispose(); throw; } + return client; + } + + static async Task Send(ClientWebSocket client, string text, bool end = true) + { + using var cancel = new CancellationTokenSource(5000); + await client.SendAsync(new ArraySegment(Encoding.UTF8.GetBytes(text)), WebSocketMessageType.Text, end, cancel.Token); + } + + static async Task ReceiveJson(ClientWebSocket client) + { + using var cancel = new CancellationTokenSource(7000); + var buffer = new byte[ApiLimits.MaxResponseBytes]; + var used = 0; + WebSocketReceiveResult result; + do + { + if (used == buffer.Length) throw new InvalidDataException("Response exceeded its limit."); + result = await client.ReceiveAsync(new ArraySegment(buffer, used, buffer.Length - used), cancel.Token); + if (result.MessageType != WebSocketMessageType.Text) throw new InvalidDataException("Expected a JSON response."); + used += result.Count; + } while (!result.EndOfMessage); + return JObject.Parse(Encoding.UTF8.GetString(buffer, 0, used)); + } + + static async Task ExpectClose(ClientWebSocket client, int code) + { + using var cancel = new CancellationTokenSource(7000); + var result = await client.ReceiveAsync(new ArraySegment(new byte[1024]), cancel.Token); + Check(result.MessageType == WebSocketMessageType.Close && (int?)result.CloseStatus == code, "WebSocket close " + code); + await Close(client); + } + + static async Task Close(ClientWebSocket client) + { + using var cancel = new CancellationTokenSource(5000); + await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", cancel.Token); + } + + static void Check(bool condition, string name) + { + Console.WriteLine((condition ? "ok " : "fail ") + name); + if (!condition) _failed++; + } + + sealed class TestSocket : WebSocket + { + WebSocketState _state = WebSocketState.Open; + public byte[] Payload; + public readonly TaskCompletionSource SendStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + public Func Sending = _ => Task.CompletedTask; + public override WebSocketCloseStatus? CloseStatus => null; + public override string CloseStatusDescription => null; + public override WebSocketState State => _state; + public override string SubProtocol => null; + public override void Abort() => _state = WebSocketState.Aborted; + public override void Dispose() => _state = WebSocketState.Closed; + public override Task CloseAsync(WebSocketCloseStatus status, string description, CancellationToken token) + { + _state = WebSocketState.Closed; + return Task.CompletedTask; + } + public override Task CloseOutputAsync(WebSocketCloseStatus status, string description, CancellationToken token) + { + _state = WebSocketState.CloseSent; + return Task.CompletedTask; + } + public override Task ReceiveAsync(ArraySegment buffer, CancellationToken token) => + throw new NotSupportedException(); + public override Task SendAsync(ArraySegment buffer, WebSocketMessageType type, bool end, CancellationToken token) + { + Payload = new byte[buffer.Count]; + Buffer.BlockCopy(buffer.Array, buffer.Offset, Payload, 0, buffer.Count); + SendStarted.TrySetResult(true); + return Sending(token); + } + } + + sealed class SerializationProbe + { + public int Value => _producing ? throw new InvalidOperationException("Inline serialization") : 42; + } + + sealed class QueuedContext : SynchronizationContext + { + readonly Queue _work = new Queue(); + public override void Post(SendOrPostCallback callback, object state) + { + lock (_work) _work.Enqueue(() => callback(state)); + } + public void RunOne() + { + Action work; + lock (_work) work = _work.Dequeue(); + work(); + } + } +} diff --git a/LiveStreamAssist/tools/WebSocketTransportCheck/Program.cs b/LiveStreamAssist/tools/WebSocketTransportCheck/Program.cs new file mode 100644 index 0000000..9b5d245 --- /dev/null +++ b/LiveStreamAssist/tools/WebSocketTransportCheck/Program.cs @@ -0,0 +1,157 @@ +using System; +using System.Net; +using System.Net.WebSockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Server.Kestrel.Core; +using Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets; +using Microsoft.AspNetCore.WebSockets; + +namespace WebSocketTransportCheck; + +static class Program +{ + static int Main(string[] args) + { + Console.OutputEncoding = new UTF8Encoding(false); + if (Array.IndexOf(args, "--regression") >= 0) + return ProductionChecks.Run().GetAwaiter().GetResult(); + var port = 18081; + var echo = false; + foreach (var arg in args) + { + if (arg == "--echo") echo = true; + else if (arg.StartsWith("--port=", StringComparison.Ordinal) && + int.TryParse(arg.Substring(7), out var p)) + port = p; + } + + using var host = BuildHost(IPAddress.Loopback, port); + Console.WriteLine("transport=" + typeof(SocketTransportFactory).Assembly.FullName); + Console.WriteLine("transportLocation=" + typeof(SocketTransportFactory).Assembly.Location); + Console.WriteLine("websockets=" + typeof(WebSocketMiddleware).Assembly.FullName); + Console.WriteLine("websocketsLocation=" + typeof(WebSocketMiddleware).Assembly.Location); + Console.WriteLine("kestrel=" + typeof(KestrelServer).Assembly.FullName); + Console.WriteLine("kestrelLocation=" + typeof(KestrelServer).Assembly.Location); + Console.WriteLine("listening=ws://127.0.0.1:" + port + "/echo"); + host.Start(); + if (!echo) + { + RunClient(port).GetAwaiter().GetResult(); + Console.WriteLine("OK"); + return 0; + } + + Console.WriteLine("echo running; Ctrl+C to stop"); + using var exit = new ManualResetEvent(false); + Console.CancelKeyPress += (_, e) => + { + e.Cancel = true; + exit.Set(); + }; + exit.WaitOne(); + return 0; + } + + internal static IWebHost BuildHost(IPAddress address, int port) + { + return new WebHostBuilder() + .UseSetting(WebHostDefaults.PreventHostingStartupKey, "true") + .UseKestrel(o => + { + o.Listen(address, port); + o.AddServerHeader = false; + o.Limits.MaxConcurrentConnections = 8; + o.Limits.MaxConcurrentUpgradedConnections = 8; + o.Limits.MaxRequestHeadersTotalSize = 16 * 1024; + o.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(5); + o.Limits.MaxRequestBodySize = 1024; + }) + .UseSockets() + .Configure(app => + { + app.UseWebSockets(new WebSocketOptions { ReceiveBufferSize = 4096 }); + app.Run(Handle); + }) + .Build(); + } + + static async Task Handle(HttpContext context) + { + if (!string.Equals(context.Request.Path.Value, "/echo", StringComparison.Ordinal)) + { + context.Response.StatusCode = 404; + return; + } + + if (!context.WebSockets.IsWebSocketRequest) + { + context.Response.StatusCode = 400; + return; + } + + using (var ws = await context.WebSockets.AcceptWebSocketAsync()) + { + Console.WriteLine("websocketType=" + ws.GetType().FullName); + Console.WriteLine("websocketAssembly=" + ws.GetType().Assembly.FullName); + using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); + var buffer = new byte[4096]; + var payload = new byte[65536]; + var used = 0; + while (ws.State == WebSocketState.Open) + { + var result = await ws.ReceiveAsync(new ArraySegment(buffer), lifetime.Token); + if (result.MessageType == WebSocketMessageType.Close) + { + lifetime.CancelAfter(5000); + await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", lifetime.Token); + return; + } + + if (used + result.Count > payload.Length) + { + lifetime.CancelAfter(5000); + await ws.CloseAsync(WebSocketCloseStatus.MessageTooBig, "", lifetime.Token); + return; + } + + Buffer.BlockCopy(buffer, 0, payload, used, result.Count); + used += result.Count; + if (!result.EndOfMessage) continue; + await ws.SendAsync(new ArraySegment(payload, 0, used), result.MessageType, true, + lifetime.Token); + used = 0; + } + } + } + + static async Task RunClient(int port) + { + using (var client = new ClientWebSocket()) + using (var timeout = new CancellationTokenSource(5000)) + { + await client.ConnectAsync(new Uri("ws://127.0.0.1:" + port + "/echo"), timeout.Token); + var payload = Encoding.UTF8.GetBytes("ping"); + await client.SendAsync(new ArraySegment(payload), WebSocketMessageType.Text, false, + timeout.Token); + await client.SendAsync(new ArraySegment(new byte[0]), WebSocketMessageType.Text, true, + timeout.Token); + var received = new byte[payload.Length]; + var used = 0; + WebSocketReceiveResult result; + do + { + result = await client.ReceiveAsync(new ArraySegment(received, used, received.Length - used), timeout.Token); + if (result.MessageType != WebSocketMessageType.Text) throw new InvalidOperationException("Expected an echo response."); + used += result.Count; + } while (!result.EndOfMessage && used < received.Length); + if (!result.EndOfMessage || used != payload.Length || Encoding.UTF8.GetString(received) != "ping") + throw new InvalidOperationException("Echo response did not match the fragmented message."); + await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", timeout.Token); + } + } +} diff --git a/LiveStreamAssist/tools/WebSocketTransportCheck/WebSocketTransportCheck.csproj b/LiveStreamAssist/tools/WebSocketTransportCheck/WebSocketTransportCheck.csproj new file mode 100644 index 0000000..473fc79 --- /dev/null +++ b/LiveStreamAssist/tools/WebSocketTransportCheck/WebSocketTransportCheck.csproj @@ -0,0 +1,26 @@ + + + + Exe + WebSocketTransportCheck + WebSocketTransportCheck + org.soardev.livestreamassist.transportcheck + none + true + + + + + + + + + + + + + + + + diff --git a/LiveStreamAssist/tools/WebSocketTransportCheck/packages.lock.json b/LiveStreamAssist/tools/WebSocketTransportCheck/packages.lock.json new file mode 100644 index 0000000..e1727af --- /dev/null +++ b/LiveStreamAssist/tools/WebSocketTransportCheck/packages.lock.json @@ -0,0 +1,655 @@ +{ + "version": 1, + "dependencies": { + ".NETFramework,Version=v4.7.2": { + "BepInEx.Core": { + "type": "Direct", + "requested": "[5.*, )", + "resolved": "5.4.21", + "contentHash": "NMUPlbHTTfJ+qIQCI90uIvjuUQ4wnwt4cpRsK3ItBh1DhsWFzAHXNiZjBxZkPysljEKQ2iu89sxMTga4bxBXVQ==", + "dependencies": { + "BepInEx.BaseLib": "5.4.20", + "HarmonyX": "2.7.0" + } + }, + "BepInEx.PluginInfoProps": { + "type": "Direct", + "requested": "[1.*, )", + "resolved": "1.1.0", + "contentHash": "RqM3aaGs8Hc2m0D+8aSt9mv09rCMYNIF35NB3D6KA2zSpcXJh/9ZVWrPlIUJfA8KYzodSWcCMUexEW24fjwR3w==" + }, + "Microsoft.NETFramework.ReferenceAssemblies": { + "type": "Direct", + "requested": "[1.0.3, )", + "resolved": "1.0.3", + "contentHash": "vUc9Npcs14QsyOD01tnv/m8sQUnGTGOw1BCmKcv77LBJY7OxhJ+zJF7UD/sCL3lYNFuqmQEVlkfS4Quif6FyYg==", + "dependencies": { + "Microsoft.NETFramework.ReferenceAssemblies.net472": "1.0.3" + } + }, + "UnityEngine.Modules": { + "type": "Direct", + "requested": "[2022.3.62, )", + "resolved": "2022.3.62", + "contentHash": "zpu5dELUCFt7Rvvzp50iTrfVusJg+2gmlcaytGEoHYuIP+AOv57X272czjp+sA8N1onPo/IiHFnOEFtT9rLJBA==" + }, + "BepInEx.BaseLib": { + "type": "Transitive", + "resolved": "5.4.20", + "contentHash": "0bXgYxbCEN2Ixp3kiFEhyw+RASeFQeg/ww+lbMt7if6XMeVS60eg6epNsMA8Jbx57dmNOzNevkKKw8mP8SUMqw==" + }, + "DysonSphereProgram.Modding.CommonAPI": { + "type": "Transitive", + "resolved": "1.6.5", + "contentHash": "1VJ3hNzvmmk6aekCF0RtmOl4vbaDtQscDNNDhIvpmMQEh3j1wESezWPPVyrQB4/+0uVlDgRoqTOJo6RS74XpIQ==", + "dependencies": { + "DysonSphereProgram.Modding.DSPModSave": "1.2.0", + "DysonSphereProgram.Modding.LDBTool": "3.0.0", + "DysonSphereProgram.Modding.NebulaMultiplayerModApi": "2.0.0" + } + }, + "DysonSphereProgram.Modding.DSPModSave": { + "type": "Transitive", + "resolved": "1.2.0", + "contentHash": "i70jjFTXtvE0UfD2PLqlkkLhF317KrcVl1W/PFoza9nWsAZuz12pyVaUS6h35hkqVN4k8ZODkVn2UpFiVr07aw==" + }, + "DysonSphereProgram.Modding.LDBTool": { + "type": "Transitive", + "resolved": "3.0.0", + "contentHash": "RY9gnVs6X6RQ5pdOrtEIYFuKijQXYZG8kcAeUEjZz+WvkmqI23igUhHFYrmTz25WGbtGzsle06fbG0K4bA0rZQ==" + }, + "DysonSphereProgram.Modding.NebulaMultiplayerModApi": { + "type": "Transitive", + "resolved": "2.0.0", + "contentHash": "ExoBArVwtbUpn2r1tTSE12sPQVxeBzmzC3MqDMxuhZTz8wgEl2RLT/USLy7DDaoK7XMAjXi29DBjopxSmsYPMA==" + }, + "HarmonyX": { + "type": "Transitive", + "resolved": "2.7.0", + "contentHash": "lec/SkduQspMa3Pi/nM/NSvA84Za8HCCWA8ybdToKiTqnBZa+JC5g6rxoFQCg/1vNuYcvjy77edePZzIEsRmvw==", + "dependencies": { + "MonoMod.RuntimeDetour": "21.12.13.1" + } + }, + "Microsoft.AspNetCore.Connections.Abstractions": { + "type": "Transitive", + "resolved": "2.3.11", + "contentHash": "lS3+85IKCaoJLqyep27kE6qd9VUB5VVGqCl4xl+gVwoidN/qH29kT7UTSncUvV2bHyc62erOHprTwVqjZb+0Aw==", + "dependencies": { + "Microsoft.AspNetCore.Http.Features": "2.3.10", + "System.IO.Pipelines": "8.0.0" + } + }, + "Microsoft.AspNetCore.Hosting": { + "type": "Transitive", + "resolved": "2.3.13", + "contentHash": "hNB7B9mtUzrJ9T8qZe8Dvm9DqSSLIASCihVqHDbq2gWGKkF6bQ3qw1Oo2PLqMCsTzf9F2sAPo9V3LO8cMP3ZNg==", + "dependencies": { + "Microsoft.AspNetCore.Hosting.Abstractions": "2.3.12", + "Microsoft.AspNetCore.Http": "2.3.12", + "Microsoft.AspNetCore.Http.Extensions": "2.3.12", + "Microsoft.Extensions.Configuration": "8.0.0", + "Microsoft.Extensions.Configuration.EnvironmentVariables": "8.0.0", + "Microsoft.Extensions.Configuration.FileExtensions": "8.0.1", + "Microsoft.Extensions.DependencyInjection": "8.0.1", + "Microsoft.Extensions.FileProviders.Physical": "8.0.0", + "Microsoft.Extensions.Hosting.Abstractions": "8.0.1", + "Microsoft.Extensions.Logging": "8.0.1", + "Microsoft.Extensions.Logging.Debug": "8.0.1", + "Microsoft.Extensions.Options": "8.0.2", + "System.Diagnostics.DiagnosticSource": "8.0.1", + "System.Reflection.Metadata": "8.0.1" + } + }, + "Microsoft.AspNetCore.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "jSEvM9Ot0ok4VIT8R5JNOSiLTay+sFBp1vCwiqWPqaY3HuvK0EAr8YfqOkxDnWw5nqyC5Z3asJ2NuddLNVzXGA==", + "dependencies": { + "Microsoft.AspNetCore.Hosting.Server.Abstractions": "2.3.11", + "Microsoft.AspNetCore.Http.Abstractions": "2.3.11", + "Microsoft.Extensions.Hosting.Abstractions": "8.0.1" + } + }, + "Microsoft.AspNetCore.Hosting.Server.Abstractions": { + "type": "Transitive", + "resolved": "2.3.11", + "contentHash": "LMp90i+SDiogwqOybUn8T6uZ0E3wmfKxZpUUMUWo/mWkaxTFtzFPTj/VU0G5ZEgYQdz6oPSwSpkoV6pzikt9Qg==", + "dependencies": { + "Microsoft.AspNetCore.Http.Features": "2.3.10", + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0" + } + }, + "Microsoft.AspNetCore.Http": { + "type": "Transitive", + "resolved": "2.3.13", + "contentHash": "6dSurGknKDspLgtKkqGw5SlDp8qpeaZ31P9RWiDsdT+CnecbNP8HgXPrAQthsIuV25FIKzfwF7VCC0JTRHtRqA==", + "dependencies": { + "Microsoft.AspNetCore.Http.Abstractions": "2.3.12", + "Microsoft.AspNetCore.WebUtilities": "2.3.12", + "Microsoft.Extensions.ObjectPool": "8.0.11", + "Microsoft.Extensions.Options": "8.0.2", + "Microsoft.Net.Http.Headers": "2.3.12" + } + }, + "Microsoft.AspNetCore.Http.Abstractions": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "Mc1UKKSU8PmOWqpNdfpRYmqotmoQlsL1SAYwLHIIlTDayjyKng3UVn5+b+mPAEp31vU4ozy0CYeRYvCPqzdxZw==", + "dependencies": { + "Microsoft.AspNetCore.Http.Features": "2.3.11", + "System.Text.Encodings.Web": "8.0.0" + } + }, + "Microsoft.AspNetCore.Http.Extensions": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "qMK/Q25fj2R97RNNnbK2WmQTBN6wAa1t0sWSyOb3XA8JYkZTGxWjoVJ3P7ntdmEdV8EVfTrV1DCQl390GAOeXg==", + "dependencies": { + "Microsoft.AspNetCore.Http.Abstractions": "2.3.11", + "Microsoft.Extensions.FileProviders.Abstractions": "8.0.0", + "Microsoft.Net.Http.Headers": "2.3.11", + "System.Buffers": "4.6.0" + } + }, + "Microsoft.AspNetCore.Http.Features": { + "type": "Transitive", + "resolved": "2.3.11", + "contentHash": "TRQWR0vHBUUAEynbgCI3/MRf4+xRj8TsljoUPYxqiombhYhoEYHnr1sowozU1L/OyJHkPdm2IscJ9JBa0kcgbw==", + "dependencies": { + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.AspNetCore.Server.Kestrel": { + "type": "Transitive", + "resolved": "2.3.13", + "contentHash": "E39NfUxxS6EGfKdUmRUU8789BDxX3Au675HaKLs3Z+EP0R6cn3iUEqYt9msHQJ0JFTJwmqt8i25GeYc8/m7w9Q==", + "dependencies": { + "Microsoft.AspNetCore.Hosting": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Core": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Https": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets": "2.3.13", + "System.IO.Pipelines": "8.0.0" + } + }, + "Microsoft.AspNetCore.Server.Kestrel.Core": { + "type": "Transitive", + "resolved": "2.3.13", + "contentHash": "mSxCuFfUJfDT+dGiXaLPT+fRsfxwIrlS1HlAIVjGEDBbxqLk/QQbI9r29xv32Yyw6tUejNAFBh/bGcEkw2Y0UA==", + "dependencies": { + "Microsoft.AspNetCore.Hosting.Abstractions": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions": "2.3.12", + "Microsoft.AspNetCore.WebUtilities": "2.3.12", + "Microsoft.Extensions.Configuration": "8.0.0", + "Microsoft.Extensions.Configuration.Binder": "8.0.2", + "Microsoft.Extensions.Logging.Abstractions": "8.0.2", + "Microsoft.Extensions.Options": "8.0.2", + "Microsoft.Net.Http.Headers": "2.3.12", + "System.Memory": "4.6.0", + "System.Numerics.Vectors": "4.6.0", + "System.Runtime.CompilerServices.Unsafe": "6.1.0", + "System.Security.Cryptography.Cng": "5.0.0", + "System.Threading.Tasks.Extensions": "4.6.0" + } + }, + "Microsoft.AspNetCore.Server.Kestrel.Https": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "WYgEPYGQStLbv8mDjM5vZ4G42inArjFQlfqZfHXLWTDabn7dFoCJMtArFITQO0ufXBnhLxT/mzpLTaBD63jI1Q==", + "dependencies": { + "Microsoft.AspNetCore.Http.Abstractions": "2.3.11", + "Microsoft.AspNetCore.Server.Kestrel.Core": "2.3.11" + } + }, + "Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "JMmL1DrpgaeEHE3jCavNFShBS1q9zt3u0PzdUSSqWHBep5MXnidbPyuHW+fIOeWVwEnN5GwXj8VINx+qyjFSAg==", + "dependencies": { + "Microsoft.AspNetCore.Connections.Abstractions": "2.3.11", + "System.IO.Pipelines": "8.0.0" + } + }, + "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets": { + "type": "Transitive", + "resolved": "2.3.13", + "contentHash": "l3URJm6IoIczXezQ1UgzCeFgak3fK781uovNKkS3Qrh9hQbsHDx0wMt3Qf9NuKyOVwkEreIB5oF/NLIb/k0N9A==", + "dependencies": { + "Microsoft.AspNetCore.Hosting.Abstractions": "2.3.12", + "Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions": "2.3.12", + "Microsoft.Extensions.Options": "8.0.2" + } + }, + "Microsoft.AspNetCore.WebSockets": { + "type": "Transitive", + "resolved": "2.3.13", + "contentHash": "9NRfb/pnNMffdqQC+AJiseOmum+Y7guPekFGJjO921EMsr/S9e0ZZ3ouoO10tlZPiJBhMHrHe6pqcUcZddFKww==", + "dependencies": { + "Microsoft.AspNetCore.Http.Extensions": "2.3.12", + "Microsoft.Extensions.Options": "8.0.2", + "System.Net.WebSockets.WebSocketProtocol": "5.1.0" + } + }, + "Microsoft.AspNetCore.WebUtilities": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "wzbAsF9N+9Eftg7+daZwPbfuT8wFQlD1duV/OPHNw5twVVgWkSjjens9QQ4ZrXSY6sd1nRYE6RZGUtZt5NaENA==", + "dependencies": { + "Microsoft.Net.Http.Headers": "2.3.11", + "System.Text.Encodings.Web": "8.0.0" + } + }, + "Microsoft.Bcl.AsyncInterfaces": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "3WA9q9yVqJp222P3x1wYIGDAkpjAku0TMUaaQV22g6L67AI0LdOIrVS7Ht2vJfLHGSPVuqN94vIr15qn+HEkHw==", + "dependencies": { + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "Microsoft.Extensions.Configuration": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "0J/9YNXTMWSZP2p2+nvl8p71zpSwokZXZuJW+VjdErkegAnFdO1XlqtA62SJtgVYHdKu3uPxJHcMR/r35HwFBA==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0", + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.Extensions.Configuration.Abstractions": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "3lE/iLSutpgX1CC0NOW70FJoGARRHbyKmG7dc0klnUZ9Dd9hS6N/POPWhKhMLCEuNN5nXEY5agmlFtH562vqhQ==", + "dependencies": { + "Microsoft.Extensions.Primitives": "8.0.0", + "System.ValueTuple": "4.5.0" + } + }, + "Microsoft.Extensions.Configuration.Binder": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "7IQhGK+wjyGrNsPBjJcZwWAr+Wf6D4+TwOptUt77bWtgNkiV8tDEbhFS+dDamtQFZ2X7kWG9m71iZQRj2x3zgQ==", + "dependencies": { + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0" + } + }, + "Microsoft.Extensions.Configuration.EnvironmentVariables": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "plvZ0ZIpq+97gdPNNvhwvrEZ92kNml9hd1pe3idMA7svR0PztdzVLkoWLcRFgySYXUJc3kSM3Xw3mNFMo/bxRA==", + "dependencies": { + "Microsoft.Extensions.Configuration": "8.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0" + } + }, + "Microsoft.Extensions.Configuration.FileExtensions": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "EJzSNO9oaAXnTdtdNO6npPRsIIeZCBSNmdQ091VDO7fBiOtJAAeEq6dtrVXIi3ZyjC5XRSAtVvF8SzcneRHqKQ==", + "dependencies": { + "Microsoft.Extensions.Configuration": "8.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0", + "Microsoft.Extensions.FileProviders.Abstractions": "8.0.0", + "Microsoft.Extensions.FileProviders.Physical": "8.0.0", + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.Extensions.DependencyInjection": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "BmANAnR5Xd4Oqw7yQ75xOAYODybZQRzdeNucg7kS5wWKd2PNnMdYtJ2Vciy0QLylRmv42DGl5+AFL9izA6F1Rw==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "8.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "Microsoft.Extensions.DependencyInjection.Abstractions": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "3iE7UF7MQkCv1cxzCahz+Y/guQbTqieyxyaWKhrRO91itI9cOKO76OHeQDahqG4MmW5umr3CcCvGmK92lWNlbg==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "8.0.0", + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "Microsoft.Extensions.Diagnostics.Abstractions": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "elH2vmwNmsXuKmUeMQ4YW9ldXiF+gSGDgg1vORksob5POnpaI6caj1Hu8zaYbEuibhqCoWg0YRWDazBY3zjBfg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "Microsoft.Extensions.Options": "8.0.2", + "System.Buffers": "4.5.1", + "System.Diagnostics.DiagnosticSource": "8.0.1", + "System.Memory": "4.5.5" + } + }, + "Microsoft.Extensions.FileProviders.Abstractions": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "ZbaMlhJlpisjuWbvXr4LdAst/1XxH3vZ6A0BsgTphZ2L4PGuxRLz7Jr/S7mkAAnOn78Vu0fKhEgNF5JO3zfjqQ==", + "dependencies": { + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.Extensions.FileProviders.Physical": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "UboiXxpPUpwulHvIAVE36Knq0VSHaAmfrFkegLyBZeaADuKezJ/AIXYAW8F5GBlGk/VaibN2k/Zn1ca8YAfVdA==", + "dependencies": { + "Microsoft.Extensions.FileProviders.Abstractions": "8.0.0", + "Microsoft.Extensions.FileSystemGlobbing": "8.0.0", + "Microsoft.Extensions.Primitives": "8.0.0" + } + }, + "Microsoft.Extensions.FileSystemGlobbing": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "OK+670i7esqlQrPjdIKRbsyMCe9g5kSLpRRQGSr4Q58AOYEe/hCnfLZprh7viNisSUUQZmMrbbuDaIrP+V1ebQ==" + }, + "Microsoft.Extensions.Hosting.Abstractions": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "nHwq9aPBdBPYXPti6wYEEfgXddfBrYC+CQLn+qISiwQq5tpfaqDZSKOJNxoe9rfQxGf1c+2wC/qWFe1QYJPYqw==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "8.0.0", + "Microsoft.Extensions.Configuration.Abstractions": "8.0.0", + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "Microsoft.Extensions.Diagnostics.Abstractions": "8.0.1", + "Microsoft.Extensions.FileProviders.Abstractions": "8.0.0", + "Microsoft.Extensions.Logging.Abstractions": "8.0.2", + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "Microsoft.Extensions.Logging": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "4x+pzsQEbqxhNf1QYRr5TDkLP9UsLT3A6MdRKDDEgrW7h1ljiEPgTNhKYUhNCCAaVpQECVQ+onA91PTPnIp6Lw==", + "dependencies": { + "Microsoft.Bcl.AsyncInterfaces": "8.0.0", + "Microsoft.Extensions.DependencyInjection": "8.0.1", + "Microsoft.Extensions.Logging.Abstractions": "8.0.2", + "Microsoft.Extensions.Options": "8.0.2", + "System.Diagnostics.DiagnosticSource": "8.0.1", + "System.ValueTuple": "4.5.0" + } + }, + "Microsoft.Extensions.Logging.Abstractions": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "nroMDjS7hNBPtkZqVBbSiQaQjWRDxITI8Y7XnDs97rqG3EbzVTNLZQf7bIeUJcaHOV8bca47s1Uxq94+2oGdxA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "System.Buffers": "4.5.1", + "System.Diagnostics.DiagnosticSource": "8.0.1", + "System.Memory": "4.5.5" + } + }, + "Microsoft.Extensions.Logging.Debug": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "B8hqNuYudC2RB+L/DI33uO4rf5by41fZVdcVL2oZj0UyoAZqnwTwYHp1KafoH4nkl1/23piNeybFFASaV2HkFg==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.2", + "Microsoft.Extensions.Logging": "8.0.1", + "Microsoft.Extensions.Logging.Abstractions": "8.0.2" + } + }, + "Microsoft.Extensions.ObjectPool": { + "type": "Transitive", + "resolved": "8.0.11", + "contentHash": "6ApKcHNJigXBfZa6XlDQ8feJpq7SG1ogZXg6M4FiNzgd6irs3LUAzo0Pfn4F2ZI9liGnH1XIBR/OtSbZmJAV5w==" + }, + "Microsoft.Extensions.Options": { + "type": "Transitive", + "resolved": "8.0.2", + "contentHash": "dWGKvhFybsaZpGmzkGCbNNwBD1rVlWzrZKANLW/CcbFJpCEceMCGzT7zZwHOGBCbwM0SzBuceMj5HN1LKV1QqA==", + "dependencies": { + "Microsoft.Extensions.DependencyInjection.Abstractions": "8.0.0", + "Microsoft.Extensions.Primitives": "8.0.0", + "System.ValueTuple": "4.5.0" + } + }, + "Microsoft.Extensions.Primitives": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "bXJEZrW9ny8vjMF1JV253WeLhpEVzFo1lyaZu1vQ4ZxWUlVvknZ/+ftFgVheLubb4eZPSwwxBeqS1JkCOjxd8g==", + "dependencies": { + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "Microsoft.Net.Http.Headers": { + "type": "Transitive", + "resolved": "2.3.12", + "contentHash": "lh9agX9zEuQy69kxwPTT2+OmK2Y49OA8r7qdwZNWNKGug45V050HLH3xhPF23y4sr5Nl6JKXo0AofCwxkNd6zw==", + "dependencies": { + "Microsoft.Extensions.Primitives": "8.0.0", + "System.Buffers": "4.6.0" + } + }, + "Microsoft.NETFramework.ReferenceAssemblies.net472": { + "type": "Transitive", + "resolved": "1.0.3", + "contentHash": "0E7evZXHXaDYYiLRfpyXvCh+yzM2rNTyuZDI+ZO7UUqSc6GfjePiXTdqJGtgIKUwdI81tzQKmaWprnUiPj9hAw==" + }, + "Mono.Cecil": { + "type": "Transitive", + "resolved": "0.11.4", + "contentHash": "IC1h5g0NeJGHIUgzM1P82ld57knhP0IcQfrYITDPXlNpMYGUrsG5TxuaWTjaeqDNQMBDNZkB8L0rBnwsY6JHuQ==" + }, + "MonoMod.RuntimeDetour": { + "type": "Transitive", + "resolved": "21.12.13.1", + "contentHash": "65mB+bHjT6UCGCgO+/pYhpuGPf96rQ1Whwkut/x7cqVIW0DTndDFyWc/3bngzhnY/Y6IYtBMlXsU2ATq+CxpHg==", + "dependencies": { + "Mono.Cecil": "0.11.4", + "MonoMod.Utils": "21.12.13.1" + } + }, + "MonoMod.Utils": { + "type": "Transitive", + "resolved": "21.12.13.1", + "contentHash": "/H+0RMWqx/D1/fSuY5jhY6GFvqhdYdlnI7J3IfL8P6y4nJkoZDxqts6+RxWWOz4pbnJdWnxSjS8XG+Lq6rUi7w==", + "dependencies": { + "Mono.Cecil": "0.11.4" + } + }, + "Newtonsoft.Json": { + "type": "Transitive", + "resolved": "13.0.3", + "contentHash": "HrC5BXdl00IP9zeV+0Z848QWPAoCr9P3bDEZguI+gkLcBKAOxix/tLEAAHC+UvDNPv4a2d18lOReHMOagPa+zQ==" + }, + "System.Buffers": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "N8GXpmiLMtljq7gwvyS+1QvKT/W2J8sNAvx+HVg4NGmsG/H+2k/y9QI23auLJRterrzCiDH+IWAw4V/GPwsMlw==" + }, + "System.Collections.Immutable": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "AurL6Y5BA1WotzlEvVaIDpqzpIPvYnnldxru8oXJU2yFxFUy3+pNXjXd1ymO+RA0rq0+590Q8gaz2l3Sr7fmqg==", + "dependencies": { + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "System.Diagnostics.DiagnosticSource": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "vaoWjvkG1aenR2XdjaVivlCV9fADfgyhW5bZtXT23qaEea0lWiUljdQuze4E31vKM7ZWJaSUsbYIKE3rnzfZUg==", + "dependencies": { + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "System.IO": { + "type": "Transitive", + "resolved": "4.3.0", + "contentHash": "3qjaHvxQPDpSOYICjUoTsmoq5u6QJAFRUITgeT/4gqkF1bajbSmb1kwSxEA8AHlofqgcKJcM8udgieRNhaJ5Cg==" + }, + "System.IO.Pipelines": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "FHNOatmUq0sqJOkTx+UF/9YK1f180cnW5FVqnQMvYUN0elp6wFzbtPSiqbo1/ru8ICp43JM1i7kKkk6GsNGHlA==", + "dependencies": { + "System.Buffers": "4.5.1", + "System.Memory": "4.5.5", + "System.Threading.Tasks.Extensions": "4.5.4" + } + }, + "System.Memory": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "qdcDOgnFZY40+Q9876JUHnlHu7bosOHX8XISRoH94fwk6hgaeQGSgfZd8srWRZNt5bV9ZW2TljcegDNxsf+96A==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.Net.WebSockets.WebSocketProtocol": { + "type": "Transitive", + "resolved": "5.1.3", + "contentHash": "n236SAZz8HzZe1BEessCoAFh+QhAXq6jgc7qkQ5hi0iEcTra21Q5o4Utm5Ln92SOWcn/Sz+YdMGJQteb/7SISg==", + "dependencies": { + "System.Buffers": "4.6.1", + "System.Memory": "4.6.3", + "System.Numerics.Vectors": "4.6.1", + "System.Runtime.CompilerServices.Unsafe": "6.1.2", + "System.Threading.Tasks.Extensions": "4.6.3" + } + }, + "System.Numerics.Vectors": { + "type": "Transitive", + "resolved": "4.6.1", + "contentHash": "sQxefTnhagrhoq2ReR0D/6K0zJcr9Hrd6kikeXsA1I8kOCboTavcUC4r7TSfpKFeE163uMuxZcyfO1mGO3EN8Q==" + }, + "System.Reflection.Metadata": { + "type": "Transitive", + "resolved": "8.0.1", + "contentHash": "+4sz5vGHPlo+5NpAxf2IlABnqVvOHOxv17b4dONv4hVwyNeFAeBevT14DIn7X3YWQ+eQFYO3YeTBNCleAblOKA==", + "dependencies": { + "System.Collections.Immutable": "8.0.0", + "System.Memory": "4.5.5" + } + }, + "System.Runtime": { + "type": "Transitive", + "resolved": "4.3.0", + "contentHash": "JufQi0vPQ0xGnAczR13AUFglDyVYt4Kqnz1AZaiKZ5+GICq0/1MH/mO/eAJHt/mHW1zjKBJd7kV26SrxddAhiw==" + }, + "System.Runtime.CompilerServices.Unsafe": { + "type": "Transitive", + "resolved": "6.1.2", + "contentHash": "2hBr6zdbIBTDE3EhK7NSVNdX58uTK6iHW/P/Axmm9sl1xoGSLqDvMtpecn226TNwHByFokYwJmt/aQQNlO5CRw==" + }, + "System.Security.Cryptography.Algorithms": { + "type": "Transitive", + "resolved": "4.3.1", + "contentHash": "DVUblnRfnarrI5olEC2B/OCsJQd0anjVaObQMndHSc43efbc88/RMOlDyg/EyY0ix5ecyZMXS8zMksb5ukebZA==", + "dependencies": { + "System.IO": "4.3.0", + "System.Runtime": "4.3.0", + "System.Security.Cryptography.Encoding": "4.3.0", + "System.Security.Cryptography.Primitives": "4.3.0" + } + }, + "System.Security.Cryptography.Cng": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "jIMXsKn94T9JY7PvPq/tMfqa6GAaHpElRDpmG+SuL+D3+sTw2M8VhnibKnN8Tq+4JqbPJ/f+BwtLeDMEnzAvRg==", + "dependencies": { + "System.Security.Cryptography.Algorithms": "4.3.1" + } + }, + "System.Security.Cryptography.Encoding": { + "type": "Transitive", + "resolved": "4.3.0", + "contentHash": "1DEWjZZly9ae9C79vFwqaO5kaOlI5q+3/55ohmq/7dpDyDfc8lYe7YVxJUZ5MF/NtbkRjwFRo14yM4OEo9EmDw==" + }, + "System.Security.Cryptography.Primitives": { + "type": "Transitive", + "resolved": "4.3.0", + "contentHash": "7bDIyVFNL/xKeFHjhobUAQqSpJq9YTOpbEs6mR233Et01STBMXNAc/V+BM6dwYGc95gVh/Zf+iVXWzj3mE8DWg==" + }, + "System.Text.Encodings.Web": { + "type": "Transitive", + "resolved": "8.0.0", + "contentHash": "yev/k9GHAEGx2Rg3/tU6MQh4HGBXJs70y7j1LaM1i/ER9po+6nnQ6RRqTJn1E7Xu0fbIFK80Nh5EoODxrbxwBQ==", + "dependencies": { + "System.Buffers": "4.5.1", + "System.Memory": "4.5.5", + "System.Runtime.CompilerServices.Unsafe": "6.0.0" + } + }, + "System.Threading.Tasks.Extensions": { + "type": "Transitive", + "resolved": "4.6.3", + "contentHash": "7sCiwilJLYbTZELaKnc7RecBBXWXA+xMLQWZKWawBxYjp6DBlSE3v9/UcvKBvr1vv2tTOhipiogM8rRmxlhrVA==", + "dependencies": { + "System.Runtime.CompilerServices.Unsafe": "6.1.2" + } + }, + "System.ValueTuple": { + "type": "Transitive", + "resolved": "4.5.0", + "contentHash": "okurQJO6NRE/apDIP23ajJ0hpiNmJ+f0BwOlB/cSqTLQlw5upkf+5+96+iG2Jw40G1fCVCyPz/FhIABUjMR+RQ==" + }, + "livestreamassist": { + "type": "Project", + "dependencies": { + "BepInEx.Core": "[5.*, )", + "BepInEx.PluginInfoProps": "[1.*, )", + "Microsoft.AspNetCore.Hosting": "[2.3.13, )", + "Microsoft.AspNetCore.Http": "[2.3.13, )", + "Microsoft.AspNetCore.Server.Kestrel": "[2.3.13, )", + "Microsoft.AspNetCore.Server.Kestrel.Core": "[2.3.13, )", + "Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets": "[2.3.13, )", + "Microsoft.AspNetCore.WebSockets": "[2.3.13, )", + "Newtonsoft.Json": "[13.0.3, )", + "System.Net.WebSockets.WebSocketProtocol": "[5.1.3, )", + "UXAssist": "[1.5.9, )", + "UnityEngine.Modules": "[2022.3.62, )" + } + }, + "uxassist": { + "type": "Project", + "dependencies": { + "BepInEx.Core": "[5.*, )", + "BepInEx.PluginInfoProps": "[1.*, )", + "DysonSphereProgram.Modding.CommonAPI": "[1.*, )", + "DysonSphereProgram.Modding.DSPModSave": "[1.*, )", + "UnityEngine.Modules": "[2022.3.62, )" + } + } + }, + ".NETFramework,Version=v4.7.2/win-x86": { + "System.Security.Cryptography.Algorithms": { + "type": "Transitive", + "resolved": "4.3.1", + "contentHash": "DVUblnRfnarrI5olEC2B/OCsJQd0anjVaObQMndHSc43efbc88/RMOlDyg/EyY0ix5ecyZMXS8zMksb5ukebZA==", + "dependencies": { + "System.IO": "4.3.0", + "System.Runtime": "4.3.0", + "System.Security.Cryptography.Encoding": "4.3.0", + "System.Security.Cryptography.Primitives": "4.3.0" + } + }, + "System.Security.Cryptography.Cng": { + "type": "Transitive", + "resolved": "5.0.0", + "contentHash": "jIMXsKn94T9JY7PvPq/tMfqa6GAaHpElRDpmG+SuL+D3+sTw2M8VhnibKnN8Tq+4JqbPJ/f+BwtLeDMEnzAvRg==", + "dependencies": { + "System.Security.Cryptography.Algorithms": "4.3.1" + } + }, + "System.Security.Cryptography.Encoding": { + "type": "Transitive", + "resolved": "4.3.0", + "contentHash": "1DEWjZZly9ae9C79vFwqaO5kaOlI5q+3/55ohmq/7dpDyDfc8lYe7YVxJUZ5MF/NtbkRjwFRo14yM4OEo9EmDw==" + } + } + } +} \ No newline at end of file