/
ForeverTransport.cs
381 lines (312 loc) · 13.8 KB
/
ForeverTransport.cs
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
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Infrastructure;
namespace Microsoft.AspNet.SignalR.Transports
{
public abstract class ForeverTransport : TransportDisconnectBase, ITransport
{
private readonly IPerformanceCounterManager _counters;
private IJsonSerializer _jsonSerializer;
private string _lastMessageId;
private const int MaxMessages = 10;
protected ForeverTransport(HostContext context, IDependencyResolver resolver)
: this(context,
resolver.Resolve<IJsonSerializer>(),
resolver.Resolve<ITransportHeartbeat>(),
resolver.Resolve<IPerformanceCounterManager>(),
resolver.Resolve<ITraceManager>())
{
}
protected ForeverTransport(HostContext context,
IJsonSerializer jsonSerializer,
ITransportHeartbeat heartbeat,
IPerformanceCounterManager performanceCounterWriter,
ITraceManager traceManager)
: base(context, jsonSerializer, heartbeat, performanceCounterWriter, traceManager)
{
_jsonSerializer = jsonSerializer;
_counters = performanceCounterWriter;
}
protected string LastMessageId
{
get
{
if (_lastMessageId == null)
{
_lastMessageId = Context.Request.QueryString["messageId"];
}
return _lastMessageId;
}
}
protected IJsonSerializer JsonSerializer
{
get { return _jsonSerializer; }
}
protected TaskCompletionSource<object> InitializeTcs { get; set; }
protected virtual void OnSending(string payload)
{
Heartbeat.MarkConnection(this);
}
protected virtual void OnSendingResponse(PersistentResponse response)
{
Heartbeat.MarkConnection(this);
}
public Func<string, Task> Received { get; set; }
public Func<Task> TransportConnected { get; set; }
public Func<Task> Connected { get; set; }
public Func<Task> Reconnected { get; set; }
// Unit testing hooks
internal Action AfterReceive;
internal Action BeforeCancellationTokenCallbackRegistered;
internal Action BeforeReceive;
internal Action AfterRequestEnd;
protected override void InitializePersistentState()
{
// PersistentConnection.OnConnectedAsync must complete before we can write to the output stream,
// so clients don't indicate the connection has started too early.
InitializeTcs = new TaskCompletionSource<object>();
WriteQueue = new TaskQueue(InitializeTcs.Task);
base.InitializePersistentState();
}
protected Task ProcessRequestCore(ITransportConnection connection)
{
Connection = connection;
if (Context.Request.Url.LocalPath.EndsWith("/send", StringComparison.OrdinalIgnoreCase))
{
return ProcessSendRequest();
}
else if (IsAbortRequest)
{
return Connection.Abort(ConnectionId);
}
else
{
InitializePersistentState();
if (IsConnectRequest)
{
if (Connected != null)
{
// Return a task that completes when the connected event task & the receive loop task are both finished
bool newConnection = Heartbeat.AddConnection(this);
// The connected callback
Func<Task> connected = () =>
{
if (newConnection)
{
return Connected().Then(() => _counters.ConnectionsConnected.Increment());
}
return TaskAsyncHelper.Empty;
};
return TaskAsyncHelper.Interleave(ProcessReceiveRequestWithoutTracking, connected, connection, Completed);
}
return ProcessReceiveRequest(connection);
}
if (Reconnected != null)
{
// Return a task that completes when the reconnected event task & the receive loop task are both finished
Func<Task> reconnected = () => Reconnected().Then(() => _counters.ConnectionsReconnected.Increment());
return TaskAsyncHelper.Interleave(ProcessReceiveRequest, reconnected, connection, Completed);
}
return ProcessReceiveRequest(connection);
}
}
public virtual Task ProcessRequest(ITransportConnection connection)
{
return ProcessRequestCore(connection);
}
public abstract Task Send(PersistentResponse response);
public virtual Task Send(object value)
{
Context.Response.ContentType = Json.MimeType;
return EnqueueOperation(() =>
{
JsonSerializer.Serialize(value, OutputWriter);
OutputWriter.Flush();
return Context.Response.EndAsync().Catch(IncrementErrorCounters);
});
}
protected virtual Task InitializeResponse(ITransportConnection connection)
{
return TaskAsyncHelper.Empty;
}
protected internal override Task EnqueueOperation(Func<Task> writeAsync)
{
Task task = base.EnqueueOperation(writeAsync);
// If PersistentConnection.OnConnectedAsync has not completed (as indicated by InitializeTcs),
// the queue will be blocked to prevent clients from prematurely indicating the connection has
// started, but we must keep receive loop running to continue processing commands and to
// prevent deadlocks caused by waiting on ACKs.
if (InitializeTcs == null || InitializeTcs.Task.IsCompleted)
{
return task;
}
return TaskAsyncHelper.Empty;
}
protected void IncrementErrorCounters(Exception exception)
{
_counters.ErrorsTransportTotal.Increment();
_counters.ErrorsTransportPerSec.Increment();
_counters.ErrorsAllTotal.Increment();
_counters.ErrorsAllPerSec.Increment();
}
private Task ProcessSendRequest()
{
string data = Context.Request.Form["data"];
if (Received != null)
{
return Received(data);
}
return TaskAsyncHelper.Empty;
}
private Task ProcessReceiveRequest(ITransportConnection connection, Func<Task> postReceive = null)
{
Heartbeat.AddConnection(this);
return ProcessReceiveRequestWithoutTracking(connection, postReceive);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions are flowed to the caller.")]
private Task ProcessReceiveRequestWithoutTracking(ITransportConnection connection, Func<Task> postReceive = null)
{
Func<Task> afterReceive = () =>
{
return TaskAsyncHelper.Series(OnTransportConnected,
() =>
{
if (postReceive != null)
{
return postReceive();
}
return TaskAsyncHelper.Empty;
},
() => InitializeResponse(connection));
};
return ProcessMessages(connection, afterReceive);
}
private Task OnTransportConnected()
{
if (TransportConnected != null)
{
return TransportConnected().Catch(_counters.ErrorsAllTotal, _counters.ErrorsAllPerSec);
}
return TaskAsyncHelper.Empty;
}
private Task ProcessMessages(ITransportConnection connection, Func<Task> postReceive)
{
var tcs = new TaskCompletionSource<object>();
Action<Exception> endRequest = (ex) =>
{
Trace.TraceInformation("DrainWrites(" + ConnectionId + ")");
// Drain the task queue for pending write operations so we don't end the request and then try to write
// to a corrupted request object.
WriteQueue.Drain().Catch().ContinueWith(task =>
{
if (ex != null)
{
tcs.TrySetUnwrappedException(ex);
}
else
{
tcs.TrySetResult(null);
}
CompleteRequest();
Trace.TraceInformation("EndRequest(" + ConnectionId + ")");
},
TaskContinuationOptions.ExecuteSynchronously);
if (AfterRequestEnd != null)
{
AfterRequestEnd();
}
};
ProcessMessages(connection, postReceive, endRequest);
return tcs.Task;
}
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "This will be cleaned up later.")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions are flowed to the caller.")]
private void ProcessMessages(ITransportConnection connection, Func<Task> postReceive, Action<Exception> endRequest)
{
IDisposable subscription = null;
IDisposable registration = null;
if (BeforeReceive != null)
{
BeforeReceive();
}
try
{
subscription = connection.Receive(LastMessageId, response =>
{
response.TimedOut = IsTimedOut;
// If we're telling the client to disconnect then clean up the instantiated connection.
if (response.Disconnect)
{
// Send the response before removing any connection data
return Send(response).Then(() =>
{
registration.Dispose();
// Remove connection without triggering disconnect
Heartbeat.RemoveConnection(this);
endRequest(null);
return TaskAsyncHelper.False;
});
}
else if (response.TimedOut ||
response.Aborted ||
ConnectionEndToken.IsCancellationRequested)
{
// If this is null it's because the cancellation token tripped
// before we setup the registration at all.
if (registration != null)
{
registration.Dispose();
}
if (response.Aborted)
{
// If this was a clean disconnect raise the event.
OnDisconnect();
}
endRequest(null);
return TaskAsyncHelper.False;
}
else
{
return Send(response).Then(() => TaskAsyncHelper.True)
.Catch(IncrementErrorCounters)
.Catch(ex =>
{
Trace.TraceInformation("Send failed for {0} with: {1}", ConnectionId, ex.GetBaseException());
});
}
},
MaxMessages);
}
catch (Exception ex)
{
endRequest(ex);
return;
}
if (AfterReceive != null)
{
AfterReceive();
}
postReceive().Catch(_counters.ErrorsAllTotal, _counters.ErrorsAllPerSec)
.Catch(ex => endRequest(ex))
.Catch(ex =>
{
Trace.TraceInformation("Failed post receive for {0} with: {1}", ConnectionId, ex.GetBaseException());
})
.ContinueWith(InitializeTcs);
if (BeforeCancellationTokenCallbackRegistered != null)
{
BeforeCancellationTokenCallbackRegistered();
}
// This has to be done last incase it runs synchronously.
registration = ConnectionEndToken.SafeRegister(state =>
{
Trace.TraceInformation("Cancel(" + ConnectionId + ")");
state.Dispose();
},
subscription);
}
}
}