This repository was archived by the owner on Jul 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServiceController.cs
More file actions
525 lines (430 loc) · 16.3 KB
/
ServiceController.cs
File metadata and controls
525 lines (430 loc) · 16.3 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using SimpleStack.Interfaces;
using SimpleStack.Logging;
using SimpleStack.Attributes;
using SimpleStack.Enums;
using SimpleStack.Extensions;
using SimpleStack.Serializers;
//using ServiceStack.Logging;
//using ServiceStack.Messaging;
//using ServiceStack.ServiceModel.Serialization;
//using ServiceStack.Text;
//using ServiceStack.WebHost.Endpoints;
namespace SimpleStack
{
public delegate object ServiceExecFn(IRequestContext requestContext, object request);
public delegate object InstanceExecFn(IRequestContext requestContext, object intance, object request);
public delegate object ActionInvokerFn(object intance, object request);
public delegate void VoidActionInvokerFn(object intance, object request);
public class ServiceController
: IServiceController
{
private static readonly ILog Log = Logger.CreateLog();
private const string ResponseDtoSuffix = "Response";
public ServiceController(Func<IEnumerable<Type>> resolveServicesFn, ServiceMetadata metadata = null)
{
this.Metadata = metadata ?? new ServiceMetadata();
this.RequestTypeFactoryMap = new Dictionary<Type, Func<IHttpRequest, object>>();
this.EnableAccessRestrictions = true;
this.ResolveServicesFn = resolveServicesFn;
}
readonly Dictionary<Type, ServiceExecFn> requestExecMap = new Dictionary<Type, ServiceExecFn>();
readonly Dictionary<Type, RestrictAttribute> requestServiceAttrs = new Dictionary<Type, RestrictAttribute>();
public bool EnableAccessRestrictions { get; set; }
public ServiceMetadata Metadata { get; internal set; }
public Dictionary<Type, Func<IHttpRequest, object>> RequestTypeFactoryMap { get; set; }
public string DefaultOperationsNamespace { get; set; }
public IServiceRoutes Routes { get { return Metadata.Routes; } }
private IResolver resolver;
public IResolver Resolver
{
get { return resolver ?? EndpointHost.AppHost; }
set { resolver = value; }
}
public Func<IEnumerable<Type>> ResolveServicesFn { get; set; }
// public void Register<TReq>(Func<IService<TReq>> invoker)
// {
// var requestType = typeof(TReq);
// ServiceExecFn handlerFn = (requestContext, dto) => {
// var service = invoker();
//
// InjectRequestContext(service, requestContext);
//
// return ServiceExec<TReq>.Execute(
// service, (TReq)dto,
// requestContext != null ? requestContext.EndpointAttributes : EndpointAttributes.None);
// };
//
// requestExecMap.Add(requestType, handlerFn);
// }
public void Register(ITypeFactory serviceFactoryFn)
{
foreach (var serviceType in ResolveServicesFn())
{
//TODO: vdaron obsolete call commented
//RegisterGService(serviceFactoryFn, serviceType);
RegisterNService(serviceFactoryFn, serviceType);
}
}
[Obsolete("use obsolete api")]
public void RegisterGService(ITypeFactory serviceFactoryFn, Type serviceType)
{
if (serviceType.IsAbstract || serviceType.ContainsGenericParameters) return;
//IService<T>
foreach (var service in serviceType.GetInterfaces())
{
//TODO: vdaron : check this deprecated call
// if (!service.IsGenericType
// || service.GetGenericTypeDefinition() != typeof(IService<>)
// ) continue;
var requestType = service.GetGenericArguments()[0];
RegisterGServiceExecutor(requestType, serviceType, serviceFactoryFn);
var responseTypeName = requestType.FullName + ResponseDtoSuffix;
var responseType = AssemblyUtils.FindType(responseTypeName);
RegisterCommon(serviceType, requestType, responseType);
}
}
public void RegisterNService(ITypeFactory serviceFactoryFn, Type serviceType)
{
var processedReqs = new HashSet<Type>();
if (typeof(IService).IsAssignableFrom(serviceType)
&& !serviceType.IsAbstract && !serviceType.IsGenericTypeDefinition)
{
foreach (var mi in serviceType.GetActions())
{
var requestType = mi.GetParameters()[0].ParameterType;
if (processedReqs.Contains(requestType)) continue;
processedReqs.Add(requestType);
RegisterNServiceExecutor(requestType, serviceType, serviceFactoryFn);
var returnMarker = requestType.GetTypeWithGenericTypeDefinitionOf(typeof(IReturn<>));
var responseType = returnMarker != null ?
returnMarker.GetGenericArguments()[0]
: mi.ReturnType != typeof(object) && mi.ReturnType != typeof(void) ?
mi.ReturnType
: AssemblyUtils.FindType(requestType.FullName + ResponseDtoSuffix);
RegisterCommon(serviceType, requestType, responseType);
}
}
}
public void RegisterCommon(Type serviceType, Type requestType, Type responseType)
{
RegisterRestPaths(requestType);
Metadata.Add(serviceType, requestType, responseType);
if (typeof(IRequiresRequestStream).IsAssignableFrom(requestType))
{
this.RequestTypeFactoryMap[requestType] = httpReq => {
var rawReq = (IRequiresRequestStream)requestType.CreateInstance();
rawReq.RequestStream = httpReq.InputStream;
return rawReq;
};
}
Log.DebugFormat("Registering {0} service '{1}' with request '{2}'",
(responseType != null ? "Reply" : "OneWay"), serviceType.Name, requestType.Name);
}
public readonly Dictionary<string, List<RestPath>> RestPathMap = new Dictionary<string, List<RestPath>>();
public void RegisterRestPaths(Type requestType)
{
var attrs = TypeDescriptor.GetAttributes(requestType).OfType<RouteAttribute>();
foreach (RouteAttribute attr in attrs)
{
var restPath = new RestPath(requestType, attr.Path, attr.Verbs, attr.Summary, attr.Notes);
if (!restPath.IsValid)
throw new NotSupportedException(string.Format(
"RestPath '{0}' on Type '{1}' is not Valid", attr.Path, requestType.Name));
RegisterRestPath(restPath);
}
}
private static readonly char[] InvalidRouteChars = new[] {'?', '&'};
public void RegisterRestPath(RestPath restPath)
{
if (!EndpointHostConfig.SkipRouteValidation)
{
if (!restPath.Path.StartsWith("/"))
throw new ArgumentException("Route '{0}' on '{1}' must start with a '/'".Fmt(restPath.Path, restPath.RequestType.Name));
if (restPath.Path.IndexOfAny(InvalidRouteChars) != -1)
throw new ArgumentException("Route '{0}' on '{1}' contains invalid chars. " +
"See https://github.com/ServiceStack/ServiceStack/wiki/Routing for info on valid routes.".Fmt(restPath.Path, restPath.RequestType.Name));
}
List<RestPath> pathsAtFirstMatch;
if (!RestPathMap.TryGetValue(restPath.FirstMatchHashKey, out pathsAtFirstMatch))
{
pathsAtFirstMatch = new List<RestPath>();
RestPathMap[restPath.FirstMatchHashKey] = pathsAtFirstMatch;
}
pathsAtFirstMatch.Add(restPath);
}
public void AfterInit()
{
//Register any routes configured on Metadata.Routes
foreach (var restPath in this.Metadata.Routes.RestPaths)
{
RegisterRestPath(restPath);
}
//Sync the RestPaths collections
Metadata.Routes.RestPaths.Clear();
Metadata.Routes.RestPaths.AddRange(RestPathMap.Values.SelectMany(x => x));
Metadata.AfterInit();
}
public IRestPath GetRestPathForRequest(string httpMethod, string pathInfo)
{
var matchUsingPathParts = RestPath.GetPathPartsForMatching(pathInfo);
List<RestPath> firstMatches;
var yieldedHashMatches = RestPath.GetFirstMatchHashKeys(matchUsingPathParts);
foreach (var potentialHashMatch in yieldedHashMatches)
{
if (!RestPathMap.TryGetValue(potentialHashMatch, out firstMatches)) continue;
var bestScore = -1;
foreach (var restPath in firstMatches)
{
var score = restPath.MatchScore(httpMethod, matchUsingPathParts);
if (score > bestScore)
bestScore = score;
}
if (bestScore > 0)
{
foreach (var restPath in firstMatches)
{
if (bestScore == restPath.MatchScore(httpMethod, matchUsingPathParts))
return restPath;
}
}
}
var yieldedWildcardMatches = RestPath.GetFirstMatchWildCardHashKeys(matchUsingPathParts);
foreach (var potentialHashMatch in yieldedWildcardMatches)
{
if (!this.RestPathMap.TryGetValue(potentialHashMatch, out firstMatches)) continue;
var bestScore = -1;
foreach (var restPath in firstMatches)
{
var score = restPath.MatchScore(httpMethod, matchUsingPathParts);
if (score > bestScore) bestScore = score;
}
if (bestScore > 0)
{
foreach (var restPath in firstMatches)
{
if (bestScore == restPath.MatchScore(httpMethod, matchUsingPathParts))
return restPath;
}
}
}
return null;
}
internal class TypeFactoryWrapper : ITypeFactory
{
private readonly Func<Type, object> typeCreator;
public TypeFactoryWrapper(Func<Type, object> typeCreator)
{
this.typeCreator = typeCreator;
}
public object CreateInstance(Type type)
{
return typeCreator(type);
}
}
[Obsolete("obsolete ?")]
public void Register(Type requestType, Type serviceType)
{
var handlerFactoryFn = Expression.Lambda<Func<Type, object>>
(
Expression.New(serviceType),
Expression.Parameter(typeof(Type), "serviceType")
).Compile();
RegisterGServiceExecutor(requestType, serviceType, new TypeFactoryWrapper(handlerFactoryFn));
}
[Obsolete("obsolete ?")]
public void Register(Type requestType, Type serviceType, Func<Type, object> handlerFactoryFn)
{
RegisterGServiceExecutor(requestType, serviceType, new TypeFactoryWrapper(handlerFactoryFn));
}
[Obsolete("use obsolete api")]
public void RegisterGServiceExecutor(Type requestType, Type serviceType, ITypeFactory serviceFactoryFn)
{
var typeFactoryFn = CallServiceExecuteGeneric(requestType, serviceType);
ServiceExecFn handlerFn = (requestContext, dto) => {
var service = serviceFactoryFn.CreateInstance(serviceType);
var endpointAttrs = requestContext != null
? requestContext.EndpointAttributes
: EndpointAttributes.None;
ServiceExecFn serviceExec = (reqCtx, req) =>
typeFactoryFn(req, service, endpointAttrs);
return ManagedServiceExec(serviceExec, service, requestContext, dto);
};
AddToRequestExecMap(requestType, serviceType, handlerFn);
}
public void RegisterNServiceExecutor(Type requestType, Type serviceType, ITypeFactory serviceFactoryFn)
{
var serviceExecDef = typeof(NServiceRequestExec<,>).MakeGenericType(serviceType, requestType);
var iserviceExec = (INServiceExec)serviceExecDef.CreateInstance();
ServiceExecFn handlerFn = (requestContext, dto) => {
var service = serviceFactoryFn.CreateInstance(serviceType);
ServiceExecFn serviceExec = (reqCtx, req) =>
iserviceExec.Execute(reqCtx, service, req);
return ManagedServiceExec(serviceExec, service, requestContext, dto);
};
AddToRequestExecMap(requestType, serviceType, handlerFn);
}
private void AddToRequestExecMap(Type requestType, Type serviceType, ServiceExecFn handlerFn)
{
if (requestExecMap.ContainsKey(requestType))
{
throw new AmbiguousMatchException(
string.Format(
"Could not register Request '{0}' with service '{1}' as it has already been assigned to another service.\n"
+ "Each Request DTO can only be handled by 1 service.",
requestType.FullName, serviceType.FullName));
}
requestExecMap.Add(requestType, handlerFn);
var serviceAttrs = requestType.GetCustomAttributes(typeof(RestrictAttribute), false);
if (serviceAttrs.Length > 0)
{
requestServiceAttrs.Add(requestType, (RestrictAttribute)serviceAttrs[0]);
}
}
private static object ManagedServiceExec(
ServiceExecFn serviceExec,
object service, IRequestContext requestContext, object dto)
{
try
{
InjectRequestContext(service, requestContext);
try
{
//Executes the service and returns the result
var response = serviceExec(requestContext, dto);
return response;
}
finally
{
if (EndpointHost.AppHost != null)
{
//Gets disposed by AppHost or ContainerAdapter if set
EndpointHost.AppHost.Release(service);
}
else
{
using (service as IDisposable) { }
}
}
}
catch (TargetInvocationException tex)
{
//Mono invokes using reflection
throw tex.InnerException ?? tex;
}
}
private static void InjectRequestContext(object service, IRequestContext requestContext)
{
if (requestContext == null) return;
var serviceRequiresContext = service as IRequiresRequestContext;
if (serviceRequiresContext != null)
{
serviceRequiresContext.RequestContext = requestContext;
}
var servicesRequiresHttpRequest = service as IRequiresHttpRequest;
if (servicesRequiresHttpRequest != null)
servicesRequiresHttpRequest.HttpRequest = requestContext.Get<IHttpRequest>();
}
[Obsolete("use obsolete api ?")]
private static Func<object, object, EndpointAttributes, object> CallServiceExecuteGeneric(Type requestType, Type serviceType)
{
var mi = GServiceExec.GetExecMethodInfo(serviceType, requestType);
try
{
var requestDtoParam = Expression.Parameter(typeof(object), "requestDto");
var requestDtoStrong = Expression.Convert(requestDtoParam, requestType);
var serviceParam = Expression.Parameter(typeof(object), "serviceObj");
var serviceStrong = Expression.Convert(serviceParam, serviceType);
var attrsParam = Expression.Parameter(typeof(EndpointAttributes), "attrs");
Expression callExecute = Expression.Call(
mi, new Expression[] { serviceStrong, requestDtoStrong, attrsParam });
var executeFunc = Expression.Lambda<Func<object, object, EndpointAttributes, object>>
(callExecute, requestDtoParam, serviceParam, attrsParam).Compile();
return executeFunc;
}
catch (Exception)
{
//problems with MONO, using reflection for fallback
return (request, service, attrs) => mi.Invoke(null, new[] { service, request, attrs });
}
}
//Execute MQ
// public object ExecuteMessage<T>(IMessage<T> mqMessage)
// {
// return Execute(mqMessage.Body, new MqRequestContext(this.Resolver, mqMessage));
// }
//
// //Execute MQ with requestContext
// public object ExecuteMessage<T>(IMessage<T> dto, IRequestContext requestContext)
// {
// return Execute(dto.Body, requestContext);
// }
public object Execute(object request)
{
return Execute(request, null);
}
//Execute HTTP
public object Execute(object request, IRequestContext requestContext)
{
var requestType = request.GetType();
if (EnableAccessRestrictions)
{
AssertServiceRestrictions(requestType,
requestContext != null ? requestContext.EndpointAttributes : EndpointAttributes.None);
}
var handlerFn = GetService(requestType);
return handlerFn(requestContext, request);
}
public ServiceExecFn GetService(Type requestType)
{
ServiceExecFn handlerFn;
if (!requestExecMap.TryGetValue(requestType, out handlerFn))
{
throw new NotImplementedException(string.Format("Unable to resolve service '{0}'", requestType.Name));
}
return handlerFn;
}
public object ExecuteText(string requestXml, Type requestType, IRequestContext requestContext)
{
var request = DataContractDeserializer.Instance.Parse(requestXml, requestType);
var response = Execute(request, requestContext);
var responseXml = DataContractSerializer.Instance.Parse(response);
return responseXml;
}
public void AssertServiceRestrictions(Type requestType, EndpointAttributes actualAttributes)
{
if (EndpointHost.Config != null && !EndpointHost.Config.EnableAccessRestrictions) return;
RestrictAttribute restrictAttr;
var hasNoAccessRestrictions = !requestServiceAttrs.TryGetValue(requestType, out restrictAttr)
|| restrictAttr.HasNoAccessRestrictions;
if (hasNoAccessRestrictions)
{
return;
}
var failedScenarios = new StringBuilder();
foreach (var requiredScenario in restrictAttr.AccessibleToAny)
{
var allServiceRestrictionsMet = (requiredScenario & actualAttributes) == actualAttributes;
if (allServiceRestrictionsMet)
{
return;
}
var passed = requiredScenario & actualAttributes;
var failed = requiredScenario & ~(passed);
failedScenarios.AppendFormat("\n -[{0}]", failed);
}
var internalDebugMsg = (EndpointAttributes.InternalNetworkAccess & actualAttributes) != 0
? "\n Unauthorized call was made from: " + actualAttributes
: "";
throw new UnauthorizedAccessException(
string.Format("Could not execute service '{0}', The following restrictions were not met: '{1}'" + internalDebugMsg,
requestType.Name, failedScenarios));
}
}
}