using System; using System.Text; using System.Threading; using xCommons.Extensions; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; namespace xHttpService.Extensions { /// /// Server-Sent Events (SSE) Helpers ... /// Format (per Spec): [event: name\n] data: line\n ... \n /// public static class XSseExtensions { // // Event Names ... public const string SseDoneEvent = "done"; public const string SseErrorEvent = "error"; public const string SseContentType = "text/event-stream; charset=utf-8"; /// /// Configure Response for SSE (Headers + Disable Buffering) ... /// Must be Called before any Write ... /// /// public static void PrepareSseResponse( this HttpResponse source ) { // if (source.IsNull() || source.HasStarted) { return; } // source.StatusCode = StatusCodes.Status200OK; source.ContentType = SseContentType; source.Headers["Cache-Control"] = "no-cache, no-store"; source.Headers["X-Accel-Buffering"] = "no"; // // Disable Response Buffering ... source.HttpContext.Features .Get()? .DisableResponseBuffering(); } /// /// Write an Object as JSON (camelCase) SSE Event ... /// public static Task WriteSseEventAsync( this HttpResponse source, T data, string eventName = null, CancellationToken cancellationToken = default ) { // var payload = data.IsNull() ? "null" : data.ToJSON(camelCase: true); // return source.WriteSseRawAsync(payload, eventName, cancellationToken); } /// /// Write Raw Text as SSE Event (Multi Line Text is Split into Multiple data: Lines) ... /// public static async Task WriteSseRawAsync( this HttpResponse source, string payload, string eventName = null, CancellationToken cancellationToken = default ) { // var builder = new StringBuilder(); if (!eventName.IsNullOrEmpty()) { builder.Append("event: ").Append(eventName).Append('\n'); } // var normalized = (payload ?? string.Empty) .Replace("\r\n", "\n") .Replace('\r', '\n'); foreach (var line in normalized.Split('\n')) { builder.Append("data: ").Append(line).Append('\n'); } builder.Append('\n'); // await source.WriteAsync(builder.ToString(), Encoding.UTF8, cancellationToken); await source.Body.FlushAsync(cancellationToken); } /// /// Write Terminating "done" Event ... /// public static Task WriteSseDoneAsync( this HttpResponse source, CancellationToken cancellationToken = default ) { return source.WriteSseRawAsync("[DONE]", SseDoneEvent, cancellationToken); } /// /// Write "error" Event (Never Throws; Used when Stream has Already Started) ... /// public static async Task WriteSseErrorAsync( this HttpResponse source, string message ) { // try { await source.WriteSseEventAsync( data: new { error = message ?? "Stream Failed" }, eventName: SseErrorEvent, cancellationToken: CancellationToken.None ); } catch { // Client Gone ... } } /// /// Is Exception Caused by Client Disconnect / Cancellation ... /// public static bool IsClientCancellation( this Exception source, CancellationToken cancellationToken ) { return source is OperationCanceledException && cancellationToken.IsCancellationRequested; } } }