From f38966b4b95013396987622bc58be99955cfc34b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 18 Aug 2026 02:29:14 +0200 Subject: [PATCH] Bound retained session callback resources --- src/GameCult.Mesh/CultMeshSessions.cs | 92 ++++++++++++++----- .../CultMeshClientTests.cs | 33 ++++++- 2 files changed, 100 insertions(+), 25 deletions(-) diff --git a/src/GameCult.Mesh/CultMeshSessions.cs b/src/GameCult.Mesh/CultMeshSessions.cs index 5011a00a..0a655ae8 100644 --- a/src/GameCult.Mesh/CultMeshSessions.cs +++ b/src/GameCult.Mesh/CultMeshSessions.cs @@ -222,7 +222,6 @@ namespace GameCult.Mesh public sealed class CultMeshSession : IDisposable { private readonly Subject _states = new(); - private readonly ConcurrentBag _subscriptions = new(); private readonly ManagedSchemaChannel _channel; private long _physicalGeneration; private bool _disposed; @@ -244,10 +243,7 @@ namespace GameCult.Mesh public IDisposable OnCultNet(Action callback) where T : ICultNetSchemaMessage { if (callback == null) throw new ArgumentNullException(nameof(callback)); - var subscription = new SessionSubscription(callback); - Channel.OnCultNet(subscription.Invoke); - _subscriptions.Add(subscription); - return subscription; + return _channel.Subscribe(callback); } internal void Transition(CultMeshSessionState state) { State = state; _states.OnNext(state); } internal void ReplacePhysicalChannel(ICultNetSchemaClient channel) @@ -259,7 +255,6 @@ namespace GameCult.Mesh { if (_disposed) return; _disposed = true; - foreach (var subscription in _subscriptions) subscription.Dispose(); _channel.Dispose(); _states.Dispose(); } @@ -267,7 +262,7 @@ namespace GameCult.Mesh private sealed class ManagedSchemaChannel : ICultNetSchemaClient { private readonly object _gate = new(); - private readonly List _registrations = new(); + private readonly Dictionary _registrations = new(); private ICultNetSchemaClient _physical; private bool _disposed; @@ -292,14 +287,23 @@ namespace GameCult.Mesh } } public void OnCultNet(Action callback) where T : ICultNetSchemaMessage + { + _ = Subscribe(callback); + } + public IDisposable Subscribe(Action callback) where T : ICultNetSchemaMessage { if (callback == null) throw new ArgumentNullException(nameof(callback)); lock (_gate) { ThrowIfDisposed(); - var registration = new ChannelRegistration(callback); - registration.Attach(_physical); - _registrations.Add(registration); + if (!_registrations.TryGetValue(typeof(T), out var existing)) + { + var created = new ChannelRegistration(); + created.Attach(_physical); + _registrations.Add(typeof(T), created); + existing = created; + } + return ((ChannelRegistration)existing).Subscribe(callback); } } public void Replace(ICultNetSchemaClient physical) @@ -310,7 +314,7 @@ namespace GameCult.Mesh { ThrowIfDisposed(); previous = _physical; - foreach (var registration in _registrations) registration.Attach(physical); + foreach (var registration in _registrations.Values) registration.Attach(physical); _physical = physical; } previous.Dispose(); @@ -323,27 +327,69 @@ namespace GameCult.Mesh if (_disposed) return; _disposed = true; physical = _physical; + foreach (var registration in _registrations.Values) registration.Dispose(); _registrations.Clear(); } physical.Dispose(); } private void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException(nameof(ManagedSchemaChannel)); } - private interface IChannelRegistration { void Attach(ICultNetSchemaClient physical); } + private interface IChannelRegistration : IDisposable { void Attach(ICultNetSchemaClient physical); } private sealed class ChannelRegistration : IChannelRegistration where T : ICultNetSchemaMessage { - private readonly Action _callback; - public ChannelRegistration(Action callback) => _callback = callback; - public void Attach(ICultNetSchemaClient physical) => physical.OnCultNet(_callback); - } - } + private readonly object _gate = new(); + private readonly Dictionary> _callbacks = new(); + private long _nextId; + private bool _disposed; - private sealed class SessionSubscription : IDisposable where T : ICultNetSchemaMessage - { - private Action? _callback; - public SessionSubscription(Action callback) { _callback = callback; } - public void Invoke(T message) => Volatile.Read(ref _callback)?.Invoke(message); - public void Dispose() => Interlocked.Exchange(ref _callback, null); + public IDisposable Subscribe(Action callback) + { + lock (_gate) + { + if (_disposed) throw new ObjectDisposedException(nameof(ChannelRegistration)); + var id = ++_nextId; + _callbacks.Add(id, callback); + return new Subscription(this, id); + } + } + + public void Attach(ICultNetSchemaClient physical) => physical.OnCultNet(Dispatch); + + public void Dispose() + { + lock (_gate) + { + _disposed = true; + _callbacks.Clear(); + } + } + + private void Dispatch(T message) + { + Action[] callbacks; + lock (_gate) callbacks = _callbacks.Values.ToArray(); + foreach (var callback in callbacks) callback(message); + } + + private void Unsubscribe(long id) + { + lock (_gate) _callbacks.Remove(id); + } + + private sealed class Subscription : IDisposable + { + private ChannelRegistration? _owner; + private readonly long _id; + + public Subscription(ChannelRegistration owner, long id) + { + _owner = owner; + _id = id; + } + + public void Dispose() => Interlocked.Exchange(ref _owner, null)?.Unsubscribe(_id); + } + } } private sealed class SessionSchemaClient : ICultNetSchemaClient diff --git a/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs index bf5de6a7..f16ee060 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshClientTests.cs @@ -205,6 +205,32 @@ public sealed class CultMeshClientTests connector.SubscribeCount.Should().Be(2); } + [Test] + public async Task Document_OneHundredThousandDistinctLeaseCyclesLeaveNoResourcesOrCallbacks() + { + const int leaseCount = 100_000; + var connector = new DocumentConnector(); + using var mesh = new CultMeshClient(new CultMeshClientOptions + { + RendezvousEndpoints = new[] { "rudp://odin:3076" }, + Discovery = new CultMeshVerseDiscoveryClientOptions { CreateClient = () => new RendezvousClient() }, + Connectors = new[] { connector } + }); + + for (var index = 0; index < leaseCount; index++) + { + var recordKey = "surface:churn:" + index; + using var lease = await mesh.LeaseDocumentAsync("aetheria", recordKey); + (await lease.Handle.LatestAsync()).Id.Should().Be(recordKey); + } + + mesh.ActiveDocumentResourceCount.Should().Be(0); + mesh.ActiveCollectionResourceCount.Should().Be(0); + connector.Clients.Should().ContainSingle(); + connector.Clients[0].HandlerRegistrationCount.Should().Be(2, + "one physical handler per message type must serve every logical lease"); + } + [Test] public async Task SubmitDocument_SendsUncommittedInputThroughStableIdentitySession() { @@ -348,6 +374,7 @@ public sealed class CultMeshClientTests public bool Connected => true; public Task BackgroundFailure => _failure.Task; public int SubscribeCount { get; private set; } + public int HandlerRegistrationCount { get; private set; } public List Submitted { get; } = new(); public void Connect(string host, int port) { } public void SendCultNet(T message) where T : ICultNetSchemaMessage @@ -364,10 +391,11 @@ public sealed class CultMeshClientTests _snapshotsToSuppress--; return; } + var recordKey = request.RecordKeys?.SingleOrDefault() ?? "surface:pilot"; var put = _documents.CreateRawDocumentPutMessage( "test-put", - new CultRecordHandle(new CultRecordKey("surface:pilot")), - new ClientTestDocument { Id = "surface:pilot", Text = _text }); + new CultRecordHandle(new CultRecordKey(recordKey)), + new ClientTestDocument { Id = recordKey, Text = _text }); var response = new CultNetSnapshotResponseRawMessage { MessageId = request.MessageId, @@ -377,6 +405,7 @@ public sealed class CultMeshClientTests } public void OnCultNet(Action callback) where T : ICultNetSchemaMessage { + HandlerRegistrationCount++; if (typeof(T) == typeof(CultNetSnapshotResponseRawMessage)) _snapshots.Add(response => callback((T)(object)response)); }