Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions packages/Realtime/Realtime.Tests/Channels/ChannelMessagingTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
Expand Down Expand Up @@ -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<bool>();
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<Todo>().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<PresenceExample>("user-1");
await first.Subscribe();
first.Unsubscribe();
var second = this.socketClient.Channel("presence-again");
second.Register<PresenceExample>("user-1");
await second.Subscribe();
Assert.IsTrue(second.IsJoined);
}

[TestMethod]
public async Task Subscribe_ShouldStillDeliver_GivenTheSameInstanceAfterUnsubscribe()
{
var fired = new TaskCompletionSource<bool>();
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<Todo>().Insert(new Todo { UserId = 1 });
Assert.IsTrue(await fired.Task.WaitAsync(TimeSpan.FromSeconds(10)));
}
}
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
[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);
}
}
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<Dictionary<string, string>>? HeadersProvider { get; private set; }

public IWebsocketClient Create(Uri uri, Func<Dictionary<string, string>> headers)
{
this.CreatedUri = uri;
this.HeadersProvider = headers;
return client;
}
}

/// <summary>Implements only the <see cref="IWebsocketClient"/> members <see cref="RealtimeSocket"/> actually touches; the rest are unreachable from this test and throw if hit.</summary>
private sealed class FakeWebsocketClient : IWebsocketClient
{
public int StartOrFailCallCount { get; private set; }
public bool IsRunning { get; set; }

public IObservable<ResponseMessage> MessageReceived => this.messageReceived;
public IObservable<ReconnectionInfo> ReconnectionHappened => this.reconnectionHappened;
public IObservable<DisconnectionInfo> DisconnectionHappened => this.disconnectionHappened;

private readonly Subject<ResponseMessage> messageReceived = new();
private readonly Subject<ReconnectionInfo> reconnectionHappened = new();
private readonly Subject<DisconnectionInfo> disconnectionHappened = new();

public TimeSpan? ReconnectTimeout { get; set; }
public TimeSpan? ErrorReconnectTimeout { get; set; }

public Task StartOrFail()
{
this.StartOrFailCallCount++;
return Task.CompletedTask;
}

public Task<bool> 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<bool> 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<byte> message) => throw new NotImplementedException();
public bool Send(ReadOnlySequence<byte> 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<byte> message) => throw new NotImplementedException();
public bool SendAsText(ReadOnlySequence<byte> message) => throw new NotImplementedException();
public void StreamFakeMessage(ResponseMessage message) => throw new NotImplementedException();
}
}
96 changes: 96 additions & 0 deletions packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs
Original file line number Diff line number Diff line change
@@ -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<Dictionary<string, string>>? HeadersProvider { get; private set; }

public IWebsocketClient Create(Uri uri, Func<Dictionary<string, string>> headers)
{
this.CreatedUri = uri;
this.HeadersProvider = headers;
return client;
}
}

/// <summary>Implements only the <see cref="IWebsocketClient"/> members <see cref="RealtimeSocket"/> actually touches; the rest are unreachable from these tests and throw if hit.</summary>
internal sealed class FakeWebsocketClient : IWebsocketClient
{
public int StartOrFailCallCount { get; private set; }
public bool IsRunning { get; set; }

public IObservable<ResponseMessage> MessageReceived => this.messageReceived;
public IObservable<ReconnectionInfo> ReconnectionHappened => this.reconnectionHappened;
public IObservable<DisconnectionInfo> DisconnectionHappened => this.disconnectionHappened;

private readonly Subject<ResponseMessage> messageReceived = new();
private readonly Subject<ReconnectionInfo> reconnectionHappened = new();
private readonly Subject<DisconnectionInfo> disconnectionHappened = new();

public TimeSpan? ReconnectTimeout { get; set; }
public TimeSpan? ErrorReconnectTimeout { get; set; }

/// <summary>When set, <c>StartOrFail</c> reports the client as connected.</summary>
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<bool> 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<bool> 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<byte> message) => throw new NotImplementedException();
public bool Send(ReadOnlySequence<byte> 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<byte> message) => throw new NotImplementedException();
public bool SendAsText(ReadOnlySequence<byte> message) => throw new NotImplementedException();
public void StreamFakeMessage(ResponseMessage message) => throw new NotImplementedException();
}
12 changes: 12 additions & 0 deletions packages/Realtime/Realtime/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}

/// <summary>
/// Removes a channel subscription.
/// </summary>
Expand Down
Loading