diff --git a/packages/Realtime/Realtime.Tests/Broadcast/BroadcastPersistenceTests.cs b/packages/Realtime/Realtime.Tests/Broadcast/BroadcastPersistenceTests.cs new file mode 100644 index 00000000..a7628bee --- /dev/null +++ b/packages/Realtime/Realtime.Tests/Broadcast/BroadcastPersistenceTests.cs @@ -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; + +/// +/// A broadcast sent with a asks the server to store it for replay: the +/// option goes out in the metadata of the binary user broadcast frame, and with ack on, the code of an +/// error reply reaches the caller. +/// +[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(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()).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()).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()).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()).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()).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> 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(broadcastAck: acknowledged); + await this.channel.Subscribe().WaitAsync(Patience); + return broadcast; + } + + private Task 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); +} diff --git a/packages/Realtime/Realtime.Tests/HttpSend/HttpSendRequestTests.cs b/packages/Realtime/Realtime.Tests/HttpSend/HttpSendRequestTests.cs index 7068f36d..917eabe0 100644 --- a/packages/Realtime/Realtime.Tests/HttpSend/HttpSendRequestTests.cs +++ b/packages/Realtime/Realtime.Tests/HttpSend/HttpSendRequestTests.cs @@ -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; @@ -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()).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(); + } + [TestMethod] public async Task HttpSendAsync_ShouldSendTheClientHeaders() { diff --git a/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs b/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs index fc02290e..f4d4e97a 100644 --- a/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs +++ b/packages/Realtime/Realtime.Tests/Support/FakeWebSocket.cs @@ -152,11 +152,11 @@ private static JsonNode AsObject(string text) } /// Delivers the server's reply to the frame sent with , in the protocol version the socket last wrote. - 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() { diff --git a/packages/Realtime/Realtime/Broadcast/BinaryBroadcast.cs b/packages/Realtime/Realtime/Broadcast/BinaryBroadcast.cs index 8d015c8a..e01bea0c 100644 --- a/packages/Realtime/Realtime/Broadcast/BinaryBroadcast.cs +++ b/packages/Realtime/Realtime/Broadcast/BinaryBroadcast.cs @@ -1,17 +1,24 @@ namespace Supabase.Realtime.Broadcast; /// -/// 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. /// 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; } } diff --git a/packages/Realtime/Realtime/Broadcast/BroadcastPersistence.cs b/packages/Realtime/Realtime/Broadcast/BroadcastPersistence.cs new file mode 100644 index 00000000..9b44daaf --- /dev/null +++ b/packages/Realtime/Realtime/Broadcast/BroadcastPersistence.cs @@ -0,0 +1,26 @@ +using System; +using System.Globalization; + +namespace Supabase.Realtime.Broadcast; + +/// +/// Asks the server to store a broadcast sent on a private channel, so it can be replayed when a channel joins. +/// +public sealed class BroadcastPersistence +{ + /// + /// Stores the broadcast for , sent in whole seconds, or for the maximum retention when null. + /// + public BroadcastPersistence(TimeSpan? ttl = null) => this.Ttl = ttl; + + /// + /// How long the server keeps the broadcast. Null keeps it for the maximum retention. + /// + 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); +} diff --git a/packages/Realtime/Realtime/ClientOptions.cs b/packages/Realtime/Realtime/ClientOptions.cs index 762f16d1..d21b5167 100644 --- a/packages/Realtime/Realtime/ClientOptions.cs +++ b/packages/Realtime/Realtime/ClientOptions.cs @@ -149,4 +149,6 @@ public class ClientOptions /// and are not affected. /// public TimeProvider TimeProvider { get; set; } = TimeProvider.System; + + internal bool IsProtocolVersionV2() => this.ProtocolVersion == ProtocolVersion.V2; } diff --git a/packages/Realtime/Realtime/Exceptions/FailureHint.cs b/packages/Realtime/Realtime/Exceptions/FailureHint.cs index 229d4bdd..49aa9d0f 100644 --- a/packages/Realtime/Realtime/Exceptions/FailureHint.cs +++ b/packages/Realtime/Realtime/Exceptions/FailureHint.cs @@ -52,6 +52,21 @@ public enum Reason /// Cannot make changes after subscribe /// StateInvalid, + + /// + /// The sender has no policy that lets it store a broadcast. The broadcast was delivered but not stored. + /// + PersistenceUnauthorized, + + /// + /// The server failed to store a broadcast. The broadcast was delivered but not stored. + /// + PersistenceFailed, + + /// + /// The server refused the ttl. The broadcast was neither delivered nor stored. + /// + PersistenceInvalidTtl, } /// @@ -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, + }; } diff --git a/packages/Realtime/Realtime/HttpSend/HttpBroadcaster.cs b/packages/Realtime/Realtime/HttpSend/HttpBroadcaster.cs index a3b588c2..b229b859 100644 --- a/packages/Realtime/Realtime/HttpSend/HttpBroadcaster.cs +++ b/packages/Realtime/Realtime/HttpSend/HttpBroadcaster.cs @@ -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; @@ -30,9 +31,9 @@ internal HttpBroadcaster(string realtimeUrl, ClientOptions options, Func diff --git a/packages/Realtime/Realtime/Interfaces/IRealtimeBroadcast.cs b/packages/Realtime/Realtime/Interfaces/IRealtimeBroadcast.cs index 8ae9a821..5b0c024f 100644 --- a/packages/Realtime/Realtime/Interfaces/IRealtimeBroadcast.cs +++ b/packages/Realtime/Realtime/Interfaces/IRealtimeBroadcast.cs @@ -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; @@ -61,6 +62,24 @@ public interface IRealtimeBroadcast /// Task SendBinary(string broadcastEventName, byte[] payload, int timeoutMs = DefaultTimeout); + /// + /// Sends a broadcast that the server stores for replay. Needs a private channel and a client that speaks + /// . Unlike , it takes the payload itself, not a + /// : a byte[] is sent as bytes, anything else as JSON. With + /// on, the send fails when the server did not store the broadcast. + /// + /// 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. + /// The payload is a , or the event name is longer than 255 bytes. + /// + /// + /// var channel = client.PrivateChannel("room"); + /// var broadcast = channel.Register<BaseBroadcast>(broadcastAck: true); + /// await channel.Subscribe(); + /// await broadcast.SendAsync("chat", new { text = "hi" }, new BroadcastPersistence(TimeSpan.FromHours(1))); + /// + /// + Task SendAsync(string eventName, object payload, BroadcastPersistence persistence, int timeoutMs = DefaultTimeout); + /// /// An internal trigger used for notifying event delegates. /// diff --git a/packages/Realtime/Realtime/Interfaces/IRealtimeChannel.cs b/packages/Realtime/Realtime/Interfaces/IRealtimeChannel.cs index a419a988..b2704444 100644 --- a/packages/Realtime/Realtime/Interfaces/IRealtimeChannel.cs +++ b/packages/Realtime/Realtime/Interfaces/IRealtimeChannel.cs @@ -246,6 +246,21 @@ IRealtimeChannel OnPostgresChange(PostgresChangesHandler postgresChangeHandler, /// Task HttpSendAsync(string eventName, object payload, CancellationToken cancellationToken = default); + /// + /// Broadcasts through the REST API and asks the server to store the message for replay. Needs a private channel. + /// + /// The channel is public, or the server rejected the broadcast. + /// + /// + /// var channel = client.PrivateChannel("room"); + /// await channel.HttpSendAsync("chat", new { text = "hi" }, new BroadcastPersistence()); + /// + /// + Task HttpSendAsync(string eventName, object payload, BroadcastPersistence persistence); + + /// + Task HttpSendAsync(string eventName, object payload, BroadcastPersistence persistence, CancellationToken cancellationToken); + /// /// Register broadcast options, must be called to use , and prior to /// diff --git a/packages/Realtime/Realtime/Interfaces/IRealtimeSocket.cs b/packages/Realtime/Realtime/Interfaces/IRealtimeSocket.cs index 3234fcbd..fb18029d 100644 --- a/packages/Realtime/Realtime/Interfaces/IRealtimeSocket.cs +++ b/packages/Realtime/Realtime/Interfaces/IRealtimeSocket.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using Supabase.Core.Interfaces; +using Supabase.Realtime.Broadcast; using Supabase.Realtime.Exceptions; using static Supabase.Realtime.Constants; @@ -148,5 +149,5 @@ public interface IRealtimeSocket: IGettableHeaders /// /// Broadcasts through the Realtime REST API. /// - internal Task HttpSendAsync(RealtimeChannel channel, string eventName, object payload, CancellationToken cancellationToken); + internal Task HttpSendAsync(RealtimeChannel channel, string eventName, object payload, BroadcastPersistence? persistence, CancellationToken cancellationToken); } \ No newline at end of file diff --git a/packages/Realtime/Realtime/PublicAPI.Unshipped.txt b/packages/Realtime/Realtime/PublicAPI.Unshipped.txt index 3216b47a..7236eee6 100644 --- a/packages/Realtime/Realtime/PublicAPI.Unshipped.txt +++ b/packages/Realtime/Realtime/PublicAPI.Unshipped.txt @@ -1,3 +1,15 @@ #nullable enable +Supabase.Realtime.Broadcast.BroadcastPersistence +Supabase.Realtime.Broadcast.BroadcastPersistence.BroadcastPersistence(System.TimeSpan? ttl = null) -> void +Supabase.Realtime.Broadcast.BroadcastPersistence.Ttl.get -> System.TimeSpan? Supabase.Realtime.ClientOptions.TimeProvider.get -> System.TimeProvider! Supabase.Realtime.ClientOptions.TimeProvider.set -> void +Supabase.Realtime.Exceptions.FailureHint.Reason.PersistenceFailed = 9 -> Supabase.Realtime.Exceptions.FailureHint.Reason +Supabase.Realtime.Exceptions.FailureHint.Reason.PersistenceInvalidTtl = 10 -> Supabase.Realtime.Exceptions.FailureHint.Reason +Supabase.Realtime.Exceptions.FailureHint.Reason.PersistenceUnauthorized = 8 -> Supabase.Realtime.Exceptions.FailureHint.Reason +Supabase.Realtime.Interfaces.IRealtimeBroadcast.SendAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence, int timeoutMs = 10000) -> System.Threading.Tasks.Task! +Supabase.Realtime.Interfaces.IRealtimeChannel.HttpSendAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence) -> System.Threading.Tasks.Task! +Supabase.Realtime.Interfaces.IRealtimeChannel.HttpSendAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! +Supabase.Realtime.RealtimeBroadcast.SendAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence, int timeoutMs = 10000) -> System.Threading.Tasks.Task! +Supabase.Realtime.RealtimeChannel.HttpSendAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence) -> System.Threading.Tasks.Task! +Supabase.Realtime.RealtimeChannel.HttpSendAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task! diff --git a/packages/Realtime/Realtime/RealtimeBroadcast.cs b/packages/Realtime/Realtime/RealtimeBroadcast.cs index 2a084844..3f1c3b52 100644 --- a/packages/Realtime/Realtime/RealtimeBroadcast.cs +++ b/packages/Realtime/Realtime/RealtimeBroadcast.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Text.Json; using System.Threading.Tasks; using Supabase.Core.Attributes; @@ -116,7 +117,7 @@ public Task Send(string? broadcastEventName, object payload, int timeoutMs /// public async Task SendBinary(string broadcastEventName, byte[] payload, int timeoutMs = DefaultTimeout) { - if (this.channel.Options.ClientOptions.ProtocolVersion != ProtocolVersion.V2) + if (!this.channel.Options.ClientOptions.IsProtocolVersionV2()) throw new RealtimeException("A broadcast of bytes needs ClientOptions.ProtocolVersion set to V2."); if (payload == null) throw new ArgumentNullException(nameof(payload)); @@ -128,4 +129,34 @@ public async Task SendBinary(string broadcastEventName, byte[] payload, int time if (!await this.channel.Send(ChannelEventName.Broadcast, null, new BinaryBroadcast(broadcastEventName, (byte[]) payload.Clone()), timeoutMs).ConfigureAwait(false)) throw new RealtimeException("The server rejected the broadcast of bytes."); } + + /// + [ImplementedCapability("realtime.channel.broadcast_persist")] + public async Task SendAsync(string eventName, object payload, BroadcastPersistence persistence, int timeoutMs = DefaultTimeout) + { + this.channel.EnsureCanPersist(persistence); + if (payload is BaseBroadcast) + throw new ArgumentException("A persisted broadcast takes the payload itself, not a BaseBroadcast.", nameof(payload)); + if (!this.channel.Options.ClientOptions.IsProtocolVersionV2()) + throw new RealtimeException("A persisted broadcast needs ClientOptions.ProtocolVersion set to V2."); + if (!WireFrame.Fits(eventName)) + throw new ArgumentException("The event name of a persisted broadcast must fit in 255 bytes.", nameof(eventName)); + if (!WireFrame.Fits(this.channel.Topic)) + throw new RealtimeException("The topic of a persisted broadcast must fit in 255 bytes."); + + var reply = await this.channel.SendForReply(ChannelEventName.Broadcast, null, this.PersistedBroadcast(eventName, payload, persistence), timeoutMs).ConfigureAwait(false); + if (reply != null && reply.Payload?.Status != PhoenixStatusOk) + throw NotStored(reply); + } + + private BinaryBroadcast PersistedBroadcast(string eventName, object payload, BroadcastPersistence persistence) => + payload is byte[] bytes + ? new BinaryBroadcast(eventName, (byte[]) bytes.Clone(), metadata: persistence.Metadata) + : new BinaryBroadcast(eventName, JsonSerializer.SerializeToUtf8Bytes(payload, this.serializerSettings), isJson: true, persistence.Metadata); + + private static RealtimeException NotStored(SocketResponse reply) + { + var code = reply.Payload?.Response is Dictionary body && body.TryGetValue("error", out var error) ? error as string : null; + return new RealtimeException($"The server did not store the broadcast ({code}).") { Reason = FailureHint.Parse(code) }; + } } diff --git a/packages/Realtime/Realtime/RealtimeChannel.cs b/packages/Realtime/Realtime/RealtimeChannel.cs index 8ea6ae95..f95bdaca 100644 --- a/packages/Realtime/Realtime/RealtimeChannel.cs +++ b/packages/Realtime/Realtime/RealtimeChannel.cs @@ -619,25 +619,58 @@ public Push Push(string eventName, string? type = null, object? payload = null, /// /// [ImplementedCapability("realtime.channel.broadcast")] - public Task Send(ChannelEventName eventName, string? type, object payload, int timeoutMs = DefaultTimeout) + public Task Send(ChannelEventName eventName, string? type, object payload, int timeoutMs = DefaultTimeout) => + IsOk(this.SendForReply(eventName, type, payload, timeoutMs)); + + /// + /// Sends a push and returns the server's reply, or null when the server sends none. + /// + internal Task SendForReply(ChannelEventName eventName, string? type, object payload, int timeoutMs) { var push = this.Push(Core.Helpers.GetMappedToAttr(eventName).Mapping, type, payload, timeoutMs); // The server only sends a `phx_reply` for a `broadcast` push when the channel joined // with `config.broadcast.ack = true`. Without that, no reply will ever arrive, so // waiting for one would hang forever - resolve as soon as the push has been dispatched. return eventName == ChannelEventName.Broadcast && this.BroadcastOptions?.BroadcastAck != true - ? Task.FromResult(true) + ? Task.FromResult(null) : PushAwaiter.Await(push); } + private static async Task IsOk(Task sending) + { + var reply = await sending.ConfigureAwait(false); + return reply == null || reply.Payload?.Status == PhoenixStatusOk; + } + /// [ImplementedCapability("realtime.channel.broadcast_http")] public Task HttpSendAsync(string eventName, object payload, CancellationToken cancellationToken = default) => - this.Socket.HttpSendAsync(this, eventName, payload, cancellationToken); + this.Socket.HttpSendAsync(this, eventName, payload, null, cancellationToken); + + /// + [ImplementedCapability("realtime.channel.broadcast_persist")] + public Task HttpSendAsync(string eventName, object payload, BroadcastPersistence persistence) => + this.HttpSendAsync(eventName, payload, persistence, CancellationToken.None); + + /// + [ImplementedCapability("realtime.channel.broadcast_persist")] + public Task HttpSendAsync(string eventName, object payload, BroadcastPersistence persistence, CancellationToken cancellationToken) + { + this.EnsureCanPersist(persistence); + return this.Socket.HttpSendAsync(this, eventName, payload, persistence, cancellationToken); + } + + internal void EnsureCanPersist(BroadcastPersistence persistence) + { + if (persistence == null) + throw new ArgumentNullException(nameof(persistence)); + if (!this.Options.IsPrivate) + throw new RealtimeException("A persisted broadcast needs a private channel."); + } /// - /// Awaits a reply for a given , resolving with whether the server replied - /// ok, or faulting with a if the push times out first. + /// Awaits a reply for a given , resolving with the reply, or faulting with a + /// if the push times out first. /// /// Kept as instance methods (rather than local lambdas referencing each other) so there's no /// self/mutually-referencing closure over locals that get assigned after the closure is created. @@ -645,7 +678,7 @@ public Task HttpSendAsync(string eventName, object payload, CancellationToken ca private sealed class PushAwaiter { private readonly Push push; - private readonly TaskCompletionSource taskCompletion = new(); + private readonly TaskCompletionSource taskCompletion = new(); private PushAwaiter(Push push) { @@ -656,12 +689,12 @@ private PushAwaiter(Push push) this.HandleMessageReceived(this.push, reply); } - public static Task Await(Push push) => new PushAwaiter(push).taskCompletion.Task; + public static Task Await(Push push) => new PushAwaiter(push).taskCompletion.Task; private void HandleMessageReceived(IRealtimePush sender, SocketResponse message) { this.Detach(); - this.taskCompletion.TrySetResult(message.Payload?.Status == PhoenixStatusOk); + this.taskCompletion.TrySetResult(message); } private void HandleTimeout(object sender, EventArgs e) diff --git a/packages/Realtime/Realtime/RealtimeSocket.cs b/packages/Realtime/Realtime/RealtimeSocket.cs index 29fbae3f..fb6c5971 100644 --- a/packages/Realtime/Realtime/RealtimeSocket.cs +++ b/packages/Realtime/Realtime/RealtimeSocket.cs @@ -119,8 +119,8 @@ public RealtimeSocket(string endpoint, ClientOptions options) this.reconnectTimer = options.TimeProvider.CreateTimer(_ => this.Reconnect(), null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan); } - Task IRealtimeSocket.HttpSendAsync(RealtimeChannel channel, string eventName, object payload, CancellationToken cancellationToken) => - this.httpBroadcaster.SendAsync(channel, eventName, payload, cancellationToken); + Task IRealtimeSocket.HttpSendAsync(RealtimeChannel channel, string eventName, object payload, BroadcastPersistence? persistence, CancellationToken cancellationToken) => + this.httpBroadcaster.SendAsync(channel, eventName, payload, persistence, cancellationToken); void IDisposable.Dispose() { @@ -316,7 +316,7 @@ public void Push(SocketRequest data) private void Write(SocketRequest data) { if (data.Payload is BinaryBroadcast broadcast) - this.connection.Send(WireFrame.UserBroadcastPush(data.JoinRef!, data.Ref!, data.Topic!, broadcast.Event, broadcast.Payload)); + this.connection.Send(WireFrame.UserBroadcastPush(data.JoinRef!, data.Ref!, data.Topic!, broadcast)); else this.options.Encode!(data, encoded => this.connection.Send(this.options.ProtocolVersion == ProtocolVersion.V2 ? WireFrame.ToTextFrame(encoded) : encoded)); } diff --git a/packages/Realtime/Realtime/Socket/WireFrame.cs b/packages/Realtime/Realtime/Socket/WireFrame.cs index 81bf9b43..0033679c 100644 --- a/packages/Realtime/Realtime/Socket/WireFrame.cs +++ b/packages/Realtime/Realtime/Socket/WireFrame.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Text; using System.Text.Json; +using Supabase.Realtime.Broadcast; namespace Supabase.Realtime.Socket; @@ -14,7 +15,6 @@ internal static class WireFrame { private const byte UserBroadcastPushType = 3; private const byte UserBroadcastType = 4; - private const byte NoMetadata = 0; private const byte BinaryEncoding = 0; private const byte JsonEncoding = 1; private const int UserBroadcastHeaderSize = 5; @@ -71,20 +71,19 @@ string Next(int size) } /// - /// Builds the binary frame that pushes a user broadcast whose payload is not JSON. + /// Builds the binary frame that pushes a user broadcast. /// - internal static byte[] UserBroadcastPush(string joinRef, string reference, string topic, string userEvent, byte[] payload) + internal static byte[] UserBroadcastPush(string joinRef, string reference, string topic, BinaryBroadcast broadcast) { - var fields = new[] { joinRef, reference, topic, userEvent }.Select(Encoding.UTF8.GetBytes).ToArray(); + var fields = new[] { joinRef, reference, topic, broadcast.Event, broadcast.Metadata }.Select(Encoding.UTF8.GetBytes).ToArray(); using var frame = new MemoryStream(); frame.WriteByte(UserBroadcastPushType); foreach (var field in fields) frame.WriteByte((byte) field.Length); - frame.WriteByte(NoMetadata); - frame.WriteByte(BinaryEncoding); + frame.WriteByte(broadcast.IsJson ? JsonEncoding : BinaryEncoding); foreach (var field in fields) frame.Write(field, 0, field.Length); - frame.Write(payload, 0, payload.Length); + frame.Write(broadcast.Payload, 0, broadcast.Payload.Length); return frame.ToArray(); } }