-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathMessageReader.cs
284 lines (229 loc) · 10.1 KB
/
MessageReader.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol
{
public class MessageReader
{
#region Private Fields
public const int DefaultBufferSize = 8192;
public const double BufferResizeTrigger = 0.25;
private const int CR = 0x0D;
private const int LF = 0x0A;
private static string[] NewLineDelimiters = new string[] { Environment.NewLine };
private ILogger logger;
private Stream inputStream;
private IMessageSerializer messageSerializer;
private Encoding messageEncoding;
private ReadState readState;
private bool needsMoreData = true;
private int readOffset;
private int bufferEndOffset;
private byte[] messageBuffer = new byte[DefaultBufferSize];
private int expectedContentLength;
private Dictionary<string, string> messageHeaders;
enum ReadState
{
Headers,
Content
}
#endregion
#region Constructors
public MessageReader(
Stream inputStream,
IMessageSerializer messageSerializer,
ILogger logger,
Encoding messageEncoding = null)
{
Validate.IsNotNull("streamReader", inputStream);
Validate.IsNotNull("messageSerializer", messageSerializer);
this.logger = logger;
this.inputStream = inputStream;
this.messageSerializer = messageSerializer;
this.messageEncoding = messageEncoding;
if (messageEncoding == null)
{
this.messageEncoding = Encoding.UTF8;
}
this.messageBuffer = new byte[DefaultBufferSize];
}
#endregion
#region Public Methods
public async Task<Message> ReadMessage()
{
string messageContent = null;
// Do we need to read more data or can we process the existing buffer?
while (!this.needsMoreData || await this.ReadNextChunk())
{
// Clear the flag since we should have what we need now
this.needsMoreData = false;
// Do we need to look for message headers?
if (this.readState == ReadState.Headers &&
!this.TryReadMessageHeaders())
{
// If we don't have enough data to read headers yet, keep reading
this.needsMoreData = true;
continue;
}
// Do we need to look for message content?
if (this.readState == ReadState.Content &&
!this.TryReadMessageContent(out messageContent))
{
// If we don't have enough data yet to construct the content, keep reading
this.needsMoreData = true;
continue;
}
// We've read a message now, break out of the loop
break;
}
// Get the JObject for the JSON content
JObject messageObject = JObject.Parse(messageContent);
// Deserialize the message from the parsed JSON message
Message parsedMessage = this.messageSerializer.DeserializeMessage(messageObject);
// Log message info - initial capacity for StringBuilder varies depending on whether
// the log level is Diagnostic where JsonRpc message payloads are logged and vary in size
// from 1K up to the edited file size. When not logging message payloads, the typical
// request log message size is under 256 chars.
var logStrBld =
new StringBuilder(this.logger.MinimumConfiguredLogLevel == LogLevel.Diagnostic ? 4096 : 256)
.Append("Received ")
.Append(parsedMessage.MessageType)
.Append(" '").Append(parsedMessage.Method).Append("'");
if (!string.IsNullOrEmpty(parsedMessage.Id))
{
logStrBld.Append(" with id ").Append(parsedMessage.Id);
}
if (this.logger.MinimumConfiguredLogLevel == LogLevel.Diagnostic)
{
// Log the JSON representation of the message payload at the Diagnostic log level
string jsonPayload = messageObject.ToString(Formatting.Indented);
logStrBld.Append(Environment.NewLine).Append(Environment.NewLine).Append(jsonPayload);
}
this.logger.Write(LogLevel.Verbose, logStrBld.ToString());
return parsedMessage;
}
#endregion
#region Private Methods
private async Task<bool> ReadNextChunk()
{
// Do we need to resize the buffer? See if less than 1/4 of the space is left.
if (((double)(this.messageBuffer.Length - this.bufferEndOffset) / this.messageBuffer.Length) < 0.25)
{
// Double the size of the buffer
Array.Resize(
ref this.messageBuffer,
this.messageBuffer.Length * 2);
}
// Read the next chunk into the message buffer
int readLength =
await this.inputStream.ReadAsync(
this.messageBuffer,
this.bufferEndOffset,
this.messageBuffer.Length - this.bufferEndOffset);
this.bufferEndOffset += readLength;
if (readLength == 0)
{
// If ReadAsync returns 0 then it means that the stream was
// closed unexpectedly (usually due to the client application
// ending suddenly). For now, just terminate the language
// server immediately.
// TODO: Provide a more graceful shutdown path
throw new EndOfStreamException(
"MessageReader's input stream ended unexpectedly, terminating.");
}
return true;
}
private bool TryReadMessageHeaders()
{
int scanOffset = this.readOffset;
// Scan for the final double-newline that marks the
// end of the header lines
while (scanOffset + 3 < this.bufferEndOffset &&
(this.messageBuffer[scanOffset] != CR ||
this.messageBuffer[scanOffset + 1] != LF ||
this.messageBuffer[scanOffset + 2] != CR ||
this.messageBuffer[scanOffset + 3] != LF))
{
scanOffset++;
}
// No header or body separator found (e.g CRLFCRLF)
if (scanOffset + 3 >= this.bufferEndOffset)
{
return false;
}
this.messageHeaders = new Dictionary<string, string>();
var headers =
Encoding.ASCII
.GetString(this.messageBuffer, this.readOffset, scanOffset)
.Split(NewLineDelimiters, StringSplitOptions.RemoveEmptyEntries);
// Read each header and store it in the dictionary
foreach (var header in headers)
{
int currentLength = header.IndexOf(':');
if (currentLength == -1)
{
throw new ArgumentException("Message header must separate key and value using :");
}
var key = header.Substring(0, currentLength);
var value = header.Substring(currentLength + 1).Trim();
this.messageHeaders[key] = value;
}
// Make sure a Content-Length header was present, otherwise it
// is a fatal error
string contentLengthString = null;
if (!this.messageHeaders.TryGetValue("Content-Length", out contentLengthString))
{
throw new MessageParseException("", "Fatal error: Content-Length header must be provided.");
}
// Parse the content length to an integer
if (!int.TryParse(contentLengthString, out this.expectedContentLength))
{
throw new MessageParseException("", "Fatal error: Content-Length value is not an integer.");
}
// Skip past the headers plus the newline characters
this.readOffset += scanOffset + 4;
// Done reading headers, now read content
this.readState = ReadState.Content;
return true;
}
private bool TryReadMessageContent(out string messageContent)
{
messageContent = null;
// Do we have enough bytes to reach the expected length?
if ((this.bufferEndOffset - this.readOffset) < this.expectedContentLength)
{
return false;
}
// Convert the message contents to a string using the specified encoding
messageContent =
this.messageEncoding.GetString(
this.messageBuffer,
this.readOffset,
this.expectedContentLength);
// Move the remaining bytes to the front of the buffer for the next message
var remainingByteCount = this.bufferEndOffset - (this.expectedContentLength + this.readOffset);
Buffer.BlockCopy(
this.messageBuffer,
this.expectedContentLength + this.readOffset,
this.messageBuffer,
0,
remainingByteCount);
// Reset the offsets for the next read
this.readOffset = 0;
this.bufferEndOffset = remainingByteCount;
// Done reading content, now look for headers
this.readState = ReadState.Headers;
return true;
}
#endregion
}
}