From ae855f29271ca6e689930c1772fc9bb3dfd9cffc Mon Sep 17 00:00:00 2001 From: tr00d Date: Thu, 26 Nov 2026 13:59:05 +0100 Subject: [PATCH] refactor(realtime): name the persisted broadcast sends and give them a cancellation token --- .../Broadcast/BroadcastPersistenceTests.cs | 78 +++++++++++++------ .../HttpSend/HttpSendRequestTests.cs | 75 +++++++++++------- .../Broadcast/BroadcastPersistence.cs | 34 ++++++-- .../Realtime/Interfaces/IRealtimeBroadcast.cs | 14 +++- .../Realtime/Interfaces/IRealtimeChannel.cs | 18 +++-- .../Realtime/Realtime/PublicAPI.Unshipped.txt | 21 +++-- .../Realtime/Realtime/RealtimeBroadcast.cs | 6 +- packages/Realtime/Realtime/RealtimeChannel.cs | 32 ++++---- 8 files changed, 182 insertions(+), 96 deletions(-) diff --git a/packages/Realtime/Realtime.Tests/Broadcast/BroadcastPersistenceTests.cs b/packages/Realtime/Realtime.Tests/Broadcast/BroadcastPersistenceTests.cs index a7628bee..bcc3aaea 100644 --- a/packages/Realtime/Realtime.Tests/Broadcast/BroadcastPersistenceTests.cs +++ b/packages/Realtime/Realtime.Tests/Broadcast/BroadcastPersistenceTests.cs @@ -1,5 +1,6 @@ using System; using System.Text; +using System.Threading; using System.Threading.Tasks; using FluentAssertions; using FluentAssertions.Execution; @@ -29,6 +30,8 @@ public class BroadcastPersistenceTests private const byte BinaryEncoding = 0; private const byte JsonEncoding = 1; private const int LongestFieldInBytes = 255; + private const int OneHourInSeconds = 3600; + private const string NotAPositiveWholeNumberOfSeconds = "The ttl of a persisted broadcast must be a positive whole number of seconds.*"; private static readonly TimeSpan Patience = TimeSpan.FromSeconds(5); private static readonly byte[] Bytes = [0, 159, 146, 150, 255]; @@ -49,29 +52,29 @@ public void CreateClient() [TestMethod] [DataRow(null, StoreForTheMaximumRetention)] - [DataRow(3600, """{"persist":{"ttl":3600}}""")] - public async Task SendAsync_ShouldPutThePersistOptionInTheFrameMetadata(int? ttlSeconds, string metadata) + [DataRow(OneHourInSeconds, """{"persist":{"ttl":3600}}""")] + public async Task SendPersistedAsync_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 broadcast.SendPersistedAsync(Event, new { text = "hi" }, Persistence(ttlSeconds)); (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() + public async Task SendPersistedAsync_ShouldPushTheBytesBinaryEncoded_GivenAByteArray() { byte[] reused = [.. Bytes]; var broadcast = await this.Joined(); - await broadcast.SendAsync(Event, reused, new BroadcastPersistence()); + await broadcast.SendPersistedAsync(Event, reused, BroadcastPersistence.ForMaximumRetention); 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() + public async Task SendPersistedAsync_ShouldComplete_GivenAnOkReply() { var broadcast = await this.Joined(acknowledged: true); - var send = broadcast.SendAsync(Event, Bytes, new BroadcastPersistence()); + var send = broadcast.SendPersistedAsync(Event, Bytes, BroadcastPersistence.ForMaximumRetention); 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"); } @@ -81,12 +84,12 @@ public async Task SendAsync_ShouldComplete_GivenAnOkReply() [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) + public async Task SendPersistedAsync_ShouldThrowTheServerCode_GivenAnErrorReply(string code, FailureHint.Reason reason) { var broadcast = await this.Joined(acknowledged: true); - var send = broadcast.SendAsync(Event, Bytes, new BroadcastPersistence()); + var send = broadcast.SendPersistedAsync(Event, Bytes, BroadcastPersistence.ForMaximumRetention); this.socket.Reply(Topic, this.channel.LastPush!.Ref, "error", $$"""{"error":"{{code}}"}"""); - var exception = (await send.Awaiting(s => s).Should().ThrowWithinAsync(Patience)).Which; + var exception = (await send.Awaiting(s => s).Should().ThrowWithinAsync(Patience, "an error reply means the server did not store the message")).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"); @@ -95,56 +98,87 @@ public async Task SendAsync_ShouldThrowTheServerCode_GivenAnErrorReply(string co } [TestMethod] - public async Task SendAsync_ShouldThrowAndSendNothing_GivenAPublicChannel() + public async Task SendPersistedAsync_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"); + (await broadcast.Awaiting(b => b.SendPersistedAsync(Event, Bytes, BroadcastPersistence.ForMaximumRetention)).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() + public async Task SendPersistedAsync_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"); + (await broadcast.Awaiting(b => b.SendPersistedAsync(Event, Bytes, BroadcastPersistence.ForMaximumRetention)).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() + public async Task SendPersistedAsync_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"); + (await broadcast.Awaiting(b => b.SendPersistedAsync(Event, new BroadcastExample { UserId = "1" }, BroadcastPersistence.ForMaximumRetention)).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() + public async Task SendPersistedAsync_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"); + (await broadcast.Awaiting(b => b.SendPersistedAsync(new string('e', LongestFieldInBytes + 1), Bytes, BroadcastPersistence.ForMaximumRetention)).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() + public async Task SendPersistedAsync_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"); + (await broadcast.Awaiting(b => b.SendPersistedAsync(Event, Bytes, BroadcastPersistence.ForMaximumRetention)).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() + public async Task SendPersistedAsync_ShouldComplete_GivenCallerBlockingOnContextThatNeverRunsContinuations() { var broadcast = await this.Joined(acknowledged: true); BlockingCaller.Completes(() => { - var sending = broadcast.SendAsync(Event, Bytes, new BroadcastPersistence()); + var sending = broadcast.SendPersistedAsync(Event, Bytes, BroadcastPersistence.ForMaximumRetention); 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"); } + [TestMethod] + public async Task SendPersistedAsync_ShouldStopWaitingForTheAck_GivenACancellation() + { + using var cancellation = new CancellationTokenSource(); + var broadcast = await this.Joined(acknowledged: true); + var send = broadcast.SendPersistedAsync(Event, Bytes, BroadcastPersistence.ForMaximumRetention, cancellationToken: cancellation.Token); + await cancellation.CancelAsync(); + await send.Awaiting(s => s).Should().ThrowWithinAsync(Patience, "a cancelled caller must not wait for an ack the server may never send"); + } + + [TestMethod] + public async Task SendPersistedAsync_ShouldThrowAndSendNothing_GivenACancelledToken() + { + using var cancellation = new CancellationTokenSource(); + await cancellation.CancelAsync(); + var broadcast = await this.Joined(acknowledged: true); + await broadcast.Awaiting(b => b.SendPersistedAsync(Event, Bytes, BroadcastPersistence.ForMaximumRetention, cancellationToken: cancellation.Token)).Should().ThrowAsync("a caller that already gave up must not have the broadcast stored"); + this.channel.LastPush.Should().BeNull("nothing must be sent once the caller cancelled"); + } + + [TestMethod] + [DataRow(0)] + [DataRow(-1000)] + [DataRow(500)] + [DataRow(1500)] + public void For_ShouldThrow_GivenATtlThatIsNotAPositiveWholeNumberOfSeconds(int milliseconds) => + FluentActions.Invoking(() => BroadcastPersistence.For(TimeSpan.FromMilliseconds(milliseconds))).Should().Throw().WithMessage(NotAPositiveWholeNumberOfSeconds, "the server reads the ttl as a positive integer of seconds, so the client must not round or truncate it"); + + private static BroadcastPersistence Persistence(int? ttlSeconds) => + ttlSeconds is { } seconds ? BroadcastPersistence.For(TimeSpan.FromSeconds(seconds)) : BroadcastPersistence.ForMaximumRetention; + private async Task> Joined(string channelName = "room", bool isPrivate = true, bool acknowledged = false) { var firstHeartbeat = this.socket.SentText("heartbeat", 1); diff --git a/packages/Realtime/Realtime.Tests/HttpSend/HttpSendRequestTests.cs b/packages/Realtime/Realtime.Tests/HttpSend/HttpSendRequestTests.cs index 917eabe0..a49fa782 100644 --- a/packages/Realtime/Realtime.Tests/HttpSend/HttpSendRequestTests.cs +++ b/packages/Realtime/Realtime.Tests/HttpSend/HttpSendRequestTests.cs @@ -1,4 +1,5 @@ using System; +using System.Threading; using System.Threading.Tasks; using FluentAssertions; using FluentAssertions.Execution; @@ -17,13 +18,15 @@ namespace Realtime.Tests.HttpSend; /// -/// The request HttpSendAsync sends and the errors it raises. +/// The request HttpSendAsync and HttpSendPersistedAsync send and the errors they raise. /// [TestClass] [TestCategory("Contract")] public class HttpSendRequestTests { private const string ApiKey = "publishable-key"; + private const int OneHourInSeconds = 3600; + private const int UnprocessableEntity = 422; private WireMockServer server = null!; private ClientOptions clientOptions = null!; @@ -45,7 +48,7 @@ public void TestInitialize() public async Task HttpSendAsync_ShouldPostToTheEventUrl(string topic) { await this.Channel(topic).HttpSendAsync("cursor/move", new { x = 1 }); - this.SentRequest().AbsoluteUrl.Should().EndWith("/realtime/v1/api/broadcast/room:1/events/cursor%2Fmove"); + this.SentRequest().AbsoluteUrl.Should().EndWith("/realtime/v1/api/broadcast/room:1/events/cursor%2Fmove", "the server reads the topic without its realtime: prefix and the event as one escaped segment"); } [TestMethod] @@ -55,8 +58,8 @@ public async Task HttpSendAsync_ShouldSendThePayloadAsJson() var sent = this.SentRequest(); using (new AssertionScope()) { - sent.Headers!["Content-Type"].Should().ContainSingle().Which.Should().StartWith("application/json"); - sent.Body.Should().Be("{\"x\":1}"); + sent.Headers!["Content-Type"].Should().ContainSingle().Which.Should().StartWith("application/json", "the server decodes a JSON body only when told it is JSON"); + sent.Body.Should().Be("{\"x\":1}", "the payload is the message subscribers receive"); } } @@ -67,8 +70,8 @@ public async Task HttpSendAsync_ShouldSendTheBytesAsOctetStream() var sent = this.SentRequest(); using (new AssertionScope()) { - sent.Headers!["Content-Type"].Should().ContainSingle().Which.Should().Be("application/octet-stream"); - sent.BodyAsBytes.Should().Equal(1, 2, 3); + sent.Headers!["Content-Type"].Should().ContainSingle().Which.Should().Be("application/octet-stream", "the server relays an octet stream body as binary"); + sent.BodyAsBytes.Should().Equal(new byte[] { 1, 2, 3 }, "the bytes must reach the server as given"); } } @@ -76,37 +79,46 @@ public async Task HttpSendAsync_ShouldSendTheBytesAsOctetStream() public async Task HttpSendAsync_ShouldSendThePrivateFlag_GivenAPrivateChannel() { await this.Channel(options: Wire.PrivateOptions()).HttpSendAsync("cursor", new { x = 1 }); - this.SentRequest().RawQuery.Should().Be("?private=true"); + this.SentRequest().RawQuery.Should().Be("?private=true", "the server authorizes a private broadcast only when the query says so"); } [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) + [DataRow(OneHourInSeconds, "?private=true&persist[ttl]=3600")] + public async Task HttpSendPersistedAsync_ShouldAskToStoreTheMessageInTheQuery(int? ttlSeconds, string query) { - await this.Channel(options: Wire.PrivateOptions()).HttpSendAsync("cursor", new { x = 1 }, new BroadcastPersistence(ttlSeconds is { } seconds ? TimeSpan.FromSeconds(seconds) : null)); + await this.Channel(options: Wire.PrivateOptions()).HttpSendPersistedAsync("cursor", new { x = 1 }, Persistence(ttlSeconds)); 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.RawQuery.Should().Be(query, "the server reads persist only from the query string"); sent.Body.Should().Be("""{"x":1}""", "a persist key in the body would be delivered as data"); } } [TestMethod] - public async Task HttpSendAsync_ShouldThrowAndSendNothing_GivenAPersistenceOnAPublicChannel() + public async Task HttpSendPersistedAsync_ShouldThrowAndSendNothing_GivenAPublicChannel() { - var act = () => this.Channel().HttpSendAsync("cursor", new { x = 1 }, new BroadcastPersistence()); - (await act.Should().ThrowAsync()).WithMessage("A persisted broadcast needs a private channel."); + var act = () => this.Channel().HttpSendPersistedAsync("cursor", new { x = 1 }, BroadcastPersistence.ForMaximumRetention); + (await act.Should().ThrowAsync()).WithMessage("A persisted broadcast needs a private channel.", "the server stores a broadcast only on 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() + public async Task HttpSendPersistedAsync_ShouldThrow_GivenNoPersistence() { - var act = () => this.Channel(options: Wire.PrivateOptions()).HttpSendAsync("cursor", new { x = 1 }, null!); - await act.Should().ThrowAsync(); + var act = () => this.Channel(options: Wire.PrivateOptions()).HttpSendPersistedAsync("cursor", new { x = 1 }, null!); + await act.Should().ThrowAsync("a persisted send needs to know how long the server keeps the broadcast"); + } + + [TestMethod] + public async Task HttpSendPersistedAsync_ShouldThrowAndSendNothing_GivenACancelledToken() + { + using var cancellation = new CancellationTokenSource(); + await cancellation.CancelAsync(); + var act = () => this.Channel(options: Wire.PrivateOptions()).HttpSendPersistedAsync("cursor", new { x = 1 }, BroadcastPersistence.ForMaximumRetention, cancellation.Token); + await act.Should().ThrowAsync("a caller that already gave up must not have the broadcast stored"); + this.server.LogEntries.Should().BeEmpty("nothing must be sent once the caller cancelled"); } [TestMethod] @@ -118,9 +130,9 @@ public async Task HttpSendAsync_ShouldSendTheClientHeaders() var headers = this.SentRequest().Headers!; using (new AssertionScope()) { - headers["apiKey"].Should().Equal(ApiKey); - headers["Authorization"].Should().Equal("Bearer user-jwt"); - headers["X-Custom"].Should().Equal("custom"); + headers["apiKey"].Should().Equal([ApiKey], "the client api key wins over a stale header"); + headers["Authorization"].Should().Equal(["Bearer user-jwt"], "the server authorizes the broadcast as the channel user"); + headers["X-Custom"].Should().Equal(["custom"], "the caller headers reach the server"); } } @@ -128,7 +140,7 @@ public async Task HttpSendAsync_ShouldSendTheClientHeaders() public async Task HttpSendAsync_ShouldOmitTheAuthorization_GivenNoAccessToken() { await this.Channel().HttpSendAsync("cursor", new { x = 1 }); - this.SentRequest().Headers!.Should().NotContainKey("Authorization"); + this.SentRequest().Headers!.Should().NotContainKey("Authorization", "an empty bearer would be rejected instead of falling back to the api key"); } [TestMethod] @@ -136,13 +148,13 @@ public async Task HttpSendAsync_ShouldThrowTheServerError_GivenARejection() { const string body = "{\"message\":\"Payload must be a JSON object\"}"; this.server.ResetMappings(); - this.server.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(422).WithBody(body)); + this.server.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(UnprocessableEntity).WithBody(body)); var act = () => this.Channel().HttpSendAsync("cursor", 1); - var exception = (await act.Should().ThrowAsync()).Which; + var exception = (await act.Should().ThrowAsync("a rejection surfaces as the SDK exception")).Which; using (new AssertionScope()) { - exception.Message.Should().Be(body); - exception.StatusCode.Should().Be(422); + exception.Message.Should().Be(body, "the caller must see why the server rejected the broadcast"); + exception.StatusCode.Should().Be(UnprocessableEntity, "the caller must see the status the server answered"); } } @@ -153,7 +165,7 @@ public async Task HttpSendAsync_ShouldThrow_GivenNoAnswerWithinTheClientTimeout( this.server.Given(Request.Create().UsingPost()).RespondWith(Response.Create().WithStatusCode(202).WithDelay(TimeSpan.FromSeconds(5))); this.clientOptions.Timeout = TimeSpan.FromMilliseconds(200); var act = () => this.Channel().HttpSendAsync("cursor", new { x = 1 }); - await act.Should().ThrowAsync(); + await act.Should().ThrowAsync("the client timeout bounds how long a send waits"); } [TestMethod] @@ -167,7 +179,7 @@ public async Task HttpSendAsync_ShouldThrow_GivenTheSuppliedClockReachedTheClien var send = this.Channel().HttpSendAsync("cursor", new { x = 1 }); clock.Advance(TimeSpan.FromHours(1)); var act = () => send; - await act.Should().ThrowAsync().WaitAsync(TimeSpan.FromSeconds(5)); + await act.Should().ThrowAsync("the client timeout runs on the supplied clock").WaitAsync(TimeSpan.FromSeconds(5)); } [TestMethod] @@ -180,12 +192,15 @@ public async Task HttpSendAsync_ShouldSendTheClientHeaders_GivenAChannelCreatedW [TestMethod] public void HttpSendAsync_ShouldComplete_GivenCallerBlockingOnContextThatNeverRunsContinuations() => - BlockingCaller.Completes(() => this.Channel().HttpSendAsync("cursor", new { x = 1 })).Should().BeTrue(); + BlockingCaller.Completes(() => this.Channel().HttpSendAsync("cursor", new { x = 1 })).Should().BeTrue("the SDK must not resume on the caller's synchronization context"); + + private static BroadcastPersistence Persistence(int? ttlSeconds) => + ttlSeconds is { } seconds ? BroadcastPersistence.For(TimeSpan.FromSeconds(seconds)) : BroadcastPersistence.ForMaximumRetention; private RealtimeChannel Channel(string topic = "realtime:room", ChannelOptions? options = null) => new(new RealtimeSocket(this.SocketUrl, this.clientOptions), topic, options ?? Wire.PublicOptions()); private string SocketUrl => $"{this.server.Url!.Replace("http", "ws")}/realtime/v1"; - private IRequestMessage SentRequest() => this.server.LogEntries.Should().ContainSingle().Which.RequestMessage!; + private IRequestMessage SentRequest() => this.server.LogEntries.Should().ContainSingle("a send posts exactly one request").Which.RequestMessage!; } diff --git a/packages/Realtime/Realtime/Broadcast/BroadcastPersistence.cs b/packages/Realtime/Realtime/Broadcast/BroadcastPersistence.cs index 9b44daaf..de4ed98a 100644 --- a/packages/Realtime/Realtime/Broadcast/BroadcastPersistence.cs +++ b/packages/Realtime/Realtime/Broadcast/BroadcastPersistence.cs @@ -6,21 +6,39 @@ 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 +/// +/// +/// await channel.HttpSendPersistedAsync("chat", new { text = "hi" }, BroadcastPersistence.For(TimeSpan.FromHours(1))); +/// await channel.HttpSendPersistedAsync("chat", new { text = "hi" }, BroadcastPersistence.ForMaximumRetention); +/// +/// +public sealed record BroadcastPersistence { + private readonly long? ttlSeconds; + + private BroadcastPersistence(long? ttlSeconds) => this.ttlSeconds = ttlSeconds; + /// - /// Stores the broadcast for , sent in whole seconds, or for the maximum retention when null. + /// Stores the broadcast for the longest retention the server allows. /// - public BroadcastPersistence(TimeSpan? ttl = null) => this.Ttl = ttl; + public static BroadcastPersistence ForMaximumRetention { get; } = new((long?) null); /// - /// How long the server keeps the broadcast. Null keeps it for the maximum retention. + /// Stores the broadcast for . The server owns the longest ttl it accepts, and rejects a + /// longer one. /// - public TimeSpan? Ttl { get; } + /// How long the server keeps the broadcast, a positive whole number of seconds. + /// is not a positive whole number of seconds, which is all the server reads. + public static BroadcastPersistence For(TimeSpan ttl) => + IsPositiveWholeSeconds(ttl) + ? new BroadcastPersistence(ttl.Ticks / TimeSpan.TicksPerSecond) + : throw new ArgumentException("The ttl of a persisted broadcast must be a positive whole number of seconds.", nameof(ttl)); + + internal string Metadata => this.ttlSeconds is { } seconds ? $"{{\"persist\":{{\"ttl\":{Invariant(seconds)}}}}}" : "{\"persist\":true}"; - internal string Metadata => this.Ttl == null ? "{\"persist\":true}" : $"{{\"persist\":{{\"ttl\":{this.TtlSeconds}}}}}"; + internal string Query => this.ttlSeconds is { } seconds ? $"persist[ttl]={Invariant(seconds)}" : "persist=true"; - internal string Query => this.Ttl == null ? "persist=true" : $"persist[ttl]={this.TtlSeconds}"; + private static bool IsPositiveWholeSeconds(TimeSpan ttl) => ttl > TimeSpan.Zero && ttl.Ticks % TimeSpan.TicksPerSecond == 0; - private string TtlSeconds => ((long) this.Ttl!.Value.TotalSeconds).ToString(CultureInfo.InvariantCulture); + private static string Invariant(long seconds) => seconds.ToString(CultureInfo.InvariantCulture); } diff --git a/packages/Realtime/Realtime/Interfaces/IRealtimeBroadcast.cs b/packages/Realtime/Realtime/Interfaces/IRealtimeBroadcast.cs index 5b0c024f..042c66cc 100644 --- a/packages/Realtime/Realtime/Interfaces/IRealtimeBroadcast.cs +++ b/packages/Realtime/Realtime/Interfaces/IRealtimeBroadcast.cs @@ -1,4 +1,5 @@ using System; +using System.Threading; using System.Threading.Tasks; using Supabase.Realtime.Broadcast; using Supabase.Realtime.Models; @@ -66,8 +67,15 @@ public interface IRealtimeBroadcast /// 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. + /// on, the send waits for the acknowledgment and fails when the server + /// did not store the broadcast, naming why in . /// + /// The event name, at most 255 bytes. + /// The payload: a byte[] is sent as bytes, anything else as JSON. + /// How long the server keeps the broadcast. + /// How long to wait for the acknowledgment, when the channel asked for one. + /// Stops the send before it goes out, or stops waiting for the acknowledgment. + /// The caller cancelled before the send went out or before the acknowledgment arrived. /// 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. /// @@ -75,10 +83,10 @@ public interface IRealtimeBroadcast /// 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))); + /// await broadcast.SendPersistedAsync("chat", new { text = "hi" }, BroadcastPersistence.For(TimeSpan.FromHours(1))); /// /// - Task SendAsync(string eventName, object payload, BroadcastPersistence persistence, int timeoutMs = DefaultTimeout); + Task SendPersistedAsync(string eventName, object payload, BroadcastPersistence persistence, int timeoutMs = DefaultTimeout, CancellationToken cancellationToken = default); /// /// 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 b2704444..d0aa1091 100644 --- a/packages/Realtime/Realtime/Interfaces/IRealtimeChannel.cs +++ b/packages/Realtime/Realtime/Interfaces/IRealtimeChannel.cs @@ -248,18 +248,22 @@ IRealtimeChannel OnPostgresChange(PostgresChangesHandler postgresChangeHandler, /// /// 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. + /// The REST API has no acknowledgment: a broadcast the server delivered but did not store, because no policy lets + /// the sender store it or storing it failed, still completes. + /// + /// The event name. + /// The payload: a byte[] is sent as raw binary, anything else as JSON. + /// How long the server keeps the broadcast. + /// Cancels the request. + /// The channel is public, or the server rejected the broadcast, for instance a ttl longer than it allows. + /// is null. /// /// /// var channel = client.PrivateChannel("room"); - /// await channel.HttpSendAsync("chat", new { text = "hi" }, new BroadcastPersistence()); + /// await channel.HttpSendPersistedAsync("chat", new { text = "hi" }, BroadcastPersistence.For(TimeSpan.FromHours(1))); /// /// - Task HttpSendAsync(string eventName, object payload, BroadcastPersistence persistence); - - /// - Task HttpSendAsync(string eventName, object payload, BroadcastPersistence persistence, CancellationToken cancellationToken); + Task HttpSendPersistedAsync(string eventName, object payload, BroadcastPersistence persistence, CancellationToken cancellationToken = default); /// /// Register broadcast options, must be called to use , and prior to diff --git a/packages/Realtime/Realtime/PublicAPI.Unshipped.txt b/packages/Realtime/Realtime/PublicAPI.Unshipped.txt index 7236eee6..b7a502c6 100644 --- a/packages/Realtime/Realtime/PublicAPI.Unshipped.txt +++ b/packages/Realtime/Realtime/PublicAPI.Unshipped.txt @@ -1,15 +1,20 @@ #nullable enable +override Supabase.Realtime.Broadcast.BroadcastPersistence.Equals(object? obj) -> bool +override Supabase.Realtime.Broadcast.BroadcastPersistence.GetHashCode() -> int +override Supabase.Realtime.Broadcast.BroadcastPersistence.ToString() -> string! +static Supabase.Realtime.Broadcast.BroadcastPersistence.For(System.TimeSpan ttl) -> Supabase.Realtime.Broadcast.BroadcastPersistence! +static Supabase.Realtime.Broadcast.BroadcastPersistence.ForMaximumRetention.get -> Supabase.Realtime.Broadcast.BroadcastPersistence! +static Supabase.Realtime.Broadcast.BroadcastPersistence.operator !=(Supabase.Realtime.Broadcast.BroadcastPersistence? left, Supabase.Realtime.Broadcast.BroadcastPersistence? right) -> bool +static Supabase.Realtime.Broadcast.BroadcastPersistence.operator ==(Supabase.Realtime.Broadcast.BroadcastPersistence? left, Supabase.Realtime.Broadcast.BroadcastPersistence? right) -> bool Supabase.Realtime.Broadcast.BroadcastPersistence -Supabase.Realtime.Broadcast.BroadcastPersistence.BroadcastPersistence(System.TimeSpan? ttl = null) -> void -Supabase.Realtime.Broadcast.BroadcastPersistence.Ttl.get -> System.TimeSpan? +Supabase.Realtime.Broadcast.BroadcastPersistence.$() -> Supabase.Realtime.Broadcast.BroadcastPersistence! +Supabase.Realtime.Broadcast.BroadcastPersistence.Equals(Supabase.Realtime.Broadcast.BroadcastPersistence? other) -> bool 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! +Supabase.Realtime.Interfaces.IRealtimeBroadcast.SendPersistedAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence, int timeoutMs = 10000, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Realtime.Interfaces.IRealtimeChannel.HttpSendPersistedAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Realtime.RealtimeBroadcast.SendPersistedAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence, int timeoutMs = 10000, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +Supabase.Realtime.RealtimeChannel.HttpSendPersistedAsync(string! eventName, object! payload, Supabase.Realtime.Broadcast.BroadcastPersistence! persistence, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! diff --git a/packages/Realtime/Realtime/RealtimeBroadcast.cs b/packages/Realtime/Realtime/RealtimeBroadcast.cs index 3f1c3b52..43cfc05c 100644 --- a/packages/Realtime/Realtime/RealtimeBroadcast.cs +++ b/packages/Realtime/Realtime/RealtimeBroadcast.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Text.Json; +using System.Threading; using System.Threading.Tasks; using Supabase.Core.Attributes; using Supabase.Realtime.Broadcast; @@ -132,7 +133,7 @@ public async Task SendBinary(string broadcastEventName, byte[] payload, int time /// [ImplementedCapability("realtime.channel.broadcast_persist")] - public async Task SendAsync(string eventName, object payload, BroadcastPersistence persistence, int timeoutMs = DefaultTimeout) + public async Task SendPersistedAsync(string eventName, object payload, BroadcastPersistence persistence, int timeoutMs = DefaultTimeout, CancellationToken cancellationToken = default) { this.channel.EnsureCanPersist(persistence); if (payload is BaseBroadcast) @@ -143,8 +144,9 @@ public async Task SendAsync(string eventName, object payload, BroadcastPersisten 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."); + cancellationToken.ThrowIfCancellationRequested(); - var reply = await this.channel.SendForReply(ChannelEventName.Broadcast, null, this.PersistedBroadcast(eventName, payload, persistence), timeoutMs).ConfigureAwait(false); + var reply = await this.channel.SendForReply(ChannelEventName.Broadcast, null, this.PersistedBroadcast(eventName, payload, persistence), timeoutMs, cancellationToken).ConfigureAwait(false); if (reply != null && reply.Payload?.Status != PhoenixStatusOk) throw NotStored(reply); } diff --git a/packages/Realtime/Realtime/RealtimeChannel.cs b/packages/Realtime/Realtime/RealtimeChannel.cs index f95bdaca..960210df 100644 --- a/packages/Realtime/Realtime/RealtimeChannel.cs +++ b/packages/Realtime/Realtime/RealtimeChannel.cs @@ -625,17 +625,17 @@ public Task Send(ChannelEventName eventName, string? type, object payload, /// /// 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) + internal Task SendForReply(ChannelEventName eventName, string? type, object payload, int timeoutMs, CancellationToken cancellationToken = default) { 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(null) - : PushAwaiter.Await(push); + return this.ServerReplies(eventName) + ? PushAwaiter.ReplyAsync(push, cancellationToken) + : Task.FromResult(null); } + private bool ServerReplies(ChannelEventName eventName) => + eventName != ChannelEventName.Broadcast || this.BroadcastOptions?.BroadcastAck == true; + private static async Task IsOk(Task sending) { var reply = await sending.ConfigureAwait(false); @@ -649,12 +649,7 @@ public Task HttpSendAsync(string eventName, object payload, CancellationToken ca /// [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) + public Task HttpSendPersistedAsync(string eventName, object payload, BroadcastPersistence persistence, CancellationToken cancellationToken = default) { this.EnsureCanPersist(persistence); return this.Socket.HttpSendAsync(this, eventName, payload, persistence, cancellationToken); @@ -669,8 +664,8 @@ internal void EnsureCanPersist(BroadcastPersistence persistence) } /// - /// Awaits a reply for a given , resolving with the reply, or faulting with a - /// if the push times out first. + /// Awaits a reply for a given , resolving with the reply, faulting with a + /// if the push times out first, or cancelled when the caller cancels 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. @@ -689,7 +684,12 @@ private PushAwaiter(Push push) this.HandleMessageReceived(this.push, reply); } - public static Task Await(Push push) => new PushAwaiter(push).taskCompletion.Task; + public static async Task ReplyAsync(Push push, CancellationToken cancellationToken) + { + var awaiter = new PushAwaiter(push); + using var stopWaiting = cancellationToken.Register(() => awaiter.taskCompletion.TrySetCanceled(cancellationToken)); + return await awaiter.taskCompletion.Task.ConfigureAwait(false); + } private void HandleMessageReceived(IRealtimePush sender, SocketResponse message) {