-
Notifications
You must be signed in to change notification settings - Fork 234
/
Copy pathMessageWriter.cs
163 lines (135 loc) · 5.78 KB
/
MessageWriter.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
//
// 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.IO;
using System.Text;
using System.Threading.Tasks;
using System;
namespace Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol
{
public class MessageWriter
{
#region Private Fields
private ILogger logger;
private Stream outputStream;
private IMessageSerializer messageSerializer;
private AsyncLock writeLock = new AsyncLock();
private JsonSerializer contentSerializer =
JsonSerializer.Create(
Constants.JsonSerializerSettings);
#endregion
#region Constructors
public MessageWriter(
Stream outputStream,
IMessageSerializer messageSerializer,
ILogger logger)
{
Validate.IsNotNull("streamWriter", outputStream);
Validate.IsNotNull("messageSerializer", messageSerializer);
this.logger = logger;
this.outputStream = outputStream;
this.messageSerializer = messageSerializer;
}
#endregion
#region Public Methods
// TODO: This method should be made protected or private
public async Task WriteMessage(Message messageToWrite)
{
Validate.IsNotNull("messageToWrite", messageToWrite);
// Serialize the message
JObject messageObject =
this.messageSerializer.SerializeMessage(
messageToWrite);
// 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 225K chars. When not logging message payloads, the typical
// response log message size is under 256 chars.
var logStrBld =
new StringBuilder(this.logger.MinimumConfiguredLogLevel == LogLevel.Diagnostic ? 4096 : 256)
.Append("Writing ")
.Append(messageToWrite.MessageType)
.Append(" '").Append(messageToWrite.Method).Append("'");
if (!string.IsNullOrEmpty(messageToWrite.Id))
{
logStrBld.Append(" with id ").Append(messageToWrite.Id);
}
if (this.logger.MinimumConfiguredLogLevel == LogLevel.Diagnostic)
{
// Log the JSON representation of the message payload at the Diagnostic log level
string jsonPayload =
JsonConvert.SerializeObject(
messageObject,
Formatting.Indented,
Constants.JsonSerializerSettings);
logStrBld.Append(Environment.NewLine).Append(Environment.NewLine).Append(jsonPayload);
}
this.logger.Write(LogLevel.Verbose, logStrBld.ToString());
string serializedMessage =
JsonConvert.SerializeObject(
messageObject,
Constants.JsonSerializerSettings);
byte[] messageBytes = Encoding.UTF8.GetBytes(serializedMessage);
byte[] headerBytes =
Encoding.ASCII.GetBytes(
string.Format(
Constants.ContentLengthFormatString,
messageBytes.Length));
// Make sure only one call is writing at a time. You might be thinking
// "Why not use a normal lock?" We use an AsyncLock here so that the
// message loop doesn't get blocked while waiting for I/O to complete.
using (await this.writeLock.LockAsync())
{
// Send the message
await this.outputStream.WriteAsync(headerBytes, 0, headerBytes.Length);
await this.outputStream.WriteAsync(messageBytes, 0, messageBytes.Length);
await this.outputStream.FlushAsync();
}
}
public async Task WriteRequest<TParams, TResult, TError, TRegistrationOptions>(
RequestType<TParams, TResult, TError, TRegistrationOptions> requestType,
TParams requestParams,
int requestId)
{
// Allow null content
JToken contentObject =
requestParams != null ?
JToken.FromObject(requestParams, contentSerializer) :
null;
await this.WriteMessage(
Message.Request(
requestId.ToString(),
requestType.Method,
contentObject));
}
public async Task WriteResponse<TResult>(TResult resultContent, string method, string requestId)
{
// Allow null content
JToken contentObject =
resultContent != null ?
JToken.FromObject(resultContent, contentSerializer) :
null;
await this.WriteMessage(
Message.Response(
requestId,
method,
contentObject));
}
public async Task WriteEvent<TParams, TRegistrationOptions>(NotificationType<TParams, TRegistrationOptions> eventType, TParams eventParams)
{
// Allow null content
JToken contentObject =
eventParams != null ?
JToken.FromObject(eventParams, contentSerializer) :
null;
await this.WriteMessage(
Message.Event(
eventType.Method,
contentObject));
}
#endregion
}
}