forked from microsoft/vs-streamjsonrpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpClientMessageHandler.cs
213 lines (190 loc) · 8.57 KB
/
HttpClientMessageHandler.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Buffers;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using Microsoft.VisualStudio.Threading;
using Nerdbank.Streams;
using StreamJsonRpc;
using StreamJsonRpc.Protocol;
/// <summary>
/// A <see cref="IJsonRpcMessageHandler"/> that sends requests and receives responses over HTTP using <see cref="HttpClient"/>.
/// </summary>
/// <remarks>
/// See the spec for JSON-RPC over HTTP here: https://www.jsonrpc.org/historical/json-rpc-over-http.html.
/// Only the POST method is supported.
/// </remarks>
public class HttpClientMessageHandler : IJsonRpcMessageHandler
{
private static readonly ReadOnlyCollection<string> AllowedContentTypes = new ReadOnlyCollection<string>(new string[]
{
"application/json-rpc",
"application/json",
"application/jsonrequest",
});
/// <summary>
/// The Content-Type header to use in requests.
/// </summary>
private static readonly MediaTypeHeaderValue ContentTypeHeader = new MediaTypeHeaderValue(AllowedContentTypes[0]);
/// <summary>
/// The Accept header to use in requests.
/// </summary>
private static readonly MediaTypeWithQualityHeaderValue AcceptHeader = new MediaTypeWithQualityHeaderValue(AllowedContentTypes[0]);
private readonly HttpClient httpClient;
private readonly Uri requestUri;
private readonly AsyncQueue<HttpResponseMessage> incomingMessages = new AsyncQueue<HttpResponseMessage>();
/// <summary>
/// Backing field for the <see cref="TraceSource"/> property.
/// </summary>
private TraceSource traceSource = new TraceSource(nameof(JsonRpc));
/// <summary>
/// Initializes a new instance of the <see cref="HttpClientMessageHandler"/> class
/// with the default <see cref="JsonMessageFormatter"/>.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> to use for transmitting JSON-RPC requests.</param>
/// <param name="requestUri">The URI to POST to where the entity will be the JSON-RPC message.</param>
public HttpClientMessageHandler(HttpClient httpClient, Uri requestUri)
: this(httpClient, requestUri, new JsonMessageFormatter())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HttpClientMessageHandler"/> class.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> to use for transmitting JSON-RPC requests.</param>
/// <param name="requestUri">The URI to POST to where the entity will be the JSON-RPC message.</param>
/// <param name="formatter">The message formatter.</param>
public HttpClientMessageHandler(HttpClient httpClient, Uri requestUri, IJsonRpcMessageFormatter formatter)
{
this.httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
this.requestUri = requestUri ?? throw new ArgumentNullException(nameof(requestUri));
this.Formatter = formatter ?? throw new ArgumentNullException(nameof(formatter));
}
/// <summary>
/// Event IDs raised to our <see cref="TraceSource"/>.
/// </summary>
public enum TraceEvents
{
/// <summary>
/// An HTTP response with an error status code was received.
/// </summary>
HttpErrorStatusCodeReceived,
}
/// <summary>
/// Gets or sets the <see cref="System.Diagnostics.TraceSource"/> used to trace details about the HTTP transport operations.
/// </summary>
/// <value>The value can never be null.</value>
/// <exception cref="ArgumentNullException">Thrown by the setter if a null value is provided.</exception>
public TraceSource TraceSource
{
get => this.traceSource;
set
{
Requires.NotNull(value, nameof(value));
this.traceSource = value;
}
}
/// <inheritdoc/>
public bool CanRead => true;
/// <inheritdoc/>
public bool CanWrite => true;
/// <inheritdoc/>
public IJsonRpcMessageFormatter Formatter { get; }
/// <inheritdoc/>
public async ValueTask<JsonRpcMessage> ReadAsync(CancellationToken cancellationToken)
{
var response = await this.incomingMessages.DequeueAsync(cancellationToken).ConfigureAwait(false);
var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
using (var sequence = new Sequence<byte>())
{
#if NETCOREAPP2_1
int bytesRead;
do
{
var memory = sequence.GetMemory(4096);
bytesRead = await responseStream.ReadAsync(memory, cancellationToken).ConfigureAwait(false);
sequence.Advance(bytesRead);
}
while (bytesRead > 0);
#else
var buffer = ArrayPool<byte>.Shared.Rent(4096);
try
{
int bytesRead;
while (true)
{
bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
if (bytesRead == 0)
{
break;
}
var memory = sequence.GetMemory(bytesRead);
buffer.AsMemory(0, bytesRead).CopyTo(memory);
sequence.Advance(bytesRead);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
#endif
return this.Formatter.Deserialize(sequence);
}
}
/// <inheritdoc/>
public async ValueTask WriteAsync(JsonRpcMessage content, CancellationToken cancellationToken)
{
// Cast here because we only support transmitting requests anyway.
var contentAsRequest = (JsonRpcRequest)content;
// The JSON-RPC over HTTP spec requires that we supply a Content-Length header, so we have to serialize up front
// in order to measure its length.
using (var sequence = new Sequence<byte>())
{
this.Formatter.Serialize(sequence, content);
var requestMessage = new HttpRequestMessage(HttpMethod.Post, this.requestUri);
requestMessage.Headers.Accept.Add(AcceptHeader);
requestMessage.Content = new StreamContent(sequence.AsReadOnlySequence.AsStream());
requestMessage.Content.Headers.ContentType = ContentTypeHeader;
requestMessage.Content.Headers.ContentLength = sequence.Length;
var response = await this.httpClient.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
VerifyThrowStatusCode(contentAsRequest.IsResponseExpected ? HttpStatusCode.OK : HttpStatusCode.NoContent, response.StatusCode);
}
else
{
this.TraceSource.TraceEvent(TraceEventType.Error, (int)TraceEvents.HttpErrorStatusCodeReceived, "Received HTTP {0} {1} response to JSON-RPC request for method \"{2}\".", (int)response.StatusCode, response.StatusCode, contentAsRequest.Method);
}
// The response is expected to be a success code, or an error code with a content-type that we can deserialize.
if (response.IsSuccessStatusCode || AllowedContentTypes.Contains(response.Content?.Headers.ContentType.MediaType))
{
// Some requests don't merit response messages, such as notifications in JSON-RPC.
// Servers may communicate this with 202 or 204 HTTPS status codes in the response.
// Others may (poorly?) send a 200 response but with an empty entity.
if (response.Content?.Headers.ContentLength > 0)
{
// Make the response available for receiving.
this.incomingMessages.Enqueue(response);
}
}
else
{
// Throw an exception because of the unexpected failure from the server without a JSON-RPC message attached.
response.EnsureSuccessStatusCode();
}
}
}
private static void VerifyThrowStatusCode(HttpStatusCode expected, HttpStatusCode actual)
{
if (expected != actual)
{
throw new BadRpcHeaderException($"Expected \"{(int)expected} {expected}\" response but received \"{(int)actual} {actual}\" instead.");
}
}
}