< Summary

Information
Class: NanoRoute.Internals.RouteMatchCursor
Assembly: NanoRoute.dll
File(s): /home/runner/work/nanoroute/nanoroute/Src/NanoRoute/Private/RouteMatchCursor.cs
Line coverage
98%
Covered lines: 186
Uncovered lines: 2
Coverable lines: 188
Total lines: 391
Line coverage: 98.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/Private/RouteMatchCursor.cs

#LineLine coverage
 1/********************************************************************************
 2* RouteMatchCursor.cs                                                           *
 3*                                                                               *
 4* Author: Denes Solti                                                           *
 5********************************************************************************/
 6using System;
 7using System.Buffers;
 8using System.Collections.Generic;
 9using System.Diagnostics;
 10using System.Net;
 11using System.Net.Http;
 12using System.Runtime.CompilerServices;
 13using System.Threading;
 14using System.Threading.Tasks;
 15
 16namespace NanoRoute.Internals
 17{
 18    using Properties;
 19
 20    internal sealed class RouteMatchCursor : IDisposable
 21    {
 22        #region Private
 23        private enum BranchKind : byte
 24        {
 25            Literal,
 26            Parsed
 27        }
 28
 29        private enum MatchPhase : byte
 30        {
 31            /// <summary>
 32            /// Emit all handlers that belong to the current node before descending into child nodes.
 33            /// </summary>
 34            EmitHandlers,
 35
 36            /// <summary>
 37            /// Explore child branches according to the configured precedence.
 38            /// </summary>
 39            Branch,
 40
 41            /// <summary>
 42            /// Terminating step
 43            /// </summary>
 44            Done
 45        }
 46
 47        private readonly record struct BranchOrder(BranchKind First, BranchKind Second)
 48        {
 249            public static BranchOrder From(MatchingPrecedence matchingPrecedence) => matchingPrecedence switch
 250            {
 251                MatchingPrecedence.LiteralFirst => new BranchOrder(BranchKind.Literal, BranchKind.Parsed),
 252                MatchingPrecedence.ParameterizedFirst => new BranchOrder(BranchKind.Parsed, BranchKind.Literal),
 253                _ => throw new ArgumentOutOfRangeException(nameof(matchingPrecedence))  // dead code (valid values enfor
 254            };
 55        }
 56
 257        private static readonly ArrayPool<char> s_arrayPool = ArrayPool<char>.Create();
 58
 259        private static readonly ValueTask<bool>
 260            s_true = new(true),
 261            s_false = new(false);
 62
 63        private readonly BranchOrder _branchOrder;
 64
 65        private readonly RouteNode _root;
 66
 67        private char[]? _decodedSegmentBuffer;
 68
 69        // Keep DelimitedSegment instead of Uri.Segments: UrlSegmentBenchmarks shows it avoids eager segment
 70        // array/string allocation and preserves this cursor's lazy traversal model.
 71        private DelimitedSegment _segment;
 72
 73        private MatchPhase _phase;
 74
 75        private int
 76            _handlerIndex,
 77            _nextDecodedSegment;
 78
 79        private RouteNode _node;
 80
 81        #region Async helpers
 82        // Keep MoveNextAsync() state-machine-free while branch matching completes synchronously
 83        private async ValueTask<bool> MoveNextAwaitedAsync(ValueTask<bool> branchMatched)
 84        {
 85            if (!await branchMatched.ConfigureAwait(false))
 86            {
 87                _phase = MatchPhase.Done;
 88                return false;
 89            }
 90
 91            _phase = GetPhaseForCurrentNode();
 92            return await MoveNextAsync().ConfigureAwait(false);
 93        }
 94
 95        private async ValueTask<bool> TryBranchPairAwaitedAsync(ValueTask<bool> firstBranchMatched, ReadOnlyMemory<char>
 96            await firstBranchMatched.ConfigureAwait(false) ||
 97            await TryBranchAsync(_branchOrder.Second, decodedSegment).ConfigureAwait(false);
 98
 99        private async ValueTask<bool> TryParsedBranchAwaitedAsync(KeyValuePair<ParameterParser, RouteNode> parsedBranch,
 100            TryParsedBranchThenAdvance(parsedBranch, await parseResult.ConfigureAwait(false)) ||
 101            await TryParsedBranchAsync(decodedSegment, branchIndex + 1).ConfigureAwait(false);
 102
 103        private async ValueTask<bool> TryAcceptParsedBranchAwaitedAsync(KeyValuePair<ParameterParser, RouteNode> parsedB
 104            TryParsedBranchThenAdvance(parsedBranch, await parseResult.ConfigureAwait(false)) &&
 105            await TrySingleBranchesAsync();
 106        #endregion
 107
 108        private ReadOnlyMemory<char> DecodeIfNeeded(ReadOnlyMemory<char> segment)
 2109        {
 110            // This check is fast since span operations are vectorized
 2111            if (segment.Span.IndexOf('%') < 0)
 2112                return segment;
 113
 1114            char[] decodedSegmentBuffer = _decodedSegmentBuffer ??= s_arrayPool.Rent(_segment.Remaining.Length);
 115
 1116            if (!UrlUtils.TryDecodeUrl(segment.Span, decodedSegmentBuffer.AsSpan(_nextDecodedSegment), UrlDecodeMode.Pat
 1117                HttpRequestException.Throw(HttpStatusCode.BadRequest, Resources.ERR_BAD_REQUEST, Resources.ERR_DECODING_
 118
 1119            ReadOnlyMemory<char> decodedSegment = decodedSegmentBuffer.AsMemory(_nextDecodedSegment, charsWritten);
 1120            _nextDecodedSegment += charsWritten;
 1121            return decodedSegment;
 2122        }
 123
 124        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 125        private void AdvanceToNextSegment(RouteNode nextNode)
 2126        {
 2127            Cancellation.ThrowIfCancellationRequested();
 128
 2129            _node = nextNode;
 2130            _handlerIndex = 0;
 131
 2132            _segment.MoveNext();
 2133        }
 134
 135        internal bool TryEmitHandler()
 2136        {
 2137            while (_handlerIndex < _node.Handlers.Count)
 2138            {
 2139                KeyValuePair<HttpVerb, HandlerRegistration> handler = _node.Handlers[_handlerIndex++];
 140
 2141                if (handler.Key != Verb)
 1142                    continue;
 143
 2144                HandlerRegistration candidate = handler.Value;
 145
 2146                if (_segment.HasValue && !candidate.IsPrefix)
 1147                    continue;
 148
 2149                HandlerRegistration = candidate;
 2150                return true;
 151            }
 152
 1153            return false;
 2154        }
 155
 156        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 2157        private MatchPhase GetPhaseForCurrentNode() => _node.Handlers.Count > 0
 2158            ? MatchPhase.EmitHandlers
 2159            : MatchPhase.Branch;
 160
 161        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1162        private ValueTask<bool> TryBranchAsync(BranchKind branchKind, ReadOnlyMemory<char> decodedSegment) => branchKind
 1163        {
 1164            BranchKind.Literal => new ValueTask<bool>(TryLiteralBranchThenAdvance(decodedSegment)),
 1165            BranchKind.Parsed => TryParsedBranchAsync(decodedSegment, 0),
 1166            _ => throw new ArgumentOutOfRangeException(nameof(branchKind))
 1167        };
 168
 169        internal ValueTask<bool> TrySingleBranchesAsync()
 2170        {
 171            // clean up recent state
 2172            _handlerIndex = 0;
 173
 174            // PERF: do not remove these local variables
 2175            DelimitedSegment segment = _segment;
 2176            RouteNode node = _node;
 177
 2178            for (; segment.HasValue && node.SingleBranch is { } branch; segment.MoveNext())
 2179            {
 2180                ReadOnlyMemory<char> segmentChars = DecodeIfNeeded(segment.Current);
 181
 2182                switch (branch)
 183                {
 184                    case KeyValuePair<ReadOnlyMemory<char>, RouteNode> literalBranch:
 2185                        if (!ReadOnlyMemoryCharComparer.Instance.Equals(literalBranch.Key, segmentChars))
 1186                            return s_false;
 187
 2188                        node = literalBranch.Value;
 2189                        break;
 190
 191                    case KeyValuePair<ParameterParser, RouteNode> parsedBranch:
 1192                        ValueTask<ValueParseResult> parseResultTask = ParseSegment(segmentChars, parsedBranch.Key);
 193
 1194                        if (!parseResultTask.IsCompletedSuccessfully)
 1195                        {
 1196                            _segment = segment;
 1197                            return TryAcceptParsedBranchAwaitedAsync(parsedBranch, parseResultTask);
 198                        }
 199
 1200                        if (!TryParsedBranch(parsedBranch.Key.Definition, parseResultTask.Result))
 1201                            return s_false;
 202
 1203                        node = parsedBranch.Value;
 1204                        break;
 205
 206                    default:
 0207                        Debug.Fail($"Unknown single branch type: {branch.GetType().Name}");
 0208                        return s_false;
 209                }
 2210            }
 211
 2212            _segment = segment;
 2213            _node = node;
 214
 2215            return s_true;
 2216        }
 217
 218        private ValueTask<bool> TryBranchPairAsync()
 1219        {
 220            // Decode only when the matcher is about to inspect the segment. Prefix handlers can still run
 221            // without paying this cost and they can catch invalid escape errors, too.
 1222            ReadOnlyMemory<char> segment = DecodeIfNeeded(_segment.Current);
 223
 1224            ValueTask<bool> firstBranchMatched = TryBranchAsync(_branchOrder.First, segment);
 225
 1226            if (!firstBranchMatched.IsCompletedSuccessfully)
 1227                return TryBranchPairAwaitedAsync(firstBranchMatched, segment);
 228
 1229            if (firstBranchMatched.Result)
 1230                return s_true;
 231
 1232            return TryBranchAsync(_branchOrder.Second, segment);
 1233        }
 234
 235        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 1236        private ValueTask<ValueParseResult> ParseSegment(ReadOnlyMemory<char> decodedSegment, ParameterParser parser) =>
 1237        (
 1238            new ValueParserContext
 1239            {
 1240                Segment = decodedSegment,
 1241                Services = Services,
 1242                Arguments = parser.Arguments,
 1243                Cancellation = Cancellation
 1244            }
 1245        );
 246
 247        private ValueTask<bool> TryParsedBranchAsync(ReadOnlyMemory<char> decodedSegment, int startIndex)
 1248        {
 1249            IList<KeyValuePair<ParameterParser, RouteNode>> parsedBranches = _node.ParsedBranches;
 250
 1251            for (int i = startIndex; i < parsedBranches.Count; i++)
 1252            {
 1253                KeyValuePair<ParameterParser, RouteNode> parsedBranch = parsedBranches[i];
 254
 1255                ValueTask<ValueParseResult> parseResult = ParseSegment(decodedSegment, parsedBranch.Key);
 256
 1257                if (!parseResult.IsCompletedSuccessfully)
 1258                    return TryParsedBranchAwaitedAsync(parsedBranch, parseResult, decodedSegment, i);
 259
 1260                if (TryParsedBranchThenAdvance(parsedBranch, parseResult.Result))
 1261                    return s_true;
 1262            }
 263
 1264            return s_false;
 1265        }
 266
 267        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 268        private bool TryParsedBranch(ParameterDefinition parameter, ValueParseResult parseResult)
 1269        {
 1270            if (!parseResult.Success)
 1271                return false;
 272
 1273            if (parameter.ParameterName is { Length: > 0 } parameterName)
 274                // This will overwrite any existing parameter on the given key
 1275                Parameters[parameterName] = parseResult.Parsed;
 276
 1277            return true;
 1278        }
 279
 280        private bool TryLiteralBranchThenAdvance(ReadOnlyMemory<char> decodedSegment)
 1281        {
 1282            if (!_node.LiteralBranches.TryGetValue(decodedSegment, out RouteNode literalBranch))
 1283                return false;
 284
 1285            AdvanceToNextSegment(literalBranch);
 1286            return true;
 1287        }
 288
 289        private bool TryParsedBranchThenAdvance(KeyValuePair<ParameterParser, RouteNode> parsedBranch, ValueParseResult 
 1290        {
 1291            if (!TryParsedBranch(parsedBranch.Key.Definition, parseResult))
 1292                return false;
 293
 1294            AdvanceToNextSegment(parsedBranch.Value);
 1295            return true;
 1296        }
 297        #endregion
 298
 2299        public RouteMatchCursor(RouteNode node, HttpVerb verb, Uri uri, IServiceProvider services, IDictionary<string, o
 2300        {
 2301            _segment = new DelimitedSegment
 2302            (
 2303                // Escaped path, not percent decoded -> "/path%2Fto%2Fsomewhere/" will be treated as a single segment
 2304                uri.AbsolutePath.AsMemory(),
 2305                '/'
 2306            );
 2307            _branchOrder = BranchOrder.From(matchingPrecedence);
 2308            _root = _node = node;
 309
 2310            Cancellation = cancellation;
 2311            Parameters = parameters;
 2312            Services = services;
 2313            Verb = verb;
 314
 2315            AdvanceToNextSegment(_root);
 2316            _phase = GetPhaseForCurrentNode();
 2317        }
 318
 2319        public HandlerRegistration HandlerRegistration { get; private set; } = null!;
 320
 2321        public ReadOnlyMemory<char> RemainingPath => _segment.Remaining;
 322
 323        public CancellationToken Cancellation { get; }
 324
 325        public IServiceProvider Services { get; }
 326
 327        public IDictionary<string, object?> Parameters { get; }
 328
 329        public HttpVerb Verb { get; }
 330
 2331        public bool Completed => _phase is MatchPhase.Done;
 332
 333        public void Dispose()
 2334        {
 2335            if (_decodedSegmentBuffer is not null)
 1336            {
 1337                s_arrayPool.Return(_decodedSegmentBuffer, clearArray: false);
 1338                _decodedSegmentBuffer = null;
 1339            }
 2340        }
 341
 342        public void Reset()
 1343        {
 1344            HandlerRegistration = null!;
 1345            _nextDecodedSegment = 0;
 346
 1347            _segment.Reset();
 1348            AdvanceToNextSegment(_root);
 1349            _phase = GetPhaseForCurrentNode();
 1350        }
 351
 352        public ValueTask<bool> MoveNextAsync()
 2353        {
 2354            while (!Completed)
 2355            {
 2356                if (_phase is MatchPhase.EmitHandlers)
 2357                {
 2358                    if (TryEmitHandler())
 2359                        return s_true;
 360
 361                    // No handler terminated the pipeline, go to the branch matching phase.
 1362                    _phase = MatchPhase.Branch;
 1363                }
 364
 2365                Debug.Assert(_phase is MatchPhase.Branch, $"Unknown phase: {_phase}");
 366
 2367                if (_segment.HasValue)
 2368                {
 2369                    ValueTask<bool> branchMatched = _node.SingleBranch is not null
 2370                        // fast path
 2371                        ? TrySingleBranchesAsync()
 2372                        : TryBranchPairAsync();
 373
 2374                    if (!branchMatched.IsCompletedSuccessfully)
 1375                        return MoveNextAwaitedAsync(branchMatched);
 376
 2377                    if (branchMatched.Result)
 2378                    {
 2379                        _phase = GetPhaseForCurrentNode();
 2380                        continue;
 381                    }
 1382                }
 383
 1384                _phase = MatchPhase.Done;
 1385                break;
 386            }
 387
 1388            return s_false;
 2389        }
 390    }
 391}