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
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
using System;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using FluentAssertions.Execution;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Realtime.Tests.Models;
using Realtime.Tests.Support;
using Supabase.Realtime;
using Supabase.Realtime.Broadcast;
using Supabase.Realtime.Exceptions;
using Supabase.Realtime.Models;

namespace Realtime.Tests.Broadcast;

/// <summary>
/// A broadcast sent with a <see cref="BroadcastPersistence" /> asks the server to store it for replay: the
/// option goes out in the metadata of the binary user broadcast frame, and with <c>ack</c> on, the code of an
/// error reply reaches the caller.
/// </summary>
[TestClass]
[TestCategory("Unit")]
public class BroadcastPersistenceTests
{
private const string Topic = "realtime:room";
private const string Event = "chat";
private const string StoreForTheMaximumRetention = """{"persist":true}""";
private const byte UserBroadcastPush = 3;
private const byte BinaryEncoding = 0;
private const byte JsonEncoding = 1;
private const int LongestFieldInBytes = 255;
private static readonly TimeSpan Patience = TimeSpan.FromSeconds(5);
private static readonly byte[] Bytes = [0, 159, 146, 150, 255];

private readonly FakeWebsocketClient socket = new() { OpenOnStart = true, AnswerJoins = true };
private readonly ClientOptions options = new() { ProtocolVersion = ProtocolVersion.V2 };
private Client client = null!;
private RealtimeChannel channel = null!;

[TestInitialize]
public void CreateClient()
{
this.options.WebSocketFactory = new FakeWebSocketFactory(this.socket);
this.client = new Client("ws://localhost/socket", this.options);
}

[TestCleanup]
public void Disconnect() => this.client.Disconnect();

[TestMethod]
[DataRow(null, StoreForTheMaximumRetention)]
[DataRow(3600, """{"persist":{"ttl":3600}}""")]
public async Task SendAsync_ShouldPutThePersistOptionInTheFrameMetadata(int? ttlSeconds, string metadata)
{
var broadcast = await this.Joined();
await broadcast.SendAsync(Event, new { text = "hi" }, new BroadcastPersistence(ttlSeconds is { } seconds ? TimeSpan.FromSeconds(seconds) : null));
(await this.SentFrame()).Should().Equal(this.Frame(metadata, JsonEncoding, Utf8("""{"text":"hi"}""")), "the server reads persist only from the frame metadata, so the JSON payload must go out as given");
}

[TestMethod]
public async Task SendAsync_ShouldPushTheBytesBinaryEncoded_GivenAByteArray()
{
byte[] reused = [.. Bytes];
var broadcast = await this.Joined();
await broadcast.SendAsync(Event, reused, new BroadcastPersistence());
Array.Clear(reused);
(await this.SentFrame()).Should().Equal(this.Frame(StoreForTheMaximumRetention, BinaryEncoding, Bytes), "a byte array must go out with the binary encoding, as it was at the call");
}

[TestMethod]
public async Task SendAsync_ShouldComplete_GivenAnOkReply()
{
var broadcast = await this.Joined(acknowledged: true);
var send = broadcast.SendAsync(Event, Bytes, new BroadcastPersistence());
this.socket.Reply(Topic, this.channel.LastPush!.Ref);
await send.Awaiting(s => s).Should().CompleteWithinAsync(Patience, "an ok reply means the server stored the message");
}

[TestMethod]
[DataRow("persistence_unauthorized", FailureHint.Reason.PersistenceUnauthorized)]
[DataRow("persistence_failed", FailureHint.Reason.PersistenceFailed)]
[DataRow("persistence_invalid_ttl", FailureHint.Reason.PersistenceInvalidTtl)]
[DataRow("persistence_unheard_of", FailureHint.Reason.Unknown)]
public async Task SendAsync_ShouldThrowTheServerCode_GivenAnErrorReply(string code, FailureHint.Reason reason)
{
var broadcast = await this.Joined(acknowledged: true);
var send = broadcast.SendAsync(Event, Bytes, new BroadcastPersistence());
this.socket.Reply(Topic, this.channel.LastPush!.Ref, "error", $$"""{"error":"{{code}}"}""");
var exception = (await send.Awaiting(s => s).Should().ThrowWithinAsync<RealtimeException>(Patience)).Which;
using (new AssertionScope())
{
exception.Reason.Should().Be(reason, "the server names why it did not store the message, and a code this client does not know must still be accepted");
exception.Message.Should().Contain(code, "the caller must see the code the server sent");
}
}

[TestMethod]
public async Task SendAsync_ShouldThrowAndSendNothing_GivenAPublicChannel()
{
var broadcast = await this.Joined(isPrivate: false);
(await broadcast.Awaiting(b => b.SendAsync(Event, Bytes, new BroadcastPersistence())).Should().ThrowAsync<RealtimeException>()).WithMessage("A persisted broadcast needs a private channel.", "the server ignores persist on a public channel and still replies ok");
this.channel.LastPush.Should().BeNull("nothing must be sent for a message the server would not store");
}

[TestMethod]
public async Task SendAsync_ShouldThrowAndSendNothing_GivenProtocolV1()
{
this.options.ProtocolVersion = ProtocolVersion.V1;
var broadcast = await this.Joined();
(await broadcast.Awaiting(b => b.SendAsync(Event, Bytes, new BroadcastPersistence())).Should().ThrowAsync<RealtimeException>()).WithMessage("A persisted broadcast needs ClientOptions.ProtocolVersion set to V2.", "only the binary frame of protocol 2.0.0 carries the metadata the server reads persist from");
this.channel.LastPush.Should().BeNull("nothing must be sent for a message the server would not store");
}

[TestMethod]
public async Task SendAsync_ShouldThrowAndSendNothing_GivenABroadcastModel()
{
var broadcast = await this.Joined();
(await broadcast.Awaiting(b => b.SendAsync(Event, new BroadcastExample { UserId = "1" }, new BroadcastPersistence())).Should().ThrowAsync<ArgumentException>()).WithMessage("A persisted broadcast takes the payload itself, not a BaseBroadcast.*", "the frame already carries the event, so a model would reach receivers nested inside the payload");
this.channel.LastPush.Should().BeNull("nothing must be sent for a payload the receivers would not read");
}

[TestMethod]
public async Task SendAsync_ShouldThrow_GivenAnEventNameOverTheLongestSize()
{
var broadcast = await this.Joined();
(await broadcast.Awaiting(b => b.SendAsync(new string('e', LongestFieldInBytes + 1), Bytes, new BroadcastPersistence())).Should().ThrowAsync<ArgumentException>()).WithMessage("The event name of a persisted broadcast must fit in 255 bytes.*", "a binary frame has one byte for the size of the event name");
}

[TestMethod]
public async Task SendAsync_ShouldThrow_GivenATopicOverTheLongestSize()
{
var broadcast = await this.Joined(new string('t', LongestFieldInBytes));
(await broadcast.Awaiting(b => b.SendAsync(Event, Bytes, new BroadcastPersistence())).Should().ThrowAsync<RealtimeException>()).WithMessage("The topic of a persisted broadcast must fit in 255 bytes.", "a binary frame has one byte for the size of the topic");
}

[TestMethod]
public async Task SendAsync_ShouldComplete_GivenCallerBlockingOnContextThatNeverRunsContinuations()
{
var broadcast = await this.Joined(acknowledged: true);
BlockingCaller.Completes(() =>
{
var sending = broadcast.SendAsync(Event, Bytes, new BroadcastPersistence());
Task.Run(() => this.socket.Reply(Topic, this.channel.LastPush!.Ref));
return sending;
}).Should().BeTrue("the SDK must not resume on the caller's synchronization context");
}

private async Task<RealtimeBroadcast<BaseBroadcast>> Joined(string channelName = "room", bool isPrivate = true, bool acknowledged = false)
{
var firstHeartbeat = this.socket.SentText("heartbeat", 1);
await this.client.ConnectAsync();
await firstHeartbeat.WaitAsync(Patience);
this.channel = isPrivate ? this.client.PrivateChannel(channelName) : this.client.Channel(channelName);
var broadcast = this.channel.Register<BaseBroadcast>(broadcastAck: acknowledged);
await this.channel.Subscribe().WaitAsync(Patience);
return broadcast;
}

private Task<byte[]> SentFrame() => this.socket.SentBinary.Task.WaitAsync(Patience);

private byte[] Frame(string metadata, byte encoding, byte[] payload)
{
var joinRef = this.channel.JoinPush!.Ref!;
var reference = this.channel.LastPush!.Ref!;
return [UserBroadcastPush, (byte) joinRef.Length, (byte) reference.Length, (byte) Topic.Length, (byte) Event.Length, (byte) metadata.Length, encoding, .. Utf8(joinRef + reference + Topic + Event + metadata), .. payload];
}

private static byte[] Utf8(string text) => Encoding.UTF8.GetBytes(text);
}
31 changes: 31 additions & 0 deletions packages/Realtime/Realtime.Tests/HttpSend/HttpSendRequestTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Realtime.Tests.Support;
using Supabase.Realtime;
using Supabase.Realtime.Broadcast;
using Supabase.Realtime.Channel;
using Supabase.Realtime.Exceptions;
using WireMock;
Expand Down Expand Up @@ -78,6 +79,36 @@ public async Task HttpSendAsync_ShouldSendThePrivateFlag_GivenAPrivateChannel()
this.SentRequest().RawQuery.Should().Be("?private=true");
}

