| | | 1 | | /******************************************************************************** |
| | | 2 | | * RouteMatchCursor.cs * |
| | | 3 | | * * |
| | | 4 | | * Author: Denes Solti * |
| | | 5 | | ********************************************************************************/ |
| | | 6 | | using System; |
| | | 7 | | using System.Buffers; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | using System.Diagnostics; |
| | | 10 | | using System.Net; |
| | | 11 | | using System.Net.Http; |
| | | 12 | | using System.Threading; |
| | | 13 | | using System.Threading.Tasks; |
| | | 14 | | |
| | | 15 | | namespace NanoRoute.Internals |
| | | 16 | | { |
| | | 17 | | using Properties; |
| | | 18 | | |
| | | 19 | | internal readonly struct RouteMatch |
| | | 20 | | { |
| | | 21 | | public required HandlerRegistration HandlerRegistration { get; init; } |
| | | 22 | | |
| | | 23 | | public required Dictionary<string, object?> AttachedParameters { get; init; } |
| | | 24 | | } |
| | | 25 | | |
| | 2 | 26 | | internal sealed class RouteMatchCursor(RouteNode node, HttpVerb verb, Uri uri, IServiceProvider services, MatchingPr |
| | | 27 | | { |
| | | 28 | | #region Private |
| | | 29 | | private enum BranchKind |
| | | 30 | | { |
| | | 31 | | Literal, |
| | | 32 | | Parsed |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | private enum MatchPhase |
| | | 36 | | { |
| | | 37 | | /// <summary> |
| | | 38 | | /// Emit all handlers that belong to the current node before descending into child nodes. |
| | | 39 | | /// </summary> |
| | | 40 | | EmitHandlers, |
| | | 41 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Explore the branch category that currently has higher precedence. |
| | | 44 | | /// </summary> |
| | | 45 | | FirstBranch, |
| | | 46 | | |
| | | 47 | | /// <summary> |
| | | 48 | | /// Explore the remaining branch category after the preferred one has been attempted. |
| | | 49 | | /// </summary> |
| | | 50 | | SecondBranch, |
| | | 51 | | |
| | | 52 | | /// <summary> |
| | | 53 | | /// Terminating step |
| | | 54 | | /// </summary> |
| | | 55 | | Done |
| | | 56 | | } |
| | | 57 | | |
| | | 58 | | private readonly record struct BranchOrder(BranchKind First, BranchKind Second); |
| | | 59 | | |
| | 1 | 60 | | private static readonly ArrayPool<char> s_arrayPool = ArrayPool<char>.Create(); |
| | | 61 | | |
| | 2 | 62 | | private readonly BranchOrder _branchOrder = matchingPrecedence switch |
| | 2 | 63 | | { |
| | 2 | 64 | | MatchingPrecedence.LiteralFirst => new BranchOrder(BranchKind.Literal, BranchKind.Parsed), |
| | 2 | 65 | | MatchingPrecedence.ParameterizedFirst => new BranchOrder(BranchKind.Parsed, BranchKind.Literal), |
| | 2 | 66 | | _ => throw new ArgumentOutOfRangeException(nameof(matchingPrecedence)) |
| | 2 | 67 | | }; |
| | | 68 | | |
| | 2 | 69 | | private readonly Dictionary<string, object?> _parameters = new(StringComparer.OrdinalIgnoreCase); |
| | | 70 | | |
| | | 71 | | private char[]? _decodedSegmentBuffer; |
| | | 72 | | |
| | | 73 | | // DelimitedSegment is a mutable struct: keep this field non-readonly so MoveNext() updates the cursor |
| | | 74 | | // itself instead of a defensive copy. |
| | 2 | 75 | | private DelimitedSegment _segment = SplitUri(uri); |
| | | 76 | | |
| | 2 | 77 | | private MatchPhase _phase = MatchPhase.EmitHandlers; |
| | | 78 | | |
| | | 79 | | private ReadOnlyMemory<char> _decodedSegment; |
| | | 80 | | |
| | | 81 | | private IList<HandlerRegistration>? _handlers; |
| | | 82 | | |
| | | 83 | | private int |
| | | 84 | | _handlerIndex, |
| | | 85 | | _nextDecodedSegment; |
| | | 86 | | |
| | | 87 | | private static DelimitedSegment SplitUri(Uri uri) |
| | 2 | 88 | | { |
| | 2 | 89 | | DelimitedSegment result = new |
| | 2 | 90 | | ( |
| | 2 | 91 | | // Escaped path, not percent decoded -> "/path%2Fto%2Fsomewhere/" will be treated as a single segment |
| | 2 | 92 | | uri.AbsolutePath.AsMemory(), |
| | 2 | 93 | | '/' |
| | 2 | 94 | | ); |
| | 2 | 95 | | result.MoveNext(); |
| | 2 | 96 | | return result; |
| | 2 | 97 | | } |
| | | 98 | | |
| | | 99 | | private ReadOnlyMemory<char> GetSegmentForMatching() |
| | 2 | 100 | | { |
| | 2 | 101 | | ReadOnlyMemory<char> current = _segment.Current; |
| | | 102 | | |
| | | 103 | | // This check is fast since span operations are vectorized |
| | 2 | 104 | | if (current.Span.IndexOf('%') < 0) |
| | 2 | 105 | | return current; |
| | | 106 | | |
| | 1 | 107 | | char[] decodedSegmentBuffer = _decodedSegmentBuffer ??= s_arrayPool.Rent(uri.AbsolutePath.Length); |
| | | 108 | | |
| | 1 | 109 | | if (!UrlUtils.TryDecodeUrl(current.Span, decodedSegmentBuffer.AsSpan(_nextDecodedSegment), UrlDecodeMode.Pat |
| | 0 | 110 | | HttpRequestException.Throw(HttpStatusCode.BadRequest, Resources.ERR_BAD_REQUEST, Resources.ERR_DECODING_ |
| | | 111 | | |
| | 1 | 112 | | ReadOnlyMemory<char> decodedSegment = decodedSegmentBuffer.AsMemory(_nextDecodedSegment, charsWritten); |
| | 1 | 113 | | _nextDecodedSegment += charsWritten; |
| | 1 | 114 | | return decodedSegment; |
| | 2 | 115 | | } |
| | | 116 | | |
| | | 117 | | // Keep MoveNextAsync() state-machine-free while branch matching completes synchronously |
| | | 118 | | private async ValueTask<bool> MoveNextAwaitedAsync(ValueTask<bool> branchMatched, MatchPhase successPhase, Match |
| | | 119 | | { |
| | | 120 | | _phase = await branchMatched ? successPhase : failurePhase; |
| | | 121 | | return await MoveNextAsync(); |
| | | 122 | | } |
| | | 123 | | |
| | | 124 | | private void AdvanceToNextSegment(RouteNode nextNode) |
| | 2 | 125 | | { |
| | 2 | 126 | | node = nextNode; |
| | | 127 | | |
| | 2 | 128 | | _handlerIndex = 0; |
| | 2 | 129 | | _handlers = null; |
| | 2 | 130 | | _decodedSegment = default; |
| | | 131 | | |
| | 2 | 132 | | _segment.MoveNext(); |
| | 2 | 133 | | } |
| | | 134 | | |
| | | 135 | | private bool TryEmitHandler() |
| | 2 | 136 | | { |
| | | 137 | | // Retrieve the handler list on the first iteration |
| | 2 | 138 | | if (_handlers is null && !node.HandlerRegistrations.TryGetValue(verb, out _handlers)) |
| | 2 | 139 | | return false; |
| | | 140 | | |
| | 2 | 141 | | while (_handlerIndex < _handlers.Count) |
| | 2 | 142 | | { |
| | 2 | 143 | | HandlerRegistration candidate = _handlers[_handlerIndex++]; |
| | | 144 | | |
| | 2 | 145 | | if (_segment.HasValue && !candidate.IsPrefix) |
| | 1 | 146 | | continue; |
| | | 147 | | |
| | 2 | 148 | | Current = new RouteMatch { HandlerRegistration = candidate, AttachedParameters = _parameters }; |
| | 2 | 149 | | return true; |
| | | 150 | | } |
| | | 151 | | |
| | 1 | 152 | | return false; |
| | 2 | 153 | | } |
| | | 154 | | |
| | 2 | 155 | | private ValueTask<bool> TryBranchAsync(BranchKind branchKind) => branchKind switch |
| | 2 | 156 | | { |
| | 2 | 157 | | BranchKind.Literal => new ValueTask<bool>(TryLiteralBranch()), |
| | 2 | 158 | | BranchKind.Parsed => TryParsedBranchAsync(), |
| | 2 | 159 | | _ => throw new ArgumentOutOfRangeException(nameof(branchKind)) |
| | 2 | 160 | | }; |
| | | 161 | | |
| | | 162 | | private bool TryLiteralBranch() |
| | 2 | 163 | | { |
| | 2 | 164 | | if (!node.LiteralChildren.TryGetValue(_decodedSegment, out RouteNode branchNode)) |
| | 1 | 165 | | return false; |
| | | 166 | | |
| | 2 | 167 | | AdvanceToNextSegment(branchNode); |
| | 2 | 168 | | return true; |
| | 2 | 169 | | } |
| | | 170 | | |
| | | 171 | | private ValueTask<bool> TryParsedBranchAsync(int startIndex = 0) |
| | 1 | 172 | | { |
| | 1 | 173 | | for (int i = startIndex; i < node.ParsedChildren.Count; i++) |
| | 1 | 174 | | { |
| | 1 | 175 | | RouteNode branchNode = node.ParsedChildren[i]; |
| | 1 | 176 | | ParameterParser parser = branchNode.ParameterParser!; |
| | | 177 | | |
| | 1 | 178 | | ValueTask<ValueParseResult> parseResult = parser.Parse |
| | 1 | 179 | | ( |
| | 1 | 180 | | new ValueParserContext |
| | 1 | 181 | | { |
| | 1 | 182 | | Segment = _decodedSegment, |
| | 1 | 183 | | Services = services, |
| | 1 | 184 | | Arguments = parser.Arguments, |
| | 1 | 185 | | Cancellation = cancellation |
| | 1 | 186 | | } |
| | 1 | 187 | | ); |
| | | 188 | | |
| | 1 | 189 | | if (!parseResult.IsCompletedSuccessfully) |
| | 1 | 190 | | return TryParsedBranchAwaitedAsync(parseResult, i, branchNode); |
| | | 191 | | |
| | 1 | 192 | | if (TryAcceptParsedBranch(branchNode, parseResult.Result)) |
| | 1 | 193 | | return new ValueTask<bool>(true); |
| | 1 | 194 | | } |
| | | 195 | | |
| | 1 | 196 | | return new ValueTask<bool>(false); |
| | 1 | 197 | | } |
| | | 198 | | |
| | | 199 | | // Keep TryParsedBranchAsync() state-machine-free while branch matching completes synchronously |
| | | 200 | | private async ValueTask<bool> TryParsedBranchAwaitedAsync(ValueTask<ValueParseResult> parseResult, int branchInd |
| | | 201 | | { |
| | | 202 | | if (TryAcceptParsedBranch(branchNode, await parseResult)) |
| | | 203 | | return true; |
| | | 204 | | |
| | | 205 | | return await TryParsedBranchAsync(branchIndex + 1); |
| | | 206 | | } |
| | | 207 | | |
| | | 208 | | private bool TryAcceptParsedBranch(RouteNode branchNode, ValueParseResult parseResult) |
| | 1 | 209 | | { |
| | 1 | 210 | | if (!parseResult.Success) |
| | 1 | 211 | | return false; |
| | | 212 | | |
| | 1 | 213 | | if (branchNode.ParameterParser!.Definition.ParameterName is { Length: > 0 } parameterName) |
| | 1 | 214 | | _parameters[parameterName] = parseResult.Parsed; |
| | | 215 | | |
| | 1 | 216 | | AdvanceToNextSegment(branchNode); |
| | 1 | 217 | | return true; |
| | 1 | 218 | | } |
| | | 219 | | #endregion |
| | | 220 | | |
| | | 221 | | public RouteMatch Current { get; private set; } |
| | | 222 | | |
| | | 223 | | public ValueTask DisposeAsync() |
| | 2 | 224 | | { |
| | 2 | 225 | | if (_decodedSegmentBuffer is not null) |
| | 1 | 226 | | s_arrayPool.Return(_decodedSegmentBuffer, clearArray: false); |
| | | 227 | | |
| | 2 | 228 | | return default; |
| | 2 | 229 | | } |
| | | 230 | | |
| | | 231 | | public ValueTask<bool> MoveNextAsync() |
| | 2 | 232 | | { |
| | 2 | 233 | | while (_phase is not MatchPhase.Done) |
| | 2 | 234 | | { |
| | 2 | 235 | | cancellation.ThrowIfCancellationRequested(); |
| | | 236 | | |
| | 2 | 237 | | switch (_phase) |
| | | 238 | | { |
| | | 239 | | case MatchPhase.EmitHandlers: |
| | 2 | 240 | | if (TryEmitHandler()) |
| | 2 | 241 | | return new ValueTask<bool>(true); |
| | | 242 | | |
| | | 243 | | // No handler terminated the pipeline, go to the first branch |
| | 2 | 244 | | _phase = MatchPhase.FirstBranch; |
| | 2 | 245 | | break; |
| | | 246 | | |
| | | 247 | | case MatchPhase.FirstBranch: |
| | 2 | 248 | | if (!_segment.HasValue) |
| | 1 | 249 | | { |
| | 1 | 250 | | _phase = MatchPhase.Done; |
| | 1 | 251 | | break; |
| | | 252 | | } |
| | | 253 | | |
| | | 254 | | // Decode only when the matcher is about to inspect the segment. Prefix handlers can still run |
| | | 255 | | // without paying this cost and they can catch invalid escape errors, too. |
| | 2 | 256 | | _decodedSegment = GetSegmentForMatching(); |
| | | 257 | | |
| | 2 | 258 | | ValueTask<bool> firstBranchMatched = TryBranchAsync(_branchOrder.First); |
| | 2 | 259 | | if (!firstBranchMatched.IsCompletedSuccessfully) |
| | 0 | 260 | | return MoveNextAwaitedAsync(firstBranchMatched, MatchPhase.EmitHandlers, MatchPhase.SecondBr |
| | | 261 | | |
| | 2 | 262 | | _phase = firstBranchMatched.Result ? MatchPhase.EmitHandlers : MatchPhase.SecondBranch; |
| | 2 | 263 | | break; |
| | | 264 | | |
| | | 265 | | case MatchPhase.SecondBranch: |
| | 1 | 266 | | Debug.Assert(_segment.HasValue, "Second branch should not be reached when there is no segment to |
| | | 267 | | |
| | 1 | 268 | | ValueTask<bool> secondBranchMatched = TryBranchAsync(_branchOrder.Second); |
| | 1 | 269 | | if (!secondBranchMatched.IsCompletedSuccessfully) |
| | 0 | 270 | | return MoveNextAwaitedAsync(secondBranchMatched, MatchPhase.EmitHandlers, MatchPhase.Done); |
| | | 271 | | |
| | 1 | 272 | | _phase = secondBranchMatched.Result ? MatchPhase.EmitHandlers : MatchPhase.Done; |
| | 1 | 273 | | break; |
| | | 274 | | |
| | | 275 | | default: |
| | 0 | 276 | | Debug.Fail($"Unknown phase: {_phase}"); |
| | 0 | 277 | | break; |
| | | 278 | | } |
| | 2 | 279 | | } |
| | | 280 | | |
| | 1 | 281 | | return new ValueTask<bool>(false); |
| | 2 | 282 | | } |
| | | 283 | | } |
| | | 284 | | } |