-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Add SseFormatter #109832
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
Merged
Merged
Add SseFormatter #109832
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
3e74111
Add SseFormatter.
eiriktsarpalis 5664a32
Update src/libraries/System.Net.ServerSentEvents/src/Resources/String…
eiriktsarpalis 4d8d363
Document SseItem exceptions.
eiriktsarpalis 7a476b1
Misc improvements and fixes.
eiriktsarpalis 1b7a3e5
Reinstate ordering of parameters in serialization callback.
eiriktsarpalis 1a12c51
Add SseItem<T>.ReconnectionInterval.
eiriktsarpalis 08334b6
Merge branch 'main' into add-sse-writer
eiriktsarpalis 2bae6f9
Address feedback.
eiriktsarpalis 06951dc
Add parser validation for too small or too large retry intervals.
eiriktsarpalis da3ef4d
Update src/libraries/System.Net.ServerSentEvents/src/System/Net/Serve…
eiriktsarpalis aa27ac4
Handle CR line breaks.
eiriktsarpalis b35c650
Simplify PooledByteBufferWriter.
eiriktsarpalis 5060dba
Merge branch 'main' into add-sse-writer
eiriktsarpalis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
100 changes: 100 additions & 0 deletions
100
src/libraries/System.Net.ServerSentEvents/src/System/Net/ServerSentEvents/Helpers.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Buffers; | ||
| using System.Diagnostics; | ||
| using System.Globalization; | ||
| using System.IO; | ||
| using System.Runtime.InteropServices; | ||
| using System.Text; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace System.Net.ServerSentEvents | ||
| { | ||
| internal static class Helpers | ||
| { | ||
| public static void WriteUtf8Number(this IBufferWriter<byte> writer, long value) | ||
| { | ||
| #if NET | ||
| const int MaxDecimalDigits = 20; | ||
| Span<byte> buffer = writer.GetSpan(MaxDecimalDigits); | ||
| Debug.Assert(MaxDecimalDigits <= buffer.Length); | ||
|
|
||
| bool success = value.TryFormat(buffer, out int bytesWritten, provider: CultureInfo.InvariantCulture); | ||
| Debug.Assert(success); | ||
| writer.Advance(bytesWritten); | ||
| #else | ||
| writer.WriteUtf8String(value.ToString(CultureInfo.InvariantCulture)); | ||
| #endif | ||
| } | ||
|
|
||
| public static void WriteUtf8String(this IBufferWriter<byte> writer, ReadOnlySpan<byte> value) | ||
| { | ||
| if (value.IsEmpty) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| Span<byte> buffer = writer.GetSpan(value.Length); | ||
| Debug.Assert(value.Length <= buffer.Length); | ||
| value.CopyTo(buffer); | ||
| writer.Advance(value.Length); | ||
| } | ||
|
|
||
| public static unsafe void WriteUtf8String(this IBufferWriter<byte> writer, ReadOnlySpan<char> value) | ||
| { | ||
| if (value.IsEmpty) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| int maxByteCount = Encoding.UTF8.GetMaxByteCount(value.Length); | ||
| Span<byte> buffer = writer.GetSpan(maxByteCount); | ||
| Debug.Assert(maxByteCount <= buffer.Length); | ||
| int bytesWritten; | ||
| #if NET | ||
| bytesWritten = Encoding.UTF8.GetBytes(value, buffer); | ||
| #else | ||
| fixed (char* chars = value) | ||
| fixed (byte* bytes = buffer) | ||
| { | ||
| bytesWritten = Encoding.UTF8.GetBytes(chars, value.Length, bytes, maxByteCount); | ||
| } | ||
| #endif | ||
| writer.Advance(bytesWritten); | ||
| } | ||
|
|
||
| public static bool ContainsLineBreaks(this ReadOnlySpan<char> text) => | ||
| text.IndexOfAny('\r', '\n') >= 0; | ||
|
|
||
| #if !NET | ||
|
|
||
| public static ValueTask WriteAsync(this Stream stream, ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) | ||
| { | ||
| if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> segment)) | ||
| { | ||
| return new ValueTask(stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken)); | ||
| } | ||
| else | ||
| { | ||
| return WriteAsyncUsingPooledBuffer(stream, buffer, cancellationToken); | ||
|
|
||
| static async ValueTask WriteAsyncUsingPooledBuffer(Stream stream, ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) | ||
| { | ||
| byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length); | ||
| buffer.Span.CopyTo(sharedBuffer); | ||
| try | ||
| { | ||
| await stream.WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); | ||
| } | ||
| finally | ||
| { | ||
| ArrayPool<byte>.Shared.Return(sharedBuffer); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| #endif | ||
| } | ||
| } | ||
33 changes: 33 additions & 0 deletions
33
...ies/System.Net.ServerSentEvents/src/System/Net/ServerSentEvents/PooledByteBufferWriter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Buffers; | ||
| using System.Diagnostics; | ||
|
|
||
| namespace System.Net.ServerSentEvents | ||
| { | ||
| internal sealed class PooledByteBufferWriter : IBufferWriter<byte>, IDisposable | ||
eiriktsarpalis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| private ArrayBuffer _buffer = new(initialSize: 256, usePool: true); | ||
|
|
||
| public void Advance(int count) => _buffer.Commit(count); | ||
|
|
||
| public Memory<byte> GetMemory(int sizeHint = 0) | ||
| { | ||
| _buffer.EnsureAvailableSpace(sizeHint); | ||
| return _buffer.AvailableMemory; | ||
| } | ||
|
|
||
| public Span<byte> GetSpan(int sizeHint = 0) | ||
| { | ||
| _buffer.EnsureAvailableSpace(sizeHint); | ||
| return _buffer.AvailableSpan; | ||
| } | ||
|
|
||
| public ReadOnlyMemory<byte> WrittenMemory => _buffer.ActiveMemory; | ||
| public int Capacity => _buffer.Capacity; | ||
| public int WrittenCount => _buffer.ActiveLength; | ||
| public void Reset() => _buffer.Discard(_buffer.ActiveLength); | ||
| public void Dispose() => _buffer.Dispose(); | ||
| } | ||
| } | ||
166 changes: 166 additions & 0 deletions
166
src/libraries/System.Net.ServerSentEvents/src/System/Net/ServerSentEvents/SseFormatter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,166 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Buffers; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics; | ||
| using System.IO; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace System.Net.ServerSentEvents | ||
| { | ||
| /// <summary> | ||
| /// Provides methods for formatting server-sent events. | ||
| /// </summary> | ||
| public static class SseFormatter | ||
| { | ||
| private static readonly byte[] s_newLine = "\n"u8.ToArray(); | ||
|
|
||
| /// <summary> | ||
| /// Writes the <paramref name="source"/> of server-sent events to the <paramref name="destination"/> stream. | ||
| /// </summary> | ||
| /// <param name="source">The events to write to the stream.</param> | ||
| /// <param name="destination">The destination stream to write the events.</param> | ||
| /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to cancel the write operation.</param> | ||
| /// <returns>A task that represents the asynchronous write operation.</returns> | ||
| public static Task WriteAsync(IAsyncEnumerable<SseItem<string>> source, Stream destination, CancellationToken cancellationToken = default) | ||
| { | ||
| if (source is null) | ||
| { | ||
| ThrowHelper.ThrowArgumentNullException(nameof(source)); | ||
| } | ||
|
|
||
| if (destination is null) | ||
| { | ||
| ThrowHelper.ThrowArgumentNullException(nameof(destination)); | ||
| } | ||
|
|
||
| return WriteAsyncCore(source, destination, static (item, writer) => writer.WriteUtf8String(item.Data), cancellationToken); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Writes the <paramref name="source"/> of server-sent events to the <paramref name="destination"/> stream. | ||
| /// </summary> | ||
| /// <typeparam name="T">The data type of the event.</typeparam> | ||
| /// <param name="source">The events to write to the stream.</param> | ||
| /// <param name="destination">The destination stream to write the events.</param> | ||
| /// <param name="itemFormatter">The formatter for the data field of given event.</param> | ||
| /// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to cancel the write operation.</param> | ||
| /// <returns>A task that represents the asynchronous write operation.</returns> | ||
| public static Task WriteAsync<T>(IAsyncEnumerable<SseItem<T>> source, Stream destination, Action<SseItem<T>, IBufferWriter<byte>> itemFormatter, CancellationToken cancellationToken = default) | ||
| { | ||
| if (source is null) | ||
| { | ||
| ThrowHelper.ThrowArgumentNullException(nameof(source)); | ||
| } | ||
|
|
||
| if (destination is null) | ||
| { | ||
| ThrowHelper.ThrowArgumentNullException(nameof(destination)); | ||
| } | ||
|
|
||
| if (itemFormatter is null) | ||
| { | ||
| ThrowHelper.ThrowArgumentNullException(nameof(itemFormatter)); | ||
| } | ||
|
|
||
| return WriteAsyncCore(source, destination, itemFormatter, cancellationToken); | ||
| } | ||
|
|
||
| private static async Task WriteAsyncCore<T>(IAsyncEnumerable<SseItem<T>> source, Stream destination, Action<SseItem<T>, IBufferWriter<byte>> itemFormatter, CancellationToken cancellationToken) | ||
| { | ||
| using PooledByteBufferWriter bufferWriter = new(); | ||
| using PooledByteBufferWriter userDataBufferWriter = new(); | ||
|
|
||
| await foreach (SseItem<T> item in source.WithCancellation(cancellationToken).ConfigureAwait(false)) | ||
| { | ||
| itemFormatter(item, userDataBufferWriter); | ||
|
|
||
| FormatSseEvent( | ||
| bufferWriter, | ||
| eventType: item._eventType, // Do not use the public property since it normalizes to "message" if null | ||
| data: userDataBufferWriter.WrittenMemory.Span, | ||
| eventId: item.EventId, | ||
| reconnectionInterval: item.ReconnectionInterval); | ||
|
|
||
| await destination.WriteAsync(bufferWriter.WrittenMemory, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| userDataBufferWriter.Reset(); | ||
| bufferWriter.Reset(); | ||
| } | ||
| } | ||
|
|
||
| private static void FormatSseEvent( | ||
| PooledByteBufferWriter bufferWriter, | ||
| string? eventType, | ||
| ReadOnlySpan<byte> data, | ||
| string? eventId, | ||
| TimeSpan? reconnectionInterval) | ||
| { | ||
| Debug.Assert(bufferWriter.WrittenCount is 0); | ||
|
|
||
| if (eventType is not null) | ||
| { | ||
| Debug.Assert(!eventType.ContainsLineBreaks()); | ||
|
|
||
| bufferWriter.WriteUtf8String("event: "u8); | ||
| bufferWriter.WriteUtf8String(eventType); | ||
| bufferWriter.WriteUtf8String(s_newLine); | ||
| } | ||
|
|
||
| WriteLinesWithPrefix(bufferWriter, prefix: "data: "u8, data); | ||
| bufferWriter.Write(s_newLine); | ||
|
|
||
| if (eventId is not null) | ||
| { | ||
| Debug.Assert(!eventId.ContainsLineBreaks()); | ||
|
|
||
| bufferWriter.WriteUtf8String("id: "u8); | ||
| bufferWriter.WriteUtf8String(eventId); | ||
| bufferWriter.WriteUtf8String(s_newLine); | ||
| } | ||
|
|
||
| if (reconnectionInterval is { } retry) | ||
| { | ||
| Debug.Assert(retry >= TimeSpan.Zero); | ||
|
|
||
| bufferWriter.WriteUtf8String("retry: "u8); | ||
| bufferWriter.WriteUtf8Number((long)retry.TotalMilliseconds); | ||
| bufferWriter.WriteUtf8String(s_newLine); | ||
| } | ||
|
|
||
| bufferWriter.WriteUtf8String(s_newLine); | ||
| } | ||
|
|
||
| private static void WriteLinesWithPrefix(PooledByteBufferWriter writer, ReadOnlySpan<byte> prefix, ReadOnlySpan<byte> data) | ||
| { | ||
| // Writes a potentially multi-line string, prefixing each line with the given prefix. | ||
| // Both \n and \r\n sequences are normalized to \n. | ||
|
|
||
| while (true) | ||
| { | ||
| writer.WriteUtf8String(prefix); | ||
|
|
||
| int i = data.IndexOfAny((byte)'\r', (byte)'\n'); | ||
| if (i < 0) | ||
| { | ||
| writer.WriteUtf8String(data); | ||
| return; | ||
| } | ||
|
|
||
| int lineLength = i; | ||
| if (data[i++] == '\r' && i < data.Length && data[i] == '\n') | ||
| { | ||
| i++; | ||
| } | ||
|
|
||
| ReadOnlySpan<byte> nextLine = data.Slice(0, lineLength); | ||
| data = data.Slice(i); | ||
|
|
||
| writer.WriteUtf8String(nextLine); | ||
| writer.WriteUtf8String(s_newLine); | ||
| } | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.