[TestMethod]
[DataRow(null, "?private=true&persist=true")]
[DataRow(3600, "?private=true&persist[ttl]=3600")]
[DataRow(0, "?private=true&persist[ttl]=0")]
public async Task HttpSendAsync_ShouldAskToStoreTheMessageInTheQuery_GivenAPersistence(int? ttlSeconds, string query)
{
await this.Channel(options: Wire.PrivateOptions()).HttpSendAsync("cursor", new { x = 1 }, new BroadcastPersistence(ttlSeconds is { } seconds ? TimeSpan.FromSeconds(seconds) : null));
var sent = this.SentRequest();
using (new AssertionScope())
{
sent.RawQuery.Should().Be(query, "the server reads persist only from the query string, and owns the range of the ttl");
sent.Body.Should().Be("""{"x":1}""", "a persist key in the body would be delivered as data");
}
}

[TestMethod]
public async Task HttpSendAsync_ShouldThrowAndSendNothing_GivenAPersistenceOnAPublicChannel()
{
var act = () => this.Channel().HttpSendAsync("cursor", new { x = 1 }, new BroadcastPersistence());
(await act.Should().ThrowAsync<RealtimeException>()).WithMessage("A persisted broadcast needs a private channel.");
this.server.LogEntries.Should().BeEmpty("the server answers 422 to persist on a public channel");
}

