forked from Code-Sharp/uHttpSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControllerHandler.cs
More file actions
351 lines (276 loc) · 15.4 KB
/
Copy pathControllerHandler.cs
File metadata and controls
351 lines (276 loc) · 15.4 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
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.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 sealed class ControllerMethod
{
public ControllerMethod(Type controllerType, HttpMethods method)
{
ControllerType = controllerType;
Method = method;
}
public Type ControllerType { get; }
public HttpMethods Method { get; }
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 method && Equals(method);
}
public override int GetHashCode()
{
unchecked
{
return (ControllerType.GetHashCode() * 397) ^ (int)Method;
}
}
}
private 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;
return ReferenceEquals(this, obj) || 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 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)
{
_controller = controller ?? throw new ArgumentNullException(nameof(controller));
ModelBinder = modelBinder ?? throw new ArgumentNullException(nameof(modelBinder));
_view = view ?? throw new ArgumentNullException(nameof(view));
_propertyNameComparer = propertyNameComparer ?? throw new ArgumentNullException(nameof(propertyNameComparer));
}
protected virtual IModelBinder ModelBinder { get; }
private static Func<IController, IController> GenerateRouteFunction(MethodInfo getter)
{
if (getter.DeclaringType == null)
throw new ArgumentException("Cannot generate route function for static method.");
ParameterExpression 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)) return;
lock (SyncRoot)
{
if (LoadedControllerRoutes.Contains(controllerType)) return;
foreach (PropertyInfo 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
List<MethodInfo> 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?
IController controller = await GetController(context.Request.RequestParameters, context).ConfigureAwait(false);
if (controller == null)
{
await next().ConfigureAwait(false);
return;
}
IControllerResponse 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)
{
IController current = _controller;
foreach (string parameter in requestParameters)
{
Type controllerType = current.GetType();
LoadRoutes(controllerType, _propertyNameComparer);
ControllerRoute route = new ControllerRoute(controllerType, parameter, _propertyNameComparer);
if (Routes.TryGetValue(route, out Func<IController, IController> 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 static async Task<IController> TryGetIndexerValue(Type controllerType, IHttpContext context, IController current,
string parameter)
{
if (!IndexerRoutes.TryGetValue(controllerType,
out Func<IHttpContext, IController, string, Task<IController>>[] indexerFunctions)) return null;
foreach (Func<IHttpContext, IController, string, Task<IController>> indexerFunction in indexerFunctions)
{
Task<IController> returnedTask = indexerFunction(context, current, parameter);
if (returnedTask != null) return await returnedTask.ConfigureAwait(false);
// TODO: Logger.Info
//Console.WriteLine("Returned task from indexer function was null. It may happen when we cannot convert from string to wanted type.");
}
return null;
}
private Task<IControllerResponse> CallMethod(IHttpContext context, IController controller)
{
ControllerMethod controllerMethod = new ControllerMethod(controller.GetType(), context.Request.Method);
if (ControllerFunctions.TryGetValue(controllerMethod, out ControllerFunction controllerFunction))
return controllerFunction(context, ModelBinder, controller);
lock (SyncRoot)
{
if (!ControllerFunctions.TryGetValue(controllerMethod, out controllerFunction))
{
ControllerFunctions[controllerMethod] = controllerFunction = CreateControllerFunction(controllerMethod);
}
}
return controllerFunction(context, ModelBinder, controller);
//context.Response = await controllerResponse.Respond(context, _view).ConfigureAwait(false);
}
private ControllerFunction CreateControllerFunction(ControllerMethod controllerMethod)
{
ParameterExpression httpContextArgument = Expression.Parameter(typeof(IHttpContext), "httpContext");
ParameterExpression modelBinderArgument = Expression.Parameter(typeof(IModelBinder), "modelBinder");
ParameterExpression controllerArgument = Expression.Parameter(typeof(object), "controller");
ParameterExpression errorContainerVariable = Expression.Variable(typeof(IErrorContainer));
MethodInfo 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(
$"Controller Methods should always return {typeof(Task<IControllerResponse>)}, The method {foundMethod.DeclaringType}.{foundMethod.Name} returns {foundMethod.ReturnType.FullName}");
}
ParameterInfo[] parameters = foundMethod.GetParameters();
IList<ParameterExpression> variables = new List<ParameterExpression>(parameters.Length);
IList<Expression> body = new List<Expression>(parameters.Length);
MethodInfo modelBindingGetMethod = typeof(IModelBinding).GetMethods()[0];
foreach (ParameterInfo parameter in parameters)
{
ParameterExpression variable = Expression.Variable(parameter.ParameterType, parameter.Name);
variables.Add(variable);
List<Attribute> attributes = parameter.GetCustomAttributes().ToList();
IModelBinding 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)));
}
}
MethodCallExpression methodCallExp = Expression.Call(Expression.Convert(controllerArgument, controllerMethod.ControllerType),
foundMethod, variables);
LabelTarget labelTarget = Expression.Label(typeof(Task<IControllerResponse>));
Expression parameterBindingExpression = body.Count > 0 ? (Expression)Expression.Block(body) : Expression.Empty();
BlockExpression 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))
);
ParameterExpression[] parameterExpressions = new[] { httpContextArgument, modelBinderArgument, controllerArgument };
Expression<ControllerFunction> lambda = Expression.Lambda<ControllerFunction>(methodBody, parameterExpressions);
return lambda.Compile();
}
private static Task<IControllerResponse> MethodNotFoundControllerFunction(IHttpContext context, IModelBinder binder,
object controller)
{
// TODO : MethodNotFound.
return Task.FromResult<IControllerResponse>(new RenderResponse(HttpResponseCode.MethodNotAllowed,
new { Message = "Not Allowed" }));
}
}
}