- Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathHandler.cs
More file actions
Latest commit
521 lines (468 loc) · 21.7 KB
/
Copy pathHandler.cs
File metadata and controls
521 lines (468 loc) · 21.7 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
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
namespaceAustinHarris.JsonRpc
{
usingSystem;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Reflection;
usingNewtonsoft.Json;
usingSystem.Threading.Tasks;
usingSystem.Collections.Concurrent;
usingNewtonsoft.Json.Linq;
usingSystem.Threading;
publicclassHandler
{
#region Members
privateconststringName_of_JSONRPCEXCEPTION="JsonRpcException&";
privatestaticint_sessionHandlerMasterVersion=1;
[ThreadStatic]
privatestaticDictionary<string,Handler>_sessionHandlersLocal;
[ThreadStatic]
privatestaticint_sessionHandlerLocalVersion=0;
privatestaticConcurrentDictionary<string,Handler>_sessionHandlersMaster;
privatestaticvolatilestring_defaultSessionId;
#endregion
#region Constructors
staticHandler()
{
//current = new Handler(Guid.NewGuid().ToString());
_defaultSessionId=Guid.NewGuid().ToString();
_sessionHandlersMaster=newConcurrentDictionary<string,Handler>();
_sessionHandlersMaster[_defaultSessionId]=newHandler(_defaultSessionId);
}
privateHandler(stringsessionId)
{
SessionId=sessionId;
this.MetaData=newSMD();
}
#endregion
#region Properties
/// <summary>
/// Returns the SessionID of the default session
/// </summary>
/// <returns></returns>
publicstaticstringDefaultSessionId(){return_defaultSessionId;}
/// <summary>
/// Gets a specific session
/// </summary>
/// <param name="sessionId">The sessionId of the handler you want to retrieve.</param>
/// <returns></returns>
publicstaticHandlerGetSessionHandler(stringsessionId)
{
if(_sessionHandlerMasterVersion!=_sessionHandlerLocalVersion)
{
_sessionHandlersLocal=newDictionary<string,Handler>(_sessionHandlersMaster);
_sessionHandlerLocalVersion=_sessionHandlerMasterVersion;
}
if(_sessionHandlersLocal.ContainsKey(sessionId))
{
return_sessionHandlersLocal[sessionId];
}
Interlocked.Increment(ref_sessionHandlerMasterVersion);
return_sessionHandlersMaster.GetOrAdd(sessionId,newHandler(sessionId));
}
/// <summary>
/// gets the default session
/// </summary>
/// <returns>The default Session Handler</returns>
publicstaticHandlerGetSessionHandler()
{
returnGetSessionHandler(_defaultSessionId);
}
/// <summary>
/// Removes and clears the Handler with the specific sessionID from the registry of Handlers
/// </summary>
/// <param name="sessionId"></param>
publicstaticvoidDestroySession(stringsessionId)
{
Handlerh;
_sessionHandlersMaster.TryRemove(sessionId,outh);
Interlocked.Increment(ref_sessionHandlerMasterVersion);
h.MetaData.Services.Clear();
}
/// <summary>
/// Removes and clears the current Handler from the registry of Handlers
/// </summary>
publicvoidDestroy()
{
DestroySession(SessionId);
}
/// <summary>
/// Gets the default session handler
/// </summary>
publicstaticHandlerDefaultHandler{get{returnGetSessionHandler(_defaultSessionId);}}
/// <summary>
/// The sessionID of this Handler
/// </summary>
publicstringSessionId{get;privateset;}
/// <summary>
/// Provides access to a context specific to each JsonRpc method invocation.
/// Warning: Must be called from within the execution context of the jsonRpc Method to return the context
/// </summary>
/// <returns></returns>
publicstaticobjectRpcContext()
{
return__currentRpcContext;
}
[ThreadStatic]
staticJsonRpcException__currentRpcException;
/// <summary>
/// Allows you to set the exception used in in the JsonRpc response.
/// Warning: Must be called from the same thread as the jsonRpc method.
/// </summary>
/// <param name="exception"></param>
publicstaticvoidRpcSetException(JsonRpcExceptionexception)
{
__currentRpcException=exception;
}
publicstaticJsonRpcExceptionRpcGetAndRemoveRpcException()
{
varex=__currentRpcException;
__currentRpcException=null;
returnex;
}
privateAustinHarris.JsonRpc.PreProcessHandlerexternalPreProcessingHandler;
privateAustinHarris.JsonRpc.PostProcessHandlerexternalPostProcessingHandler;
privateFunc<JsonRequest,JsonRpcException,JsonRpcException>externalErrorHandler;
privateFunc<string,JsonRpcException,JsonRpcException>parseErrorHandler;
#endregion
/// <summary>
/// This metadata contains all the types and mappings of all the methods in this handler. Warning: Modifying this directly could cause your handler to no longer function.
/// </summary>
publicSMDMetaData{get;set;}
#region Public Methods
/// <summary>
/// Allows you to register all the functions on a Pojo Type that have been attributed as [JsonRpcMethod] to the specified sessionId
/// </summary>
/// <param name="sessionID">The session to register against</param>
/// <param name="instance">The instance containing JsonRpcMethods to register</param>
publicstaticvoidRegisterInstance(stringsessionID,objectinstance)
{
ServiceBinder.BindService(sessionID,instance);
}
/// <summary>
/// Allows you to register any function, lambda, etc even when not attributed with JsonRpcMethod.
/// Requires you to specify all types and defaults
/// </summary>
/// <param name="methodName">The method name that will map to the registered function</param>
/// <param name="parameterNameTypeMapping">The parameter names and types that will be positionally bound to the function</param>
/// <param name="parameterNameDefaultValueMapping">Optional default values for parameters</param>
/// <param name="implementation">A reference to the Function</param>
publicvoidRegisterFuction(stringmethodName,Dictionary<string,Type>parameterNameTypeMapping,Dictionary<string,object>parameterNameDefaultValueMapping,Delegateimplementation)
{
MetaData.AddService(methodName,parameterNameTypeMapping,parameterNameDefaultValueMapping,implementation);
}
publicvoidUnRegisterFunction(stringmethodName)
{
MetaData.Services.Remove(methodName);
}
publicvoidSetPreProcessHandler(AustinHarris.JsonRpc.PreProcessHandlerhandler)
{
externalPreProcessingHandler=handler;
}
publicvoidSetPostProcessHandler(AustinHarris.JsonRpc.PostProcessHandlerhandler)
{
externalPostProcessingHandler=handler;
}
/// <summary>
/// Invokes a method to handle a JsonRpc request.
/// </summary>
/// <param name="Rpc">JsonRpc Request to be processed</param>
/// <param name="RpcContext">Optional context that will be available from within the jsonRpcMethod.</param>
/// <returns></returns>
publicJsonResponseHandle(JsonRequestRpc,ObjectRpcContext=null)
{
AddRpcContext(RpcContext);
varpreProcessingException=PreProcess(Rpc,RpcContext);
if(preProcessingException!=null)
{
JsonResponseresponse=newJsonResponse()
{
Error=preProcessingException,
Id=Rpc.Id
};
//callback is called - if it is empty then nothing will be done
//return response always- if callback is empty or not
returnPostProcess(Rpc,response,RpcContext);
}
SMDServicemetadata=null;
Delegatehandle=null;
if(this.MetaData.Services.TryGetValue(Rpc.Method,outmetadata))
{
handle=metadata.dele;
}elseif(metadata==null)
{
JsonResponseresponse=newJsonResponse()
{
Result=null,
Error=newJsonRpcException(-32601,"Method not found","The method does not exist / is not available."),
Id=Rpc.Id
};
returnPostProcess(Rpc,response,RpcContext);
}
object[]parameters=null;
boolexpectsRefException=false;
varmetaDataParamCount=metadata.parameters.Count(x =>x!=null);
varloopCt=0;
vargetCount=Rpc.ParamsasICollection;
if(getCount!=null)
{
loopCt=getCount.Count;
}
varparamCount=loopCt;
if(paramCount==metaDataParamCount-1&&metadata.parameters[metaDataParamCount-1].ObjectType.Name.Equals(Name_of_JSONRPCEXCEPTION))
{
paramCount++;
expectsRefException=true;
}
parameters=newobject[paramCount];
if(Rpc.ParamsisNewtonsoft.Json.Linq.JArray)
{
varjarr=((Newtonsoft.Json.Linq.JArray)Rpc.Params);
for(inti=0;i<loopCt&&i<metadata.parameters.Length;i++)
{
parameters[i]=CleanUpParameter(jarr[i],metadata.parameters[i]);
}
}
elseif(Rpc.ParamsisNewtonsoft.Json.Linq.JObject)
{
varasDict=Rpc.ParamsasIDictionary<string,Newtonsoft.Json.Linq.JToken>;
for(inti=0;i<loopCt&&i<metadata.parameters.Length;i++)
{
if(asDict.ContainsKey(metadata.parameters[i].Name)==true)
{
parameters[i]=CleanUpParameter(asDict[metadata.parameters[i].Name],metadata.parameters[i]);
continue;
}
else
{
varfoundDefault=metadata.defaultValues
.FirstOrDefault(defaul =>defaul.Name==metadata.parameters[i].Name);
if(foundDefault!=null)
{
parameters[i]=foundDefault.Value;
continue;
}
JsonResponseresponse=newJsonResponse()
{
Error=ProcessException(Rpc,
newJsonRpcException(-32602,
"Invalid params",
string.Format("Named parameter '{0}' was not present.",
metadata.parameters[i].Name)
)),
Id=Rpc.Id
};
returnPostProcess(Rpc,response,RpcContext);
}
}
}
// Optional Parameter support
// check if we still miss parameters compared to metadata which may include optional parameters.
// if the rpc-call didn't supply a value for an optional parameter, we should be assinging the default value of it.
if(parameters.Length<metaDataParamCount&&metadata.defaultValues.Length>0)// rpc call didn't set values for all optional parameters, so we need to assign the default values for them.
{
varsuppliedParamsCount=parameters.Length;// the index we should start storing default values of optional parameters.
varmissingParamsCount=metaDataParamCount-parameters.Length;// the amount of optional parameters without a value set by rpc-call.
Array.Resize(refparameters,parameters.Length+missingParamsCount);// resize the array to include all optional parameters.
for(intparamIndex=parameters.Length-1,defaultIndex=metadata.defaultValues.Length-1;// fill missing parameters from the back
paramIndex>=suppliedParamsCount&&defaultIndex>=0;// to don't overwrite supplied ones.
paramIndex--,defaultIndex--)
{
parameters[paramIndex]=metadata.defaultValues[defaultIndex].Value;
}
if(missingParamsCount>metadata.defaultValues.Length)
{
JsonResponseresponse=newJsonResponse
{
Error=ProcessException(Rpc,
newJsonRpcException(-32602,
"Invalid params",
string.Format(
"Number of default parameters {0} not sufficient to fill all missing parameters {1}",
metadata.defaultValues.Length,missingParamsCount)
)),
Id=Rpc.Id
};
returnPostProcess(Rpc,response,RpcContext);
}
}
if(parameters.Length!=metaDataParamCount)
{
JsonResponseresponse=newJsonResponse()
{
Error=ProcessException(Rpc,
newJsonRpcException(-32602,
"Invalid params",
string.Format("Expecting {0} parameters, and received {1}",
metadata.parameters.Length,
parameters.Length)
)),
Id=Rpc.Id
};
returnPostProcess(Rpc,response,RpcContext);
}
try
{
varresults=handle.DynamicInvoke(parameters);
varlast=parameters.LastOrDefault();
varcontextException=RpcGetAndRemoveRpcException();
JsonResponseresponse=null;
if(contextException!=null)
{
response=newJsonResponse(){Error=ProcessException(Rpc,contextException),Id=Rpc.Id};
}
elseif(expectsRefException&&last!=null&&lastisJsonRpcException)
{
response=newJsonResponse(){Error=ProcessException(Rpc,lastasJsonRpcException),Id=Rpc.Id};
}
else
{
response=newJsonResponse(){Result=results};
}
returnPostProcess(Rpc,response,RpcContext);
}
catch(Exceptionex)
{
JsonResponseresponse;
if(exisTargetParameterCountException)
{
response=newJsonResponse(){Error=ProcessException(Rpc,newJsonRpcException(-32602,"Invalid params",ex))};
returnPostProcess(Rpc,response,RpcContext);
}
// We really dont care about the TargetInvocationException, just pass on the inner exception
if(exisJsonRpcException)
{
response=newJsonResponse(){Error=ProcessException(Rpc,exasJsonRpcException)};
returnPostProcess(Rpc,response,RpcContext);
}
if(ex.InnerException!=null&&ex.InnerExceptionisJsonRpcException)
{
response=newJsonResponse(){Error=ProcessException(Rpc,ex.InnerExceptionasJsonRpcException)};
returnPostProcess(Rpc,response,RpcContext);
}
elseif(ex.InnerException!=null)
{
response=newJsonResponse(){Error=ProcessException(Rpc,newJsonRpcException(-32603,"Internal Error",ex.InnerException))};
returnPostProcess(Rpc,response,RpcContext);
}
response=newJsonResponse(){Error=ProcessException(Rpc,newJsonRpcException(-32603,"Internal Error",ex))};
returnPostProcess(Rpc,response,RpcContext);
}
finally
{
RemoveRpcContext();
}
}
#endregion
[ThreadStatic]
staticobject__currentRpcContext;
privatevoidAddRpcContext(objectRpcContext)
{
__currentRpcContext=RpcContext;
}
privatevoidRemoveRpcContext()
{
__currentRpcContext=null;
}
privateJsonRpcExceptionProcessException(JsonRequestreq,JsonRpcExceptionex)
{
if(externalErrorHandler!=null)
returnexternalErrorHandler(req,ex);
returnex;
}
internalJsonRpcExceptionProcessParseException(stringreq,JsonRpcExceptionex)
{
if(parseErrorHandler!=null)
returnparseErrorHandler(req,ex);
returnex;
}
internalvoidSetErrorHandler(Func<JsonRequest,JsonRpcException,JsonRpcException>handler)
{
externalErrorHandler=handler;
}
internalvoidSetParseErrorHandler(Func<string,JsonRpcException,JsonRpcException>handler)
{
parseErrorHandler=handler;
}
privateobjectCleanUpParameter(objectp,SMDAdditionalParametersmetaData)
{
varbob=pasJValue;
if(bob!=null)
{
if(bob.Value==null||metaData.ObjectType==bob.Value.GetType())
{
returnbob.Value;
}
try
{
// Avoid calling DeserializeObject on types that JValue has an explicit converter for
// try to optimize for the most common types
if(metaData.ObjectType==typeof(string))return(string)bob;
if(metaData.ObjectType==typeof(int))return(int)bob;
if(metaData.ObjectType==typeof(double))return(double)bob;
if(metaData.ObjectType==typeof(float))return(float)bob;
//if (metaData.ObjectType == typeof(long)) return (long)bob;
//if (metaData.ObjectType == typeof(uint)) return (uint)bob;
//if (metaData.ObjectType == typeof(ulong)) return (ulong)bob;
//if (metaData.ObjectType == typeof(byte[])) return (byte[])bob;
//if (metaData.ObjectType == typeof(Guid)) return (Guid)bob;
if(metaData.ObjectType==typeof(decimal))return(decimal)bob;
//if (metaData.ObjectType == typeof(TimeSpan)) return (TimeSpan)bob;
//if (metaData.ObjectType == typeof(short)) return (short)bob;
//if (metaData.ObjectType == typeof(ushort)) return (ushort)bob;
//if (metaData.ObjectType == typeof(char)) return (char)bob;
//if (metaData.ObjectType == typeof(DateTime)) return (DateTime)bob;
//if (metaData.ObjectType == typeof(bool)) return (bool)bob;
//if (metaData.ObjectType == typeof(DateTimeOffset)) return (DateTimeOffset)bob;
if(metaData.ObjectType.IsAssignableFrom(typeof(JValue)))
returnbob;
returnbob.ToObject(metaData.ObjectType);
}
catch(Exception)
{
// no need to throw here, they will
// get an invalid cast exception right after this.
}
}
else
{
try
{
if(pisstring)
returnJsonConvert.DeserializeObject((string)p,metaData.ObjectType);
returnJsonConvert.DeserializeObject(p.ToString(),metaData.ObjectType);
}
catch(Exception)
{
// no need to throw here, they will
// get an invalid cast exception right after this.
}
}
returnp;
}
privateJsonRpcExceptionPreProcess(JsonRequestrequest,objectcontext)
{
returnexternalPreProcessingHandler?.Invoke(request,context);
}
privateJsonResponsePostProcess(JsonRequestrequest,JsonResponseresponse,objectcontext)
{
if(externalPostProcessingHandler!=null)
{
try
{
JsonRpcExceptionexception=externalPostProcessingHandler(request,response,context);
if(exception!=null)
{
response=newJsonResponse(){Error=exception};
}
}
catch(Exceptionex)
{
response=newJsonResponse(){Error=ProcessException(request,newJsonRpcException(-32603,"Internal Error",ex))};
}
}
returnresponse;
}
}
}