From d24711b5072b0ca2bc92ed0149c4133b03c9d0b8 Mon Sep 17 00:00:00 2001 From: Vitor Hugo <65777252+hugoalves-dev@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:39:27 -0300 Subject: [PATCH] feat(launch-intents): stream session_ready events to the bot via SSE Add GET /api/launch-intents/events under the launch-intents:bot policy. The stream sends connected, then session_ready {intentId} after the Ready transition commits, plus heartbeats. An in-memory broadcaster with bounded per-subscriber buffers disconnects slow readers so they reconcile via /pending. Document the race-safe bootstrap, single-instance limits and rollout. Closes #64 --- docs/discord-activity-launch-contract.md | 40 +++ .../Endpoints/LaunchIntentEndpoints.cs | 57 ++++ services/SonicRelay.Api/Program.cs | 1 + .../Services/LaunchIntentEventBroadcaster.cs | 103 ++++++ .../Services/LaunchIntentOptions.cs | 6 + .../Services/LaunchIntentService.cs | 5 +- .../LaunchIntentEventsTests.cs | 305 ++++++++++++++++++ 7 files changed, 516 insertions(+), 1 deletion(-) create mode 100644 services/SonicRelay.Api/Services/LaunchIntentEventBroadcaster.cs create mode 100644 tests/SonicRelay.Api.IntegrationTests/LaunchIntentEventsTests.cs diff --git a/docs/discord-activity-launch-contract.md b/docs/discord-activity-launch-contract.md index bfb4892..c69c941 100644 --- a/docs/discord-activity-launch-contract.md +++ b/docs/discord-activity-launch-contract.md @@ -12,6 +12,7 @@ All bot operations use `Authorization: Bearer `: |---|---|---| | POST /api/launch-intents/share | `{provider:"discord",guildId,channelId,requestedByUserId,ttlSeconds}` | `{id,launchUrl,expiresAt}` | | GET /api/launch-intents/pending | none | `[{id,guildId,channelId,requestedByUserId,status,expiresAt}]` | +| GET /api/launch-intents/events | `Accept: text/event-stream` | SSE stream, see below | | GET /api/launch-intents/{id} | `watchTtlSeconds` optional | `{id,status,sessionId,watchLaunchUrl,expiresAt}` | | POST /api/launch-intents/{id}/published | `{messageId?}` | 204 | | POST /api/launch-intents/watch | `{code,ttlSeconds}` | `{launchUrl,expiresAt}` | @@ -29,6 +30,45 @@ single-use capability among participants. Each participant runs `/framerelay wat to obtain an individual Activity intent and individual desktop fallback, so status polling does not create unused credentials. +## Bot event stream (SSE) + +`GET /api/launch-intents/events` replaces steady-state polling of `/pending`. It uses the same +`launch-intents:bot` policy and service bearer; anonymous, wrong-token and device callers get +401/403. It never reuses `/ws/signaling`. Frames (`text/event-stream`, `Cache-Control: no-cache`): + +| event | data | when | +|---|---|---| +| `connected` | `{}` (plus `retry: 5000`) | first frame, sent after the subscription is registered | +| `session_ready` | `{"intentId":""}` with `id: ` | after the `Ready` transition has committed | +| `heartbeat` | `{}` | every `LaunchIntents:EventsHeartbeatSeconds` (default 20s) while idle | + +Payloads carry no watch URLs, tokens or Discord ids; fetch details with `GET /{id}` and acknowledge +with `POST /{id}/published` as before. Idempotent completion retries and rejected writes emit +nothing. Clients must ignore unknown event types. + +**Race-safe bootstrap.** On every (re)connect: wait for `connected`, then call `GET /pending` once +and process its ready, unpublished intents. Anything committed before `connected` is in that +snapshot; anything after it arrives on the stream. Duplicates are possible, so handling must be +idempotent on `intentId`. `id` sequences are per process and `Last-Event-ID` is not honoured; +reconciliation through `/pending` (backed by PostgreSQL status and `PublishedAt`) is the recovery +path across API restarts and disconnects. + +**Bounded resources.** Each subscriber has a 64-event buffer; a subscriber that falls behind is +disconnected (stream ends) rather than silently losing events, and recovers by reconnecting. +At most `LaunchIntents:EventsMaxSubscribers` (default 8) streams per instance; extra connections +get 503 `too_many_subscribers`. Heartbeats keep Cloudflare Tunnel (≈100s idle limit) and other +proxies from closing idle streams; any proxy must not buffer the response (`X-Accel-Buffering: no` +is sent). + +**Single instance.** The broadcaster is in-memory. With more than one API replica, a bot connected +to replica A misses events committed on replica B until it reconciles. Before scaling out, add a +backplane (e.g. PostgreSQL `LISTEN/NOTIFY`) or have the bot reconcile `/pending` periodically. + +**Rollout.** Deploy this API first; `/pending` and all other routes are unchanged, so the current +polling bot keeps working. Then enable SSE in the bot (go_discord_FrameRelay#15), which falls back +to low-frequency polling only when `/events` returns 404. Confirm in Cloudflare Analytics that +`/api/launch-intents/pending` traffic drops from the ~86k/day baseline. + Public URLs are `/open/launch#`: the fragment is absent from HTTP access logs. The landing page clears it from history and opens `framerelay://launch?token=`, and shows the configured download/help link. The operating system cannot reliably report whether a protocol handler is diff --git a/services/SonicRelay.Api/Endpoints/LaunchIntentEndpoints.cs b/services/SonicRelay.Api/Endpoints/LaunchIntentEndpoints.cs index 1bd1a3a..8c748c5 100644 --- a/services/SonicRelay.Api/Endpoints/LaunchIntentEndpoints.cs +++ b/services/SonicRelay.Api/Endpoints/LaunchIntentEndpoints.cs @@ -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 ListPendingAsync(LaunchIntentService service, x.ExpiresAt <= DateTimeOffset.UtcNow ? "expired" : x.Status, x.ExpiresAt))); } + /// + /// Server-sent events for the bot. The subscription is registered before the response starts + /// and the first frame is connected; a client that reconciles GET /pending after + /// receiving it cannot miss a session_ready committed in between (duplicates are possible). + /// + private static IResult StreamEvents(HttpContext context, LaunchIntentEventBroadcaster broadcaster, + IOptions 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(); + 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> ReadEventsAsync(ILaunchIntentSubscription subscription, + TimeSpan heartbeat, TimeProvider timeProvider, [EnumeratorCancellation] CancellationToken ct) + { + await using var _ = subscription; + yield return new SseItem("{}", "connected") { ReconnectionInterval = EventsReconnectInterval }; + + var reader = subscription.Reader; + Task? 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("{}", "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( + $"{{\"intentId\":\"{item.IntentId:D}\"}}", item.Type) { EventId = item.Sequence.ToString() }; + } + } + } + private static async Task GetStatusAsync(Guid intentId, int? watchTtlSeconds, LaunchIntentService service, CancellationToken ct) { diff --git a/services/SonicRelay.Api/Program.cs b/services/SonicRelay.Api/Program.cs index 391dff4..a9b4d51 100644 --- a/services/SonicRelay.Api/Program.cs +++ b/services/SonicRelay.Api/Program.cs @@ -136,6 +136,7 @@ builder.Services.AddHttpClient("DiscordActivityInstances", client => client.Timeout = TimeSpan.FromSeconds(10)); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); diff --git a/services/SonicRelay.Api/Services/LaunchIntentEventBroadcaster.cs b/services/SonicRelay.Api/Services/LaunchIntentEventBroadcaster.cs new file mode 100644 index 0000000..a54c14f --- /dev/null +++ b/services/SonicRelay.Api/Services/LaunchIntentEventBroadcaster.cs @@ -0,0 +1,103 @@ +using System.Collections.Concurrent; +using System.Threading.Channels; + +namespace SonicRelay.Api.Services; + +/// A committed launch-intent change the bot should react to. +public sealed record LaunchIntentEvent(long Sequence, string Type, Guid IntentId); + +public static class LaunchIntentEventTypes +{ + public const string SessionReady = "session_ready"; +} + +/// +/// 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 +/// GET /api/launch-intents/pending. +/// +/// +/// 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. +/// +public sealed class LaunchIntentEventBroadcaster +{ + public const int DefaultBufferCapacity = 64; + + private readonly ConcurrentDictionary _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; + + /// Registers a subscriber. Events published after this call returns are delivered. + public ILaunchIntentSubscription Subscribe() + { + var id = Interlocked.Increment(ref _nextSubscriptionId); + var channel = Channel.CreateBounded(new BoundedChannelOptions(_bufferCapacity) + { + SingleReader = true, + SingleWriter = false, + FullMode = BoundedChannelFullMode.Wait + }); + var subscription = new Subscription(this, id, channel); + _subscribers[id] = subscription; + return subscription; + } + + /// Publishes an event. Call only after the state change has been committed. + 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 channel) : ILaunchIntentSubscription + { + public Channel Channel { get; } = channel; + public ChannelReader 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 Reader { get; } + + /// True when the subscriber was dropped because its buffer filled up. + bool Overflowed { get; } +} diff --git a/services/SonicRelay.Api/Services/LaunchIntentOptions.cs b/services/SonicRelay.Api/Services/LaunchIntentOptions.cs index ffcf0ea..cc56fdb 100644 --- a/services/SonicRelay.Api/Services/LaunchIntentOptions.cs +++ b/services/SonicRelay.Api/Services/LaunchIntentOptions.cs @@ -7,4 +7,10 @@ public sealed class LaunchIntentOptions public string PublicBaseUrl { get; set; } = "https://framerelay.hugojava.dev"; public int ShareTtlSeconds { get; set; } = 600; public int WatchTtlSeconds { get; set; } = 1800; + + /// Keep-alive cadence on the bot SSE stream; below Cloudflare's ~100s idle cutoff. + public int EventsHeartbeatSeconds { get; set; } = 20; + + /// Upper bound on concurrent bot SSE connections per API instance. + public int EventsMaxSubscribers { get; set; } = 8; } diff --git a/services/SonicRelay.Api/Services/LaunchIntentService.cs b/services/SonicRelay.Api/Services/LaunchIntentService.cs index 46eb990..81708f0 100644 --- a/services/SonicRelay.Api/Services/LaunchIntentService.cs +++ b/services/SonicRelay.Api/Services/LaunchIntentService.cs @@ -14,7 +14,8 @@ public sealed class LaunchIntentService( ISessionCodeStore sessionCodeStore, IConfiguration configuration, IOptions options, - TimeProvider timeProvider) + TimeProvider timeProvider, + LaunchIntentEventBroadcaster events) { private readonly LaunchIntentOptions _options = options.Value; @@ -101,6 +102,8 @@ public async Task CompleteShareAsync(Guid intentId, Guid deviceId, Guid sessionI { throw new LaunchIntentException("intent_session_mismatch"); } + // Only reached once the Ready transition has committed; idempotent retries return above. + events.Publish(LaunchIntentEventTypes.SessionReady, intent.Id); } public async Task> ListRecoverableAsync(CancellationToken ct) => diff --git a/tests/SonicRelay.Api.IntegrationTests/LaunchIntentEventsTests.cs b/tests/SonicRelay.Api.IntegrationTests/LaunchIntentEventsTests.cs new file mode 100644 index 0000000..88e9e1b --- /dev/null +++ b/tests/SonicRelay.Api.IntegrationTests/LaunchIntentEventsTests.cs @@ -0,0 +1,305 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using Microsoft.Extensions.DependencyInjection; +using SonicRelay.Api.Services; +using SonicRelay.Domain.Devices; +using Xunit; + +namespace SonicRelay.Api.IntegrationTests; + +public sealed class LaunchIntentEventsTests +{ + private const string ServiceToken = "integration-test-discord-service-token"; + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); + + [Fact] + public async Task Events_stream_rejects_anonymous_wrong_token_and_device_callers() + { + using var factory = new SonicRelayApiFactory(); + using var anonymous = factory.CreateClient(); + Assert.Equal(HttpStatusCode.Unauthorized, (await anonymous.GetAsync("/api/launch-intents/events")).StatusCode); + + using var wrong = factory.CreateClient(); + wrong.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "not-the-service-token"); + Assert.Equal(HttpStatusCode.Unauthorized, (await wrong.GetAsync("/api/launch-intents/events")).StatusCode); + + using var device = factory.CreateClient(); + await DeviceIdentityTestHelper.BootstrapAndAuthorizeAsync( + device, DeviceTypes.WindowsPublisher, DevicePlatforms.Windows); + var deviceResponse = await device.GetAsync("/api/launch-intents/events"); + Assert.Contains(deviceResponse.StatusCode, new[] { HttpStatusCode.Unauthorized, HttpStatusCode.Forbidden }); + Assert.Equal(0, factory.Services.GetRequiredService().SubscriberCount); + } + + [Fact] + public async Task Completing_a_share_emits_one_session_ready_after_connected() + { + using var factory = new SonicRelayApiFactory(new Dictionary + { + ["LaunchIntents:EventsHeartbeatSeconds"] = "1" + }); + using var bot = CreateBot(factory); + await using var stream = await SseReader.OpenAsync(bot); + + Assert.Equal("text/event-stream", stream.ContentType); + var connected = await stream.NextAsync(); + Assert.Equal("connected", connected.Type); + Assert.Equal("5000", connected.Retry); + + var (intentId, sessionId, publisher) = await CreateConsumedShareAsync(factory, bot); + var complete = await publisher.PostAsJsonAsync($"/api/launch-intents/share/{intentId}/complete", new { sessionId }); + Assert.Equal(HttpStatusCode.NoContent, complete.StatusCode); + // An idempotent retry must not emit a second notification. + var retry = await publisher.PostAsJsonAsync($"/api/launch-intents/share/{intentId}/complete", new { sessionId }); + Assert.Equal(HttpStatusCode.NoContent, retry.StatusCode); + // A rejected completion must not emit either. + var rejected = await publisher.PostAsJsonAsync($"/api/launch-intents/share/{Guid.NewGuid()}/complete", new { sessionId }); + Assert.Equal(HttpStatusCode.Conflict, rejected.StatusCode); + + var ready = await stream.NextAsync(); + Assert.Equal("session_ready", ready.Type); + Assert.False(string.IsNullOrEmpty(ready.Id)); + var payload = JsonDocument.Parse(ready.Data).RootElement; + Assert.Equal(intentId, payload.GetProperty("intentId").GetGuid()); + Assert.Single(payload.EnumerateObject()); // no watch URLs or capabilities on the wire + + // The bot then fetches authoritative details and acknowledges through the existing routes. + var status = await bot.GetFromJsonAsync($"/api/launch-intents/{intentId}?watchTtlSeconds=0"); + Assert.Equal("session_ready", status.GetProperty("status").GetString()); + var published = await bot.PostAsJsonAsync($"/api/launch-intents/{intentId}/published", new { messageId = "m-1" }); + Assert.Equal(HttpStatusCode.NoContent, published.StatusCode); + + // Retry and rejected completions queued nothing: the next frame is an idle heartbeat. + Assert.Equal("heartbeat", (await stream.NextAsync()).Type); + } + + [Fact] + public async Task Stream_sends_heartbeats_while_idle() + { + using var factory = new SonicRelayApiFactory(new Dictionary + { + ["LaunchIntents:EventsHeartbeatSeconds"] = "1" + }); + using var bot = CreateBot(factory); + await using var stream = await SseReader.OpenAsync(bot); + + Assert.Equal("connected", (await stream.NextAsync()).Type); + Assert.Equal("heartbeat", (await stream.NextAsync()).Type); + Assert.Equal("heartbeat", (await stream.NextAsync()).Type); + } + + [Fact] + public async Task Disconnecting_releases_the_subscription() + { + using var factory = new SonicRelayApiFactory(new Dictionary + { + ["LaunchIntents:EventsHeartbeatSeconds"] = "1" + }); + var broadcaster = factory.Services.GetRequiredService(); + using var bot = CreateBot(factory); + var stream = await SseReader.OpenAsync(bot); + Assert.Equal("connected", (await stream.NextAsync()).Type); + Assert.Equal(1, broadcaster.SubscriberCount); + + await stream.DisposeAsync(); + + await WaitUntilAsync(() => broadcaster.SubscriberCount == 0); + } + + [Fact] + public async Task Subscriber_limit_rejects_extra_connections() + { + using var factory = new SonicRelayApiFactory(new Dictionary + { + ["LaunchIntents:EventsMaxSubscribers"] = "1" + }); + using var bot = CreateBot(factory); + await using var first = await SseReader.OpenAsync(bot); + Assert.Equal("connected", (await first.NextAsync()).Type); + + var second = await bot.GetAsync("/api/launch-intents/events"); + + Assert.Equal(HttpStatusCode.ServiceUnavailable, second.StatusCode); + } + + [Fact] + public async Task Reconnect_reconciles_ready_intents_committed_while_disconnected() + { + using var factory = new SonicRelayApiFactory(); + using var bot = CreateBot(factory); + var (intentId, sessionId, publisher) = await CreateConsumedShareAsync(factory, bot); + (await publisher.PostAsJsonAsync($"/api/launch-intents/share/{intentId}/complete", new { sessionId })) + .EnsureSuccessStatusCode(); // no subscriber connected: this notification is not observed + + await using var stream = await SseReader.OpenAsync(bot); + Assert.Equal("connected", (await stream.NextAsync()).Type); + var pending = await bot.GetFromJsonAsync("/api/launch-intents/pending"); + + var recovered = Assert.Single(pending.EnumerateArray()); + Assert.Equal(intentId, recovered.GetProperty("id").GetGuid()); + Assert.Equal("session_ready", recovered.GetProperty("status").GetString()); + } + + [Fact] + public async Task Broadcaster_delivers_to_every_subscriber_in_order() + { + var broadcaster = new LaunchIntentEventBroadcaster(); + await using var first = broadcaster.Subscribe(); + await using var second = broadcaster.Subscribe(); + var a = Guid.NewGuid(); + var b = Guid.NewGuid(); + + broadcaster.Publish(LaunchIntentEventTypes.SessionReady, a); + broadcaster.Publish(LaunchIntentEventTypes.SessionReady, b); + + foreach (var subscription in new[] { first, second }) + { + Assert.True(subscription.Reader.TryRead(out var one)); + Assert.True(subscription.Reader.TryRead(out var two)); + Assert.Equal(a, one!.IntentId); + Assert.Equal(b, two!.IntentId); + Assert.True(two.Sequence > one.Sequence); + } + } + + [Fact] + public async Task Broadcaster_disconnects_a_slow_subscriber_without_affecting_others() + { + var broadcaster = new LaunchIntentEventBroadcaster(bufferCapacity: 2); + await using var slow = broadcaster.Subscribe(); + await using var fast = broadcaster.Subscribe(); + + for (var i = 0; i < 3; i++) + { + broadcaster.Publish(LaunchIntentEventTypes.SessionReady, Guid.NewGuid()); + while (fast.Reader.TryRead(out _)) { } + } + + Assert.True(slow.Overflowed); + Assert.False(fast.Overflowed); + Assert.Equal(1, broadcaster.SubscriberCount); + // The slow reader drains what it had, then sees completion and must reconnect + reconcile. + Assert.True(slow.Reader.TryRead(out _)); + Assert.True(slow.Reader.TryRead(out _)); + Assert.False(await slow.Reader.WaitToReadAsync()); + } + + [Fact] + public async Task Broadcaster_dispose_unsubscribes() + { + var broadcaster = new LaunchIntentEventBroadcaster(); + var subscription = broadcaster.Subscribe(); + Assert.Equal(1, broadcaster.SubscriberCount); + + await subscription.DisposeAsync(); + broadcaster.Publish(LaunchIntentEventTypes.SessionReady, Guid.NewGuid()); + + Assert.Equal(0, broadcaster.SubscriberCount); + Assert.False(await subscription.Reader.WaitToReadAsync()); + } + + private static HttpClient CreateBot(SonicRelayApiFactory factory) + { + var bot = factory.CreateClient(); + bot.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", ServiceToken); + return bot; + } + + private static async Task<(Guid IntentId, Guid SessionId, HttpClient Publisher)> CreateConsumedShareAsync( + SonicRelayApiFactory factory, HttpClient bot) + { + var created = await bot.PostAsJsonAsync("/api/launch-intents/share", new + { + provider = "discord", guildId = "guild-1", channelId = "channel-2", requestedByUserId = "user-3" + }); + created.EnsureSuccessStatusCode(); + var launch = await created.Content.ReadFromJsonAsync(); + var url = launch.GetProperty("launchUrl").GetString()!; + var token = url[(url.LastIndexOf('/') + 1)..]; + + var publisher = factory.CreateClient(); + await DeviceIdentityTestHelper.BootstrapAndAuthorizeAsync( + publisher, DeviceTypes.WindowsPublisher, DevicePlatforms.Windows); + (await publisher.PostAsJsonAsync("/api/launch-intents/share/consume", new { token })).EnsureSuccessStatusCode(); + var session = await (await publisher.PostAsJsonAsync("/api/sessions", new { maxViewers = 3, mode = "screen_share" })) + .Content.ReadFromJsonAsync(); + return (launch.GetProperty("id").GetGuid(), session.GetProperty("id").GetGuid(), publisher); + } + + private static async Task WaitUntilAsync(Func condition) + { + var deadline = DateTime.UtcNow + Timeout; + while (!condition()) + { + if (DateTime.UtcNow > deadline) throw new TimeoutException("Condition was not met."); + await Task.Delay(25); + } + } + + private sealed record SseFrame(string? Type, string Data, string? Id, string? Retry); + + /// Minimal text/event-stream reader for asserting on the wire format. + private sealed class SseReader : IAsyncDisposable + { + private readonly HttpResponseMessage _response; + private readonly StreamReader _reader; + private readonly CancellationTokenSource _cancellation = new(); + + private SseReader(HttpResponseMessage response, Stream body) + { + _response = response; + _reader = new StreamReader(body); + } + + public string? ContentType => _response.Content.Headers.ContentType?.MediaType; + + public static async Task OpenAsync(HttpClient client) + { + var request = new HttpRequestMessage(HttpMethod.Get, "/api/launch-intents/events"); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); + var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + return new SseReader(response, await response.Content.ReadAsStreamAsync()); + } + + public async Task NextAsync() + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(_cancellation.Token); + timeout.CancelAfter(Timeout); + string? type = null, id = null, retry = null; + var data = new List(); + while (true) + { + var line = await _reader.ReadLineAsync(timeout.Token) + ?? throw new EndOfStreamException("SSE stream ended."); + if (line.Length == 0) + { + if (type is null && data.Count == 0) continue; + return new SseFrame(type, string.Join('\n', data), id, retry); + } + if (line.StartsWith(':')) continue; + var separator = line.IndexOf(':'); + var field = separator < 0 ? line : line[..separator]; + var value = separator < 0 ? string.Empty : line[(separator + 1)..].TrimStart(' '); + switch (field) + { + case "event": type = value; break; + case "data": data.Add(value); break; + case "id": id = value; break; + case "retry": retry = value; break; + } + } + } + + public ValueTask DisposeAsync() + { + _cancellation.Cancel(); + _reader.Dispose(); + _response.Dispose(); + _cancellation.Dispose(); + return ValueTask.CompletedTask; + } + } +}