[TestMethod]
public async Task HttpSendAsync_ShouldThrow_GivenNoPersistence()
{
var act = () => this.Channel(options: Wire.PrivateOptions()).HttpSendAsync("cursor", new { x = 1 }, null!);
await act.Should().ThrowAsync<ArgumentNullException>();
}

[TestMethod]
public async Task HttpSendAsync_ShouldSendTheClientHeaders()
{
Expand Down
8 changes: 4 additions & 4 deletions packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,11 +152,11 @@ private static JsonNode AsObject(string text)
}

/// <summary>Delivers the server's reply to the frame sent with <paramref name="reference" />, in the protocol version the socket last wrote.</summary>
public void Reply(string topic, string? reference, string status = "ok") =>
public void Reply(string topic, string? reference, string status = "ok", string response = "{}") =>
this.Receive((this.speaksArrays
? """[null,"REF","TOPIC","phx_reply",{"status":"STATUS","response":{}}]"""
: """{"topic":"TOPIC","event":"phx_reply","ref":"REF","payload":{"status":"STATUS","response":{}}}""")
.Replace("TOPIC", topic).Replace("REF", reference).Replace("STATUS", status));
? """[null,"REF","TOPIC","phx_reply",{"status":"STATUS","response":RESPONSE}]"""
: """{"topic":"TOPIC","event":"phx_reply","ref":"REF","payload":{"status":"STATUS","response":RESPONSE}}""")
.Replace("TOPIC", topic).Replace("REF", reference).Replace("STATUS", status).Replace("RESPONSE", response));

