Skip to content

refactor(realtime): name the persisted broadcast sends and give them a cancellation token - #914

Merged
Tr00d merged 1 commit into
masterfrom
refactor/realtime-persisted-broadcast
Nov 26, 2026
Merged

Tr00d merged 1 commit into
masterfrom
refactor/realtime-persisted-broadcast

Conversation

@Tr00d

@Tr00d Tr00d commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

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.txt is byte-identical.

Before / after

// Before
await channel.HttpSendAsync("chat", new { text = "hi" }, new BroadcastPersistence());
await channel.HttpSendAsync("chat", new { text = "hi" }, new BroadcastPersistence(TimeSpan.FromHours(1)), token);
await broadcast.SendAsync("chat", new { text = "hi" }, new BroadcastPersistence(TimeSpan.FromHours(1)));

// After
await channel.HttpSendPersistedAsync("chat", new { text = "hi" }, BroadcastPersistence.ForMaximumRetention);
await channel.HttpSendPersistedAsync("chat", new { text = "hi" }, BroadcastPersistence.For(TimeSpan.FromHours(1)), token);
await broadcast.SendPersistedAsync("chat", new { text = "hi" }, BroadcastPersistence.For(TimeSpan.FromHours(1)), cancellationToken: token);
Before (unshipped) After
IRealtimeChannel.HttpSendAsync(string, object, BroadcastPersistence) and HttpSendAsync(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) with TimeSpan? Ttl sealed record BroadcastPersistence, private constructor, ForMaximumRetention and For(TimeSpan ttl)

The same changes apply to RealtimeChannel and RealtimeBroadcast<T>. The shipped HttpSendAsync(string, object, CancellationToken = default) is unchanged. [ImplementedCapability("realtime.channel.broadcast_persist")] stays on both entry points.

  • One HTTP member instead of two. The twins differed only in the token. A defaulted token covers both.
  • SendAsync becomes SendPersistedAsync. SendAsync read like the async version of Send, 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 timeoutMs stays for consistency with the shipped Send and SendBinary beside it. Moving the ack timeout to TimeSpan belongs with those members in v9.
  • The token cancels the wait for the ack. SendForReply waited on a TaskCompletionSource that only a reply or the push timeout completed. The token now reaches PushAwaiter, which registers it for the length of the wait and cancels the task. A token that is already cancelled throws OperationCanceledException before anything is sent. Without BroadcastAck, the send completes once the push is dispatched, as before.
  • SendForReply lost its explanatory comment. The rule now lives in a named predicate, ServerReplies(eventName).

Decision: BroadcastPersistence (point 3)

ForMaximumRetention is a static get-only property, not a method. It returns one immutable value with no inputs and no work to do, like TimeSpan.Zero, CancellationToken.None or StringComparer.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.

For throws ArgumentException for 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.ex parse_persist/1 accepts a ttl only as an integer with seconds > 0 and seconds <= @max_ttl_seconds. A string goes through Integer.parse and must parse fully ({seconds, ""}). A float, "1.5" or 0 is {:error, :invalid_ttl}. The WebSocket frame metadata and the REST query string both use this parser.
  • broadcast_single_controller.ex documents persist[ttl] as type: :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)TotalSeconds turned 1.5 s into ttl=1 and 500 ms into ttl=0. The SDK changed the caller's value without saying so, and the zero case turned into a server rejection. For now 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: PersistenceInvalidTtl on 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_GivenATtlThatIsNotAPositiveWholeNumberOfSeconds replaces it, covering 0, -1 s, 500 ms and 1.5 s.

The public TimeSpan? Ttl getter, where null meant maximum retention, is gone: callers build the value and never need to read it back. Seconds are computed as Ticks / TicksPerSecond, which avoids the double round 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_unauthorized and persistence_failed do not exist over REST. lib/realtime/tenants/single_broadcast.ex maybe_persist/1 says: "This API has no ACK, so it saves in a task and logs failures rather than reporting them." Without a persist policy the broadcast is silently not stored. A storage failure is logged as UnableToPersistMessage in 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 with ack_broadcast.
  • An invalid ttl is a plain 422 with free text. broadcast_single_controller.ex parse_persist/1 returns {:error, :unprocessable_entity, "persist ttl must be a positive integer of seconds from 1 to N"}. FallbackController renders 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 HttpSendPersistedAsync docs 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

  • Tests were changed first, through the public surface: renames, the factory, SendPersistedAsync_ShouldStopWaitingForTheAck_GivenACancellation, SendPersistedAsync_ShouldThrowAndSendNothing_GivenACancelledToken and HttpSendPersistedAsync_ShouldThrowAndSendNothing_GivenACancelledToken.
  • Every assertion in the two touched test files has a reason string. That includes HttpSendPersistedAsync_ShouldThrow_GivenNoPersistence. Magic numbers are now named constants.

Verification

  • Changed-lines coverage (changed-lines-coverage.py packages/Realtime): 20/20, 100%.
  • Stryker on BroadcastPersistence.cs, RealtimeBroadcast.cs and RealtimeChannel.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 of PublicAPI.Unshipped.txt, so no shipped member is removed.

🤖 Generated with Claude Code

@Tr00d
Tr00d marked this pull request as ready for review November 26, 2026 13:08
@Tr00d
Tr00d merged commit 3acb6cc into master Nov 26, 2026
7 checks passed
@Tr00d
Tr00d deleted the refactor/realtime-persisted-broadcast branch November 26, 2026 13:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant