|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using System.Buffers; |
| 5 | +using System.Net.ServerSentEvents; |
| 6 | +using Microsoft.AspNetCore.Http.Metadata; |
| 7 | +using System.Reflection; |
| 8 | +using Microsoft.AspNetCore.Builder; |
| 9 | +using System.Text.Json; |
| 10 | +using Microsoft.Extensions.Options; |
| 11 | +using Microsoft.AspNetCore.Http.Json; |
| 12 | +using Microsoft.Extensions.DependencyInjection; |
| 13 | +using Microsoft.AspNetCore.Http.Features; |
| 14 | + |
| 15 | +namespace Microsoft.AspNetCore.Http.HttpResults; |
| 16 | + |
| 17 | +/// <summary> |
| 18 | +/// Represents a result that writes a stream of server-sent events to the response. |
| 19 | +/// </summary> |
| 20 | +/// <typeparam name="T">The underlying type of the events emitted.</typeparam> |
| 21 | +public sealed class ServerSentEventsResult<T> : IResult, IEndpointMetadataProvider, IStatusCodeHttpResult |
| 22 | +{ |
| 23 | + private readonly IAsyncEnumerable<SseItem<T>> _events; |
| 24 | + |
| 25 | + /// <inheritdoc/> |
| 26 | + public int? StatusCode => StatusCodes.Status200OK; |
| 27 | + |
| 28 | + internal ServerSentEventsResult(IAsyncEnumerable<T> events, string? eventType) |
| 29 | + { |
| 30 | + _events = WrapEvents(events, eventType); |
| 31 | + } |
| 32 | + |
| 33 | + internal ServerSentEventsResult(IAsyncEnumerable<SseItem<T>> events) |
| 34 | + { |
| 35 | + _events = events; |
| 36 | + } |
| 37 | + |
| 38 | + /// <inheritdoc /> |
| 39 | + public async Task ExecuteAsync(HttpContext httpContext) |
| 40 | + { |
| 41 | + ArgumentNullException.ThrowIfNull(httpContext); |
| 42 | + |
| 43 | + httpContext.Response.ContentType = "text/event-stream"; |
| 44 | + httpContext.Response.Headers.CacheControl = "no-cache,no-store"; |
| 45 | + httpContext.Response.Headers.Pragma = "no-cache"; |
| 46 | + httpContext.Response.Headers.ContentEncoding = "identity"; |
| 47 | + |
| 48 | + var bufferingFeature = httpContext.Features.GetRequiredFeature<IHttpResponseBodyFeature>(); |
| 49 | + bufferingFeature.DisableBuffering(); |
| 50 | + |
| 51 | + var jsonOptions = httpContext.RequestServices.GetService<IOptions<JsonOptions>>()?.Value ?? new JsonOptions(); |
| 52 | + |
| 53 | + // If the event type is string, we can skip JSON serialization |
| 54 | + // and directly use the SseFormatter's WriteAsync overload for strings. |
| 55 | + if (_events is IAsyncEnumerable<SseItem<string>> stringEvents) |
| 56 | + { |
| 57 | + await SseFormatter.WriteAsync(stringEvents, httpContext.Response.Body, httpContext.RequestAborted); |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + await SseFormatter.WriteAsync(_events, httpContext.Response.Body, |
| 62 | + (item, writer) => FormatSseItem(item, writer, jsonOptions), |
| 63 | + httpContext.RequestAborted); |
| 64 | + } |
| 65 | + |
| 66 | + private static void FormatSseItem(SseItem<T> item, IBufferWriter<byte> writer, JsonOptions jsonOptions) |
| 67 | + { |
| 68 | + if (item.Data is null) |
| 69 | + { |
| 70 | + writer.Write([]); |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + // Handle byte arrays byt writing them directly as strings. |
| 75 | + if (item.Data is byte[] byteArray) |
| 76 | + { |
| 77 | + writer.Write(byteArray); |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + // For non-string types, use JSON serialization with options from DI |
| 82 | + var runtimeType = item.Data.GetType(); |
| 83 | + var jsonTypeInfo = jsonOptions.SerializerOptions.GetTypeInfo(typeof(T)); |
| 84 | + |
| 85 | + // Use the appropriate JsonTypeInfo based on whether we need polymorphic serialization |
| 86 | + var typeInfo = jsonTypeInfo.ShouldUseWith(runtimeType) |
| 87 | + ? jsonTypeInfo |
| 88 | + : jsonOptions.SerializerOptions.GetTypeInfo(typeof(object)); |
| 89 | + |
| 90 | + var json = JsonSerializer.SerializeToUtf8Bytes(item.Data, typeInfo); |
| 91 | + writer.Write(json); |
| 92 | + } |
| 93 | + |
| 94 | + private static async IAsyncEnumerable<SseItem<T>> WrapEvents(IAsyncEnumerable<T> events, string? eventType = null) |
| 95 | + { |
| 96 | + await foreach (var item in events) |
| 97 | + { |
| 98 | + yield return new SseItem<T>(item, eventType); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + static void IEndpointMetadataProvider.PopulateMetadata(MethodInfo method, EndpointBuilder builder) |
| 103 | + { |
| 104 | + ArgumentNullException.ThrowIfNull(method); |
| 105 | + ArgumentNullException.ThrowIfNull(builder); |
| 106 | + |
| 107 | + builder.Metadata.Add(new ProducesResponseTypeMetadata(StatusCodes.Status200OK, typeof(SseItem<T>), contentTypes: ["text/event-stream"])); |
| 108 | + } |
| 109 | +} |
0 commit comments