< Summary

Information
Class: NanoRoute.RouteScopeBuilder
Assembly: NanoRoute.dll
File(s): /home/runner/work/nanoroute/nanoroute/Src/NanoRoute/Public/RouteScopeBuilder.cs
Line coverage
97%
Covered lines: 95
Uncovered lines: 2
Coverable lines: 97
Total lines: 334
Line coverage: 97.9%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

File(s)

/home/runner/work/nanoroute/nanoroute/Src/NanoRoute/Public/RouteScopeBuilder.cs

#LineLine coverage
 1/********************************************************************************
 2* RouteScopeBuilder.cs                                                          *
 3*                                                                               *
 4* Author: Denes Solti                                                           *
 5********************************************************************************/
 6using System;
 7using System.Collections.Generic;
 8using System.Diagnostics;
 9using System.Linq;
 10
 11namespace 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, _) =&gt; 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, _) =&gt; 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) =&gt; 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)
 263        {
 264            RouteNode target = _root;
 65
 266            foreach (object parsedPattern in DslParser.ParseRoutePattern(pattern))
 267            {
 68                switch (parsedPattern)
 69                {
 70                    case ParameterDefinition parameterDefinition:
 171                        if (!_valueParsers.TryGetValue(parameterDefinition.ValueParser.Name, out ValueParserRegistration
 172                            throw new InvalidOperationException
 173                            (
 174                                string.Format(Resources.Culture, Resources.ERR_NO_SUCH_PARSER, parameterDefinition.Value
 175                            );
 76
 177                        KeyValuePair<ParameterParser, RouteNode> parsedBranch = target
 178                            .ParsedBranches
 179                            .SingleOrDefault(c => c.Key.Definition.ValueParser.Equals(parameterDefinition.ValueParser));
 80
 181                        if (parsedBranch.Equals(default(KeyValuePair<ParameterParser, RouteNode>)))
 182                        {
 183                            parsedBranch = new KeyValuePair<ParameterParser, RouteNode>
 184                            (
 185                                new ParameterParser
 186                                (
 187                                    parameterDefinition,
 188                                    parserRegistration.Parse,
 189                                    parserRegistration.BindArguments(parameterDefinition.ValueParser.RawArguments)
 190                                ),
 191                                new RouteNode()
 192                            );
 93
 194                            target.ParsedBranches.Add(parsedBranch);
 195                        }
 196                        else if (!StringComparer.OrdinalIgnoreCase.Equals(parsedBranch.Key.Definition.ParameterName, par
 197                            throw new InvalidOperationException(Resources.ERR_PARAMETER_OVERRIDE);
 98
 199                        target = parsedBranch.Value;
 1100                        break;
 101
 102                    case ReadOnlyMemory<char> literalSegmentDefinition:
 2103                        if (!target.LiteralBranches.TryGetValue(literalSegmentDefinition, out RouteNode exactChild))
 2104                        {
 2105                            exactChild = new RouteNode();
 2106                            target.LiteralBranches.Add(literalSegmentDefinition, exactChild);
 2107                        }
 108
 2109                        target = exactChild;
 2110                        break;
 111
 112                    default:
 0113                        Debug.Fail("Unknown definition");
 0114                        break;
 115                }
 2116            }
 117
 2118            return target;
 2119        }
 120
 121        private static string JoinPattern(string @base, string extensions)
 2122        {
 2123            Debug.Assert(@base.EndsWith(CurrentPrefix), "Base patterns must be prefix routes");
 124
 2125            return @base.TrimEnd('*') + extensions.TrimStart('/');
 2126        }
 127
 1128        private RouteScopeBuilder(RouteScopeBuilder parent, string pattern)
 1129        {
 1130            _root = parent.GetOrCreateNode(pattern);
 1131            _valueParsers = new Dictionary<string, ValueParserRegistration>(parent._valueParsers, StringComparer.Ordinal
 132
 1133            BasePattern = JoinPattern(parent.BasePattern, pattern);
 1134        }
 135
 2136        internal RouteScopeBuilder()
 2137        {
 2138            _root = new RouteNode();
 2139            _valueParsers = new Dictionary<string, ValueParserRegistration>(StringComparer.OrdinalIgnoreCase);
 140
 2141            BasePattern = CurrentPrefix;
 2142        }
 143
 144        /// <summary>
 145        /// Creates an immutable snapshot of the current route tree.
 146        /// </summary>
 147        /// <returns>A frozen snapshot of the configured root node.</returns>
 2148        internal RouteNode CreateSnapshot() => _root.Freeze();
 149        #endregion
 150
 151        /// <summary>
 152        /// Registers a parser that can convert a route segment into a typed value and bind parser arguments once during
 153        /// </summary>
 154        /// <param name="parserName">The name used in route patterns such as <c>{id:int(min=1)}</c>.</param>
 155        /// <param name="bindArguments">Converts raw parser arguments into typed values once per route-template branch.<
 156        /// <param name="tryParseDelegate">The delegate that validates and parses a single path segment.</param>
 157        /// <returns>The current instance.</returns>
 158        /// <exception cref="ArgumentNullException">
 159        /// Thrown when <paramref name="parserName"/>, <paramref name="bindArguments"/>, or
 160        /// <paramref name="tryParseDelegate"/> is <see langword="null"/>.
 161        /// </exception>
 162        /// <example>
 163        /// <code>
 164        /// builder.AddValueParser("slug", static rawArgs =&gt; null, static context =&gt;
 165        ///     ValueTask.FromResult(new ValueParseResult(context.Segment.Length &gt; 0, context.Segment.ToString())));
 166        /// </code>
 167        /// </example>
 168        public RouteScopeBuilder AddValueParser(string parserName, BindArgumentsDelegate bindArguments, ValueParserDeleg
 1169        {
 1170            Ensure.NotNull(parserName);
 1171            Ensure.NotNull(bindArguments);
 1172            Ensure.NotNull(tryParseDelegate);
 173
 1174            _valueParsers[parserName] = new ValueParserRegistration(parserName, tryParseDelegate, bindArguments);
 175
 1176            return this;
 1177        }
 178
 179        /// <summary>
 180        /// Registers a handler for a single HTTP method.
 181        /// </summary>
 182        /// <param name="verb">The HTTP method that activates the handler.</param>
 183        /// <param name="pattern">
 184        /// The route pattern to match. Literal segments are matched case-insensitively, parameter segments use
 185        /// registered parsers in the form <c>{parameterName:parserName}</c>. Exact patterns must end with
 186        /// <c>/</c>, prefix patterns must end with <c>/*</c>, and repeated <c>/</c> separators are invalid.
 187        /// </param>
 188        /// <param name="handler">
 189        /// The handler to execute. If several handlers match, calling the supplied <c>next</c> delegate continues
 190        /// the pipeline with the next compatible handler from the already selected route branch.
 191        /// </param>
 192        /// <returns>The current route scope builder instance.</returns>
 193        /// <exception cref="ArgumentNullException">
 194        /// Thrown when <paramref name="verb"/>, <paramref name="pattern"/>, or <paramref name="handler"/> is
 195        /// <see langword="null"/>.
 196        /// </exception>
 197        /// <exception cref="ArgumentException">Thrown when <paramref name="verb"/> is not a supported HTTP method.</exc
 198        /// <exception cref="InvalidOperationException">
 199        /// Thrown when <paramref name="pattern"/> uses an unsupported optional parameter or list parser, references
 200        /// a value parser that has not been registered yet, or reuses a parser-backed branch with a different
 201        /// parameter name.
 202        /// </exception>
 203        /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template syntax
 204        /// <example>
 205        /// <code>
 206        /// builder.AddHandler("GET", "/files/{path:any}/*", (context, next) =&gt;
 207        /// {
 208        ///     string path = (string) context.Parameters["path"]!;
 209        ///     return ServeFile(path);
 210        /// });
 211        /// </code>
 212        /// </example>
 213        public RouteScopeBuilder AddHandler(string verb, string pattern, RequestHandlerDelegate handler)
 2214        {
 2215            Ensure.NotNull(verb);
 2216            Ensure.NotNull(pattern);
 2217            Ensure.NotNull(handler);
 218
 2219            if (!HttpVerb.TryParseFast(verb, out HttpVerb v))
 1220                throw new ArgumentException
 1221                (
 1222                    string.Format(Resources.Culture, Resources.ERR_INVALID_VERB, verb), nameof(verb)
 1223                );
 224
 2225            GetOrCreateNode(pattern).Handlers.Add
 2226            (
 2227                new KeyValuePair<HttpVerb, HandlerRegistration>
 2228                (
 2229                    v,
 2230                    new HandlerRegistration(handler, JoinPattern(BasePattern, pattern))
 2231                )
 2232            );
 233
 2234            return this;
 2235        }
 236
 237        /// <summary>
 238        /// Creates a child route scope whose routes are rooted under the given prefix.
 239        /// </summary>
 240        /// <param name="pattern">
 241        /// The base prefix. It must be a valid route pattern ending in <c>/*</c> so child routes can be appended to it.
 242        /// </param>
 243        /// <returns>A child route scope builder that shares the current route tree but has its own parser registration 
 244        /// <remarks>
 245        /// Child route scopes inherit the parent's registered value parsers at creation time. Additional parser
 246        /// registrations or overrides made on the child scope stay local to that branch.
 247        /// </remarks>
 248        /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> does not end with <c>/*</c>.</exc
 249        /// <exception cref="ArgumentNullException">Thrown when <paramref name="pattern"/> is <see langword="null"/>.</e
 250        /// <exception cref="InvalidOperationException">
 251        /// Thrown when <paramref name="pattern"/> uses an unsupported optional parameter or list parser, references
 252        /// a value parser that has not been registered yet, or reuses a parser-backed branch with a different
 253        /// parameter name.
 254        /// </exception>
 255        /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template syntax
 256        /// <example>
 257        /// <code>
 258        /// RouteScopeBuilder api = builder.CreatePrefix("/api/*");
 259        ///
 260        /// api.AddHandler("GET", "/health/", (context, _) =&gt; Results.Ok());
 261        /// </code>
 262        /// </example>
 263        public RouteScopeBuilder CreatePrefix(string pattern)
 1264        {
 1265            Ensure.NotNull(pattern);
 266
 1267            if (!pattern.EndsWith(CurrentPrefix))
 1268                throw new ArgumentException(Resources.ERR_NOT_PREFIX, nameof(pattern));
 269
 1270            return new RouteScopeBuilder(this, pattern);
 1271        }
 272
 273        /// <summary>
 274        /// Gets the value parser registrations currently visible from this route scope.
 275        /// </summary>
 276        /// <remarks>
 277        /// For child scopes created with <see cref="CreatePrefix(string)"/>, this dictionary reflects the inherited
 278        /// registrations plus any overrides added to that child scope.
 279        /// </remarks>
 280        /// <example>
 281        /// <code>
 282        /// bool hasIntParser = builder.ValueParsers.ContainsKey("int");
 283        /// </code>
 284        /// </example>
 1285        public IReadOnlyDictionary<string, ValueParserRegistration> ValueParsers => _valueParsers;
 286
 287        /// <summary>
 288        /// Gets the route pattern prefix for this route scope.
 289        /// </summary>
 290        /// <remarks>
 291        /// The root scope exposes <see cref="CurrentPrefix"/>. Child scopes created with
 292        /// <see cref="CreatePrefix(string)"/> expose the accumulated prefix inherited from their parent scopes.
 293        /// </remarks>
 294        public string BasePattern { get; }
 295
 296        /// <summary>
 297        /// Gets the distinct route patterns currently visible from this route scope.
 298        /// </summary>
 299        /// <remarks>
 300        /// Each entry is formatted as <c>[Verb] Pattern</c>. Child scopes list only the routes reachable from
 301        /// their base path, while the root scope lists the whole configured tree.
 302        /// </remarks>
 303        /// <example>
 304        /// <code>
 305        /// foreach (string pattern in builder.Patterns)
 306        ///     Console.WriteLine(pattern);
 307        /// </code>
 308        /// </example>
 309        public IEnumerable<string> Patterns
 310        {
 311            get
 1312            {
 1313                HashSet<string> patterns = [];
 314
 1315                Walk(_root, patterns);
 316
 1317                return patterns.OrderBy(static p => p, StringComparer.Ordinal);
 318
 319                static void Walk(RouteNode node, HashSet<string> patterns)
 320                {
 321                    foreach (KeyValuePair<HttpVerb, HandlerRegistration> handlerEntry in node.Handlers)
 322                        patterns.Add($"[{handlerEntry.Key}] {handlerEntry.Value.Pattern}");
 323
 324                    foreach (RouteNode literalBranch in node.LiteralBranches.Values)
 325                        Walk(literalBranch, patterns);
 326
 327                    foreach (KeyValuePair<ParameterParser, RouteNode> parsedBranch in node.ParsedBranches)
 328                        Walk(parsedBranch.Value, patterns);
 329                }
 1330            }
 331        }
 332    }
 333}
 334