-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathServer.cs
More file actions
315 lines (279 loc) · 11.8 KB
/
Server.cs
File metadata and controls
315 lines (279 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
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
using System.Linq.Expressions;
namespace UiPath.Ipc;
using GetTaskResultFunc = Func<Task, object>;
using MethodExecutor = Func<object, object?[], CancellationToken, Task>;
using static Expression;
using static CancellationTokenSourcePool;
internal class Server
{
static Server()
{
var prototype = GetTaskResultImpl<object>;
GetResultMethod = prototype.Method.GetGenericMethodDefinition();
}
private static readonly MethodInfo GetResultMethod;
private static readonly ConcurrentDictionary<MethodKey, Method> Methods = new();
private static readonly ConcurrentDictionary<Type, GetTaskResultFunc> GetTaskResultByType = new();
private readonly Router _router;
private readonly Connection _connection;
private readonly IClient? _client;
private readonly ConcurrentDictionary<string, PooledCancellationTokenSource> _requests = new();
private readonly TimeSpan? _requestTimeout;
private ILogger? Logger => _connection.Logger;
private bool LogEnabled => _connection.LogEnabled;
public string DebugName => _connection.DebugName;
public Server(Router router, TimeSpan? requestTimeout, Connection connection, IClient? client = null)
{
_router = router;
_requestTimeout = requestTimeout;
_connection = connection;
_client = client;
connection.RequestReceived += OnRequestReceived;
connection.CancellationReceived += CancelRequest;
connection.Closed += delegate
{
if (LogEnabled)
{
Log($"Server {DebugName} closed.");
}
foreach (var requestId in _requests.Keys)
{
try
{
CancelRequest(requestId);
}
catch (Exception ex)
{
Logger.OrDefault().LogException(ex, $"{DebugName}");
}
}
};
}
private void CancelRequest(string requestId)
{
if (_requests.TryRemove(requestId, out var cancellation))
{
cancellation.Cancel();
cancellation.Return();
}
}
#if !NET461
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))]
#endif
private async ValueTask OnRequestReceived(Request request)
{
try
{
if (LogEnabled)
{
Log($"{DebugName} received request {request}");
}
if (!_router.TryResolve(request.Endpoint, out var route))
{
await OnError(request, new EndpointNotFoundException(nameof(request.Endpoint), DebugName, request.Endpoint));
return;
}
var method = GetMethod(route.Service.Type, request.MethodName);
Response? response = null;
var requestCancellation = Rent();
_requests[request.Id] = requestCancellation;
var timeout = request.GetTimeout(_requestTimeout);
var timeoutHelper = new TimeoutHelper(timeout, requestCancellation.Token);
try
{
var token = timeoutHelper.Token;
response = await HandleRequest(method, route, request, token);
if (LogEnabled)
{
Log($"{DebugName} sending response for {request}");
}
await SendResponse(response, token);
}
catch (Exception ex) when (response is null)
{
try
{
ex = route.OnError?.Invoke(null, ex) ?? ex;
}
catch (Exception handlerEx)
{
ex = new AggregateException(
$"Error while handling error for {request}.",
ex, handlerEx);
}
await OnError(request, timeoutHelper.CheckTimeout(ex, request.MethodName));
}
finally
{
timeoutHelper.Dispose();
}
}
catch (Exception ex)
{
Logger.LogException(ex, $"{DebugName} {request}");
}
if (_requests.TryRemove(request.Id, out var cancellation))
{
cancellation.Return();
}
}
ValueTask OnError(Request request, Exception ex)
{
Logger.LogException(ex, $"{DebugName} {request}");
return SendResponse(Response.Fail(request, ex), default);
}
#if !NET461
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
#endif
private async ValueTask<Response> HandleRequest(Method method, Route route, Request request, CancellationToken cancellationToken)
{
var arguments = GetArguments();
object service;
using (route.Service.Get(out service))
{
return await InvokeMethod();
}
#if !NET461
[AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))]
#endif
async ValueTask<Response> InvokeMethod()
{
var returnTaskType = method.ReturnType;
var scheduler = route.Scheduler;
var defaultScheduler = scheduler == TaskScheduler.Default;
Debug.Assert(scheduler != null);
if (returnTaskType.IsGenericType)
{
var result = await ScheduleMethodCall();
return result switch
{
Stream downloadStream => Response.Success(request, downloadStream),
var x => Response.Success(request, IpcJsonSerializer.Instance.Serialize(x))
};
}
ScheduleMethodCall().LogException(Logger, method.MethodInfo);
return Response.Success(request, "");
Task<object?> ScheduleMethodCall() => defaultScheduler ? MethodCall() : RunOnScheduler();
async Task<object?> MethodCall()
{
await (route.BeforeCall?.Invoke(
new CallInfo(newConnection: false, method.MethodInfo, arguments),
cancellationToken) ?? Task.CompletedTask);
Task invocationTask = null!;
invocationTask = method.Invoke(service, arguments, cancellationToken);
await invocationTask;
if (!returnTaskType.IsGenericType)
{
return null;
}
return GetTaskResult(returnTaskType, invocationTask);
}
Task<object?> RunOnScheduler() => Task.Factory.StartNew(MethodCall, cancellationToken, TaskCreationOptions.DenyChildAttach, scheduler).Unwrap();
}
object?[] GetArguments()
{
var parameters = method.Parameters;
var allParametersLength = parameters.Length;
var requestParametersLength = request.Parameters.Length;
if (requestParametersLength > allParametersLength)
{
throw new ArgumentException("Too many parameters for " + method.MethodInfo);
}
var allArguments = new object?[allParametersLength];
Deserialize();
SetOptionalArguments();
return allArguments;
void Deserialize()
{
object? argument;
for (int index = 0; index < requestParametersLength; index++)
{
var parameterType = parameters[index].ParameterType;
if (parameterType == typeof(CancellationToken))
{
argument = null;
}
else if (parameterType == typeof(Stream))
{
argument = request.UploadStream;
}
else
{
argument = IpcJsonSerializer.Instance.Deserialize(request.Parameters[index], parameterType);
argument = CheckMessage(argument, parameterType);
}
allArguments[index] = argument;
}
}
object? CheckMessage(object? argument, Type parameterType)
{
if (parameterType == typeof(Message) && argument is null)
{
argument = new Message();
}
if (argument is Message message)
{
message.Client = _client!;
}
return argument;
}
void SetOptionalArguments()
{
for (int index = requestParametersLength; index < allParametersLength; index++)
{
allArguments[index] = CheckMessage(method.Defaults[index], parameters[index].ParameterType);
}
}
}
}
private void Log(string message) => Logger.OrDefault().LogInformation(message);
private ValueTask SendResponse(Response response, CancellationToken responseCancellation) => _connection.Send(response, responseCancellation);
private static object? GetTaskResultImpl<T>(Task task) => (task as Task<T>)!.Result;
private static object GetTaskResult(Type taskType, Task task)
=> GetTaskResultByType.GetOrAdd(
taskType.GenericTypeArguments[0],
GetResultMethod.MakeGenericDelegate<GetTaskResultFunc>)(task);
private static Method GetMethod(Type contract, string methodName)
=> Methods.GetOrAdd(new(contract, methodName), Method.FromKey);
private readonly record struct MethodKey(Type Contract, string MethodName);
private readonly struct Method
{
public static Method FromKey(MethodKey key)
{
var methodInfo = key.Contract.GetInterfaceMethod(key.MethodName);
return new(methodInfo);
}
private static readonly ParameterExpression TargetParameter = Parameter(typeof(object), "target");
private static readonly ParameterExpression TokenParameter = Parameter(typeof(CancellationToken), "cancellationToken");
private static readonly ParameterExpression ParametersParameter = Parameter(typeof(object[]), "parameters");
private readonly MethodExecutor _executor;
public readonly MethodInfo MethodInfo;
public readonly ParameterInfo[] Parameters;
public readonly object?[] Defaults;
public Type ReturnType => MethodInfo.ReturnType;
private Method(MethodInfo method)
{
// https://github.com/dotnet/aspnetcore/blob/3f620310883092905ed6f13d784c908b5f4a9d7e/src/Shared/ObjectMethodExecutor/ObjectMethodExecutor.cs#L156
var parameters = method.GetParameters();
var parametersLength = parameters.Length;
var callParameters = new Expression[parametersLength];
var defaults = new object?[parametersLength];
for (int index = 0; index < parametersLength; index++)
{
var parameter = parameters[index];
defaults[index] = parameter.GetDefaultValue();
callParameters[index] = parameter.ParameterType == typeof(CancellationToken) ? TokenParameter :
Convert(ArrayIndex(ParametersParameter, Constant(index, typeof(int))), parameter.ParameterType);
}
var instanceCast = Convert(TargetParameter, method.DeclaringType!);
var methodCall = Call(instanceCast, method, callParameters);
var lambda = Lambda<MethodExecutor>(methodCall, TargetParameter, ParametersParameter, TokenParameter);
_executor = lambda.Compile();
MethodInfo = method;
Parameters = parameters;
Defaults = defaults;
}
public Task Invoke(object service, object?[] arguments, CancellationToken cancellationToken) => _executor.Invoke(service, arguments, cancellationToken);
public override string ToString() => MethodInfo.ToString()!;
}
}