DefaultRequestMatcher.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using EdjCase.JsonRpc.Core;
  6. using EdjCase.JsonRpc.Router.Abstractions;
  7. using JsonRPCTest.Controllers;
  8. using Microsoft.Extensions.Logging;
  9. using Microsoft.Extensions.Options;
  10. using Newtonsoft.Json;
  11. using Newtonsoft.Json.Linq;
  12. namespace EdjCase.JsonRpc.Router.Defaults
  13. {
  14. public class DefaultRequestMatcher : IRpcRequestMatcher
  15. {
  16. private ILogger<DefaultRequestMatcher> logger { get; }
  17. private IOptions<RpcServerConfiguration> serverConfig { get; }
  18. public DefaultRequestMatcher(ILogger<DefaultRequestMatcher> logger,
  19. IOptions<RpcServerConfiguration> serverConfig)
  20. {
  21. this.logger = logger;
  22. this.serverConfig = serverConfig;
  23. }
  24. private JsonSerializer jsonSerializerCache { get; set; }
  25. private JsonSerializer GetJsonSerializer()
  26. {
  27. if (this.jsonSerializerCache == null)
  28. {
  29. this.jsonSerializerCache = this.serverConfig.Value?.JsonSerializerSettings == null
  30. ? JsonSerializer.CreateDefault()
  31. : JsonSerializer.Create(this.serverConfig.Value.JsonSerializerSettings);
  32. }
  33. return this.jsonSerializerCache;
  34. }
  35. public List<RpcMethodInfo> FilterAndBuildMethodInfoByRequest(List<MethodInfo> methods, RpcRequest request)
  36. {
  37. //Case insenstive check for hybrid approach. Will check for case sensitive if there is ambiguity
  38. List<MethodInfo> methodsWithSameName = methods
  39. .Where(m => string.Equals(m.Name, request.Method, StringComparison.OrdinalIgnoreCase))
  40. .ToList();
  41. if (!methodsWithSameName.Any())
  42. {
  43. string methodName = DefaultRequestMatcher.FixCase(request.Method);
  44. if (methodName != null)
  45. {
  46. methodsWithSameName = methods
  47. .Where(m => string.Equals(m.Name, methodName, StringComparison.OrdinalIgnoreCase))
  48. .ToList();
  49. }
  50. }
  51. var potentialMatches = new List<RpcMethodInfo>();
  52. foreach (MethodInfo method in methodsWithSameName)
  53. {
  54. (bool isMatch, RpcMethodInfo methodInfo) = this.HasParameterSignature(method, request);
  55. if (isMatch)
  56. {
  57. potentialMatches.Add(methodInfo);
  58. }
  59. }
  60. if (potentialMatches.Count > 1)
  61. {
  62. //Try to remove ambiguity with 'perfect matching' (usually optional params and types)
  63. List<RpcMethodInfo> exactMatches = potentialMatches
  64. .Where(p => p.HasExactParameterMatch())
  65. .ToList();
  66. if (exactMatches.Any())
  67. {
  68. potentialMatches = exactMatches;
  69. }
  70. if (potentialMatches.Count > 1)
  71. {
  72. //Try to remove ambiguity with case sensitive check
  73. potentialMatches = potentialMatches
  74. .Where(m => string.Equals(m.Method.Name, request.Method, StringComparison.Ordinal))
  75. .ToList();
  76. }
  77. }
  78. return potentialMatches;
  79. }
  80. private static string FixCase(string method)
  81. {
  82. //Snake case
  83. if (method.Contains('_'))
  84. {
  85. return method
  86. .Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries)
  87. .Aggregate((s1, s2) => s1 + s2);
  88. }
  89. //Spinal case
  90. else if (method.Contains('-'))
  91. {
  92. return method
  93. .Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries)
  94. .Aggregate((s1, s2) => s1 + s2);
  95. }
  96. else
  97. {
  98. return null;
  99. }
  100. }
  101. /// <summary>
  102. /// Converts the object array into the exact types the method needs (e.g. long -> int)
  103. /// </summary>
  104. /// <param name="parameters">Array of parameters for the method</param>
  105. /// <returns>Array of objects with the exact types required by the method</returns>
  106. private object[] ConvertParameters(MethodInfo method, object[] parameters)
  107. {
  108. if (parameters == null || !parameters.Any())
  109. {
  110. return new object[0];
  111. }
  112. ParameterInfo[] parameterInfoList = method.GetParameters();
  113. for (int index = 0; index < parameters.Length; index++)
  114. {
  115. ParameterInfo parameterInfo = parameterInfoList[index];
  116. parameters[index] = this.ConvertParameter(parameterInfo.ParameterType, parameters[index]);
  117. }
  118. return parameters;
  119. }
  120. private object ConvertParameter(Type parameterType, object parameterValue)
  121. {
  122. if (parameterValue == null)
  123. {
  124. return null;
  125. }
  126. //Missing type is for optional parameters
  127. if (parameterValue is Missing)
  128. {
  129. return parameterValue;
  130. }
  131. Type nullableType = Nullable.GetUnderlyingType(parameterType);
  132. if (nullableType != null)
  133. {
  134. return this.ConvertParameter(nullableType, parameterValue);
  135. }
  136. if (parameterValue is string && parameterType == typeof(Guid))
  137. {
  138. Guid.TryParse((string)parameterValue, out Guid guid);
  139. return guid;
  140. }
  141. if (parameterType.GetTypeInfo().IsEnum)
  142. {
  143. if (parameterValue is string)
  144. {
  145. return Enum.Parse(parameterType, (string)parameterValue);
  146. }
  147. else if (parameterValue is long)
  148. {
  149. return Enum.ToObject(parameterType, parameterValue);
  150. }
  151. }
  152. if (parameterValue is JToken jToken)
  153. {
  154. JsonSerializer jsonSerializer = this.GetJsonSerializer();
  155. return jToken.ToObject(parameterType, jsonSerializer);
  156. }
  157. return Convert.ChangeType(parameterValue, parameterType);
  158. }
  159. /// <summary>
  160. /// Detects if list of parameters matches the method signature
  161. /// </summary>
  162. /// <param name="parameterList">Array of parameters for the method</param>
  163. /// <returns>True if the method signature matches the parameterList, otherwise False</returns>
  164. private (bool Matches, RpcMethodInfo MethodInfo) HasParameterSignature(MethodInfo method, RpcRequest rpcRequest)
  165. {
  166. object[] orignialParameterList;
  167. if (!rpcRequest.Parameters.HasValue)
  168. {
  169. orignialParameterList = new object[0];
  170. }
  171. else
  172. {
  173. switch (rpcRequest.Parameters.Type)
  174. {
  175. case RpcParametersType.Dictionary:
  176. Dictionary<string, object> parameterMap = rpcRequest.Parameters.DictionaryValue;
  177. bool canParse = this.TryParseParameterList(method, parameterMap, out orignialParameterList);
  178. if (!canParse)
  179. {
  180. return (false, null);
  181. }
  182. break;
  183. case RpcParametersType.Array:
  184. orignialParameterList = rpcRequest.Parameters.ArrayValue;
  185. break;
  186. default:
  187. orignialParameterList = new JToken[0];
  188. break;
  189. }
  190. }
  191. ParameterInfo[] parameterInfoList = method.GetParameters();
  192. if (orignialParameterList.Length > parameterInfoList.Length)
  193. {
  194. return (false, null);
  195. }
  196. object[] correctedParameterList = new object[parameterInfoList.Length];
  197. for (int i = 0; i < orignialParameterList.Length; i++)
  198. {
  199. ParameterInfo parameterInfo = parameterInfoList[i];
  200. object parameter = orignialParameterList[i];
  201. bool isMatch = this.ParameterMatches(parameterInfo, parameter, out object convertedParameter);
  202. if (!isMatch)
  203. {
  204. return (false, null);
  205. }
  206. correctedParameterList[i] = convertedParameter;
  207. }
  208. if (orignialParameterList.Length < parameterInfoList.Length)
  209. {
  210. //make a new array at the same length with padded 'missing' parameters (if optional)
  211. for (int i = orignialParameterList.Length; i < parameterInfoList.Length; i++)
  212. {
  213. if (!parameterInfoList[i].IsOptional)
  214. {
  215. return (false, null);
  216. }
  217. correctedParameterList[i] = Type.Missing;
  218. }
  219. }
  220. var rpcMethodInfo = new RpcMethodInfo(method, correctedParameterList, orignialParameterList);
  221. return (true, rpcMethodInfo);
  222. }
  223. /// <summary>
  224. /// Detects if the request parameter matches the method parameter
  225. /// </summary>
  226. /// <param name="parameterInfo">Reflection info about a method parameter</param>
  227. /// <param name="value">The request's value for the parameter</param>
  228. /// <returns>True if the request parameter matches the type of the method parameter</returns>
  229. private bool ParameterMatches(ParameterInfo parameterInfo, object value, out object convertedValue)
  230. {
  231. Type parameterType = parameterInfo.ParameterType;
  232. try
  233. {
  234. if (value is JToken tokenValue)
  235. {
  236. switch (tokenValue.Type)
  237. {
  238. case JTokenType.Array:
  239. {
  240. JsonSerializer serializer = this.GetJsonSerializer();
  241. JArray jArray = (JArray)tokenValue;
  242. convertedValue = jArray.ToObject(parameterType, serializer);
  243. return true;
  244. }
  245. case JTokenType.Object:
  246. {
  247. JsonSerializer serializer = this.GetJsonSerializer();
  248. JObject jObject = (JObject)tokenValue;
  249. convertedValue = jObject.ToObject(parameterType, serializer);
  250. return true;
  251. }
  252. default:
  253. convertedValue = tokenValue.ToObject(parameterType);
  254. return true;
  255. }
  256. }
  257. else
  258. {
  259. convertedValue = value;
  260. return true;
  261. }
  262. }
  263. catch (Exception ex)
  264. {
  265. this.logger?.LogWarning($"Parameter '{parameterInfo.Name}' failed to deserialize: " + ex);
  266. convertedValue = null;
  267. return false;
  268. }
  269. }
  270. /// <summary>
  271. /// Tries to parse the parameter map into an ordered parameter list
  272. /// </summary>
  273. /// <param name="parametersMap">Map of parameter name to parameter value</param>
  274. /// <param name="parameterList">Result of converting the map to an ordered list, null if result is False</param>
  275. /// <returns>True if the parameters can convert to an ordered list based on the method signature, otherwise Fasle</returns>
  276. private bool TryParseParameterList(MethodInfo method, Dictionary<string, object> parametersMap, out object[] parameterList)
  277. {
  278. parametersMap = parametersMap
  279. .ToDictionary(x => DefaultRequestMatcher.FixCase(x.Key) ?? x.Key, v => v.Value, StringComparer.OrdinalIgnoreCase);
  280. ParameterInfo[] parameterInfoList = method.GetParameters();
  281. parameterList = new object[parameterInfoList.Count()];
  282. foreach (ParameterInfo parameterInfo in parameterInfoList)
  283. {
  284. if (!parametersMap.ContainsKey(parameterInfo.Name))
  285. {
  286. //if (parameterInfoList.Length == 1 && parametersMap != null && parametersMap.Keys.Count > 0)
  287. //{
  288. // Type type= parameterInfo.ParameterType;
  289. // parameterList[parameterInfo.Position] = JsonNetHelper.FromJson(parametersMap.ToJson(), type);
  290. // return true;
  291. //}
  292. if (!parameterInfo.IsOptional)
  293. {
  294. parameterList = null;
  295. return false;
  296. }
  297. }
  298. else
  299. {
  300. parameterList[parameterInfo.Position] = parametersMap[parameterInfo.Name];
  301. }
  302. }
  303. return true;
  304. }
  305. }
  306. }