forked from bonesoul/uhttpsharp
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathControllerHandler.cs
More file actions
366 lines (297 loc) · 15.6 KB
/
ControllerHandler.cs
File metadata and controls
366 lines (297 loc) · 15.6 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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using uhttpsharp.Attributes;
using uhttpsharp.Controllers;
using uhttpsharp.Logging;
using uhttpsharp.ModelBinders;
namespace uhttpsharp.Handlers
{
/// <summary>
/// Need some kind of way to prevent default behavior of controller that inherits a base controller...
/// since we are not using virtual methods
/// </summary>
public class ControllerHandler : IHttpRequestHandler
{
private static readonly ILog Logger = LogProvider.For<ControllerHandler>();
sealed class ControllerMethod
{
private readonly Type _controllerType;
private readonly HttpMethods _method;
public ControllerMethod(Type controllerType, HttpMethods method)
{
_controllerType = controllerType;
_method = method;
}
public Type ControllerType
{
get { return _controllerType; }
}
public HttpMethods Method
{
get { return _method; }
}
private bool Equals(ControllerMethod other)
{
return _controllerType == other._controllerType && _method == other._method;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj is ControllerMethod && Equals((ControllerMethod)obj);
}
public override int GetHashCode()
{
unchecked
{
return (_controllerType.GetHashCode() * 397) ^ (int)_method;
}
}
}
sealed class ControllerRoute
{
private readonly Type _controllerType;
private readonly string _propertyName;
private readonly IEqualityComparer<string> _propertyNameComparer;
public ControllerRoute(Type controllerType, string propertyName, IEqualityComparer<string> propertyNameComparer)
{
_controllerType = controllerType;
_propertyName = propertyName;
_propertyNameComparer = propertyNameComparer;
}
private bool Equals(ControllerRoute other)
{
return other != null
&& _controllerType == other._controllerType
&& _propertyNameComparer.Equals(_propertyName, other._propertyName);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return Equals(obj as ControllerRoute);
}
public override int GetHashCode()
{
unchecked
{
return ((_controllerType != null ? _controllerType.GetHashCode() : 0) * 397) ^
(_propertyName != null ? _propertyNameComparer.GetHashCode(_propertyName) : 0);
}
}
}
private static readonly IDictionary<ControllerMethod, ControllerFunction> ControllerFunctions = new Dictionary<ControllerMethod, ControllerFunction>();
private static readonly IDictionary<ControllerRoute, Func<IController, IController>> Routes = new Dictionary<ControllerRoute, Func<IController, IController>>();
private static readonly IDictionary<Type, Func<IHttpContext, IController, string, Task<IController>>[]> IndexerRoutes = new Dictionary<Type, Func<IHttpContext, IController, string, Task<IController>>[]>();
private static readonly ICollection<Type> LoadedControllerRoutes = new HashSet<Type>();
private static readonly object SyncRoot = new object();
public delegate Task<IControllerResponse> ControllerFunction(IHttpContext context, IModelBinder binder, IController controller);
private readonly IController _controller;
private readonly IModelBinder _modelBinder;
private readonly IView _view;
private readonly IEqualityComparer<string> _propertyNameComparer;
public ControllerHandler(IController controller, IModelBinder modelBinder, IView view)
: this(controller, modelBinder, view, StringComparer.CurrentCulture) { }
public ControllerHandler(IController controller, IModelBinder modelBinder, IView view, IEqualityComparer<string> propertyNameComparer)
{
if (controller == null)
throw new ArgumentNullException("controller");
if (modelBinder == null)
throw new ArgumentNullException("modelBinder");
if (view == null)
throw new ArgumentNullException("view");
if (propertyNameComparer == null)
throw new ArgumentNullException("propertyNameComparer");
_controller = controller;
_modelBinder = modelBinder;
_view = view;
_propertyNameComparer = propertyNameComparer;
}
protected virtual IModelBinder ModelBinder
{
get { return _modelBinder; }
}
private static Func<IController, IController> GenerateRouteFunction(MethodInfo getter)
{
if (getter.DeclaringType == null)
throw new ArgumentException("Cannot generate route function for static method.");
var instance = Expression.Parameter(typeof(IController), "instance");
return Expression.Lambda<Func<IController, IController>>(Expression.Call(Expression.Convert(instance, getter.DeclaringType), getter), instance).Compile();
}
private static void LoadRoutes(Type controllerType, IEqualityComparer<string> propertyNameComparer)
{
if (!LoadedControllerRoutes.Contains(controllerType))
{
lock (SyncRoot)
{
if (!LoadedControllerRoutes.Contains(controllerType))
{
foreach (var prop in controllerType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.PropertyType == typeof(IController)))
{
Routes.Add(new ControllerRoute(controllerType, prop.Name, propertyNameComparer),
GenerateRouteFunction(prop.GetMethod));
}
// Indexers
var methods = controllerType.GetMethods().Where(m => Attribute.IsDefined(m, typeof(IndexerAttribute))).OrderBy(m => m.GetCustomAttribute<IndexerAttribute>().Precedence).ToList();
if (methods.Select(m => m.GetCustomAttribute<IndexerAttribute>().Precedence)
.GroupBy(c => c)
.Any(c => c.Count() > 1))
{
throw new ArgumentException("Controller " + controllerType + " Has more then two indexer functions with the same precedence, Please set precedence.");
}
if (methods.Count > 0)
{
IndexerRoutes.Add(controllerType, methods.Select(m => ClassRouter.CreateIndexerFunction<IController>(controllerType, m)).ToArray());
}
LoadedControllerRoutes.Add(controllerType);
}
}
}
}
public async Task Handle(IHttpContext context, Func<Task> next)
{
// I/O Bound?
var controller = await GetController(context.Request.RequestParameters, context).ConfigureAwait(false);
if (controller == null)
{
await next().ConfigureAwait(false);
return;
}
var response = await controller.Pipeline.Go(() => CallMethod(context, controller), context).ConfigureAwait(false);
context.Response = await response.Respond(context, _view).ConfigureAwait(false);
}
private async Task<IController> GetController(IEnumerable<string> requestParameters, IHttpContext context)
{
var current = _controller;
foreach (var parameter in requestParameters)
{
var controllerType = current.GetType();
LoadRoutes(controllerType, _propertyNameComparer);
var route = new ControllerRoute(controllerType, parameter, _propertyNameComparer);
Func<IController, IController> routeFunction;
if (Routes.TryGetValue(route, out routeFunction))
{
current = routeFunction(current);
continue;
}
// Try find indexer.
current = await TryGetIndexerValue(controllerType, context, current, parameter).ConfigureAwait(false);
if (current != null)
{
continue;
}
return null;
}
return current;
}
private async Task<IController> TryGetIndexerValue(Type controllerType, IHttpContext context, IController current, string parameter)
{
Func<IHttpContext, IController, string, Task<IController>>[] indexerFunctions;
if (IndexerRoutes.TryGetValue(controllerType, out indexerFunctions))
{
foreach (var indexerFunction in indexerFunctions)
{
var returnedTask = indexerFunction(context, current, parameter);
if (returnedTask == null)
{
Logger.Info("Returned task from indexer function was null. It may happen when we cannot convert from string to wanted type.");
continue;
}
return await returnedTask.ConfigureAwait(false);
}
}
return null;
}
private Task<IControllerResponse> CallMethod(IHttpContext context, IController controller)
{
var controllerMethod = new ControllerMethod(controller.GetType(), context.Request.Method);
ControllerFunction controllerFunction;
if (!ControllerFunctions.TryGetValue(controllerMethod, out controllerFunction))
{
lock (SyncRoot)
{
if (!ControllerFunctions.TryGetValue(controllerMethod, out controllerFunction))
{
ControllerFunctions[controllerMethod] = controllerFunction = CreateControllerFunction(controllerMethod);
}
}
}
return controllerFunction(context, this.ModelBinder, controller);
//context.Response = await controllerResponse.Respond(context, _view).ConfigureAwait(false);
}
private ControllerFunction CreateControllerFunction(ControllerMethod controllerMethod)
{
var httpContextArgument = Expression.Parameter(typeof(IHttpContext), "httpContext");
var modelBinderArgument = Expression.Parameter(typeof(IModelBinder), "modelBinder");
var controllerArgument = Expression.Parameter(typeof(object), "controller");
var errorContainerVariable = Expression.Variable(typeof(IErrorContainer));
var foundMethod =
(from method in controllerMethod.ControllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
let attributes = method.GetCustomAttributes<HttpMethodAttribute>()
where attributes.Any(a => a.HttpMethod == controllerMethod.Method)
select method).FirstOrDefault();
if (foundMethod == null)
{
return MethodNotFoundControllerFunction;
}
if (foundMethod.ReturnType != typeof(Task<IControllerResponse>))
{
throw new ArgumentException(
string.Format("Controller Methods should always return {0}, The method {1}.{2} returns {3}",
typeof(Task<IControllerResponse>), foundMethod.DeclaringType, foundMethod.Name,
foundMethod.ReturnType.FullName));
}
var parameters = foundMethod.GetParameters();
IList<ParameterExpression> variables = new List<ParameterExpression>(parameters.Length);
IList<Expression> body = new List<Expression>(parameters.Length);
var modelBindingGetMethod = typeof(IModelBinding).GetMethods()[0];
foreach (var parameter in parameters)
{
var variable = Expression.Variable(parameter.ParameterType, parameter.Name);
variables.Add(variable);
var attributes = parameter.GetCustomAttributes().ToList();
var modelBindingAttribute = attributes.OfType<IModelBinding>().Single();
body.Add(
Expression.Assign(variable,
Expression.Call(Expression.Constant(modelBindingAttribute),
modelBindingGetMethod.MakeGenericMethod(parameter.ParameterType),
httpContextArgument, modelBinderArgument
)));
if (!attributes.OfType<NullableAttribute>().Any())
{
body.Add(Expression.IfThen(Expression.Equal(variable, Expression.Constant(null)),
Expression.Call(errorContainerVariable, "Log", Type.EmptyTypes,
Expression.Constant(parameter.Name + " Is not found (null) and not marked as nullable."))));
}
if (parameter.ParameterType.GetInterfaces().Contains(typeof(IValidate)))
{
body.Add(Expression.IfThen(Expression.NotEqual(variable, Expression.Constant(null)),
Expression.Call(variable, "Validate", Type.EmptyTypes, errorContainerVariable)));
}
}
var methodCallExp = Expression.Call(Expression.Convert(controllerArgument, controllerMethod.ControllerType), foundMethod, variables);
var labelTarget = Expression.Label(typeof(Task<IControllerResponse>));
var parameterBindingExpression = body.Count > 0 ? (Expression)Expression.Block(body) : Expression.Empty();
var methodBody = Expression.Block(
variables.Concat(new[] { errorContainerVariable }),
Expression.Assign(errorContainerVariable, Expression.New(typeof(ErrorContainer))),
parameterBindingExpression,
Expression.IfThen(Expression.Not(Expression.Property(errorContainerVariable, "Any")),
Expression.Return(labelTarget, methodCallExp)),
Expression.Label(labelTarget, Expression.Call(errorContainerVariable, "GetResponse", Type.EmptyTypes))
);
var parameterExpressions = new[] { httpContextArgument, modelBinderArgument, controllerArgument };
var lambda = Expression.Lambda<ControllerFunction>(methodBody, parameterExpressions);
return lambda.Compile();
}
private Task<IControllerResponse> MethodNotFoundControllerFunction(IHttpContext context, IModelBinder binder, object controller)
{
// TODO : MethodNotFound.
return Task.FromResult<IControllerResponse>(new RenderResponse(HttpResponseCode.MethodNotAllowed, new { Message = "Not Allowed" }));
}
}
}