forked from Code-Sharp/uHttpSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassRouter.cs
More file actions
233 lines (189 loc) · 9.31 KB
/
Copy pathClassRouter.cs
File metadata and controls
233 lines (189 loc) · 9.31 KB
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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
namespace uhttpsharp.Handlers
{
public class ClassRouter : IHttpRequestHandler
{
private static readonly object SyncRoot = new object();
private static readonly HashSet<Type> LoadedRoutes = new HashSet<Type>();
private static readonly IDictionary<Tuple<Type, string>, Func<IHttpRequestHandler, IHttpRequestHandler>>
Routers = new Dictionary<Tuple<Type, string>, Func<IHttpRequestHandler, IHttpRequestHandler>>();
private static readonly ConcurrentDictionary<Type,
Func<IHttpContext, IHttpRequestHandler, string, Task<IHttpRequestHandler>>>
IndexerRouters =
new ConcurrentDictionary<Type, Func<IHttpContext, IHttpRequestHandler, string, Task<IHttpRequestHandler>>>();
private readonly IHttpRequestHandler _root;
public ClassRouter(IHttpRequestHandler root)
{
_root = root;
LoadRoute(_root);
}
private void LoadRoute(IHttpRequestHandler root)
{
Type rootType = root.GetType();
if (LoadedRoutes.Contains(rootType))
{
return;
}
lock (SyncRoot)
{
if (!LoadedRoutes.Add(rootType)) return;
foreach (PropertyInfo route in GetRoutesOfHandler(rootType))
{
Tuple<Type, string> tuple = Tuple.Create(rootType, route.Name);
Func<IHttpRequestHandler, IHttpRequestHandler> value = CreateRoute(tuple);
Routers.Add(tuple, value);
}
}
}
private static IEnumerable<PropertyInfo> GetRoutesOfHandler(Type type)
{
return type
.GetProperties()
.Where(p => typeof(IHttpRequestHandler).IsAssignableFrom(p.PropertyType));
}
public async Task Handle(IHttpContext context, Func<Task> next)
{
IHttpRequestHandler handler = _root;
foreach (string parameter in context.Request.RequestParameters)
{
LoadRoute(handler);
if (Routers.TryGetValue(Tuple.Create(handler.GetType(), parameter),
out Func<IHttpRequestHandler, IHttpRequestHandler> getNextHandler))
{
handler = getNextHandler(handler);
}
else
{
Func<IHttpContext, IHttpRequestHandler, string, Task<IHttpRequestHandler>> getNextByIndex =
IndexerRouters.GetOrAdd(handler.GetType(), GetIndexerRouter);
// Indexer is not found
if (getNextByIndex == null)
{
await next().ConfigureAwait(false);
return;
}
Task<IHttpRequestHandler> returnedTask = getNextByIndex(context, handler, parameter);
// Indexer found, but returned null (for whatever reason)
if (returnedTask == null)
{
await next().ConfigureAwait(false);
return;
}
handler = await returnedTask.ConfigureAwait(false);
}
// Incase that one of the methods returned null (Indexer / Getter)
if (handler != null) continue;
await next().ConfigureAwait(false);
return;
}
await handler.Handle(context, next).ConfigureAwait(false);
}
private Func<IHttpContext, IHttpRequestHandler, string, Task<IHttpRequestHandler>> GetIndexerRouter(Type arg)
{
MethodInfo indexer = GetIndexer(arg);
return indexer == null ? null : CreateIndexerFunction<IHttpRequestHandler>(arg, indexer);
}
internal static Func<IHttpContext, T, string, Task<T>> CreateIndexerFunction<T>(Type arg, MethodInfo indexer)
{
AssertIndexerParameters<T>(indexer);
Type parameterType = indexer.GetParameters()[1].ParameterType;
ParameterExpression httpContext = Expression.Parameter(typeof(IHttpContext), "context");
ParameterExpression inputHandler = Expression.Parameter(typeof(T), "instance");
ParameterExpression inputObject = Expression.Parameter(typeof(string), "input");
MethodInfo tryParseMethod =
parameterType.GetMethod("TryParse", new[] { typeof(string), parameterType.MakeByRefType() });
Expression body;
if (tryParseMethod == null)
{
UnaryExpression handlerConverted = Expression.Convert(inputHandler, arg);
UnaryExpression objectConverted =
Expression.Convert(
Expression.Call(
typeof(Convert).GetMethod("ChangeType", new[] { typeof(object), typeof(Type) }) ??
throw new InvalidOperationException(),
inputObject,
Expression.Constant(parameterType)), parameterType);
MethodCallExpression indexerExpression =
Expression.Call(handlerConverted, indexer, httpContext, objectConverted);
UnaryExpression returnValue = Expression.Convert(indexerExpression, typeof(Task<T>));
body = returnValue;
}
else
{
ParameterExpression inputConvertedVar = Expression.Variable(parameterType, "inputObjectConverted");
UnaryExpression handlerConverted = Expression.Convert(inputHandler, arg);
MethodCallExpression indexerExpression =
Expression.Call(handlerConverted, indexer, httpContext, inputConvertedVar);
UnaryExpression returnValue = Expression.Convert(indexerExpression, typeof(Task<T>));
LabelTarget returnTarget = Expression.Label(typeof(Task<T>));
LabelExpression returnLabel = Expression.Label(returnTarget,
Expression.Convert(Expression.Constant(null), typeof(Task<T>)));
body =
Expression.Block(
new[] { inputConvertedVar },
Expression.IfThen(
Expression.Call(tryParseMethod, inputObject,
inputConvertedVar),
Expression.Return(returnTarget, returnValue)
),
returnLabel);
}
return
Expression.Lambda<Func<IHttpContext, T, string, Task<T>>>(body, httpContext,
inputHandler,
inputObject).Compile();
}
private static void AssertIndexerParameters<T>(MethodInfo methodInfo)
{
ParameterInfo[] parameters = methodInfo.GetParameters();
if (parameters.Length != 2 || parameters[0].ParameterType != typeof(IHttpContext))
{
throw new ArgumentException(
string.Format(
"Indexer Method ({2}.{3}) should always receive two parameters, The first one should be of type {0} and the second should be of primitive type (string, int, long, etc'). Also, It must return {1}.",
typeof(IHttpContext).FullName, typeof(Task<T>).FullName, methodInfo.DeclaringType, methodInfo.Name));
}
if (methodInfo.ReturnType != typeof(Task<T>))
{
throw new ArgumentException($"Indexer method should always return {typeof(Task<T>).FullName}.");
}
}
private static MethodInfo GetIndexer(Type arg)
{
MethodInfo indexer =
arg.GetMethods().SingleOrDefault(m => Attribute.IsDefined(m, typeof(IndexerAttribute))
&& m.GetParameters().Length == 2
&& typeof(Task<IHttpRequestHandler>).IsAssignableFrom(m.ReturnType));
return indexer;
}
private static Func<IHttpRequestHandler, IHttpRequestHandler> CreateRoute(Tuple<Type, string> arg)
{
ParameterExpression parameter = Expression.Parameter(typeof(IHttpRequestHandler), "input");
(Type item1, string item2) = arg;
UnaryExpression converted = Expression.Convert(parameter, item1);
PropertyInfo propertyInfo = item1.GetProperty(item2);
if (propertyInfo == null)
{
return null;
}
MemberExpression property = Expression.Property(converted, propertyInfo);
UnaryExpression propertyConverted = Expression.Convert(property, typeof(IHttpRequestHandler));
return Expression.Lambda<Func<IHttpRequestHandler, IHttpRequestHandler>>(propertyConverted, parameter)
.Compile();
}
}
public class IndexerAttribute : Attribute
{
public IndexerAttribute(int precedence = 0)
{
Precedence = precedence;
}
public int Precedence { get; }
}
}