public Task Reconnect()
{
Expand Down
11 changes: 9 additions & 2 deletions packages/Realtime/Realtime/Broadcast/BinaryBroadcast.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
namespace Supabase.Realtime.Broadcast;

/// <summary>
/// The payload of a push that goes out as a binary user broadcast frame.
/// The payload of a push that goes out as a binary user broadcast frame. A JSON payload goes out this way when
/// it carries metadata.
/// </summary>
internal sealed class BinaryBroadcast
{
internal BinaryBroadcast(string userEvent, byte[] payload)
internal BinaryBroadcast(string userEvent, byte[] payload, bool isJson = false, string metadata = "")
{
this.Event = userEvent;
this.Payload = payload;
this.IsJson = isJson;
this.Metadata = metadata;
}

internal string Event { get; }

internal byte[] Payload { get; }

internal bool IsJson { get; }

internal string Metadata { get; }
}
26 changes: 26 additions & 0 deletions packages/Realtime/Realtime/Broadcast/BroadcastPersistence.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System;
using System.Globalization;

namespace Supabase.Realtime.Broadcast;

/// <summary>
/// Asks the server to store a broadcast sent on a private channel, so it can be replayed when a channel joins.
/// </summary>
public sealed class BroadcastPersistence
{
/// <summary>
/// Stores the broadcast for <paramref name="ttl"/>, sent in whole seconds, or for the maximum retention when null.
/// </summary>
public BroadcastPersistence(TimeSpan? ttl = null) => this.Ttl = ttl;

/// <summary>
/// How long the server keeps the broadcast. Null keeps it for the maximum retention.
/// </summary>
public TimeSpan? Ttl { get; }

internal string Metadata => this.Ttl == null ? "{\"persist\":true}" : $"{{\"persist\":{{\"ttl\":{this.TtlSeconds}}}}}";

internal string Query => this.Ttl == null ? "persist=true" : $"persist[ttl]={this.TtlSeconds}";

private string TtlSeconds => ((long) this.Ttl!.Value.TotalSeconds).ToString(CultureInfo.InvariantCulture);
}
2 changes: 2 additions & 0 deletions packages/Realtime/Realtime/ClientOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,6 @@ public class ClientOptions
/// <see cref="IWebSocketFactory"/> and are not affected.
/// </summary>
public TimeProvider TimeProvider { get; set; } = TimeProvider.System;

internal bool IsProtocolVersionV2() => this.ProtocolVersion == ProtocolVersion.V2;
}
23 changes: 23 additions & 0 deletions packages/Realtime/Realtime/Exceptions/FailureHint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,21 @@ public enum Reason
/// Cannot make changes after subscribe
/// </summary>
StateInvalid,

/// <summary>
/// The sender has no policy that lets it store a broadcast. The broadcast was delivered but not stored.
/// </summary>
PersistenceUnauthorized,

/// <summary>
/// The server failed to store a broadcast. The broadcast was delivered but not stored.
/// </summary>
PersistenceFailed,

/// <summary>
/// The server refused the ttl. The broadcast was neither delivered nor stored.
/// </summary>
PersistenceInvalidTtl,
}

/// <summary>
Expand All @@ -70,4 +85,12 @@ public static Reason Parse(DisconnectionInfo info)
_ => Reason.Unknown,
};
}

internal static Reason Parse(string? code) => code switch
{
"persistence_unauthorized" => Reason.PersistenceUnauthorized,
"persistence_failed" => Reason.PersistenceFailed,
"persistence_invalid_ttl" => Reason.PersistenceInvalidTtl,
_ => Reason.Unknown,
};
}
11 changes: 7 additions & 4 deletions packages/Realtime/Realtime/HttpSend/HttpBroadcaster.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Supabase.Realtime.Broadcast;
using Supabase.Realtime.Exceptions;

