Repository navigation
feat(launch-intents): stream session_ready events to the bot via SSE #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,6 @@ | ||
| using System.Net; | ||
| using System.Net.ServerSentEvents; | ||
| using System.Runtime.CompilerServices; | ||
| using System.Security.Claims; | ||
| using Microsoft.AspNetCore.WebUtilities; | ||
| using Microsoft.Extensions.Options; | ||
|
|
@@ -18,6 +20,7 @@ public static IEndpointRouteBuilder MapLaunchIntentEndpoints(this IEndpointRoute | |
| .RequireAuthorization("launch-intents:bot"); | ||
| bot.MapPost("/share", CreateShareAsync); | ||
| bot.MapGet("/pending", ListPendingAsync); | ||
| bot.MapGet("/events", StreamEvents); | ||
| bot.MapGet("/{intentId:guid}", GetStatusAsync); | ||
| bot.MapPost("/{intentId:guid}/published", MarkPublishedAsync); | ||
| bot.MapPost("/watch", CreateWatchAsync); | ||
|
|
@@ -56,6 +59,60 @@ private static async Task<IResult> ListPendingAsync(LaunchIntentService service, | |
| x.ExpiresAt <= DateTimeOffset.UtcNow ? "expired" : x.Status, x.ExpiresAt))); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Server-sent events for the bot. The subscription is registered before the response starts | ||
| /// and the first frame is <c>connected</c>; a client that reconciles <c>GET /pending</c> after | ||
| /// receiving it cannot miss a <c>session_ready</c> committed in between (duplicates are possible). | ||
| /// </summary> | ||
| private static IResult StreamEvents(HttpContext context, LaunchIntentEventBroadcaster broadcaster, | ||
| IOptions<LaunchIntentOptions> options, TimeProvider timeProvider) | ||
| { | ||
| if (broadcaster.SubscriberCount >= Math.Max(1, options.Value.EventsMaxSubscribers)) | ||
| return Results.Json(new { code = "too_many_subscribers" }, statusCode: StatusCodes.Status503ServiceUnavailable); | ||
|
|
||
| var subscription = broadcaster.Subscribe(); | ||
|
Comment on lines
+70
to
+73
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When multiple authenticated stream requests arrive concurrently near Useful? React with 👍 / 👎. |
||
| context.Response.RegisterForDisposeAsync(subscription); | ||
| context.Response.Headers.CacheControl = "no-cache, no-store"; | ||
| context.Response.Headers["X-Accel-Buffering"] = "no"; | ||
| var heartbeat = TimeSpan.FromSeconds(Math.Clamp(options.Value.EventsHeartbeatSeconds, 1, 60)); | ||
| return TypedResults.ServerSentEvents( | ||
| ReadEventsAsync(subscription, heartbeat, timeProvider, context.RequestAborted)); | ||
| } | ||
|
|
||
| internal static readonly TimeSpan EventsReconnectInterval = TimeSpan.FromSeconds(5); | ||
|
|
||
| private static async IAsyncEnumerable<SseItem<string>> ReadEventsAsync(ILaunchIntentSubscription subscription, | ||
| TimeSpan heartbeat, TimeProvider timeProvider, [EnumeratorCancellation] CancellationToken ct) | ||
| { | ||
| await using var _ = subscription; | ||
| yield return new SseItem<string>("{}", "connected") { ReconnectionInterval = EventsReconnectInterval }; | ||
|
|
||
| var reader = subscription.Reader; | ||
| Task<bool>? pendingRead = null; | ||
| while (!ct.IsCancellationRequested) | ||
| { | ||
| pendingRead ??= reader.WaitToReadAsync(ct).AsTask(); | ||
| using var delayCancellation = CancellationTokenSource.CreateLinkedTokenSource(ct); | ||
| var delay = Task.Delay(heartbeat, timeProvider, delayCancellation.Token); | ||
| var completed = await Task.WhenAny(pendingRead, delay); | ||
| await delayCancellation.CancelAsync(); | ||
| if (completed != pendingRead) | ||
| { | ||
| yield return new SseItem<string>("{}", "heartbeat"); | ||
| continue; | ||
| } | ||
|
|
||
| var hasMore = await pendingRead; | ||
| pendingRead = null; | ||
| if (!hasMore) yield break; // overflowed: the client reconnects and reconciles | ||
| while (reader.TryRead(out var item)) | ||
| { | ||
| yield return new SseItem<string>( | ||
| $"{{\"intentId\":\"{item.IntentId:D}\"}}", item.Type) { EventId = item.Sequence.ToString() }; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static async Task<IResult> GetStatusAsync(Guid intentId, int? watchTtlSeconds, | ||
| LaunchIntentService service, CancellationToken ct) | ||
| { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| using System.Collections.Concurrent; | ||
| using System.Threading.Channels; | ||
|
|
||
| namespace SonicRelay.Api.Services; | ||
|
|
||
| /// <summary>A committed launch-intent change the bot should react to.</summary> | ||
| public sealed record LaunchIntentEvent(long Sequence, string Type, Guid IntentId); | ||
|
|
||
| public static class LaunchIntentEventTypes | ||
| { | ||
| public const string SessionReady = "session_ready"; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// In-process fan-out of launch-intent events to SSE subscribers. Each subscriber owns a bounded | ||
| /// buffer; a subscriber that falls behind is disconnected (its channel completes) instead of | ||
| /// silently losing events, so its client reconnects and reconciles through | ||
| /// <c>GET /api/launch-intents/pending</c>. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Single-instance by design: events published on one API replica reach only subscribers | ||
| /// connected to that replica. Running several replicas requires a backplane or relying on the | ||
| /// bot's reconciliation; see docs/discord-activity-launch-contract.md. | ||
| /// </remarks> | ||
| public sealed class LaunchIntentEventBroadcaster | ||
| { | ||
| public const int DefaultBufferCapacity = 64; | ||
|
|
||
| private readonly ConcurrentDictionary<long, Subscription> _subscribers = new(); | ||
| private readonly int _bufferCapacity; | ||
| private long _nextSubscriptionId; | ||
| private long _nextSequence; | ||
|
|
||
| public LaunchIntentEventBroadcaster() : this(DefaultBufferCapacity) | ||
| { | ||
| } | ||
|
|
||
| public LaunchIntentEventBroadcaster(int bufferCapacity) | ||
| { | ||
| ArgumentOutOfRangeException.ThrowIfLessThan(bufferCapacity, 1); | ||
| _bufferCapacity = bufferCapacity; | ||
| } | ||
|
|
||
| public int SubscriberCount => _subscribers.Count; | ||
|
|
||
| /// <summary>Registers a subscriber. Events published after this call returns are delivered.</summary> | ||
| public ILaunchIntentSubscription Subscribe() | ||
| { | ||
| var id = Interlocked.Increment(ref _nextSubscriptionId); | ||
| var channel = Channel.CreateBounded<LaunchIntentEvent>(new BoundedChannelOptions(_bufferCapacity) | ||
| { | ||
| SingleReader = true, | ||
| SingleWriter = false, | ||
| FullMode = BoundedChannelFullMode.Wait | ||
| }); | ||
| var subscription = new Subscription(this, id, channel); | ||
| _subscribers[id] = subscription; | ||
| return subscription; | ||
| } | ||
|
|
||
| /// <summary>Publishes an event. Call only after the state change has been committed.</summary> | ||
| public void Publish(string type, Guid intentId) | ||
| { | ||
| var item = new LaunchIntentEvent(Interlocked.Increment(ref _nextSequence), type, intentId); | ||
| foreach (var subscription in _subscribers.Values) | ||
| { | ||
| if (!subscription.Channel.Writer.TryWrite(item)) | ||
| subscription.Overflow(); | ||
| } | ||
| } | ||
|
|
||
| private void Remove(long id) => _subscribers.TryRemove(id, out _); | ||
|
|
||
| private sealed class Subscription( | ||
| LaunchIntentEventBroadcaster owner, long id, Channel<LaunchIntentEvent> channel) : ILaunchIntentSubscription | ||
| { | ||
| public Channel<LaunchIntentEvent> Channel { get; } = channel; | ||
| public ChannelReader<LaunchIntentEvent> Reader => Channel.Reader; | ||
| public bool Overflowed { get; private set; } | ||
|
|
||
| public void Overflow() | ||
| { | ||
| Overflowed = true; | ||
| owner.Remove(id); | ||
| Channel.Writer.TryComplete(); | ||
| } | ||
|
|
||
| public ValueTask DisposeAsync() | ||
| { | ||
| owner.Remove(id); | ||
| Channel.Writer.TryComplete(); | ||
| return ValueTask.CompletedTask; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public interface ILaunchIntentSubscription : IAsyncDisposable | ||
| { | ||
| ChannelReader<LaunchIntentEvent> Reader { get; } | ||
|
|
||
| /// <summary>True when the subscriber was dropped because its buffer filled up.</summary> | ||
| bool Overflowed { get; } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If more than 100 unpublished ready intents accumulate while the bot is disconnected, this bootstrap permanently misses the remainder:
LaunchIntentService.ListRecoverableAsyncorders by creation time and applies.Take(100), so one/pendingrequest is not a complete snapshot. After the bot acknowledges those first 100, the remaining intents emit no new events because their Ready transitions already occurred before subscription. Unlike the previous polling flow, the documented events-only flow never fetches them again until another disconnect. Provide a complete reconciliation mechanism, such as paginated draining or periodic reconciliation, before instructing clients to query only once.Useful? React with 👍 / 👎.