RestPath.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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 || string.Equals(verbs, WildCard, StringComparison.OrdinalIgnoreCase);
  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 (StringContains(component, 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 = string.Equals(httpMethod, AllowedVerbs, StringComparison.OrdinalIgnoreCase);
  194. score += exactVerb ? 10 : 1;
  195. return score;
  196. }
  197. private bool StringContains(string str1, string str2)
  198. {
  199. return str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) != -1;
  200. }
  201. /// <summary>
  202. /// For performance withPathInfoParts should already be a lower case string
  203. /// to minimize redundant matching operations.
  204. /// </summary>
  205. /// <param name="httpMethod"></param>
  206. /// <param name="withPathInfoParts"></param>
  207. /// <param name="wildcardMatchCount"></param>
  208. /// <returns></returns>
  209. public bool IsMatch(string httpMethod, string[] withPathInfoParts, out int wildcardMatchCount)
  210. {
  211. wildcardMatchCount = 0;
  212. if (withPathInfoParts.Length != this.PathComponentsCount && !this.IsWildCardPath) return false;
  213. if (!this.allowsAllVerbs && !StringContains(this.allowedVerbs, httpMethod)) return false;
  214. if (!ExplodeComponents(ref withPathInfoParts)) return false;
  215. if (this.TotalComponentsCount != withPathInfoParts.Length && !this.IsWildCardPath) return false;
  216. int pathIx = 0;
  217. for (var i = 0; i < this.TotalComponentsCount; i++)
  218. {
  219. if (this.isWildcard[i])
  220. {
  221. if (i < this.TotalComponentsCount - 1)
  222. {
  223. // Continue to consume up until a match with the next literal
  224. while (pathIx < withPathInfoParts.Length && withPathInfoParts[pathIx] != this.literalsToMatch[i + 1])
  225. {
  226. pathIx++;
  227. wildcardMatchCount++;
  228. }
  229. // Ensure there are still enough parts left to match the remainder
  230. if ((withPathInfoParts.Length - pathIx) < (this.TotalComponentsCount - i - 1))
  231. {
  232. return false;
  233. }
  234. }
  235. else
  236. {
  237. // A wildcard at the end matches the remainder of path
  238. wildcardMatchCount += withPathInfoParts.Length - pathIx;
  239. pathIx = withPathInfoParts.Length;
  240. }
  241. }
  242. else
  243. {
  244. var literalToMatch = this.literalsToMatch[i];
  245. if (literalToMatch == null)
  246. {
  247. // Matching an ordinary (non-wildcard) variable consumes a single part
  248. pathIx++;
  249. continue;
  250. }
  251. if (withPathInfoParts.Length <= pathIx || withPathInfoParts[pathIx] != literalToMatch) return false;
  252. pathIx++;
  253. }
  254. }
  255. return pathIx == withPathInfoParts.Length;
  256. }
  257. private bool ExplodeComponents(ref string[] withPathInfoParts)
  258. {
  259. var totalComponents = new List<string>();
  260. for (var i = 0; i < withPathInfoParts.Length; i++)
  261. {
  262. var component = withPathInfoParts[i];
  263. if (string.IsNullOrEmpty(component)) continue;
  264. if (this.PathComponentsCount != this.TotalComponentsCount
  265. && this.componentsWithSeparators[i])
  266. {
  267. var subComponents = component.Split(ComponentSeperator);
  268. if (subComponents.Length < 2) return false;
  269. totalComponents.AddRange(subComponents);
  270. }
  271. else
  272. {
  273. totalComponents.Add(component);
  274. }
  275. }
  276. withPathInfoParts = totalComponents.ToArray();
  277. return true;
  278. }
  279. public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance)
  280. {
  281. var requestComponents = pathInfo.Split(PathSeperatorChar)
  282. .Where(x => !string.IsNullOrEmpty(x)).ToArray();
  283. ExplodeComponents(ref requestComponents);
  284. if (requestComponents.Length != this.TotalComponentsCount)
  285. {
  286. var isValidWildCardPath = this.IsWildCardPath
  287. && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount;
  288. if (!isValidWildCardPath)
  289. throw new ArgumentException(string.Format(
  290. "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'",
  291. pathInfo, this.restPath));
  292. }
  293. var requestKeyValuesMap = new Dictionary<string, string>();
  294. var pathIx = 0;
  295. for (var i = 0; i < this.TotalComponentsCount; i++)
  296. {
  297. var variableName = this.variablesNames[i];
  298. if (variableName == null)
  299. {
  300. pathIx++;
  301. continue;
  302. }
  303. string propertyNameOnRequest;
  304. if (!this.propertyNamesMap.TryGetValue(variableName.ToLower(), out propertyNameOnRequest))
  305. {
  306. if (string.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase))
  307. {
  308. pathIx++;
  309. continue;
  310. }
  311. throw new ArgumentException("Could not find property "
  312. + variableName + " on " + RequestType.GetOperationName());
  313. }
  314. var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch
  315. if (value != null && this.isWildcard[i])
  316. {
  317. if (i == this.TotalComponentsCount - 1)
  318. {
  319. // Wildcard at end of path definition consumes all the rest
  320. var sb = new StringBuilder();
  321. sb.Append(value);
  322. for (var j = pathIx + 1; j < requestComponents.Length; j++)
  323. {
  324. sb.Append(PathSeperatorChar + requestComponents[j]);
  325. }
  326. value = sb.ToString();
  327. }
  328. else
  329. {
  330. // Wildcard in middle of path definition consumes up until it
  331. // hits a match for the next element in the definition (which must be a literal)
  332. // It may consume 0 or more path parts
  333. var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1];
  334. if (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  335. {
  336. var sb = new StringBuilder();
  337. sb.Append(value);
  338. pathIx++;
  339. while (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase))
  340. {
  341. sb.Append(PathSeperatorChar + requestComponents[pathIx++]);
  342. }
  343. value = sb.ToString();
  344. }
  345. else
  346. {
  347. value = null;
  348. }
  349. }
  350. }
  351. else
  352. {
  353. // Variable consumes single path item
  354. pathIx++;
  355. }
  356. requestKeyValuesMap[propertyNameOnRequest] = value;
  357. }
  358. if (queryStringAndFormData != null)
  359. {
  360. //Query String and form data can override variable path matches
  361. //path variables < query string < form data
  362. foreach (var name in queryStringAndFormData)
  363. {
  364. requestKeyValuesMap[name.Key] = name.Value;
  365. }
  366. }
  367. return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap);
  368. }
  369. public override int GetHashCode()
  370. {
  371. return UniqueMatchHashKey.GetHashCode();
  372. }
  373. }
  374. }