ServiceController.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Model.Services;
  9. namespace ServiceStack.Host
  10. {
  11. public delegate Task<object> InstanceExecFn(IRequest requestContext, object intance, object request);
  12. public delegate object ActionInvokerFn(object intance, object request);
  13. public delegate void VoidActionInvokerFn(object intance, object request);
  14. public class ServiceController
  15. {
  16. private readonly Func<IEnumerable<Type>> _resolveServicesFn;
  17. public ServiceController(Func<IEnumerable<Type>> resolveServicesFn)
  18. {
  19. _resolveServicesFn = resolveServicesFn;
  20. this.RequestTypeFactoryMap = new Dictionary<Type, Func<IRequest, object>>();
  21. }
  22. public Dictionary<Type, Func<IRequest, object>> RequestTypeFactoryMap { get; set; }
  23. public void Init()
  24. {
  25. foreach (var serviceType in _resolveServicesFn())
  26. {
  27. RegisterService(serviceType);
  28. }
  29. }
  30. private Type[] GetGenericArguments(Type type)
  31. {
  32. return type.GetTypeInfo().IsGenericTypeDefinition
  33. ? type.GetTypeInfo().GenericTypeParameters
  34. : type.GetTypeInfo().GenericTypeArguments;
  35. }
  36. public void RegisterService(Type serviceType)
  37. {
  38. var processedReqs = new HashSet<Type>();
  39. var actions = ServiceExecGeneral.Reset(serviceType);
  40. var requiresRequestStreamTypeInfo = typeof(IRequiresRequestStream).GetTypeInfo();
  41. var appHost = ServiceStackHost.Instance;
  42. foreach (var mi in serviceType.GetActions())
  43. {
  44. var requestType = mi.GetParameters()[0].ParameterType;
  45. if (processedReqs.Contains(requestType)) continue;
  46. processedReqs.Add(requestType);
  47. ServiceExecGeneral.CreateServiceRunnersFor(requestType, actions);
  48. var returnMarker = requestType.GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>));
  49. var responseType = returnMarker != null ?
  50. GetGenericArguments(returnMarker)[0]
  51. : mi.ReturnType != typeof(object) && mi.ReturnType != typeof(void) ?
  52. mi.ReturnType
  53. : Type.GetType(requestType.FullName + "Response");
  54. RegisterRestPaths(requestType);
  55. appHost.Metadata.Add(serviceType, requestType, responseType);
  56. if (requiresRequestStreamTypeInfo.IsAssignableFrom(requestType.GetTypeInfo()))
  57. {
  58. this.RequestTypeFactoryMap[requestType] = req =>
  59. {
  60. var restPath = req.GetRoute();
  61. var request = RestHandler.CreateRequest(req, restPath, req.GetRequestParams(), ServiceStackHost.Instance.CreateInstance(requestType));
  62. var rawReq = (IRequiresRequestStream)request;
  63. rawReq.RequestStream = req.InputStream;
  64. return rawReq;
  65. };
  66. }
  67. }
  68. }
  69. public readonly Dictionary<string, List<RestPath>> RestPathMap = new Dictionary<string, List<RestPath>>();
  70. public void RegisterRestPaths(Type requestType)
  71. {
  72. var appHost = ServiceStackHost.Instance;
  73. var attrs = appHost.GetRouteAttributes(requestType);
  74. foreach (MediaBrowser.Model.Services.RouteAttribute attr in attrs)
  75. {
  76. var restPath = new RestPath(requestType, attr.Path, attr.Verbs, attr.Summary, attr.Notes);
  77. if (!restPath.IsValid)
  78. throw new NotSupportedException(string.Format(
  79. "RestPath '{0}' on Type '{1}' is not Valid", attr.Path, requestType.GetOperationName()));
  80. RegisterRestPath(restPath);
  81. }
  82. }
  83. private static readonly char[] InvalidRouteChars = new[] { '?', '&' };
  84. public void RegisterRestPath(RestPath restPath)
  85. {
  86. if (!restPath.Path.StartsWith("/"))
  87. throw new ArgumentException(string.Format("Route '{0}' on '{1}' must start with a '/'", restPath.Path, restPath.RequestType.GetOperationName()));
  88. if (restPath.Path.IndexOfAny(InvalidRouteChars) != -1)
  89. throw new ArgumentException(string.Format("Route '{0}' on '{1}' contains invalid chars. " +
  90. "See https://github.com/ServiceStack/ServiceStack/wiki/Routing for info on valid routes.", restPath.Path, restPath.RequestType.GetOperationName()));
  91. List<RestPath> pathsAtFirstMatch;
  92. if (!RestPathMap.TryGetValue(restPath.FirstMatchHashKey, out pathsAtFirstMatch))
  93. {
  94. pathsAtFirstMatch = new List<RestPath>();
  95. RestPathMap[restPath.FirstMatchHashKey] = pathsAtFirstMatch;
  96. }
  97. pathsAtFirstMatch.Add(restPath);
  98. }
  99. public void AfterInit()
  100. {
  101. var appHost = ServiceStackHost.Instance;
  102. //Register any routes configured on Metadata.Routes
  103. foreach (var restPath in appHost.RestPaths)
  104. {
  105. RegisterRestPath(restPath);
  106. }
  107. //Sync the RestPaths collections
  108. appHost.RestPaths.Clear();
  109. appHost.RestPaths.AddRange(RestPathMap.Values.SelectMany(x => x));
  110. }
  111. public RestPath GetRestPathForRequest(string httpMethod, string pathInfo)
  112. {
  113. var matchUsingPathParts = RestPath.GetPathPartsForMatching(pathInfo);
  114. List<RestPath> firstMatches;
  115. var yieldedHashMatches = RestPath.GetFirstMatchHashKeys(matchUsingPathParts);
  116. foreach (var potentialHashMatch in yieldedHashMatches)
  117. {
  118. if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches)) continue;
  119. var bestScore = -1;
  120. foreach (var restPath in firstMatches)
  121. {
  122. var score = restPath.MatchScore(httpMethod, matchUsingPathParts);
  123. if (score > bestScore) bestScore = score;
  124. }
  125. if (bestScore > 0)
  126. {
  127. foreach (var restPath in firstMatches)
  128. {
  129. if (bestScore == restPath.MatchScore(httpMethod, matchUsingPathParts))
  130. return restPath;
  131. }
  132. }
  133. }
  134. var yieldedWildcardMatches = RestPath.GetFirstMatchWildCardHashKeys(matchUsingPathParts);
  135. foreach (var potentialHashMatch in yieldedWildcardMatches)
  136. {
  137. if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches)) continue;
  138. var bestScore = -1;
  139. foreach (var restPath in firstMatches)
  140. {
  141. var score = restPath.MatchScore(httpMethod, matchUsingPathParts);
  142. if (score > bestScore) bestScore = score;
  143. }
  144. if (bestScore > 0)
  145. {
  146. foreach (var restPath in firstMatches)
  147. {
  148. if (bestScore == restPath.MatchScore(httpMethod, matchUsingPathParts))
  149. return restPath;
  150. }
  151. }
  152. }
  153. return null;
  154. }
  155. public async Task<object> Execute(object requestDto, IRequest req)
  156. {
  157. req.Dto = requestDto;
  158. var requestType = requestDto.GetType();
  159. req.OperationName = requestType.Name;
  160. var serviceType = ServiceStackHost.Instance.Metadata.GetServiceTypeByRequest(requestType);
  161. var service = ServiceStackHost.Instance.CreateInstance(serviceType);
  162. //var service = typeFactory.CreateInstance(serviceType);
  163. var serviceRequiresContext = service as IRequiresRequest;
  164. if (serviceRequiresContext != null)
  165. {
  166. serviceRequiresContext.Request = req;
  167. }
  168. if (req.Dto == null) // Don't override existing batched DTO[]
  169. req.Dto = requestDto;
  170. //Executes the service and returns the result
  171. var response = await ServiceExecGeneral.Execute(serviceType, req, service, requestDto, requestType.GetOperationName()).ConfigureAwait(false);
  172. if (req.Response.Dto == null)
  173. req.Response.Dto = response;
  174. return response;
  175. }
  176. }
  177. }