| | | 1 | | /******************************************************************************** |
| | | 2 | | * RouteScopeBuilder.cs * |
| | | 3 | | * * |
| | | 4 | | * Author: Denes Solti * |
| | | 5 | | ********************************************************************************/ |
| | | 6 | | using System; |
| | | 7 | | using System.Collections.Generic; |
| | | 8 | | using System.Diagnostics; |
| | | 9 | | using System.Linq; |
| | | 10 | | |
| | | 11 | | namespace NanoRoute |
| | | 12 | | { |
| | | 13 | | using Internals; |
| | | 14 | | using Properties; |
| | | 15 | | |
| | | 16 | | /// <summary> |
| | | 17 | | /// Builder responsible for configuring a route scope and its child route tree. |
| | | 18 | | /// </summary> |
| | | 19 | | /// <remarks> |
| | | 20 | | /// Route patterns support literal segments and parser-backed parameter segments such as |
| | | 21 | | /// <c>/users/{id:int}/</c>. Patterns must start with <c>/</c>, exact patterns must end with <c>/</c>, |
| | | 22 | | /// prefix patterns must end with <c>/*</c>, and repeated <c>/</c> separators such as <c>//</c> are invalid. |
| | | 23 | | /// </remarks> |
| | | 24 | | /// <example> |
| | | 25 | | /// <code> |
| | | 26 | | /// builder |
| | | 27 | | /// .AddDefaultValueParsers() |
| | | 28 | | /// .AddHandler("GET", "/users/{id:int}/", (context, _) => Results.Ok(context.Parameters["id"])); |
| | | 29 | | /// </code> |
| | | 30 | | /// </example> |
| | | 31 | | public class RouteScopeBuilder |
| | | 32 | | { |
| | | 33 | | /// <summary> |
| | | 34 | | /// The route pattern that matches the current route scope exactly. |
| | | 35 | | /// </summary> |
| | | 36 | | /// <example> |
| | | 37 | | /// <code> |
| | | 38 | | /// builder.AddHandler("GET", RouteScopeBuilder.CurrentExact, (context, _) => Results.Ok()); |
| | | 39 | | /// </code> |
| | | 40 | | /// </example> |
| | | 41 | | public const string CurrentExact = "/"; |
| | | 42 | | |
| | | 43 | | /// <summary> |
| | | 44 | | /// The route pattern that matches the current route scope as a prefix. |
| | | 45 | | /// </summary> |
| | | 46 | | /// <example> |
| | | 47 | | /// <code> |
| | | 48 | | /// builder.AddHandler("GET", RouteScopeBuilder.CurrentPrefix, (context, next) => next()); |
| | | 49 | | /// </code> |
| | | 50 | | /// </example> |
| | | 51 | | public const string CurrentPrefix = "/*"; |
| | | 52 | | |
| | | 53 | | #region Private |
| | | 54 | | private readonly RouteNode _root; |
| | | 55 | | |
| | | 56 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 57 | | private readonly Dictionary<string, ValueParserRegistration> _valueParsers; |
| | | 58 | | |
| | | 59 | | /// <summary> |
| | | 60 | | /// Gets or creates the <see cref="RouteNode"/> that matches the given <paramref name="pattern"/>. |
| | | 61 | | /// </summary> |
| | | 62 | | private RouteNode GetOrCreateNode(string pattern) |
| | 2 | 63 | | { |
| | 2 | 64 | | RouteNode target = _root; |
| | | 65 | | |
| | 2 | 66 | | foreach (object parsedPattern in DslParser.ParseRoutePattern(pattern)) |
| | 2 | 67 | | { |
| | | 68 | | switch (parsedPattern) |
| | | 69 | | { |
| | | 70 | | case ParameterDefinition parameterDefinition: |
| | 1 | 71 | | if (!_valueParsers.TryGetValue(parameterDefinition.ValueParser.Name, out ValueParserRegistration |
| | 1 | 72 | | throw new InvalidOperationException |
| | 1 | 73 | | ( |
| | 1 | 74 | | string.Format(Resources.Culture, Resources.ERR_NO_SUCH_PARSER, parameterDefinition.Value |
| | 1 | 75 | | ); |
| | | 76 | | |
| | 1 | 77 | | KeyValuePair<ParameterParser, RouteNode> parsedBranch = target |
| | 1 | 78 | | .ParsedBranches |
| | 1 | 79 | | .SingleOrDefault(c => c.Key.Definition.ValueParser.Equals(parameterDefinition.ValueParser)); |
| | | 80 | | |
| | 1 | 81 | | if (parsedBranch.Equals(default(KeyValuePair<ParameterParser, RouteNode>))) |
| | 1 | 82 | | { |
| | 1 | 83 | | parsedBranch = new KeyValuePair<ParameterParser, RouteNode> |
| | 1 | 84 | | ( |
| | 1 | 85 | | new ParameterParser |
| | 1 | 86 | | ( |
| | 1 | 87 | | parameterDefinition, |
| | 1 | 88 | | parserRegistration.Parse, |
| | 1 | 89 | | parserRegistration.BindArguments(parameterDefinition.ValueParser.RawArguments) |
| | 1 | 90 | | ), |
| | 1 | 91 | | new RouteNode() |
| | 1 | 92 | | ); |
| | | 93 | | |
| | 1 | 94 | | target.ParsedBranches.Add(parsedBranch); |
| | 1 | 95 | | } |
| | 1 | 96 | | else if (!StringComparer.OrdinalIgnoreCase.Equals(parsedBranch.Key.Definition.ParameterName, par |
| | 1 | 97 | | throw new InvalidOperationException(Resources.ERR_PARAMETER_OVERRIDE); |
| | | 98 | | |
| | 1 | 99 | | target = parsedBranch.Value; |
| | 1 | 100 | | break; |
| | | 101 | | |
| | | 102 | | case ReadOnlyMemory<char> literalSegmentDefinition: |
| | 2 | 103 | | if (!target.LiteralBranches.TryGetValue(literalSegmentDefinition, out RouteNode exactChild)) |
| | 2 | 104 | | { |
| | 2 | 105 | | exactChild = new RouteNode(); |
| | 2 | 106 | | target.LiteralBranches.Add(literalSegmentDefinition, exactChild); |
| | 2 | 107 | | } |
| | | 108 | | |
| | 2 | 109 | | target = exactChild; |
| | 2 | 110 | | break; |
| | | 111 | | |
| | | 112 | | default: |
| | 0 | 113 | | Debug.Fail("Unknown definition"); |
| | 0 | 114 | | break; |
| | | 115 | | } |
| | 2 | 116 | | } |
| | | 117 | | |
| | 2 | 118 | | return target; |
| | 2 | 119 | | } |
| | | 120 | | |
| | | 121 | | private static string JoinPattern(string @base, string extensions) |
| | 2 | 122 | | { |
| | 2 | 123 | | Debug.Assert(@base.EndsWith(CurrentPrefix), "Base patterns must be prefix routes"); |
| | | 124 | | |
| | 2 | 125 | | return @base.TrimEnd('*') + extensions.TrimStart('/'); |
| | 2 | 126 | | } |
| | | 127 | | |
| | 1 | 128 | | private RouteScopeBuilder(RouteScopeBuilder parent, string pattern) |
| | 1 | 129 | | { |
| | 1 | 130 | | _root = parent.GetOrCreateNode(pattern); |
| | 1 | 131 | | _valueParsers = new Dictionary<string, ValueParserRegistration>(parent._valueParsers, StringComparer.Ordinal |
| | | 132 | | |
| | 1 | 133 | | BasePattern = JoinPattern(parent.BasePattern, pattern); |
| | 1 | 134 | | Metadata = parent.Metadata.CreateScope(); |
| | 1 | 135 | | } |
| | | 136 | | |
| | 2 | 137 | | internal RouteScopeBuilder() |
| | 2 | 138 | | { |
| | 2 | 139 | | _root = new RouteNode(); |
| | 2 | 140 | | _valueParsers = new Dictionary<string, ValueParserRegistration>(StringComparer.OrdinalIgnoreCase); |
| | | 141 | | |
| | 2 | 142 | | BasePattern = CurrentPrefix; |
| | 2 | 143 | | Metadata = new BuilderMetadata(); |
| | 2 | 144 | | } |
| | | 145 | | |
| | | 146 | | /// <summary> |
| | | 147 | | /// Creates an immutable snapshot of the current route tree. |
| | | 148 | | /// </summary> |
| | | 149 | | /// <returns>A frozen snapshot of the configured root node.</returns> |
| | 2 | 150 | | internal RouteNode CreateSnapshot() => _root.Freeze(); |
| | | 151 | | #endregion |
| | | 152 | | |
| | | 153 | | /// <summary> |
| | | 154 | | /// Registers a parser that can convert a route segment into a typed value and bind parser arguments once during |
| | | 155 | | /// </summary> |
| | | 156 | | /// <param name="parserName">The name used in route patterns such as <c>{id:int(min=1)}</c>.</param> |
| | | 157 | | /// <param name="bindArguments">Converts raw parser arguments into typed values once per route-template branch.< |
| | | 158 | | /// <param name="tryParseDelegate">The delegate that validates and parses a single path segment.</param> |
| | | 159 | | /// <returns>The current instance.</returns> |
| | | 160 | | /// <exception cref="ArgumentNullException"> |
| | | 161 | | /// Thrown when <paramref name="parserName"/>, <paramref name="bindArguments"/>, or |
| | | 162 | | /// <paramref name="tryParseDelegate"/> is <see langword="null"/>. |
| | | 163 | | /// </exception> |
| | | 164 | | /// <example> |
| | | 165 | | /// <code> |
| | | 166 | | /// builder.AddValueParser("slug", static rawArgs => null, static context => |
| | | 167 | | /// ValueTask.FromResult(new ValueParseResult(context.Segment.Length > 0, context.Segment.ToString()))); |
| | | 168 | | /// </code> |
| | | 169 | | /// </example> |
| | | 170 | | public RouteScopeBuilder AddValueParser(string parserName, BindArgumentsDelegate bindArguments, ValueParserDeleg |
| | 1 | 171 | | { |
| | 1 | 172 | | Ensure.NotNull(parserName); |
| | 1 | 173 | | Ensure.NotNull(bindArguments); |
| | 1 | 174 | | Ensure.NotNull(tryParseDelegate); |
| | | 175 | | |
| | 1 | 176 | | _valueParsers[parserName] = new ValueParserRegistration(parserName, tryParseDelegate, bindArguments); |
| | | 177 | | |
| | 1 | 178 | | return this; |
| | 1 | 179 | | } |
| | | 180 | | |
| | | 181 | | /// <summary> |
| | | 182 | | /// Registers a handler for a single HTTP method. |
| | | 183 | | /// </summary> |
| | | 184 | | /// <param name="verb">The HTTP method that activates the handler.</param> |
| | | 185 | | /// <param name="pattern"> |
| | | 186 | | /// The route pattern to match. Literal segments are matched case-insensitively, parameter segments use |
| | | 187 | | /// registered parsers in the form <c>{parameterName:parserName}</c>. Exact patterns must end with |
| | | 188 | | /// <c>/</c>, prefix patterns must end with <c>/*</c>, and repeated <c>/</c> separators are invalid. |
| | | 189 | | /// </param> |
| | | 190 | | /// <param name="handler"> |
| | | 191 | | /// The handler to execute. If several handlers match, calling the supplied <c>next</c> delegate continues |
| | | 192 | | /// the pipeline with the next compatible handler from the already selected route branch. |
| | | 193 | | /// </param> |
| | | 194 | | /// <returns>The current route scope builder instance.</returns> |
| | | 195 | | /// <exception cref="ArgumentNullException"> |
| | | 196 | | /// Thrown when <paramref name="verb"/>, <paramref name="pattern"/>, or <paramref name="handler"/> is |
| | | 197 | | /// <see langword="null"/>. |
| | | 198 | | /// </exception> |
| | | 199 | | /// <exception cref="ArgumentException">Thrown when <paramref name="verb"/> is not a supported HTTP method.</exc |
| | | 200 | | /// <exception cref="InvalidOperationException"> |
| | | 201 | | /// Thrown when <paramref name="pattern"/> uses an unsupported optional parameter or list parser, references |
| | | 202 | | /// a value parser that has not been registered yet, or reuses a parser-backed branch with a different |
| | | 203 | | /// parameter name. |
| | | 204 | | /// </exception> |
| | | 205 | | /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template syntax |
| | | 206 | | /// <example> |
| | | 207 | | /// <code> |
| | | 208 | | /// builder.AddHandler("GET", "/files/{path:any}/*", (context, next) => |
| | | 209 | | /// { |
| | | 210 | | /// string path = (string) context.Parameters["path"]!; |
| | | 211 | | /// return ServeFile(path); |
| | | 212 | | /// }); |
| | | 213 | | /// </code> |
| | | 214 | | /// </example> |
| | | 215 | | public RouteScopeBuilder AddHandler(string verb, string pattern, RequestHandlerDelegate handler) |
| | 2 | 216 | | { |
| | 2 | 217 | | Ensure.NotNull(verb); |
| | 2 | 218 | | Ensure.NotNull(pattern); |
| | 2 | 219 | | Ensure.NotNull(handler); |
| | | 220 | | |
| | 2 | 221 | | if (!Enum.TryParse(verb, ignoreCase: true, out HttpVerb v)) |
| | 1 | 222 | | throw new ArgumentException |
| | 1 | 223 | | ( |
| | 1 | 224 | | string.Format(Resources.Culture, Resources.ERR_INVALID_VERB, verb), nameof(verb) |
| | 1 | 225 | | ); |
| | | 226 | | |
| | 2 | 227 | | GetOrCreateNode(pattern).Handlers.Add |
| | 2 | 228 | | ( |
| | 2 | 229 | | new KeyValuePair<HttpVerb, HandlerRegistration> |
| | 2 | 230 | | ( |
| | 2 | 231 | | v, |
| | 2 | 232 | | new HandlerRegistration(handler, JoinPattern(BasePattern, pattern)) |
| | 2 | 233 | | ) |
| | 2 | 234 | | ); |
| | | 235 | | |
| | 2 | 236 | | return this; |
| | 2 | 237 | | } |
| | | 238 | | |
| | | 239 | | /// <summary> |
| | | 240 | | /// Creates a child route scope whose routes are rooted under the given prefix. |
| | | 241 | | /// </summary> |
| | | 242 | | /// <param name="pattern"> |
| | | 243 | | /// The base prefix. It must be a valid route pattern ending in <c>/*</c> so child routes can be appended to it. |
| | | 244 | | /// </param> |
| | | 245 | | /// <returns>A child route scope builder that shares the current route tree but has its own parser registration |
| | | 246 | | /// <remarks> |
| | | 247 | | /// Child route scopes inherit the parent's registered value parsers at creation time. Additional parser |
| | | 248 | | /// registrations or overrides made on the child scope stay local to that branch. |
| | | 249 | | /// </remarks> |
| | | 250 | | /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> does not end with <c>/*</c>.</exc |
| | | 251 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="pattern"/> is <see langword="null"/>.</e |
| | | 252 | | /// <exception cref="InvalidOperationException"> |
| | | 253 | | /// Thrown when <paramref name="pattern"/> uses an unsupported optional parameter or list parser, references |
| | | 254 | | /// a value parser that has not been registered yet, or reuses a parser-backed branch with a different |
| | | 255 | | /// parameter name. |
| | | 256 | | /// </exception> |
| | | 257 | | /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template syntax |
| | | 258 | | /// <example> |
| | | 259 | | /// <code> |
| | | 260 | | /// RouteScopeBuilder api = builder.CreatePrefix("/api/*"); |
| | | 261 | | /// |
| | | 262 | | /// api.AddHandler("GET", "/health/", (context, _) => Results.Ok()); |
| | | 263 | | /// </code> |
| | | 264 | | /// </example> |
| | | 265 | | public RouteScopeBuilder CreatePrefix(string pattern) |
| | 1 | 266 | | { |
| | 1 | 267 | | Ensure.NotNull(pattern); |
| | | 268 | | |
| | 1 | 269 | | if (!pattern.EndsWith(CurrentPrefix)) |
| | 1 | 270 | | throw new ArgumentException(Resources.ERR_NOT_PREFIX, nameof(pattern)); |
| | | 271 | | |
| | 1 | 272 | | return new RouteScopeBuilder(this, pattern); |
| | 1 | 273 | | } |
| | | 274 | | |
| | | 275 | | /// <summary> |
| | | 276 | | /// Gets the value parser registrations currently visible from this route scope. |
| | | 277 | | /// </summary> |
| | | 278 | | /// <remarks> |
| | | 279 | | /// For child scopes created with <see cref="CreatePrefix(string)"/>, this dictionary reflects the inherited |
| | | 280 | | /// registrations plus any overrides added to that child scope. |
| | | 281 | | /// </remarks> |
| | | 282 | | /// <example> |
| | | 283 | | /// <code> |
| | | 284 | | /// bool hasIntParser = builder.ValueParsers.ContainsKey("int"); |
| | | 285 | | /// </code> |
| | | 286 | | /// </example> |
| | 1 | 287 | | public IReadOnlyDictionary<string, ValueParserRegistration> ValueParsers => _valueParsers; |
| | | 288 | | |
| | | 289 | | /// <summary> |
| | | 290 | | /// Gets the route pattern prefix for this route scope. |
| | | 291 | | /// </summary> |
| | | 292 | | /// <remarks> |
| | | 293 | | /// The root scope exposes <see cref="CurrentPrefix"/>. Child scopes created with |
| | | 294 | | /// <see cref="CreatePrefix(string)"/> expose the accumulated prefix inherited from their parent scopes. |
| | | 295 | | /// </remarks> |
| | | 296 | | public string BasePattern { get; } |
| | | 297 | | |
| | | 298 | | /// <summary> |
| | | 299 | | /// Gets extension-defined builder metadata visible from this route scope. |
| | | 300 | | /// </summary> |
| | | 301 | | /// <remarks> |
| | | 302 | | /// Metadata is public for extension authors who need scoped build-time settings behind module-specific |
| | | 303 | | /// configuration methods. Application code usually should prefer those module APIs instead of reading or |
| | | 304 | | /// writing metadata directly. |
| | | 305 | | /// <para> |
| | | 306 | | /// Child scopes created with <see cref="CreatePrefix(string)"/> inherit a scoped copy of their parent's |
| | | 307 | | /// metadata. Metadata updates made after the child scope is created stay local to the scope where they |
| | | 308 | | /// are made. |
| | | 309 | | /// </para> |
| | | 310 | | /// </remarks> |
| | | 311 | | /// <example> |
| | | 312 | | /// <code> |
| | | 313 | | /// builder.Metadata.Set(new MyFeatureOptions { Enabled = true }); |
| | | 314 | | /// </code> |
| | | 315 | | /// </example> |
| | | 316 | | public BuilderMetadata Metadata { get; } |
| | | 317 | | |
| | | 318 | | /// <summary> |
| | | 319 | | /// Gets the distinct route patterns currently visible from this route scope. |
| | | 320 | | /// </summary> |
| | | 321 | | /// <remarks> |
| | | 322 | | /// Each entry is formatted as <c>[Verb] Pattern</c>. Child scopes list only the routes reachable from |
| | | 323 | | /// their base path, while the root scope lists the whole configured tree. |
| | | 324 | | /// </remarks> |
| | | 325 | | /// <example> |
| | | 326 | | /// <code> |
| | | 327 | | /// foreach (string pattern in builder.Patterns) |
| | | 328 | | /// Console.WriteLine(pattern); |
| | | 329 | | /// </code> |
| | | 330 | | /// </example> |
| | | 331 | | public IEnumerable<string> Patterns |
| | | 332 | | { |
| | | 333 | | get |
| | 1 | 334 | | { |
| | 1 | 335 | | HashSet<string> patterns = []; |
| | | 336 | | |
| | 1 | 337 | | Walk(_root, patterns); |
| | | 338 | | |
| | 1 | 339 | | return patterns.OrderBy(static p => p, StringComparer.Ordinal); |
| | | 340 | | |
| | | 341 | | static void Walk(RouteNode node, HashSet<string> patterns) |
| | | 342 | | { |
| | | 343 | | foreach (KeyValuePair<HttpVerb, HandlerRegistration> handlerEntry in node.Handlers) |
| | | 344 | | patterns.Add($"[{handlerEntry.Key}] {handlerEntry.Value.Pattern}"); |
| | | 345 | | |
| | | 346 | | foreach (RouteNode literalBranch in node.LiteralBranches.Values) |
| | | 347 | | Walk(literalBranch, patterns); |
| | | 348 | | |
| | | 349 | | foreach (KeyValuePair<ParameterParser, RouteNode> parsedBranch in node.ParsedBranches) |
| | | 350 | | Walk(parsedBranch.Value, patterns); |
| | | 351 | | } |
| | 1 | 352 | | } |
| | | 353 | | } |
| | | 354 | | } |
| | | 355 | | } |
| | | 356 | | |