-
-
Notifications
You must be signed in to change notification settings - Fork 722
/
EventStreamResultFormatter.cs
182 lines (164 loc) · 6.97 KB
/
EventStreamResultFormatter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
using System;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using HotChocolate.Utilities;
using static HotChocolate.Execution.ExecutionResultKind;
namespace HotChocolate.Execution.Serialization;
/// <summary>
/// The default GraphQL-SSE formatter for <see cref="IExecutionResult"/>.
/// https://github.com/enisdenjo/graphql-sse/blob/master/PROTOCOL.md
/// </summary>
public sealed class EventStreamResultFormatter : IExecutionResultFormatter
{
private static readonly byte[] _eventField
= { (byte)'e', (byte)'v', (byte)'e', (byte)'n', (byte)'t', (byte)':', (byte)' ' };
private static readonly byte[] _dataField
= { (byte)'d', (byte)'a', (byte)'t', (byte)'a', (byte)':', (byte)' ' };
private static readonly byte[] _nextEvent
= { (byte)'n', (byte)'e', (byte)'x', (byte)'t' };
private static readonly byte[] _completeEvent
=
{
(byte)'c', (byte)'o', (byte)'m', (byte)'p',
(byte)'l', (byte)'e', (byte)'t', (byte)'e'
};
private static readonly byte[] _newLine = { (byte)'\n' };
private readonly JsonResultFormatter _payloadFormatter;
private readonly JsonWriterOptions _options;
/// <summary>
/// Creates a new instance of <see cref="EventStreamResultFormatter" />.
/// </summary>
/// <param name="indented">
/// Defines whether the underlying <see cref="Utf8JsonWriter"/>
/// should pretty print the JSON which includes:
/// indenting nested JSON tokens, adding new lines, and adding
/// white space between property names and values.
/// By default, the JSON is written without any extra white space.
/// </param>
/// <param name="encoder">
/// Gets or sets the encoder to use when escaping strings, or null to use the default encoder.
/// </param>
public EventStreamResultFormatter(
bool indented = false,
JavaScriptEncoder? encoder = null)
{
_options = new JsonWriterOptions { Indented = indented, Encoder = encoder };
_payloadFormatter = new JsonResultFormatter(indented, encoder);
}
/// <inheritdoc cref="IExecutionResultFormatter.FormatAsync(IExecutionResult, Stream, CancellationToken)" />
public ValueTask FormatAsync(
IExecutionResult result,
Stream outputStream,
CancellationToken cancellationToken = default)
{
if (result is null)
{
throw new ArgumentNullException(nameof(result));
}
if (outputStream is null)
{
throw new ArgumentNullException(nameof(outputStream));
}
return FormatInternalAsync(result, outputStream, cancellationToken);
}
private async ValueTask FormatInternalAsync(
IExecutionResult result,
Stream outputStream,
CancellationToken ct)
{
if (result.Kind is SingleResult)
{
await WriteNextMessageAsync((IQueryResult)result, outputStream).ConfigureAwait(false);
await WriteNewLineAndFlushAsync(outputStream, ct).ConfigureAwait(false);
await WriteCompleteMessage(outputStream).ConfigureAwait(false);
await WriteNewLineAndFlushAsync(outputStream, ct).ConfigureAwait(false);
}
else if (result.Kind is DeferredResult or BatchResult or SubscriptionResult)
{
var responseStream = (IResponseStream)result;
await foreach (var queryResult in responseStream.ReadResultsAsync()
.WithCancellation(ct).ConfigureAwait(false))
{
try
{
await WriteNextMessageAsync(queryResult, outputStream)
.ConfigureAwait(false);
}
finally
{
await queryResult.DisposeAsync().ConfigureAwait(false);
}
await WriteNewLineAndFlushAsync(outputStream, ct).ConfigureAwait(false);
}
await WriteCompleteMessage(outputStream).ConfigureAwait(false);
await WriteNewLineAndFlushAsync(outputStream, ct).ConfigureAwait(false);
}
else
{
throw new NotSupportedException();
}
}
private async ValueTask WriteNextMessageAsync(IQueryResult result, Stream outputStream)
{
#if NETCOREAPP3_1_OR_GREATER
await outputStream.WriteAsync(_eventField).ConfigureAwait(false);
await outputStream.WriteAsync(_nextEvent).ConfigureAwait(false);
await outputStream.WriteAsync(_newLine).ConfigureAwait(false);
#else
await outputStream.WriteAsync(_eventField, 0, _eventField.Length).ConfigureAwait(false);
await outputStream.WriteAsync(_nextEvent, 0, _nextEvent.Length).ConfigureAwait(false);
await outputStream.WriteAsync(_newLine, 0, _newLine.Length).ConfigureAwait(false);
#endif
using var bufferWriter = new ArrayWriter();
await using (var writer = new Utf8JsonWriter(bufferWriter, _options))
{
_payloadFormatter.Format(result, writer);
}
var read = 0;
while (read < bufferWriter.Length)
{
var buffer = bufferWriter.Body.Slice(read);
if (buffer.Span.IndexOf(_newLine) is var newLineIndex && newLineIndex != -1)
{
buffer = buffer.Slice(0, newLineIndex);
}
#if NETCOREAPP3_1_OR_GREATER
await outputStream.WriteAsync(_dataField).ConfigureAwait(false);
await outputStream.WriteAsync(buffer).ConfigureAwait(false);
await outputStream.WriteAsync(_newLine).ConfigureAwait(false);
#else
await outputStream.WriteAsync(_dataField, 0, _dataField.Length).ConfigureAwait(false);
await outputStream.WriteAsync(bufferWriter.GetInternalBuffer(), read, buffer.Length)
.ConfigureAwait(false);
await outputStream.WriteAsync(_newLine, 0, _newLine.Length).ConfigureAwait(false);
#endif
read += buffer.Length + 1;
}
}
private static async ValueTask WriteCompleteMessage(Stream outputStream)
{
#if NETCOREAPP3_1_OR_GREATER
await outputStream.WriteAsync(_eventField).ConfigureAwait(false);
await outputStream.WriteAsync(_completeEvent).ConfigureAwait(false);
await outputStream.WriteAsync(_newLine).ConfigureAwait(false);
#else
await outputStream.WriteAsync(_eventField, 0, _eventField.Length).ConfigureAwait(false);
await outputStream.WriteAsync(_completeEvent, 0, _completeEvent.Length).ConfigureAwait(false);
await outputStream.WriteAsync(_newLine, 0, _newLine.Length).ConfigureAwait(false);
#endif
}
private static async ValueTask WriteNewLineAndFlushAsync(
Stream outputStream,
CancellationToken ct)
{
#if NETCOREAPP3_1_OR_GREATER
await outputStream.WriteAsync(_newLine, ct).ConfigureAwait(false);
#else
await outputStream.WriteAsync(_newLine, 0, _newLine.Length, ct).ConfigureAwait(false);
#endif
await outputStream.FlushAsync(ct);
}
}