From 70f3e531908299326d4664491c6ef366b15792d6 Mon Sep 17 00:00:00 2001 From: Bruno Gale Date: Wed, 21 Oct 2026 01:19:45 +0200 Subject: [PATCH 1/4] fix(realtime): forget a channel on Unsubscribe Channel(name) returned the cached channel after Unsubscribe(), so presence Register threw and new handlers never fired. --- .../Channels/ChannelMessagingTests.cs | 47 +++++++++++++++++++ packages/Realtime/Realtime/Client.cs | 12 +++++ 2 files changed, 59 insertions(+) diff --git a/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs b/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs index 0ad96642..da5411e1 100644 --- a/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs +++ b/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; @@ -114,4 +115,50 @@ public async Task Channel_ShouldRegisterAndRemoveHandlers() await channel.Subscribe(); await Task.Delay(500); } + + [TestMethod] + public async Task Channel_ShouldDeliverToTheNewHandler_GivenResubscribeAfterUnsubscribe() + { + var oldHandlerFired = false; + var newHandlerFired = new TaskCompletionSource(); + var first = this.socketClient.Channel("resubscribe"); + first.Register(new PostgresChangesOptions("public", "todos", ListenType.Inserts)); + first.AddPostgresChangeHandler(ListenType.Inserts, (_, _) => oldHandlerFired = true); + await first.Subscribe(); + first.Unsubscribe(); + var second = this.socketClient.Channel("resubscribe"); + second.Register(new PostgresChangesOptions("public", "todos", ListenType.Inserts)); + second.AddPostgresChangeHandler(ListenType.Inserts, (_, _) => newHandlerFired.TrySetResult(true)); + await second.Subscribe(); + await this.restClient.Table().Insert(new Todo { UserId = 1 }); + await newHandlerFired.Task.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.IsFalse(oldHandlerFired, "the handler from before Unsubscribe must not fire"); + } + + [TestMethod] + public async Task Channel_ShouldAllowPresenceAgain_GivenResubscribeAfterUnsubscribe() + { + var first = this.socketClient.Channel("presence-again"); + first.Register("user-1"); + await first.Subscribe(); + first.Unsubscribe(); + var second = this.socketClient.Channel("presence-again"); + second.Register("user-1"); + await second.Subscribe(); + Assert.IsTrue(second.IsJoined); + } + + [TestMethod] + public async Task Subscribe_ShouldStillDeliver_GivenTheSameInstanceAfterUnsubscribe() + { + var fired = new TaskCompletionSource(); + var channel = this.socketClient.Channel("same-instance"); + channel.Register(new PostgresChangesOptions("public", "todos", ListenType.Inserts)); + channel.AddPostgresChangeHandler(ListenType.Inserts, (_, _) => fired.TrySetResult(true)); + await channel.Subscribe(); + channel.Unsubscribe(); + await channel.Subscribe(); + await this.restClient.Table().Insert(new Todo { UserId = 1 }); + Assert.IsTrue(await fired.Task.WaitAsync(TimeSpan.FromSeconds(10))); + } } diff --git a/packages/Realtime/Realtime/Client.cs b/packages/Realtime/Realtime/Client.cs index 7b1e40fc..cebbe9d7 100644 --- a/packages/Realtime/Realtime/Client.cs +++ b/packages/Realtime/Realtime/Client.cs @@ -358,6 +358,7 @@ public RealtimeChannel Channel(string channelName, ChannelOptions options) throw new Exception("Socket must exist, was `Connect` called?"); var subscription = new RealtimeChannel(this.Socket!, topic, options); + subscription.AddStateChangedHandler(this.HandleChannelStateChanged); this.subscriptions.Add(topic, subscription); return subscription; @@ -390,12 +391,23 @@ public RealtimeChannel Channel(string database = "realtime", string schema = "pu var subscription = new RealtimeChannel(this.Socket!, key, options); subscription.RegisterPostgresChangesOptions(changesOptions); + subscription.AddStateChangedHandler(this.HandleChannelStateChanged); this.subscriptions.Add(key, subscription); return subscription; } + // Forget a closed channel so Channel(name) returns a fresh one. If the old one joins again, it comes back. + private void HandleChannelStateChanged(IRealtimeChannel sender, ChannelState state) + { + var channel = (RealtimeChannel) sender; + if (state == ChannelState.Closed && this.subscriptions.TryGetValue(channel.Topic, out var current) && current == channel) + this.subscriptions.Remove(channel.Topic); + else if (state == ChannelState.Joining) + this.subscriptions.TryAdd(channel.Topic, channel); + } + /// /// Removes a channel subscription. /// From 233bd56a043bc82cd20966bfe73cc89b5c593ad4 Mon Sep 17 00:00:00 2001 From: Bruno Gale Date: Wed, 21 Oct 2026 11:49:40 +0200 Subject: [PATCH 2/4] test(realtime): unit tests for the channel cache Use OnPostgresChange in the new E2E tests, and move the fake websocket to Support so the client can connect without a server. --- .../Channels/ChannelMessagingTests.cs | 9 +- .../Channels/ClientChannelCacheTests.cs | 72 ++++++++++++++ .../Socket/WebSocketFactoryInjectionTests.cs | 81 +--------------- .../Realtime.Tests/Support/FakeWebSocket.cs | 96 +++++++++++++++++++ 4 files changed, 172 insertions(+), 86 deletions(-) create mode 100644 packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs create mode 100644 packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs diff --git a/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs b/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs index da5411e1..fd53d984 100644 --- a/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs +++ b/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs @@ -122,13 +122,11 @@ public async Task Channel_ShouldDeliverToTheNewHandler_GivenResubscribeAfterUnsu var oldHandlerFired = false; var newHandlerFired = new TaskCompletionSource(); var first = this.socketClient.Channel("resubscribe"); - first.Register(new PostgresChangesOptions("public", "todos", ListenType.Inserts)); - first.AddPostgresChangeHandler(ListenType.Inserts, (_, _) => oldHandlerFired = true); + first.OnPostgresChange((_, _) => oldHandlerFired = true, ListenType.Inserts, new PostgresChangesFilter { Table = "todos" }); await first.Subscribe(); first.Unsubscribe(); var second = this.socketClient.Channel("resubscribe"); - second.Register(new PostgresChangesOptions("public", "todos", ListenType.Inserts)); - second.AddPostgresChangeHandler(ListenType.Inserts, (_, _) => newHandlerFired.TrySetResult(true)); + second.OnPostgresChange((_, _) => newHandlerFired.TrySetResult(true), ListenType.Inserts, new PostgresChangesFilter { Table = "todos" }); await second.Subscribe(); await this.restClient.Table().Insert(new Todo { UserId = 1 }); await newHandlerFired.Task.WaitAsync(TimeSpan.FromSeconds(10)); @@ -153,8 +151,7 @@ public async Task Subscribe_ShouldStillDeliver_GivenTheSameInstanceAfterUnsubscr { var fired = new TaskCompletionSource(); var channel = this.socketClient.Channel("same-instance"); - channel.Register(new PostgresChangesOptions("public", "todos", ListenType.Inserts)); - channel.AddPostgresChangeHandler(ListenType.Inserts, (_, _) => fired.TrySetResult(true)); + channel.OnPostgresChange((_, _) => fired.TrySetResult(true), ListenType.Inserts, new PostgresChangesFilter { Table = "todos" }); await channel.Subscribe(); channel.Unsubscribe(); await channel.Subscribe(); diff --git a/packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs b/packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs new file mode 100644 index 00000000..4b64a59a --- /dev/null +++ b/packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs @@ -0,0 +1,72 @@ +using System.Threading.Tasks; +using FluentAssertions; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Realtime.Tests.Support; +using Supabase.Realtime; + +namespace Realtime.Tests.Channels; + +/// +/// The client hands out a fresh channel after the cached one is unsubscribed. Runs over a fake socket that +/// reports itself connected, so no server is needed. +/// +[TestClass] +[TestCategory("Unit")] +public class ClientChannelCacheTests +{ + private Client client = null!; + + [TestInitialize] + public async Task Connect() + { + var socket = new FakeWebsocketClient { OpenOnStart = true }; + this.client = new Client("ws://localhost/socket", new ClientOptions { WebSocketFactory = new FakeWebSocketFactory(socket) }); + await this.client.ConnectAsync(); + } + + [TestMethod] + public void Channel_ShouldReturnAFreshChannel_GivenUnsubscribe() + { + var first = this.client.Channel("room"); + first.Unsubscribe(); + this.client.Channel("room").Should().NotBeSameAs(first); + } + + [TestMethod] + public void Channel_ShouldReturnAFreshChannel_GivenUnsubscribeOnATableChannel() + { + var first = this.client.Channel("realtime", "public", "todos"); + first.Unsubscribe(); + this.client.Channel("realtime", "public", "todos").Should().NotBeSameAs(first); + } + + [TestMethod] + public void Unsubscribe_ShouldKeepTheNewerChannel_GivenAStaleChannelClosesAgain() + { + var first = this.client.Channel("room"); + first.Unsubscribe(); + var second = this.client.Channel("room"); + first.Unsubscribe(); + this.client.Channel("room").Should().BeSameAs(second); + } + + [TestMethod] + public async Task Subscribe_ShouldKeepTheChannel_GivenItIsJoining() + { + var channel = this.client.Channel("room"); + _ = channel.Subscribe(100); + await Task.Yield(); + this.client.Channel("room").Should().BeSameAs(channel); + } + + [TestMethod] + public async Task Subscribe_ShouldAddTheChannelBack_GivenTheSameInstanceAfterUnsubscribe() + { + var channel = this.client.Channel("room"); + channel.Unsubscribe(); + // No server answers the join; only the moment it starts joining matters here. + _ = channel.Subscribe(100); + await Task.Yield(); + this.client.Channel("room").Should().BeSameAs(channel); + } +} diff --git a/packages/Realtime/Realtime.Tests/Socket/WebSocketFactoryInjectionTests.cs b/packages/Realtime/Realtime.Tests/Socket/WebSocketFactoryInjectionTests.cs index 4363cfe1..c5877988 100644 --- a/packages/Realtime/Realtime.Tests/Socket/WebSocketFactoryInjectionTests.cs +++ b/packages/Realtime/Realtime.Tests/Socket/WebSocketFactoryInjectionTests.cs @@ -1,12 +1,8 @@ -using System; -using System.Buffers; using System.Collections.Generic; -using System.Net.WebSockets; -using System.Reactive.Subjects; -using System.Text; using System.Threading.Tasks; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; +using Realtime.Tests.Support; using Supabase.Realtime; using Supabase.Realtime.Sockets; using Websocket.Client; @@ -76,79 +72,4 @@ public void HeadersProvider_ShouldReEvaluateLazily_GivenALateSetGetHeaders() factory.HeadersProvider!().Should().ContainKey("X-Late", "the header provider must be re-invoked at connect time so headers set after construction are honored"); } - - private sealed class FakeWebSocketFactory(IWebsocketClient client) : IWebSocketFactory - { - public Uri? CreatedUri { get; private set; } - public Func>? HeadersProvider { get; private set; } - - public IWebsocketClient Create(Uri uri, Func> headers) - { - this.CreatedUri = uri; - this.HeadersProvider = headers; - return client; - } - } - - /// Implements only the members actually touches; the rest are unreachable from this test and throw if hit. - private sealed class FakeWebsocketClient : IWebsocketClient - { - public int StartOrFailCallCount { get; private set; } - public bool IsRunning { get; set; } - - public IObservable MessageReceived => this.messageReceived; - public IObservable ReconnectionHappened => this.reconnectionHappened; - public IObservable DisconnectionHappened => this.disconnectionHappened; - - private readonly Subject messageReceived = new(); - private readonly Subject reconnectionHappened = new(); - private readonly Subject disconnectionHappened = new(); - - public TimeSpan? ReconnectTimeout { get; set; } - public TimeSpan? ErrorReconnectTimeout { get; set; } - - public Task StartOrFail() - { - this.StartOrFailCallCount++; - return Task.CompletedTask; - } - - public Task Stop(WebSocketCloseStatus status, string reason) - { - this.IsRunning = false; - return Task.FromResult(true); - } - - public bool Send(string message) => true; - - public void Dispose() { } - - // Unused by RealtimeSocket — not exercised by these tests. - public Uri Url { get; set; } = new("ws://localhost/unused"); - public TimeSpan ConnectTimeout { get; set; } - public TimeSpan? LostReconnectTimeout { get; set; } - public bool IsReconnectionEnabled { get; set; } - public string? Name { get; set; } - public bool IsStarted => this.IsRunning; - public bool TextSenderRunning => throw new NotImplementedException(); - public bool BinarySenderRunning => throw new NotImplementedException(); - public bool IsInsideLock => throw new NotImplementedException(); - public bool IsTextMessageConversionEnabled { get; set; } - public bool IsStreamDisposedAutomatically { get; set; } - public Encoding? MessageEncoding { get; set; } = Encoding.UTF8; - public ClientWebSocket NativeClient => throw new NotImplementedException(); - public Task Start() => throw new NotImplementedException(); - public Task StopOrFail(WebSocketCloseStatus status, string reason) => throw new NotImplementedException(); - public Task Reconnect() => throw new NotImplementedException(); - public Task ReconnectOrFail() => throw new NotImplementedException(); - public bool Send(byte[] message) => throw new NotImplementedException(); - public bool Send(ArraySegment message) => throw new NotImplementedException(); - public bool Send(ReadOnlySequence message) => throw new NotImplementedException(); - public Task SendInstant(string message) => throw new NotImplementedException(); - public Task SendInstant(byte[] message) => throw new NotImplementedException(); - public bool SendAsText(byte[] message) => throw new NotImplementedException(); - public bool SendAsText(ArraySegment message) => throw new NotImplementedException(); - public bool SendAsText(ReadOnlySequence message) => throw new NotImplementedException(); - public void StreamFakeMessage(ResponseMessage message) => throw new NotImplementedException(); - } } diff --git a/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs b/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs new file mode 100644 index 00000000..2e28f79b --- /dev/null +++ b/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs @@ -0,0 +1,96 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Net.WebSockets; +using System.Reactive.Subjects; +using System.Text; +using System.Threading.Tasks; +using Supabase.Realtime; +using Supabase.Realtime.Sockets; +using Websocket.Client; + +namespace Realtime.Tests.Support; + +internal sealed class FakeWebSocketFactory(IWebsocketClient client) : IWebSocketFactory +{ + public Uri? CreatedUri { get; private set; } + public Func>? HeadersProvider { get; private set; } + + public IWebsocketClient Create(Uri uri, Func> headers) + { + this.CreatedUri = uri; + this.HeadersProvider = headers; + return client; + } +} + +/// Implements only the members actually touches; the rest are unreachable from this test and throw if hit. +internal sealed class FakeWebsocketClient : IWebsocketClient +{ + public int StartOrFailCallCount { get; private set; } + public bool IsRunning { get; set; } + + public IObservable MessageReceived => this.messageReceived; + public IObservable ReconnectionHappened => this.reconnectionHappened; + public IObservable DisconnectionHappened => this.disconnectionHappened; + + private readonly Subject messageReceived = new(); + private readonly Subject reconnectionHappened = new(); + private readonly Subject disconnectionHappened = new(); + + public TimeSpan? ReconnectTimeout { get; set; } + public TimeSpan? ErrorReconnectTimeout { get; set; } + + /// When set, starting the client reports it as connected, the way the real transport does. + public bool OpenOnStart { get; init; } + + public Task StartOrFail() + { + this.StartOrFailCallCount++; + if (this.OpenOnStart) + { + this.IsRunning = true; + this.reconnectionHappened.OnNext(ReconnectionInfo.Create(ReconnectionType.Initial)); + } + + return Task.CompletedTask; + } + + public Task Stop(WebSocketCloseStatus status, string reason) + { + this.IsRunning = false; + return Task.FromResult(true); + } + + public bool Send(string message) => true; + + public void Dispose() { } + + // Unused by RealtimeSocket — not exercised by these tests. + public Uri Url { get; set; } = new("ws://localhost/unused"); + public TimeSpan ConnectTimeout { get; set; } + public TimeSpan? LostReconnectTimeout { get; set; } + public bool IsReconnectionEnabled { get; set; } + public string? Name { get; set; } + public bool IsStarted => this.IsRunning; + public bool TextSenderRunning => throw new NotImplementedException(); + public bool BinarySenderRunning => throw new NotImplementedException(); + public bool IsInsideLock => throw new NotImplementedException(); + public bool IsTextMessageConversionEnabled { get; set; } + public bool IsStreamDisposedAutomatically { get; set; } + public Encoding? MessageEncoding { get; set; } = Encoding.UTF8; + public ClientWebSocket NativeClient => throw new NotImplementedException(); + public Task Start() => throw new NotImplementedException(); + public Task StopOrFail(WebSocketCloseStatus status, string reason) => throw new NotImplementedException(); + public Task Reconnect() => throw new NotImplementedException(); + public Task ReconnectOrFail() => throw new NotImplementedException(); + public bool Send(byte[] message) => throw new NotImplementedException(); + public bool Send(ArraySegment message) => throw new NotImplementedException(); + public bool Send(ReadOnlySequence message) => throw new NotImplementedException(); + public Task SendInstant(string message) => throw new NotImplementedException(); + public Task SendInstant(byte[] message) => throw new NotImplementedException(); + public bool SendAsText(byte[] message) => throw new NotImplementedException(); + public bool SendAsText(ArraySegment message) => throw new NotImplementedException(); + public bool SendAsText(ReadOnlySequence message) => throw new NotImplementedException(); + public void StreamFakeMessage(ResponseMessage message) => throw new NotImplementedException(); +} From 46d3121462eaf2bdf362ddae4bd659ba9dbb25bf Mon Sep 17 00:00:00 2001 From: Bruno Gale Date: Wed, 21 Oct 2026 12:00:25 +0200 Subject: [PATCH 3/4] test(realtime): merge the two fresh channel tests --- .../Channels/ClientChannelCacheTests.cs | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs b/packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs index 4b64a59a..6cbe1660 100644 --- a/packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs +++ b/packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs @@ -27,17 +27,12 @@ public async Task Connect() [TestMethod] public void Channel_ShouldReturnAFreshChannel_GivenUnsubscribe() { - var first = this.client.Channel("room"); - first.Unsubscribe(); - this.client.Channel("room").Should().NotBeSameAs(first); - } - - [TestMethod] - public void Channel_ShouldReturnAFreshChannel_GivenUnsubscribeOnATableChannel() - { - var first = this.client.Channel("realtime", "public", "todos"); - first.Unsubscribe(); - this.client.Channel("realtime", "public", "todos").Should().NotBeSameAs(first); + var named = this.client.Channel("room"); + var table = this.client.Channel("realtime", "public", "todos"); + named.Unsubscribe(); + table.Unsubscribe(); + this.client.Channel("room").Should().NotBeSameAs(named); + this.client.Channel("realtime", "public", "todos").Should().NotBeSameAs(table); } [TestMethod] @@ -64,7 +59,6 @@ public async Task Subscribe_ShouldAddTheChannelBack_GivenTheSameInstanceAfterUns { var channel = this.client.Channel("room"); channel.Unsubscribe(); - // No server answers the join; only the moment it starts joining matters here. _ = channel.Subscribe(100); await Task.Yield(); this.client.Channel("room").Should().BeSameAs(channel); From baeeebc104e220bd605029406e3e03a024e042b3 Mon Sep 17 00:00:00 2001 From: Bruno Gale Date: Wed, 21 Oct 2026 15:12:06 +0200 Subject: [PATCH 4/4] test(realtime): tidy the fake websocket comments --- packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs b/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs index 2e28f79b..c0de0567 100644 --- a/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs +++ b/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs @@ -24,7 +24,7 @@ public IWebsocketClient Create(Uri uri, Func> headers } } -/// Implements only the members actually touches; the rest are unreachable from this test and throw if hit. +/// Implements only the members actually touches; the rest are unreachable from these tests and throw if hit. internal sealed class FakeWebsocketClient : IWebsocketClient { public int StartOrFailCallCount { get; private set; } @@ -41,7 +41,7 @@ internal sealed class FakeWebsocketClient : IWebsocketClient public TimeSpan? ReconnectTimeout { get; set; } public TimeSpan? ErrorReconnectTimeout { get; set; } - /// When set, starting the client reports it as connected, the way the real transport does. + /// When set, StartOrFail reports the client as connected. public bool OpenOnStart { get; init; } public Task StartOrFail() @@ -66,7 +66,7 @@ public Task Stop(WebSocketCloseStatus status, string reason) public void Dispose() { } - // Unused by RealtimeSocket — not exercised by these tests. + // Unused by RealtimeSocket, not exercised by these tests. public Uri Url { get; set; } = new("ws://localhost/unused"); public TimeSpan ConnectTimeout { get; set; } public TimeSpan? LostReconnectTimeout { get; set; }