Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions docs/discord-activity-launch-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ All bot operations use `Authorization: Bearer <RelayLaunch:ServiceToken>`:
|---|---|---|
| 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}` |
Expand All @@ -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":"<guid>"}` with `id: <sequence>` | 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
Comment on lines +49 to +51

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reconcile all pending batches before switching to events only

If more than 100 unpublished ready intents accumulate while the bot is disconnected, this bootstrap permanently misses the remainder: LaunchIntentService.ListRecoverableAsync orders by creation time and applies .Take(100), so one /pending request 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 👍 / 👎.

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#<token>`: the fragment is absent from HTTP access logs. The landing
page clears it from history and opens `framerelay://launch?token=<token>`, and shows the configured
download/help link. The operating system cannot reliably report whether a protocol handler is
Expand Down
57 changes: 57 additions & 0 deletions services/SonicRelay.Api/Endpoints/LaunchIntentEndpoints.cs
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;
Expand All @@ -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);
Expand Down Expand Up @@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce the subscriber limit atomically with registration

When multiple authenticated stream requests arrive concurrently near EventsMaxSubscribers, they can all observe a count below the limit before any calls Subscribe(), and all are then admitted. The concurrent dictionary makes individual operations thread-safe but does not make this check-and-register sequence atomic, so the advertised connection/resource bound can be exceeded. Move the capacity check and registration into a single atomic broadcaster operation, and return 503 when that operation cannot reserve a slot.

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)
{
Expand Down
1 change: 1 addition & 0 deletions services/SonicRelay.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@
builder.Services.AddHttpClient("DiscordActivityInstances", client => client.Timeout = TimeSpan.FromSeconds(10));
builder.Services.AddSingleton<DiscordActivityInstanceCache>();
builder.Services.AddSingleton<DeviceCredentialService>();
builder.Services.AddSingleton<LaunchIntentEventBroadcaster>();
builder.Services.AddScoped<LaunchIntentService>();
builder.Services.AddScoped<MediaRelayGrantService>();
builder.Services.AddSingleton<SignalingGrantService>();
Expand Down
103 changes: 103 additions & 0 deletions services/SonicRelay.Api/Services/LaunchIntentEventBroadcaster.cs
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; }
}
6 changes: 6 additions & 0 deletions services/SonicRelay.Api/Services/LaunchIntentOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>Keep-alive cadence on the bot SSE stream; below Cloudflare's ~100s idle cutoff.</summary>
public int EventsHeartbeatSeconds { get; set; } = 20;

/// <summary>Upper bound on concurrent bot SSE connections per API instance.</summary>
public int EventsMaxSubscribers { get; set; } = 8;
}
5 changes: 4 additions & 1 deletion services/SonicRelay.Api/Services/LaunchIntentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ public sealed class LaunchIntentService(
ISessionCodeStore sessionCodeStore,
IConfiguration configuration,
IOptions<LaunchIntentOptions> options,
TimeProvider timeProvider)
TimeProvider timeProvider,
LaunchIntentEventBroadcaster events)
{
private readonly LaunchIntentOptions _options = options.Value;

Expand Down Expand Up @@ -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<IReadOnlyList<ShareLaunchIntent>> ListRecoverableAsync(CancellationToken ct) =>
Expand Down
Loading
Loading