RestPath.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using ServiceStack.Serialization;
  7. namespace ServiceStack.Host
  8. {
  9. public class RestPath
  10. {
  11. private const string WildCard = "*";
  12. private const char WildCardChar = '*';
  13. private const string PathSeperator = "/";
  14. private const char PathSeperatorChar = '/';
  15. private const char ComponentSeperator = '.';
  16. private const string VariablePrefix = "{";
  17. readonly bool[] componentsWithSeparators;
  18. private readonly string restPath;
  19. private readonly string allowedVerbs;
  20. private readonly bool allowsAllVerbs;
  21. public bool IsWildCardPath { get; private set; }
  22. private readonly string[] literalsToMatch;
  23. private readonly string[] variablesNames;
  24. private readonly bool[] isWildcard;
  25. private readonly int wildcardCount = 0;
  26. public int VariableArgsCount { get; set; }
  27. /// <summary>
  28. /// The number of segments separated by '/' determinable by path.Split('/').Length
  29. /// e.g. /path/to/here.ext == 3
  30. /// </summary>
  31. public int PathComponentsCount { get; set; }
  32. /// <summary>
  33. /// The total number of segments after subparts have been exploded ('.')
  34. /// e.g. /path/to/here.ext == 4
  35. /// </summary>
  36. public int TotalComponentsCount { get; set; }
  37. public string[] Verbs
  38. {
  39. get
  40. {
  41. return allowsAllVerbs
  42. ? new[] { ActionContext.AnyAction }
  43. : AllowedVerbs.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
  44. }
  45. }
  46. public Type RequestType { get; private set; }
  47. public string Path { get { return this.restPath; } }
  48. public string Summary { get; private set; }
  49. public string Notes { get; private set; }
  50. public bool AllowsAllVerbs { get { return this.allowsAllVerbs; } }
  51. public string AllowedVerbs { get { return this.allowedVerbs; } }
  52. public int Priority { get; set; } //passed back to RouteAttribute
  53. public static string[] GetPathPartsForMatching(string pathInfo)
  54. {
  55. var parts = pathInfo.ToLower().Split(PathSeperatorChar)
  56. .Where(x => !string.IsNullOrEmpty(x)).ToArray();
  57. return parts;
  58. }
  59. public static IEnumerable<string> GetFirstMatchHashKeys(string[] pathPartsForMatching)
  60. {
  61. var hashPrefix = pathPartsForMatching.Length + PathSeperator;
  62. return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching);
  63. }
  64. public static IEnumerable<string> GetFirstMatchWildCardHashKeys(string[] pathPartsForMatching)
  65. {
  66. const string hashPrefix = WildCard + PathSeperator;
  67. return GetPotentialMatchesWithPrefix(hashPrefix, pathPartsForMatching);
  68. }
  69. private static IEnumerable<string> GetPotentialMatchesWithPrefix(string hashPrefix, string[] pathPartsForMatching)
  70. {
  71. foreach (var part in pathPartsForMatching)
  72. {
  73. yield return hashPrefix + part;
  74. var subParts = part.Split(ComponentSeperator);
  75. if (subParts.Length == 1) continue;
  76. foreach (var subPart in subParts)
  77. {
  78. yield return hashPrefix + subPart;
  79. }
  80. }
  81. }
  82. public RestPath(Type requestType, string path, string verbs, string summary = null, string notes = null)
  83. {
  84. this.RequestType = requestType;
  85. this.Summary = summary;
  86. this.Notes = notes;
  87. this.restPath = path;
  88. this.allowsAllVerbs = verbs == null || verbs == WildCard;
  89. if (!this.allowsAllVerbs)
  90. {
  91. this.allowedVerbs = verbs.ToUpper();
  92. }
  93. var componentsList = new List<string>();
  94. //We only split on '.' if the restPath has them. Allows for /{action}.{type}
  95. var hasSeparators = new List<bool>();
  96. foreach (var component in this.restPath.Split(PathSeperatorChar))
  97. {
  98. if (string.IsNullOrEmpty(component)) continue;
  99. if (component.Contains(VariablePrefix)
  100. && component.IndexOf(ComponentSeperator) != -1)
  101. {
  102. hasSeparators.Add(true);
  103. componentsList.AddRange(component.Split(ComponentSeperator));
  104. }
  105. else
  106. {
  107. hasSeparators.Add(false);
  108. componentsList.Add(component);
  109. }
  110. }
  111. var components = componentsList.ToArray();
  112. this.TotalComponentsCount = components.Length;
  113. this.literalsToMatch = new string[this.TotalComponentsCount];
  114. this.variablesNames = new string[this.TotalComponentsCount];
  115. this.isWildcard = new bool[this.TotalComponentsCount];
  116. this.componentsWithSeparators = hasSeparators.ToArray();
  117. this.PathComponentsCount = this.componentsWithSeparators.Length;
  118. string firstLiteralMatch = null;
  119. var sbHashKey = new StringBuilder();
  120. for (var i = 0; i < components.Length; i++)
  121. {
  122. var component = components[i];
  123. if (component.StartsWith(VariablePrefix))
  124. {
  125. var variableName = component.Substring(1, component.Length - 2);
  126. if (variableName[variableName.Length - 1] == WildCardChar)
  127. {
  128. this.isWildcard[i] = true;
  129. variableName = variableName.Substring(0, variableName.Length - 1);
  130. }
  131. this.variablesNames[i] = variableName;
  132. this.VariableArgsCount++;
  133. }
  134. else
  135. {
  136. this.literalsToMatch[i] = component.ToLower();
  137. sbHashKey.Append(i + PathSeperatorChar.ToString() + this.literalsToMatch);
  138. if (firstLiteralMatch == null)
  139. {
  140. firstLiteralMatch = this.literalsToMatch[i];
  141. }
  142. }
  143. }
  144. for (var i = 0; i < components.Length - 1; i++)
  145. {
  146. if (!this.isWildcard[i]) continue;
  147. if (this.literalsToMatch[i + 1] == null)
  148. {
  149. throw new ArgumentException(
  150. "A wildcard path component must be at the end of the path or followed by a literal path component.");
  151. }
  152. }
  153. this.wildcardCount = this.isWildcard.Count(x => x);
  154. this.IsWildCardPath = this.wildcardCount > 0;
  155. this.FirstMatchHashKey = !this.IsWildCardPath
  156. ? this.PathComponentsCount + PathSeperator + firstLiteralMatch
  157. : WildCardChar + PathSeperator + firstLiteralMatch;
  158. this.IsValid = sbHashKey.Length > 0;
  159. this.UniqueMatchHashKey = sbHashKey.ToString();
  160. this.typeDeserializer = new StringMapTypeDeserializer(this.RequestType);
  161. RegisterCaseInsenstivePropertyNameMappings();
  162. }
  163. private void RegisterCaseInsenstivePropertyNameMappings()
  164. {
  165. foreach (var propertyInfo in RequestType.GetSerializableProperties())
  166. {
  167. var propertyName = propertyInfo.Name;
  168. propertyNamesMap.Add(propertyName.ToLower(), propertyName);
  169. }
  170. }
  171. public bool IsValid { get; set; }
  172. /// <summary>
  173. /// Provide for quick lookups based on hashes that can be determined from a request url
  174. /// </summary>
  175. public string FirstMatchHashKey { get; private set; }
  176. public string UniqueMatchHashKey { get; private set; }
  177. private readonly StringMapTypeDeserializer typeDeserializer;
  178. private readonly Dictionary<string, string> propertyNamesMap = new Dictionary<string, string>();
  179. public static Func<RestPath, string, string[], int> CalculateMatchScore { get; set; }
  180. public int MatchScore(string httpMethod, string[] withPathInfoParts)
  181. {
  182. if (CalculateMatchScore != null)
  183. return CalculateMatchScore(this, httpMethod, withPathInfoParts);
  184. int wildcardMatchCount;
  185. var isMatch = IsMatch(httpMethod, withPathInfoParts, out wildcardMatchCount);
  186. if (!isMatch) return -1;
  187. var score = 0;
  188. //Routes with least wildcard matches get the highest score
  189. score += Math.Max((100 - wildcardMatchCount), 1) * 1000;
  190. //Routes with less variable (and more literal) matches
  191. score += Math.Max((10 - VariableArgsCount), 1) * 100;
  192. //Exact verb match is better than ANY
  193. var exactVerb = httpMethod == AllowedVerbs;
  194. score += exactVerb ? 10 : 1;
  195. return score;
  196. }
  197. /// <summary>
  198. /// For performance withPathInfoParts should already be a lower case string
  199. /// to minimize redundant matching operations.
  200. /// </summary>
  201. /// <param name="httpMethod"></param>
  202. /// <param name="withPathInfoParts"></param>
  203. /// <param name="wildcardMatchCount"></param>
  204. /// <returns></returns>
  205. public bool IsMatch(string httpMethod, string[] withPathInfoParts, out int wildcardMatchCount)
  206. {
  207. wildcardMatchCount = 0;
  208. if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath) return false;
  209. if (!this.allowsAllVerbs && !this.allowedVerbs.Contains(httpMethod.ToUpper())) return false;
  210. if (!ExplodeComponents(ref withPathInfoParts)) return false;
  211. if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath) return false;
  212. int pathIx = 0;
  213. for (var i = 0; i < this.TotalComponentsCount; i++)
  214. {
  215. if (this.isWildcard[i])
  216. {
  217. if (i < this.TotalComponentsCount - 1)
  218. {
  219. // Continue to consume up until a match with the next literal
  220. while (pathIx < withPathInfoParts.Length && withPathInfoParts[pathIx] != this.literalsToMatch[i + 1])
  221. {
  222. pathIx++;
  223. wildcardMatchCount++;
  224. }
  225. // Ensure there are still enough parts left to match the remainder
  226. if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
  227. {
  228. return false;
  229. }
  230. }
  231. else
  232. {
  233. // A wildcard at the end matches the remainder of path
  234. wildcardMatchCount += withPathInfoParts.Length - pathIx;
  235. pathIx = withPathInfoParts.Length;
  236. }
  237. }
  238. else
  239. {
  240. var literalToMatch = this.literalsToMatch[i];
  241. if (literalToMatch == null)
  242. {
  243. // Matching an ordinary (non-wildcard) variable consumes a single part
  244. pathIx++;
  245. continue;
  246. }
  247. if (withPathInfoParts.Length <= pathIx || withPathInfoParts[pathIx] != literalToMatch) return false;
  248. pathIx++;
  249. }
  250. }
  251. return pathIx == withPathInfoParts.Length;
  252. }
  253. private bool ExplodeComponents(ref string[] withPathInfoParts)
  254. {
  255. var totalComponents = new List<string>();
  256. for (var i = 0; i < withPathInfoParts.Length; i++)
  257. {
  258. var component = withPathInfoParts[i];
  259. if (string.IsNullOrEmpty(component)) continue;
  260. if (this.PathComponentsCount != this.TotalComponentsCount
  261. && this.componentsWithSeparators[i])
  262. {
  263. var subComponents = component.Split(ComponentSeperator);
  264. if (subComponents.Length < 2) return false;
  265. totalComponents.AddRange(subComponents);
  266. }
  267. else
  268. {
  269. totalComponents.Add(component);
  270. }
  271. }
  272. withPathInfoParts = totalComponents.ToArray();
  273. return true;
  274. }
  275. public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance)
  276. {
  277. var requestComponents = pathInfo.Split(PathSeperatorChar)
  278. .Where(x => !string.IsNullOrEmpty(x)).ToArray();
  279. ExplodeComponents(ref requestComponents);
  280. if (requestComponents.Length != this.TotalComponentsCount)
  281. {
  282. var isValidWildCardPath = this.IsWildCardPath
  283. && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount;
  284. if (!isValidWildCardPath)
  285. throw new ArgumentException(string.Format(
  286. "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'",
  287. pathInfo, this.restPath));
  288. }
  289. var requestKeyValuesMap = new Dictionary<string, string>();
  290. var pathIx = 0;
  291. for (var i = 0; i < this.TotalComponentsCount; i++)
  292. {
  293. var variableName = this.variablesNames[i];
  294. if (variableName == null)
  295. {
  296. pathIx++;
  297. continue;
  298. }
  299. string propertyNameOnRequest;
  300. if (!this.propertyNamesMap.TryGetValue(variableName.ToLower(), out propertyNameOnRequest))
  301. {
  302. if (string.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase))
  303. {
  304. pathIx++;
  305. continue;
  306. }
  307. throw new ArgumentException("Could not find property "
  308. + variableName + " on " + RequestType.GetOperationName());
  309. }
  310. var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch
  311. if (value != null && this.isWildcard[i])
  312. {
  313. if (i == this.TotalComponentsCount - 1)
  314. {
  315. // Wildcard at end of path definition consumes all the rest
  316. var sb = new StringBuilder();
  317. sb.Append(value);
  318. for (var j = pathIx + 1; j < requestComponents.Length; j++)
  319. {
  320. sb.Append(PathSeperatorChar + requestComponents[j]);
  321. }
  322. value = sb.ToString();
  323. }
  324. else
  325. {
  326. // Wildcard in middle of path definition consumes up until it
  327. // hits a match for the next element in the definition (which must be a literal)
  328. // It may consume 0 or more path parts
  329. var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1];
  330. if (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  331. {
  332. var sb = new StringBuilder();
  333. sb.Append(value);
  334. pathIx++;
  335. while (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  336. {
  337. sb.Append(PathSeperatorChar + requestComponents[pathIx++]);
  338. }
  339. value = sb.ToString();
  340. }
  341. else
  342. {
  343. value = null;
  344. }
  345. }
  346. }
  347. else
  348. {
  349. // Variable consumes single path item
  350. pathIx++;
  351. }
  352. requestKeyValuesMap[propertyNameOnRequest] = value;
  353. }
  354. if (queryStringAndFormData != null)
  355. {
  356. //Query String and form data can override variable path matches
  357. //path variables < query string < form data
  358. foreach (var name in queryStringAndFormData)
  359. {
  360. requestKeyValuesMap[name.Key] = name.Value;
  361. }
  362. }
  363. return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap);
  364. }
  365. public override int GetHashCode()
  366. {
  367. return UniqueMatchHashKey.GetHashCode();
  368. }
  369. }
  370. }