| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using System.Collections.Frozen; |
| | 4 | |
|
| | 5 | | namespace IceRpc; |
| | 6 | |
|
| | 7 | | /// <summary>Provides methods for routing incoming requests to dispatchers.</summary> |
| | 8 | | /// <example> |
| | 9 | | /// The following example shows how you would install a middleware, and map a service. |
| | 10 | | /// <code source="../../docfx/examples/IceRpc.Examples/RouterExamples.cs" region="CreatingAndUsingTheRouterWithMiddlewar |
| | 11 | | /// You can easily create your own middleware and add it to the router. The next example shows how you can create a |
| | 12 | | /// middleware using an <see cref="InlineDispatcher"/> and add it to the router with |
| | 13 | | /// <see cref="Use(Func{IDispatcher, IDispatcher})"/>. |
| | 14 | | /// <code source="../../docfx/examples/IceRpc.Examples/RouterExamples.cs" region="CreatingAndUsingTheRouterWithAnInlineD |
| | 15 | | /// </example> |
| | 16 | | /// <remarks><para>The <see cref="Router"/> class allows you to define a dispatch pipeline for customizing how incoming |
| | 17 | | /// requests are processed. You utilize the Router class for creating routes with various middleware, sub-routers, |
| | 18 | | /// and dispatchers.</para> |
| | 19 | | /// <para>Incoming requests flow through the dispatch pipeline. An incoming request is first processed by the router's |
| | 20 | | /// middleware and then routed to a target dispatcher based on its path. The target dispatcher returns an outgoing |
| | 21 | | /// response that goes through the dispatch pipeline in the opposite direction.</para> |
| | 22 | | /// <para>The routing algorithm determines how incoming requests are routed to dispatchers. The router first checks if |
| | 23 | | /// a dispatcher is registered with the request's path, which corresponds to dispatchers registered using |
| | 24 | | /// <see cref="Map(string, IDispatcher)"/>. If there isn't a dispatcher registered for the request's path, the router |
| | 25 | | /// looks for dispatchers registered with a matching prefix, which corresponds to dispatchers installed using |
| | 26 | | /// <see cref="Mount(string, IDispatcher)"/>. When searching for a matching prefix, the router starts with the request |
| | 27 | | /// path and successively tries chopping segments from the end of the path until either the path is exhausted or a |
| | 28 | | /// dispatcher matching the prefix is found. Finally, if the router cannot find any dispatcher, it returns an |
| | 29 | | /// <see cref="OutgoingResponse"/> with a <see cref="StatusCode.NotFound"/> status code.</para></remarks> |
| | 30 | | public sealed class Router : IDispatcher |
| | 31 | | { |
| | 32 | | /// <summary>Gets the absolute path-prefix of this router. The absolute path of a service added to this |
| | 33 | | /// Router is: <c>$"{AbsolutePrefix}{path}"</c> where <c>path</c> corresponds to the argument given to |
| | 34 | | /// <see cref="Map(string, IDispatcher)" />.</summary> |
| | 35 | | /// <value>The absolute prefix of this router. It is either an empty string or a string with two or more |
| | 36 | | /// characters starting with a <c>/</c>.</value> |
| 304 | 37 | | public string AbsolutePrefix { get; } = ""; |
| | 38 | |
|
| | 39 | | // When searching in the prefixMatchRoutes, we search up to MaxSegments before giving up. This prevents a |
| | 40 | | // a malicious client from sending a request with a huge number of segments (/a/a/a/a/a/a/a/a/a/a...) that |
| | 41 | | // results in numerous unsuccessful lookups. |
| | 42 | | private const int MaxSegments = 10; |
| | 43 | |
|
| | 44 | | private readonly Lazy<IDispatcher> _dispatcher; |
| 88 | 45 | | private readonly Dictionary<string, IDispatcher> _exactMatchRoutes = new(); |
| | 46 | |
|
| 88 | 47 | | private readonly Stack<Func<IDispatcher, IDispatcher>> _middlewareStack = new(); |
| | 48 | |
|
| 88 | 49 | | private readonly Dictionary<string, IDispatcher> _prefixMatchRoutes = new(); |
| | 50 | |
|
| | 51 | | /// <summary>Constructs a top-level router.</summary> |
| 176 | 52 | | public Router() => _dispatcher = new Lazy<IDispatcher>(CreateDispatchPipeline); |
| | 53 | |
|
| | 54 | | /// <summary>Constructs a router with an absolute prefix.</summary> |
| | 55 | | /// <param name="absolutePrefix">The absolute prefix of the new router. It must start with a <c>/</c>.</param> |
| | 56 | | /// <exception cref="FormatException">Thrown if <paramref name="absolutePrefix" /> is not a valid path. |
| | 57 | | /// </exception> |
| | 58 | | public Router(string absolutePrefix) |
| 32 | 59 | | : this() |
| 32 | 60 | | { |
| 32 | 61 | | ServiceAddress.CheckPath(absolutePrefix); |
| 30 | 62 | | absolutePrefix = NormalizePrefix(absolutePrefix); |
| 30 | 63 | | AbsolutePrefix = absolutePrefix.Length > 1 ? absolutePrefix : ""; |
| 30 | 64 | | } |
| | 65 | |
|
| | 66 | | /// <inheritdoc/> |
| | 67 | | public ValueTask<OutgoingResponse> DispatchAsync( |
| | 68 | | IncomingRequest request, |
| | 69 | | CancellationToken cancellationToken = default) => |
| 144 | 70 | | _dispatcher.Value.DispatchAsync(request, cancellationToken); |
| | 71 | |
|
| | 72 | | /// <summary>Registers a route with a path. If there is an existing route at the same path, it is replaced. |
| | 73 | | /// </summary> |
| | 74 | | /// <param name="path">The path of this route. It must match exactly the path of the request. In particular, it |
| | 75 | | /// must start with a <c>/</c>.</param> |
| | 76 | | /// <param name="dispatcher">The target of this route. It is typically a service.</param> |
| | 77 | | /// <returns>This router.</returns> |
| | 78 | | /// <exception cref="FormatException">Thrown if <paramref name="path" /> is not a valid path.</exception> |
| | 79 | | /// <exception cref="InvalidOperationException">Thrown if <see cref="IDispatcher.DispatchAsync" /> was already |
| | 80 | | /// called on this router.</exception> |
| | 81 | | /// <seealso cref="Mount" /> |
| | 82 | | public Router Map(string path, IDispatcher dispatcher) |
| 35 | 83 | | { |
| 35 | 84 | | if (_dispatcher.IsValueCreated) |
| 2 | 85 | | { |
| 2 | 86 | | throw new InvalidOperationException( |
| 2 | 87 | | $"Cannot call {nameof(Map)} after calling {nameof(IDispatcher.DispatchAsync)}."); |
| | 88 | | } |
| 33 | 89 | | ServiceAddress.CheckPath(path); |
| 33 | 90 | | _exactMatchRoutes[path] = dispatcher; |
| 33 | 91 | | return this; |
| 33 | 92 | | } |
| | 93 | |
|
| | 94 | | /// <summary>Registers a route with a prefix. If there is an existing route at the same prefix, it is replaced. |
| | 95 | | /// </summary> |
| | 96 | | /// <param name="prefix">The prefix of this route. This prefix will be compared with the start of the path of |
| | 97 | | /// the request.</param> |
| | 98 | | /// <param name="dispatcher">The target of this route.</param> |
| | 99 | | /// <returns>This router.</returns> |
| | 100 | | /// <exception cref="FormatException">Thrown if <paramref name="prefix" /> is not a valid path.</exception> |
| | 101 | | /// <exception cref="InvalidOperationException">Thrown if <see cref="IDispatcher.DispatchAsync" /> was already |
| | 102 | | /// called on this router.</exception> |
| | 103 | | /// <seealso cref="Map(string, IDispatcher)" /> |
| | 104 | | public Router Mount(string prefix, IDispatcher dispatcher) |
| 47 | 105 | | { |
| 47 | 106 | | if (_dispatcher.IsValueCreated) |
| 2 | 107 | | { |
| 2 | 108 | | throw new InvalidOperationException( |
| 2 | 109 | | $"Cannot call {nameof(Mount)} after calling {nameof(IDispatcher.DispatchAsync)}."); |
| | 110 | | } |
| 45 | 111 | | ServiceAddress.CheckPath(prefix); |
| 41 | 112 | | prefix = NormalizePrefix(prefix); |
| 41 | 113 | | _prefixMatchRoutes[prefix] = dispatcher; |
| 41 | 114 | | return this; |
| 41 | 115 | | } |
| | 116 | |
|
| | 117 | | /// <summary>Installs a middleware in this router. A middleware must be installed before calling |
| | 118 | | /// <see cref="IDispatcher.DispatchAsync" />.</summary> |
| | 119 | | /// <param name="middleware">The middleware to install.</param> |
| | 120 | | /// <returns>This router.</returns> |
| | 121 | | /// <exception cref="InvalidOperationException">Thrown if <see cref="IDispatcher.DispatchAsync" /> was already |
| | 122 | | /// called on this router.</exception> |
| | 123 | | public Router Use(Func<IDispatcher, IDispatcher> middleware) |
| 54 | 124 | | { |
| 54 | 125 | | if (_dispatcher.IsValueCreated) |
| 2 | 126 | | { |
| 2 | 127 | | throw new InvalidOperationException( |
| 2 | 128 | | $"All middleware must be registered before calling {nameof(IDispatcher.DispatchAsync)}."); |
| | 129 | | } |
| 52 | 130 | | _middlewareStack.Push(middleware); |
| 52 | 131 | | return this; |
| 52 | 132 | | } |
| | 133 | |
|
| | 134 | | /// <summary>Returns a string that represents this router.</summary> |
| | 135 | | /// <returns>A string that represents this router.</returns> |
| 0 | 136 | | public override string ToString() => AbsolutePrefix.Length > 0 ? $"router({AbsolutePrefix})" : "router"; |
| | 137 | |
|
| | 138 | | // Trim trailing slashes but keep the leading slash. |
| | 139 | | private static string NormalizePrefix(string prefix) |
| 134 | 140 | | { |
| 134 | 141 | | if (prefix.Length > 1) |
| 115 | 142 | | { |
| 115 | 143 | | prefix = prefix.TrimEnd('/'); |
| 115 | 144 | | if (prefix.Length == 0) |
| 4 | 145 | | { |
| 4 | 146 | | prefix = "/"; |
| 4 | 147 | | } |
| 115 | 148 | | } |
| 134 | 149 | | return prefix; |
| 134 | 150 | | } |
| | 151 | |
|
| | 152 | | private IDispatcher CreateDispatchPipeline() |
| 68 | 153 | | { |
| 68 | 154 | | var exactMatchRoutes = _exactMatchRoutes.ToFrozenDictionary(); |
| 68 | 155 | | var prefixMatchRoutes = _prefixMatchRoutes.ToFrozenDictionary(); |
| | 156 | |
|
| | 157 | | // The last dispatcher of the pipeline: |
| 68 | 158 | | IDispatcher dispatchPipeline = new InlineDispatcher( |
| 68 | 159 | | (request, cancellationToken) => |
| 142 | 160 | | { |
| 142 | 161 | | string path = request.Path; |
| 68 | 162 | |
|
| 142 | 163 | | if (AbsolutePrefix.Length > 0) |
| 16 | 164 | | { |
| 68 | 165 | | // Remove AbsolutePrefix from path. AbsolutePrefix starts with a '/' but usually does not end with |
| 68 | 166 | | // one. |
| 16 | 167 | | path = path.StartsWith(AbsolutePrefix, StringComparison.Ordinal) ? |
| 16 | 168 | | (path.Length == AbsolutePrefix.Length ? "/" : path[AbsolutePrefix.Length..]) : |
| 16 | 169 | | throw new InvalidOperationException( |
| 16 | 170 | | $"Received request for path '{path}' in router mounted at '{AbsolutePrefix}'."); |
| 16 | 171 | | } |
| 68 | 172 | | // else there is nothing to remove |
| 68 | 173 | |
|
| 68 | 174 | | // First check for an exact match |
| 142 | 175 | | if (exactMatchRoutes.TryGetValue(path, out IDispatcher? dispatcher)) |
| 109 | 176 | | { |
| 109 | 177 | | return dispatcher.DispatchAsync(request, cancellationToken); |
| 68 | 178 | | } |
| 68 | 179 | | else |
| 33 | 180 | | { |
| 68 | 181 | | // Then a prefix match |
| 33 | 182 | | string prefix = NormalizePrefix(path); |
| 68 | 183 | |
|
| 194 | 184 | | foreach (int _ in Enumerable.Range(0, MaxSegments)) |
| 64 | 185 | | { |
| 64 | 186 | | if (prefixMatchRoutes.TryGetValue(prefix, out dispatcher)) |
| 31 | 187 | | { |
| 31 | 188 | | return dispatcher.DispatchAsync(request, cancellationToken); |
| 68 | 189 | | } |
| 68 | 190 | |
|
| 33 | 191 | | if (prefix == "/") |
| 2 | 192 | | { |
| 2 | 193 | | return new(new OutgoingResponse(request, StatusCode.NotFound)); |
| 68 | 194 | | } |
| 68 | 195 | |
|
| 68 | 196 | | // Cut last segment |
| 31 | 197 | | int lastSlashPos = prefix.LastIndexOf('/'); |
| 31 | 198 | | prefix = lastSlashPos > 0 ? NormalizePrefix(prefix[..lastSlashPos]) : "/"; |
| 68 | 199 | | // and try again with the new shorter prefix |
| 31 | 200 | | } |
| 0 | 201 | | return new(new OutgoingResponse(request, StatusCode.InvalidData, "Too many segments in path.")); |
| 68 | 202 | | } |
| 210 | 203 | | }); |
| | 204 | |
|
| 308 | 205 | | foreach (Func<IDispatcher, IDispatcher> middleware in _middlewareStack) |
| 52 | 206 | | { |
| 52 | 207 | | dispatchPipeline = middleware(dispatchPipeline); |
| 52 | 208 | | } |
| 68 | 209 | | _middlewareStack.Clear(); // we no longer need these functions |
| 68 | 210 | | return dispatchPipeline; |
| 68 | 211 | | } |
| | 212 | | } |