forked from bonesoul/uhttpsharp
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathClassRouter.cs
More file actions
231 lines (190 loc) · 8.87 KB
/
ClassRouter.cs
File metadata and controls
231 lines (190 loc) · 8.87 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
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)
{
var rootType = root.GetType();
if (LoadedRoutes.Contains(rootType))
{
return;
}
lock (SyncRoot)
{
if (LoadedRoutes.Add(rootType))
{
var routes = GetRoutesOfHandler(rootType);
foreach (var route in routes)
{
var tuple = Tuple.Create(rootType, route.Name);
var value = CreateRoute(tuple);
Routers.Add(tuple, value);
}
}
}
}
private IEnumerable<PropertyInfo> GetRoutesOfHandler(Type type)
{
return type
.GetProperties()
.Where(p => typeof(IHttpRequestHandler).IsAssignableFrom(p.PropertyType));
}
public async Task Handle(IHttpContext context, Func<Task> next)
{
var handler = _root;
foreach (var parameter in context.Request.RequestParameters)
{
Func<IHttpRequestHandler, IHttpRequestHandler> getNextHandler;
LoadRoute(handler);
if (Routers.TryGetValue(Tuple.Create(handler.GetType(), parameter), out getNextHandler))
{
handler = getNextHandler(handler);
}
else
{
var getNextByIndex = IndexerRouters.GetOrAdd(handler.GetType(), GetIndexerRouter);
if (getNextByIndex == null) //Indexer is not found
{
await next().ConfigureAwait(false);
return;
}
var returnedTask = getNextByIndex(context, handler, parameter);
if (returnedTask == null) //Indexer found, but returned null (for whatever reason)
{
await next().ConfigureAwait(false);
return;
}
handler = await returnedTask.ConfigureAwait(false);
}
// Incase that one of the methods returned null (Indexer / Getter)
if (handler == null)
{
await next().ConfigureAwait(false);
return;
}
}
await handler.Handle(context, next).ConfigureAwait(false);
}
private Func<IHttpContext, IHttpRequestHandler, string, Task<IHttpRequestHandler>> GetIndexerRouter(Type arg)
{
var indexer = GetIndexer(arg);
if (indexer == null)
{
return null;
}
return CreateIndexerFunction<IHttpRequestHandler>(arg, indexer);
}
internal static Func<IHttpContext, T, string, Task<T>> CreateIndexerFunction<T>(Type arg, MethodInfo indexer)
{
AssertIndexerParameters<T>(indexer);
var parameterType = indexer.GetParameters()[1].ParameterType;
var httpContext = Expression.Parameter(typeof(IHttpContext), "context");
var inputHandler = Expression.Parameter(typeof(T), "instance");
var inputObject = Expression.Parameter(typeof(string), "input");
var tryParseMethod = parameterType.GetMethod("TryParse", new[] {typeof(string), parameterType.MakeByRefType()});
Expression body;
if (tryParseMethod == null)
{
var handlerConverted = Expression.Convert(inputHandler, arg);
var objectConverted =
Expression.Convert(
Expression.Call(typeof(Convert).GetMethod("ChangeType", new[] {typeof(object), typeof(Type)}), inputObject,
Expression.Constant(parameterType)), parameterType);
var indexerExpression = Expression.Call (handlerConverted, indexer, httpContext, objectConverted);
var returnValue = Expression.Convert (indexerExpression, typeof(Task<T>));
body = returnValue;
}
else
{
var inputConvertedVar = Expression.Variable(parameterType, "inputObjectConverted");
var handlerConverted = Expression.Convert(inputHandler, arg);
var objectConverted = inputConvertedVar;
var indexerExpression = Expression.Call(handlerConverted, indexer, httpContext, objectConverted);
var returnValue = Expression.Convert(indexerExpression, typeof(Task<T>));
var returnTarget = Expression.Label(typeof(Task<T>));
var 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)
{
var 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(string.Format("Indexer method should always return {0}.", typeof(Task<T>).FullName));
}
}
private MethodInfo GetIndexer(Type arg)
{
var indexer =
arg.GetMethods().SingleOrDefault(m => Attribute.IsDefined(m, typeof(IndexerAttribute))
&& m.GetParameters().Length == 2
&& typeof(Task<IHttpRequestHandler>).IsAssignableFrom(m.ReturnType));
return indexer;
}
private Func<IHttpRequestHandler, IHttpRequestHandler> CreateRoute(Tuple<Type, string> arg)
{
var parameter = Expression.Parameter(typeof(IHttpRequestHandler), "input");
var converted = Expression.Convert(parameter, arg.Item1);
var propertyInfo = arg.Item1.GetProperty(arg.Item2);
if (propertyInfo == null)
{
return null;
}
var property = Expression.Property(converted, propertyInfo);
var propertyConverted = Expression.Convert(property, typeof(IHttpRequestHandler));
return Expression.Lambda<Func<IHttpRequestHandler, IHttpRequestHandler>>(propertyConverted, new[] { parameter }).Compile();
}
}
public class IndexerAttribute : Attribute
{
private readonly int _precedence;
public IndexerAttribute(int precedence = 0)
{
_precedence = precedence;
}
public int Precedence
{
get { return _precedence; }
}
}
}