-
Notifications
You must be signed in to change notification settings - Fork 19
/
MqttRouteTableFactory.cs
320 lines (269 loc) · 13.4 KB
/
MqttRouteTableFactory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Copyright (c) .NET Foundation. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt
// in the project root for license information.
// Modifications Copyright (c) Atlas Lift Tech Inc. All rights reserved.
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace MQTTnet.AspNetCore.AttributeRouting
{
internal static class MqttRouteTableFactory
{
private static readonly ConcurrentDictionary<Key, MqttRouteTable> Cache = new ConcurrentDictionary<Key, MqttRouteTable>();
public static readonly IComparer<MqttRoute> RoutePrecedence = Comparer<MqttRoute>.Create(RouteComparison);
/// <summary>
/// Given a list of assemblies, find all instances of MqttControllers and wire up routing for them. Instances of
/// controllers must inherit from MqttBaseController and be decorated with an MqttRoute attribute.
/// </summary>
/// <param name="assembly">Assemblies to scan for routes</param>
/// <returns></returns>
internal static MqttRouteTable Create(IEnumerable<Assembly> assemblies)
{
var key = new Key(assemblies.OrderBy(a => a.FullName).ToArray());
if (Cache.TryGetValue(key, out var resolvedComponents))
{
return resolvedComponents;
}
var asm = assemblies ?? new Assembly[] { Assembly.GetExecutingAssembly() };
var actions = asm.SelectMany(a => a.GetTypes())
.Where(type => type.GetCustomAttribute(typeof(MqttControllerAttribute), true) != null)
.SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
.Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute), true).Any() && !m.IsDefined(typeof(NonActionAttribute)));
var routeTable = Create(actions);
Cache.TryAdd(key, routeTable);
return routeTable;
}
internal static MqttRouteTable Create(IEnumerable<MethodInfo> actions)
{
// A future perf improvement would be to use a stringbuilder to avoid multiple string allocations
var templatesByHandler = new Dictionary<MethodInfo, string[]>();
foreach (var action in actions)
{
// We're deliberately using inherit = false here. // MqttRouteAttribute is defined as non-inherited,
// because inheriting a route attribute always causes an ambiguity. You end up with two components (base
// class and derived class) with the same route.
var controllerTemplates = action.DeclaringType.GetCustomAttributes<MqttRouteAttribute>(inherit: false)
.Select(c => ReplaceTokens(c.Template, action.DeclaringType.Name, action.Name) + "/")
.ToArray();
var routeAttributes = action.GetCustomAttributes<MqttRouteAttribute>(inherit: false)
.Select(a => ReplaceTokens(a.Template, action.DeclaringType.Name, action.Name))
.ToArray();
if (controllerTemplates.Length == 0)
{
controllerTemplates = new string[] { "" };
}
// If an action doesn't have a route attribute on it, we use the action name. Unlike Mvc/WebAPI we don't
// need to strip the "Get", "Put", etc. prefixes from the action because MQTT doesn't have verbs by convention.
if (routeAttributes.Length == 0)
{
routeAttributes = new string[] { action.Name };
}
// If an action starts with a /, we throw away the inherited portion of the path. We don't process ~/
// because it wouldn't make sense in the context of Mqtt routing which has no concept of relative paths.
var templates = controllerTemplates.SelectMany((c) => routeAttributes, (c, a) => a[0] == '/' ? a.Substring(1) : $"{c}{a}").ToArray();
templatesByHandler.Add(action, templates);
}
return Create(templatesByHandler);
}
/// <summary>
/// Generate routes given a collection of MethodInfo objects and templates that should call those methods
/// </summary>
/// <param name="templatesByHandler">Templates that should route to each handler</param>
internal static MqttRouteTable Create(Dictionary<MethodInfo, string[]> templatesByHandler)
{
var routes = new List<MqttRoute>();
foreach (var keyValuePair in templatesByHandler)
{
var parsedTemplates = keyValuePair.Value.Select(v => TemplateParser.ParseTemplate(v)).ToArray();
var allRouteParameterNames = parsedTemplates
.SelectMany(GetParameterNames)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
foreach (var parsedTemplate in parsedTemplates)
{
var unusedRouteParameterNames = allRouteParameterNames
.Except(GetParameterNames(parsedTemplate), StringComparer.OrdinalIgnoreCase)
.ToArray();
var entry = new MqttRoute(parsedTemplate, keyValuePair.Key, unusedRouteParameterNames);
routes.Add(entry);
}
}
return new MqttRouteTable(routes.OrderBy(id => id, RoutePrecedence).ToArray());
}
/// <summary>
/// Returns the names of all parameters in a given RouteTemplate
/// </summary>
private static string[] GetParameterNames(RouteTemplate routeTemplate)
{
return routeTemplate.Segments
.Where(s => s.IsParameter)
.Select(s => s.Value)
.ToArray();
}
/// <summary>
/// Given a route template string suchs a "[controller]/[action]" replace the tokens with the values provided.
/// /// Controllers with a suffix of "Controller" will be chopped to exclude the word Controller from the
/// returns route string.
/// </summary>
/// <param name="template">Template string</param>
/// <param name="controllerName">Name of the controller object</param>
/// <param name="actionName">Name of the action method</param>
/// <returns>String with replaced values</returns>
private static string ReplaceTokens(string template, string controllerName, string actionName)
{
// In a future enhancement, we may allow escaping tokens with a "[[" to have feature parity with AspNet routing.
return template
// Strip "Controller" suffix from controller name if needed
.Replace("[controller]", controllerName.EndsWith("Controller") ? controllerName.Substring(0, controllerName.Length - 10) : controllerName)
.Replace("[action]", actionName);
}
/// <summary>
/// Route precedence algorithm. We collect all the routes and sort them from most specific to less specific. The
/// specificity of a route is given by the specificity of its segments and the position of those segments in the route.
/// * A literal segment is more specific than a parameter segment.
/// * A parameter segment with more constraints is more specific than one with fewer constraints
/// * Segment earlier in the route are evaluated before segments later in the route. For example: /Literal is
/// more specific than /Parameter /Route/With/{parameter} is more specific than /{multiple}/With/{parameters}
/// /Product/{id:int} is more specific than /Product/{id}
///
/// Routes can be ambiguous if: They are composed of literals and those literals have the same values (case
/// insensitive) They are composed of a mix of literals and parameters, in the same relative order and the
/// literals have the same values. For example:
/// * /literal and /Literal /{parameter}/literal and /{something}/literal /{parameter:constraint}/literal and /{something:constraint}/literal
///
/// To calculate the precedence we sort the list of routes as follows:
/// * Shorter routes go first.
/// * A literal wins over a parameter in precedence.
/// * For literals with different values (case insensitive) we choose the lexical order
/// * For parameters with different numbers of constraints, the one with more wins If we get to the end of the
/// comparison routing we've detected an ambiguous pair of routes.
/// * Catch-all routes go last
/// </summary>
internal static int RouteComparison(MqttRoute x, MqttRoute y)
{
if (ReferenceEquals(x, y))
{
return 0;
}
var xTemplate = x.Template;
var yTemplate = y.Template;
if (xTemplate.Segments.Count != y.Template.Segments.Count)
{
if (!xTemplate.Segments[xTemplate.Segments.Count - 1].IsCatchAll && yTemplate.Segments[yTemplate.Segments.Count - 1].IsCatchAll)
{
return -1;
}
if (xTemplate.Segments[xTemplate.Segments.Count - 1].IsCatchAll && !yTemplate.Segments[yTemplate.Segments.Count - 1].IsCatchAll)
{
return 1;
}
return xTemplate.Segments.Count < y.Template.Segments.Count ? -1 : 1;
}
else
{
for (var i = 0; i < xTemplate.Segments.Count; i++)
{
var xSegment = xTemplate.Segments[i];
var ySegment = yTemplate.Segments[i];
if (!xSegment.IsCatchAll && ySegment.IsCatchAll)
{
return -1;
}
if (xSegment.IsCatchAll && !ySegment.IsCatchAll)
{
return 1;
}
if (!xSegment.IsParameter && ySegment.IsParameter)
{
return -1;
}
if (xSegment.IsParameter && !ySegment.IsParameter)
{
return 1;
}
if (xSegment.IsParameter)
{
// Always favor non-optional parameters over optional ones
if (!xSegment.IsOptional && ySegment.IsOptional)
{
return -1;
}
if (xSegment.IsOptional && !ySegment.IsOptional)
{
return 1;
}
if (xSegment.Constraints.Length > ySegment.Constraints.Length)
{
return -1;
}
else if (xSegment.Constraints.Length < ySegment.Constraints.Length)
{
return 1;
}
}
else
{
var comparison = string.Compare(xSegment.Value, ySegment.Value, StringComparison.OrdinalIgnoreCase);
if (comparison != 0)
{
return comparison;
}
}
}
throw new InvalidOperationException($@"The following routes are ambiguous:
'{x.Template.TemplateText}' in '{x.Handler.DeclaringType.FullName}.{x.Handler.Name}'
'{y.Template.TemplateText}' in '{y.Handler.DeclaringType.FullName}.{y.Handler.Name}'
");
}
}
private readonly struct Key : IEquatable<Key>
{
public readonly Assembly[] Assemblies;
public Key(Assembly[] assemblies)
{
Assemblies = assemblies;
}
public override bool Equals(object obj)
{
return obj is Key other ? base.Equals(other) : false;
}
public bool Equals(Key other)
{
if (Assemblies == null && other.Assemblies == null)
{
return true;
}
else if ((Assemblies == null) || (other.Assemblies == null))
{
return false;
}
else if (Assemblies.Length != other.Assemblies.Length)
{
return false;
}
for (var i = 0; i < Assemblies.Length; i++)
{
if (!Assemblies[i].Equals(other.Assemblies[i]))
{
return false;
}
}
return true;
}
public override int GetHashCode()
{
var hash = new HashCode();
if (Assemblies != null)
{
for (var i = 0; i < Assemblies.Length; i++)
{
hash.Add(Assemblies[i]);
}
}
return hash.ToHashCode();
}
}
}
}