diff --git a/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs b/packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs index 0ad96642..fd53d984 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,47 @@ 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.OnPostgresChange((_, _) => oldHandlerFired = true, ListenType.Inserts, new PostgresChangesFilter { Table = "todos" }); + await first.Subscribe(); + first.Unsubscribe(); + var second = this.socketClient.Channel("resubscribe"); + 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)); + 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.OnPostgresChange((_, _) => fired.TrySetResult(true), ListenType.Inserts, new PostgresChangesFilter { Table = "todos" }); + 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.Tests/Channels/ClientChannelCacheTests.cs b/packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs new file mode 100644 index 00000000..6cbe1660 --- /dev/null +++ b/packages/Realtime/Realtime.Tests/Channels/ClientChannelCacheTests.cs @@ -0,0 +1,66 @@ +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 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] + 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(); + _ = 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..c0de0567 --- /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 these tests 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, StartOrFail reports the client as connected. + 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(); +} 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. ///