PageRenderTime 41ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/SignalR/Hubs/Lookup/ReflectedMethodDescriptorProvider.cs

https://github.com/kpmrafeeq/SignalR
C# | 143 lines | 97 code | 17 blank | 29 comment | 8 complexity | 82e1849b585544d6fceb84175d561823 MD5 | raw file
Possible License(s): MIT
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Reflection;
  7. using Newtonsoft.Json.Linq;
  8. using SignalR.Infrastructure;
  9. namespace SignalR.Hubs
  10. {
  11. public class ReflectedMethodDescriptorProvider : IMethodDescriptorProvider
  12. {
  13. private readonly ConcurrentDictionary<string, IDictionary<string, IEnumerable<MethodDescriptor>>> _methods;
  14. private readonly ConcurrentDictionary<string, MethodDescriptor> _executableMethods;
  15. public ReflectedMethodDescriptorProvider()
  16. {
  17. _methods = new ConcurrentDictionary<string, IDictionary<string, IEnumerable<MethodDescriptor>>>(StringComparer.OrdinalIgnoreCase);
  18. _executableMethods = new ConcurrentDictionary<string, MethodDescriptor>(StringComparer.OrdinalIgnoreCase);
  19. }
  20. public IEnumerable<MethodDescriptor> GetMethods(HubDescriptor hub)
  21. {
  22. return FetchMethodsFor(hub)
  23. .SelectMany(kv => kv.Value)
  24. .ToList();
  25. }
  26. /// <summary>
  27. /// Retrieves an existing dictionary of all available methods for a given hub from cache.
  28. /// If cache entry does not exist - it is created automatically by BuildMethodCacheFor.
  29. /// </summary>
  30. /// <param name="hub"></param>
  31. /// <returns></returns>
  32. private IDictionary<string, IEnumerable<MethodDescriptor>> FetchMethodsFor(HubDescriptor hub)
  33. {
  34. return _methods.GetOrAdd(
  35. hub.Name,
  36. key => BuildMethodCacheFor(hub));
  37. }
  38. /// <summary>
  39. /// Builds a dictionary of all possible methods on a given hub.
  40. /// Single entry contains a collection of available overloads for a given method name (key).
  41. /// This dictionary is being cached afterwards.
  42. /// </summary>
  43. /// <param name="hub">Hub to build cache for</param>
  44. /// <returns>Dictionary of available methods</returns>
  45. private IDictionary<string, IEnumerable<MethodDescriptor>> BuildMethodCacheFor(HubDescriptor hub)
  46. {
  47. return ReflectionHelper.GetExportedHubMethods(hub.Type)
  48. .GroupBy(GetMethodName, StringComparer.OrdinalIgnoreCase)
  49. .ToDictionary(group => group.Key,
  50. group => group.Select(oload =>
  51. new MethodDescriptor
  52. {
  53. ReturnType = oload.ReturnType,
  54. Name = group.Key,
  55. Invoker = oload.Invoke,
  56. Hub = hub,
  57. Parameters = oload.GetParameters()
  58. .Select(p => new ParameterDescriptor
  59. {
  60. Name = p.Name,
  61. Type = p.ParameterType,
  62. })
  63. .ToList()
  64. }),
  65. StringComparer.OrdinalIgnoreCase);
  66. }
  67. /// <summary>
  68. /// Searches the specified <paramref name="hub">Hub</paramref> for the specified <paramref name="method"/>.
  69. /// </summary>
  70. /// <remarks>
  71. /// In the case that there are multiple overloads of the specified <paramref name="method"/>, the <paramref name="parameter">parameter set</paramref> helps determine exactly which instance of the overload should be resolved.
  72. /// If there are multiple overloads found with the same number of matching paramters, none of the methods will be returned because it is not possible to determine which overload of the method was intended to be resolved.
  73. /// </remarks>
  74. /// <param name="hub">Hub to search for the specified <paramref name="method"/> on.</param>
  75. /// <param name="method">The method name to search for.</param>
  76. /// <param name="descriptor">If successful, the <see cref="MethodDescriptor"/> that was resolved.</param>
  77. /// <param name="parameters">The set of parameters that will be used to help locate a specific overload of the specified <paramref name="method"/>.</param>
  78. /// <returns>True if the method matching the name/parameter set is found on the hub, otherwise false.</returns>
  79. public bool TryGetMethod(HubDescriptor hub, string method, out MethodDescriptor descriptor, params IJsonValue[] parameters)
  80. {
  81. string hubMethodKey = BuildHubExecutableMethodCacheKey(hub, method, parameters);
  82. if(!_executableMethods.TryGetValue(hubMethodKey, out descriptor))
  83. {
  84. IEnumerable<MethodDescriptor> overloads;
  85. if(FetchMethodsFor(hub).TryGetValue(method, out overloads))
  86. {
  87. var matches = overloads.Where(o => o.Matches(parameters)).ToList();
  88. // If only one match is found, that is the "executable" version, otherwise none of the methods can be returned because we don't know which one was actually being targeted
  89. descriptor = matches.Count == 1 ? matches[0] : null;
  90. }
  91. else
  92. {
  93. descriptor = null;
  94. }
  95. // If an executable method was found, cache it for future lookups (NOTE: we don't cache null instances because it could be a surface area for DoS attack by supplying random method names to flood the cache)
  96. if(descriptor != null)
  97. {
  98. _executableMethods.TryAdd(hubMethodKey, descriptor);
  99. }
  100. }
  101. return descriptor != null;
  102. }
  103. private static string BuildHubExecutableMethodCacheKey(HubDescriptor hub, string method, IJsonValue[] parameters)
  104. {
  105. string normalizedParameterCountKeyPart;
  106. if(parameters != null)
  107. {
  108. normalizedParameterCountKeyPart = parameters.Length.ToString(CultureInfo.InvariantCulture);
  109. }
  110. else
  111. {
  112. // NOTE: we normailize a null parameter array to be the same as an empty (i.e. Length == 0) parameter array
  113. normalizedParameterCountKeyPart = "0";
  114. }
  115. // NOTE: we always normalize to all uppercase since method names are case insensitive and could theoretically come in diff. variations per call
  116. string normalizedMethodName = method.ToUpperInvariant();
  117. string methodKey = hub.Name + "::" + normalizedMethodName + "(" + normalizedParameterCountKeyPart + ")";
  118. return methodKey;
  119. }
  120. private static string GetMethodName(MethodInfo method)
  121. {
  122. return ReflectionHelper.GetAttributeValue<HubMethodNameAttribute, string>(method, a => a.MethodName)
  123. ?? method.Name;
  124. }
  125. }
  126. }