forked from Astn/JSON-RPC.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonRpcProcessor.cs
More file actions
244 lines (215 loc) · 8.88 KB
/
JsonRpcProcessor.cs
File metadata and controls
244 lines (215 loc) · 8.88 KB
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
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace AustinHarris.JsonRpc
{
public static class JsonRpcProcessor
{
public static void Process(JsonRpcStateAsync async, object context = null)
{
Process(Handler.DefaultSessionId(), async, context);
}
public static void Process(string sessionId, JsonRpcStateAsync async, object context = null)
{
Process(sessionId, async.JsonRpc, context)
.ContinueWith(t =>
{
async.Result = t.Result;
async.SetCompleted();
});
}
public static async Task<string> Process(string jsonRpc, object context = null)
{
return await Process(Handler.DefaultSessionId(), jsonRpc, context);
}
public static async Task<string> Process(string sessionId, string jsonRpc, object context = null)
{
return await ProcessInternal(sessionId, jsonRpc, context);
}
public static async Task<JsonResponse> Process(string jsonRpc, JsonRequest jsonRequest, object context = null)
{
return await Process(Handler.DefaultSessionId(), jsonRpc, jsonRequest, context);
}
public static async Task<JsonResponse> Process(string sessionId, string jsonRpc, JsonRequest jsonRequest, object context = null)
{
return await ProcessInternal(sessionId, jsonRpc, jsonRequest, context);
}
public static async Task<JsonResponse[]> Process(string jsonRpc, JsonRequest[] jsonRequests, object context = null)
{
return await Process(Handler.DefaultSessionId(), jsonRpc, jsonRequests, context);
}
public static async Task<JsonResponse[]> Process(string sessionId, string jsonRpc, JsonRequest[] jsonRequests, object context = null)
{
return await ProcessInternal(sessionId, jsonRpc, jsonRequests, context);
}
private static async Task<string> ProcessInternal(string sessionId, string jsonRpc, object jsonRpcContext)
{
var handler = Handler.GetSessionHandler(sessionId);
JsonRequest[] batch = null;
bool singleBatch;
try
{
batch = DeserializeRequest(jsonRpc, out singleBatch);
}
catch (Exception ex)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(new JsonResponse
{
Error = handler.ProcessParseException(jsonRpc, new JsonRpcException(-32700, "Parse error", ex))
});
}
JsonResponse[] jsonResponses = await ProcessInternal(sessionId, jsonRpc, batch, jsonRpcContext);
return SerializeResponse(jsonResponses, singleBatch);
}
private static async Task<JsonResponse[]> ProcessInternal(string sessionId, string jsonRpc, JsonRequest[] jsonRequests, object jsonRpcContext)
{
var handler = Handler.GetSessionHandler(sessionId);
if (jsonRequests.Length == 0)
{
return new JsonResponse[]
{
new JsonResponse
{
Error = handler.ProcessParseException(jsonRpc,
new JsonRpcException(-32600, "Invalid Request", "Batch of calls was empty."))
}
};
}
List<JsonResponse> jsonResponses = null;
for (var i = 0; i < jsonRequests.Length; i++)
{
var jsonRequest = jsonRequests[i];
var jsonResponse = await ProcessInternal(sessionId, jsonRpc, jsonRequest, jsonRpcContext);
// single rpc optimization
if (jsonRequests.Length == 1 && (jsonResponse.Id != null || jsonResponse.Error != null))
{
return new JsonResponse[] { jsonResponse };
}
if (jsonResponses == null)
{
jsonResponses = new List<JsonResponse>();
}
jsonResponses.Add(jsonResponse);
}
return jsonResponses.ToArray();
}
private static async Task<JsonResponse> ProcessInternal(string sessionId, string jsonRpc, JsonRequest jsonRequest, object jsonRpcContext)
{
var handler = Handler.GetSessionHandler(sessionId);
var jsonResponse = new JsonResponse();
if (jsonRequest == null)
{
jsonResponse.Error = handler.ProcessParseException(jsonRpc,
new JsonRpcException(-32700, "Parse error",
"Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."));
}
else if (jsonRequest.Method == null)
{
jsonResponse.Error = handler.ProcessParseException(jsonRpc,
new JsonRpcException(-32601, "Invalid Request", "Missing property 'method'"));
}
else
{
jsonResponse.Id = jsonRequest.Id;
var data = await handler.Handle(jsonRequest, jsonRpcContext);
if (data == null) return null;
jsonResponse.Error = data.Error;
jsonResponse.Result = data.Result;
}
return jsonResponse;
}
private static bool IsSingleRpc(string json)
{
for (int i = 0; i < json.Length; i++)
{
if (json[i] == '{') return true;
else if (json[i] == '[') return false;
}
return true;
}
public static JsonRequest[] DeserializeRequest(string jsonRpc, out bool isSingleRpc)
{
JsonRequest[] batch = null;
try
{
isSingleRpc = IsSingleRpc(jsonRpc);
if (isSingleRpc)
{
var foo = JsonConvert.DeserializeObject<JsonRequest>(jsonRpc);
batch = new[] { foo };
}
else
{
batch = JsonConvert.DeserializeObject<JsonRequest[]>(jsonRpc);
}
}
catch (Exception ex)
{
throw new JsonRpcException(-32700, "Parse error", ex);
}
return batch;
}
public static string SerializeResponse(JsonResponse jsonResponse)
{
if (jsonResponse.Id == null && jsonResponse.Error == null)
{
// notification returns empty string
return "";
}
if (jsonResponse.Result == null && jsonResponse.Error == null)
{
// Per json rpc 2.0 spec
// result : This member is REQUIRED on success.
// This member MUST NOT exist if there was an error invoking the method.
// Either the result member or error member MUST be included, but both members MUST NOT be included.
jsonResponse.Result = new Newtonsoft.Json.Linq.JValue((Object)null);
}
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName("jsonrpc"); writer.WriteValue("2.0");
if (jsonResponse.Error != null)
{
writer.WritePropertyName("error"); writer.WriteRawValue(JsonConvert.SerializeObject(jsonResponse.Error));
}
else
{
writer.WritePropertyName("result"); writer.WriteRawValue(JsonConvert.SerializeObject(jsonResponse.Result));
}
writer.WritePropertyName("id"); writer.WriteValue(jsonResponse.Id);
writer.WriteEndObject();
return sw.ToString();
}
public static string SerializeResponse(IEnumerable<JsonResponse> jsonResponses, bool isSingleRpc)
{
if (isSingleRpc)
{
return SerializeResponse(jsonResponses.First<JsonResponse>());
}
StringBuilder sbResult = new StringBuilder(0);
foreach (JsonResponse jsonResponse in jsonResponses)
{
string str = SerializeResponse(jsonResponse);
if (str.Length == 0)
{
// this is notification
continue;
}
sbResult.Append(sbResult.Length == 0 ? "[" : ",");
sbResult.Append(str);
}
if (sbResult.Length > 0)
{
sbResult.Append("]");
}
return sbResult.ToString();
}
}
}