namespace Supabase.Realtime.HttpSend;
Expand All @@ -30,9 +31,9 @@ internal HttpBroadcaster(string realtimeUrl, ClientOptions options, Func<Diction
this.getHeaders = getHeaders;
}

internal async Task SendAsync(RealtimeChannel channel, string eventName, object payload, CancellationToken cancellationToken)
internal async Task SendAsync(RealtimeChannel channel, string eventName, object payload, BroadcastPersistence? persistence, CancellationToken cancellationToken)
{
using var request = new HttpRequestMessage(HttpMethod.Post, this.BuildUrl(channel, eventName))
using var request = new HttpRequestMessage(HttpMethod.Post, this.BuildUrl(channel, eventName, persistence))
{
Content = BuildContent(payload, channel.Options.SerializerSettings)
};
Expand All @@ -45,13 +46,15 @@ internal async Task SendAsync(RealtimeChannel channel, string eventName, object
throw new RealtimeException(await response.Content.ReadAsStringAsync()) { StatusCode = (int) response.StatusCode };
}

private string BuildUrl(RealtimeChannel channel, string eventName)
private string BuildUrl(RealtimeChannel channel, string eventName, BroadcastPersistence? persistence)
{
var topic = channel.Topic.StartsWith(TopicPrefix, StringComparison.Ordinal)
? channel.Topic.Substring(TopicPrefix.Length)
: channel.Topic;
var url = $"{this.endpoint}/{Uri.EscapeDataString(topic)}/events/{Uri.EscapeDataString(eventName)}";
return channel.Options.IsPrivate ? $"{url}?private=true" : url;
if (!channel.Options.IsPrivate)
return url;
return persistence == null ? $"{url}?private=true" : $"{url}?private=true&{persistence.Query}";
}

private static HttpContent BuildContent(object payload, JsonSerializerOptions serializerOptions) =>
Expand Down
19 changes: 19 additions & 0 deletions packages/Realtime/Realtime/Interfaces/IRealtimeBroadcast.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Supabase.Realtime.Broadcast;
using Supabase.Realtime.Models;
using Supabase.Realtime.Socket;
using static Supabase.Realtime.Constants;
Expand Down Expand Up @@ -61,6 +62,24 @@ public interface IRealtimeBroadcast
/// </example>
Task SendBinary(string broadcastEventName, byte[] payload, int timeoutMs = DefaultTimeout);

/// <summary>
/// Sends a broadcast that the server stores for replay. Needs a private channel and a client that speaks
/// <see cref="ProtocolVersion.V2"/>. Unlike <see cref="Send"/>, it takes the payload itself, not a
/// <see cref="BaseBroadcast"/>: a <c>byte[]</c> is sent as bytes, anything else as JSON. With
/// <see cref="BroadcastOptions.BroadcastAck"/> on, the send fails when the server did not store the broadcast.
/// </summary>
/// <exception cref="Supabase.Realtime.Exceptions.RealtimeException">The channel is public, the client speaks protocol 1.0.0, the channel topic is longer than 255 bytes, or the server did not store the broadcast or did not acknowledge it in time.</exception>
/// <exception cref="ArgumentException">The payload is a <see cref="BaseBroadcast"/>, or the event name is longer than 255 bytes.</exception>
/// <example>
/// <code>
/// var channel = client.PrivateChannel("room");
/// var broadcast = channel.Register&lt;BaseBroadcast&gt;(broadcastAck: true);
/// await channel.Subscribe();
/// await broadcast.SendAsync("chat", new { text = "hi" }, new BroadcastPersistence(TimeSpan.FromHours(1)));
/// </code>
/// </example>
Task SendAsync(string eventName, object payload, BroadcastPersistence persistence, int timeoutMs = DefaultTimeout);

/// <summary>
/// An internal trigger used for notifying event delegates.
/// </summary>
Expand Down
Loading
Loading