Repository navigation
refactor(realtime): name the persisted broadcast sends and give them a cancellation token - #914
Merged
Merged
Conversation
…a cancellation token
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Reshapes the public API of "store a broadcast for replay" (#850) before it ships. Every member touched here is only in
packages/Realtime/Realtime/PublicAPI.Unshipped.txt, so nothing released breaks.PublicAPI.Shipped.txtis byte-identical.Before / after
IRealtimeChannel.HttpSendAsync(string, object, BroadcastPersistence)andHttpSendAsync(string, object, BroadcastPersistence, CancellationToken)(no default)HttpSendPersistedAsync(string eventName, object payload, BroadcastPersistence persistence, CancellationToken cancellationToken = default)IRealtimeBroadcast.SendAsync(string, object, BroadcastPersistence, int timeoutMs = DefaultTimeout)SendPersistedAsync(string eventName, object payload, BroadcastPersistence persistence, int timeoutMs = DefaultTimeout, CancellationToken cancellationToken = default)sealed class BroadcastPersistence(TimeSpan? ttl = null)withTimeSpan? Ttlsealed record BroadcastPersistence, private constructor,ForMaximumRetentionandFor(TimeSpan ttl)The same changes apply to
RealtimeChannelandRealtimeBroadcast<T>. The shippedHttpSendAsync(string, object, CancellationToken = default)is unchanged.[ImplementedCapability("realtime.channel.broadcast_persist")]stays on both entry points.SendAsyncbecomesSendPersistedAsync.SendAsyncread like the async version ofSend, but it takes the payload itself, needs a private channel and protocol 2.0.0, and fails when the server does not store the broadcast. The two are not interchangeable.int timeoutMsstays for consistency with the shippedSendandSendBinarybeside it. Moving the ack timeout toTimeSpanbelongs with those members in v9.SendForReplywaited on aTaskCompletionSourcethat only a reply or the push timeout completed. The token now reachesPushAwaiter, which registers it for the length of the wait and cancels the task. A token that is already cancelled throwsOperationCanceledExceptionbefore anything is sent. WithoutBroadcastAck, the send completes once the push is dispatched, as before.SendForReplylost its explanatory comment. The rule now lives in a named predicate,ServerReplies(eventName).Decision:
BroadcastPersistence(point 3)ForMaximumRetentionis a static get-only property, not a method. It returns one immutable value with no inputs and no work to do, likeTimeSpan.Zero,CancellationToken.NoneorStringComparer.Ordinal. In .NET, a method suggests computation or a new instance each call.For(TimeSpan)is a method because it takes an argument and validates it.ForthrowsArgumentExceptionfor a TTL that is not a positive whole number of seconds. It does no range check beyond that. Evidence from supabase/realtime (main@ 8b45308):lib/realtime/messages.exparse_persist/1accepts a ttl only as an integer withseconds > 0 and seconds <= @max_ttl_seconds. A string goes throughInteger.parseand must parse fully ({seconds, ""}). A float,"1.5"or0is{:error, :invalid_ttl}. The WebSocket frame metadata and the REST query string both use this parser.broadcast_single_controller.exdocumentspersist[ttl]astype: :integer, minimum: 1: "Seconds to keep the broadcast ... Values outside the range return 422."The wire carries only positive whole seconds. Before this change,
(long)TotalSecondsturned 1.5 s intottl=1and 500 ms intottl=0. The SDK changed the caller's value without saying so, and the zero case turned into a server rejection.Fornow rejects both before any I/O and never rounds. The upper bound (max_ttl_seconds) belongs to the service, so the SDK does not check it, and a longer TTL comes back from the server:PersistenceInvalidTtlon the WebSocket ack, or 422 over REST. The[DataRow(0, "?private=true&persist[ttl]=0")]row that recorded the old truncation is gone.For_ShouldThrow_GivenATtlThatIsNotAPositiveWholeNumberOfSecondsreplaces it, covering 0, -1 s, 500 ms and 1.5 s.The public
TimeSpan? Ttlgetter, where null meant maximum retention, is gone: callers build the value and never need to read it back. Seconds are computed asTicks / TicksPerSecond, which avoids thedoubleround trip.Decision: no error mapping on the HTTP path (point 4)
FailureHint.Reason.Persistence*stays mapped only on the WebSocket ack path. The REST endpoint returns no identifiable code for these failures:persistence_unauthorizedandpersistence_faileddo not exist over REST.lib/realtime/tenants/single_broadcast.exmaybe_persist/1says: "This API has no ACK, so it saves in a task and logs failures rather than reporting them." Without apersistpolicy the broadcast is silently not stored. A storage failure is logged asUnableToPersistMessagein a background task. In both cases the response is 202. The WebSocket handler (broadcast_handler.ex) is the only place that returns{:error, :persistence_unauthorized | :persistence_failed}, and only withack_broadcast.broadcast_single_controller.exparse_persist/1returns{:error, :unprocessable_entity, "persist ttl must be a positive integer of seconds from 1 to N"}.FallbackControllerrenders that as{"message": ...}. Other invalid requests share the same 422 status and shape, for example "Payload must be a JSON object" and the changeset error for persist on a public channel. The ttl case has no code. Matching on the message text would break the next time the wording changes, and it would put service logic in the client.The
HttpSendPersistedAsyncdocs now say that the REST API has no acknowledgment, and that a broadcast that was delivered but not stored still completes. If the service adds an error code to REST responses, mapping it is a small follow-up.Tests
SendPersistedAsync_ShouldStopWaitingForTheAck_GivenACancellation,SendPersistedAsync_ShouldThrowAndSendNothing_GivenACancelledTokenandHttpSendPersistedAsync_ShouldThrowAndSendNothing_GivenACancelledToken.HttpSendPersistedAsync_ShouldThrow_GivenNoPersistence. Magic numbers are now named constants.Verification
changed-lines-coverage.py packages/Realtime): 20/20, 100%.BroadcastPersistence.cs,RealtimeBroadcast.csandRealtimeChannel.cs: 0 survived and 0 uncovered mutants on changed lines. All were killed or timed out; the only exceptions are compile errors and one ignored block.gate.sh packages/Realtime: INCOMPLETE. Build, format, inner loop (385/385) and public API declared all PASS. E2E and coverage were skipped because the local stack was down, so CI is the gate. The public API diff signal lists 8 removals. All of them are members ofPublicAPI.Unshipped.txt, so no shipped member is removed.🤖 Generated with Claude Code