forked from WKleinschmit/uHttpSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathControllerHandler.cs
More file actions
242 lines (185 loc) · 11.8 KB
/
Copy pathControllerHandler.cs
File metadata and controls
242 lines (185 loc) · 11.8 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
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 {
public delegate Task<IControllerResponse> ControllerFunction(IHttpContext context, IModelBinder binder, IController controller);
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();
private readonly IController _controller;
private readonly IView _view;
protected virtual IModelBinder ModelBinder { get; }
public ControllerHandler(IController controller, IModelBinder modelBinder, IView view) {
_controller = controller;
ModelBinder = modelBinder;
_view = view;
}
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 static Func<IController, IController> GenerateRouteFunction(MethodInfo getter) {
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) {
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),
GenerateRouteFunction(prop.GetMethod));
// Indexers
var method = controllerType.GetMethods().SingleOrDefault(m => Attribute.IsDefined(m, typeof(IndexerAttribute)));
if (method != null) IndexerRoutes.Add(controllerType, ClassRouter.CreateIndexerFunction<IController>(controllerType, method));
LoadedControllerRoutes.Add(controllerType);
}
}
}
private async Task<IController> GetController(IEnumerable<string> requestParameters, IHttpContext context) {
var current = _controller;
foreach (var parameter in requestParameters) {
var controllerType = current.GetType();
LoadRoutes(controllerType);
var route = new ControllerRoute(controllerType, parameter);
Func<IController, IController> routeFunction;
if (Routes.TryGetValue(route, out routeFunction)) {
current = routeFunction(current);
continue;
}
// Try find indexer.
Func<IHttpContext, IController, string, Task<IController>> indexerFunction;
if (IndexerRoutes.TryGetValue(controllerType, out indexerFunction)) {
current = await indexerFunction(context, current, parameter).ConfigureAwait(false);
continue;
}
return null;
}
return current;
}
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, 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 attribute = method.GetCustomAttribute<HttpMethodAttribute>()
where attribute != null && attribute.HttpMethod == controllerMethod.Method
select method).FirstOrDefault();
if (foundMethod == null) return MethodNotFoundControllerFunction;
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"}));
}
private sealed class ControllerMethod {
public Type ControllerType { get; }
public HttpMethods Method { get; }
public ControllerMethod(Type controllerType, HttpMethods method) {
ControllerType = controllerType;
Method = 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;
}
}
}
private sealed class ControllerRoute {
private readonly Type _controllerType;
private readonly string _propertyName;
public ControllerRoute(Type controllerType, string propertyName) {
_controllerType = controllerType;
_propertyName = propertyName;
}
private bool Equals(ControllerRoute other) {
return _controllerType == other._controllerType && string.Equals(_propertyName, other._propertyName, StringComparison.InvariantCultureIgnoreCase);
}
public override bool Equals(object obj) {
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj is ControllerRoute && Equals((ControllerRoute) obj);
}
public override int GetHashCode() {
unchecked {
return ((_controllerType != null ? _controllerType.GetHashCode() : 0) * 397) ^ (_propertyName != null ? _propertyName.ToLowerInvariant().GetHashCode() : 0);
}
}
}
}
}