public TransportInitializationHandler(IHttpClient httpClient, IConnection connection, string connectionData, string transport, CancellationToken disconnectToken) { if (connection == null) { throw new ArgumentNullException("connection"); } _connection = connection; _httpClient = httpClient; _connectionData = connectionData; _transport = transport; _initializationTask = new TaskCompletionSource<object>(); _initializationInvoker = new ThreadSafeInvoker(); // Default event OnFailure = () => { }; // We want to fail if the disconnect token is tripped while we're waiting on initialization _tokenCleanup = disconnectToken.SafeRegister(_ => { Fail(); }, state: null); TaskAsyncHelper.Delay(connection.TotalTransportConnectTimeout).Then(() => { Fail(new TimeoutException(Resources.Error_TransportTimedOutTryingToConnect)); }); }
private static void InitializeResolverDispose(this IDependencyResolver resolver, CancellationToken hostShutdownToken) { // TODO: Guard against multiple calls to this // When the host triggers the shutdown token, dispose the resolver hostShutdownToken.SafeRegister(state => { ((IDependencyResolver)state).Dispose(); }, resolver); }
protected override void OnStart(IConnection connection, string connectionData, CancellationToken disconnectToken) { _disconnectRegistration = disconnectToken.SafeRegister(state => { // _reconnectInvoker can be null if disconnectToken is tripped before the polling loop is started if (_reconnectInvoker != null) { _reconnectInvoker.Invoke(); } StopPolling(); }, null); StartPolling(connection, connectionData); }
public TransportInitializationHandler(TimeSpan failureTimeout, CancellationToken disconnectToken) { _initializationTask = new TaskCompletionSource<object>(); _initializationInvoker = new ThreadSafeInvoker(); // Default event OnFailure = () => { }; // We want to fail if the disconnect token is tripped while we're waiting on initialization _tokenCleanup = disconnectToken.SafeRegister(_ => { Fail(); }, state: null); TaskAsyncHelper.Delay(failureTimeout).Then(() => { Fail(new TimeoutException(Resources.Error_TransportTimedOutTryingToConnect)); }); }
public TransportInitializationHandler(IHttpClient httpClient, IConnection connection, string connectionData, string transport, CancellationToken disconnectToken, TransportHelper transportHelper) { if (connection == null) { throw new ArgumentNullException("connection"); } _connection = connection; _httpClient = httpClient; _connectionData = connectionData; _transport = transport; _transportHelper = transportHelper; _initializationTask = new TaskCompletionSource<object>(); _initializationInvoker = new ThreadSafeInvoker(); // Default event OnFailure = () => { }; // We want to fail if the disconnect token is tripped while we're waiting on initialization _tokenCleanup = disconnectToken.SafeRegister( _ => Fail(new OperationCanceledException(Resources.Error_ConnectionCancelled, disconnectToken)), state: null); TaskAsyncHelper.Delay(connection.TotalTransportConnectTimeout) .Then(() => { // don't timeout once connect request has finished if (Interlocked.CompareExchange(ref _state, InitializationState.Failed, InitializationState.Initial) == InitializationState.Initial) { Fail(new TimeoutException(Resources.Error_TransportTimedOutTryingToConnect)); } }); }
private void OpenConnection(IConnection connection, string data, CancellationToken disconnectToken, Action initializeCallback, Action<Exception> errorCallback) { // If we're reconnecting add /connect to the url bool reconnecting = initializeCallback == null; var callbackInvoker = new ThreadSafeInvoker(); var requestDisposer = new Disposer(); var url = (reconnecting ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data); connection.Trace(TraceLevels.Events, "SSE: GET {0}", url); HttpClient.Get(url, req => { _request = req; connection.PrepareRequest(_request); _request.Accept = "text/event-stream"; }).ContinueWith(task => { if (task.IsFaulted) { Exception exception = task.Exception.Unwrap(); if (!ExceptionHelper.IsRequestAborted(exception)) { if (errorCallback != null) { callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception); } else if (reconnecting) { // Only raise the error event if we failed to reconnect connection.OnError(exception); Reconnect(connection, data, disconnectToken); } } requestDisposer.Dispose(); } else { var response = task.Result; Stream stream = response.GetStream(); var eventSource = new EventSourceStreamReader(connection, stream); bool retry = true; var esCancellationRegistration = disconnectToken.SafeRegister(state => { retry = false; ((IRequest)state).Abort(); }, _request); eventSource.Opened = () => { // If we're not reconnecting, then we're starting the transport for the first time. Trigger callback only on first start. if (!reconnecting) { callbackInvoker.Invoke(initializeCallback); } else if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected)) { // Raise the reconnect event if the connection comes back up connection.OnReconnected(); } }; eventSource.Message = sseEvent => { if (sseEvent.EventType == EventType.Data) { if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase)) { return; } bool timedOut; bool disconnected; TransportHelper.ProcessResponse(connection, sseEvent.Data, out timedOut, out disconnected); if (disconnected) { retry = false; connection.Disconnect(); } } }; eventSource.Closed = exception => { if (exception != null) { // Check if the request is aborted bool isRequestAborted = ExceptionHelper.IsRequestAborted(exception); if (!isRequestAborted) { // Don't raise exceptions if the request was aborted (connection was stopped). connection.OnError(exception); } } requestDisposer.Dispose(); esCancellationRegistration.Dispose(); response.Dispose(); if (AbortResetEvent != null) { AbortResetEvent.Set(); } else if (retry) { Reconnect(connection, data, disconnectToken); } }; eventSource.Start(); } }); var requestCancellationRegistration = disconnectToken.SafeRegister(state => { if (state != null) { // This will no-op if the request is already finished. ((IRequest)state).Abort(); } if (errorCallback != null) { callbackInvoker.Invoke((cb, token) => { #if NET35 || WINDOWS_PHONE cb(new OperationCanceledException(Resources.Error_ConnectionCancelled)); #else cb(new OperationCanceledException(Resources.Error_ConnectionCancelled, token)); #endif }, errorCallback, disconnectToken); } }, _request); requestDisposer.Set(requestCancellationRegistration); if (errorCallback != null) { TaskAsyncHelper.Delay(ConnectionTimeout).Then(() => { callbackInvoker.Invoke((conn, cb) => { // Abort the request before cancelling _request.Abort(); // Connection timeout occurred cb(new TimeoutException()); }, connection, errorCallback); }); } }
internal void OpenConnection(IConnection connection, string data, CancellationToken disconnectToken, bool reconnecting) { // If we're reconnecting add /connect to the url var url = reconnecting ? UrlBuilder.BuildReconnect(connection, Name, data) : UrlBuilder.BuildConnect(connection, Name, data); connection.Trace(TraceLevels.Events, "SSE: GET {0}", url); var getTask = HttpClient.Get(url, req => { _request = req; _request.Accept = "text/event-stream"; connection.PrepareRequest(_request); }, isLongRunning: true); var requestCancellationRegistration = disconnectToken.SafeRegister(state => { _stop = true; // This will no-op if the request is already finished. ((IRequest)state).Abort(); }, _request); getTask.ContinueWith(task => { if (task.IsFaulted || task.IsCanceled) { var exception = task.IsCanceled ? new OperationCanceledException(Resources.Error_TaskCancelledException) : task.Exception.Unwrap(); if (!reconnecting) { TransportFailed(exception); } else if (!_stop) { // Only raise the error event if we failed to reconnect connection.OnError(exception); Reconnect(connection, data, disconnectToken); } requestCancellationRegistration.Dispose(); } else { // If the disconnect token is canceled the response to the task doesn't matter. if (disconnectToken.IsCancellationRequested) { return; } var response = task.Result; Stream stream = response.GetStream(); var eventSource = new EventSourceStreamReader(connection, stream); eventSource.Opened = () => { // This will noop if we're not in the reconnecting state if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected)) { // Raise the reconnect event if the connection comes back up connection.OnReconnected(); } }; eventSource.Message = sseEvent => { if (sseEvent.EventType == EventType.Data && !sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase)) { ProcessResponse(connection, sseEvent.Data); } }; eventSource.Closed = exception => { if (exception != null) { // Check if the request is aborted if (!ExceptionHelper.IsRequestAborted(exception)) { // Don't raise exceptions if the request was aborted (connection was stopped). connection.OnError(exception); } } requestCancellationRegistration.Dispose(); response.Dispose(); if (_stop) { AbortHandler.CompleteAbort(); } else if (AbortHandler.TryCompleteAbort()) { // Abort() was called, so don't reconnect } else { Reconnect(connection, data, disconnectToken); } }; eventSource.Start(); } }); }
protected virtual Task InitializePersistentState() { _hostShutdownToken = _context.Environment.GetShutdownToken(); _requestLifeTime = new HttpRequestLifeTime(this, WriteQueue, Trace, ConnectionId); // Create the TCS that completes when the task returned by PersistentConnection.OnConnected does. _connectTcs = new TaskCompletionSource<object>(); // Create a token that represents the end of this connection's life _connectionEndTokenSource = new SafeCancellationTokenSource(); _connectionEndToken = _connectionEndTokenSource.Token; // Handle the shutdown token's callback so we can end our token if it trips _hostRegistration = _hostShutdownToken.SafeRegister(state => { ((SafeCancellationTokenSource)state).Cancel(); }, _connectionEndTokenSource); // When the connection ends release the request _connectionEndRegistration = CancellationToken.SafeRegister(state => { ((HttpRequestLifeTime)state).Complete(); }, _requestLifeTime); return InitializeMessageId(); }
private void PollingLoop(IConnection connection, string data, CancellationToken disconnectToken, Action initializeCallback, Action<Exception> errorCallback, bool raiseReconnect = false) { string url = connection.Url; IRequest request = null; var reconnectInvoker = new ThreadSafeInvoker(); var callbackInvoker = new ThreadSafeInvoker(); var requestDisposer = new Disposer(); if (connection.MessageId == null) { url += "connect"; } else if (raiseReconnect) { url += "reconnect"; // FIX: Race if the connection is stopped and completely restarted between checking the token and calling // connection.EnsureReconnecting() if (disconnectToken.IsCancellationRequested || !connection.EnsureReconnecting()) { return; } } url += GetReceiveQueryString(connection, data); #if NET35 Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "LP: {0}", (object)url)); #else Debug.WriteLine("LP: {0}", (object)url); #endif HttpClient.Post(url, req => { request = req; connection.PrepareRequest(request); }).ContinueWith(task => { bool shouldRaiseReconnect = false; bool disconnectedReceived = false; try { if (!task.IsFaulted) { if (raiseReconnect) { // If the timeout for the reconnect hasn't fired as yet just fire the // event here before any incoming messages are processed reconnectInvoker.Invoke((conn) => FireReconnected(conn), connection); } if (initializeCallback != null) { // If the timeout for connect hasn't fired as yet then just fire // the event before any incoming messages are processed callbackInvoker.Invoke(initializeCallback); } // Get the response var raw = task.Result.ReadAsString(); #if NET35 Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "LP Receive: {0}", (object)raw)); #else Debug.WriteLine("LP Receive: {0}", (object)raw); #endif TransportHelper.ProcessResponse(connection, raw, out shouldRaiseReconnect, out disconnectedReceived); } } finally { if (disconnectedReceived) { connection.Disconnect(); } else { bool requestAborted = false; if (task.IsFaulted) { reconnectInvoker.Invoke(); // Raise the reconnect event if we successfully reconnect after failing shouldRaiseReconnect = true; // Get the underlying exception Exception exception = task.Exception.Unwrap(); // If the error callback isn't null then raise it and don't continue polling if (errorCallback != null) { callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception); } else { // Figure out if the request was aborted requestAborted = ExceptionHelper.IsRequestAborted(exception); // Sometimes a connection might have been closed by the server before we get to write anything // so just try again and don't raise OnError. if (!requestAborted && !(exception is IOException)) { // Raise on error connection.OnError(exception); // If the connection is still active after raising the error event wait for 2 seconds // before polling again so we aren't hammering the server TaskAsyncHelper.Delay(ErrorDelay).Then(() => { if (!disconnectToken.IsCancellationRequested) { PollingLoop(connection, data, disconnectToken, initializeCallback: null, errorCallback: null, raiseReconnect: shouldRaiseReconnect); } }); } } } else { if (!disconnectToken.IsCancellationRequested) { // Continue polling if there was no error PollingLoop(connection, data, disconnectToken, initializeCallback: null, errorCallback: null, raiseReconnect: shouldRaiseReconnect); } } } requestDisposer.Dispose(); } }); var requestCancellationRegistration = disconnectToken.SafeRegister(req => { if (req != null) { // This will no-op if the request is already finished. req.Abort(); } // Prevent the connection state from switching to the reconnected state. reconnectInvoker.Invoke(); if (errorCallback != null) { callbackInvoker.Invoke((cb, token) => { #if NET35 || WINDOWS_PHONE cb(new OperationCanceledException(Resources.Error_ConnectionCancelled)); #else cb(new OperationCanceledException(Resources.Error_ConnectionCancelled, token)); #endif }, errorCallback, disconnectToken); } }, request); requestDisposer.Set(requestCancellationRegistration); if (initializeCallback != null) { TaskAsyncHelper.Delay(ConnectDelay).Then(() => { callbackInvoker.Invoke(initializeCallback); }); } if (raiseReconnect) { TaskAsyncHelper.Delay(ReconnectDelay).Then(() => { // Fire the reconnect event after the delay. This gives the reconnectInvoker.Invoke((conn) => FireReconnected(conn), connection); }); } }
private void OpenConnection(IConnection connection, string data, CancellationToken disconnectToken, Action initializeCallback, Action<Exception> errorCallback) { // If we're reconnecting add /connect to the url bool reconnecting = initializeCallback == null; var callbackInvoker = new ThreadSafeInvoker(); var requestDisposer = new Disposer(); var url = (reconnecting ? connection.Url : connection.Url + "connect") + GetReceiveQueryString(connection, data); IRequest request = null; #if NET35 Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "SSE: GET {0}", (object)url)); #else Debug.WriteLine("SSE: GET {0}", (object)url); #endif HttpClient.Get(url, req => { request = req; connection.PrepareRequest(request); request.Accept = "text/event-stream"; }).ContinueWith(task => { if (task.IsFaulted) { Exception exception = task.Exception.Unwrap(); if (!ExceptionHelper.IsRequestAborted(exception)) { if (errorCallback != null) { callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception); } else if (reconnecting) { // Only raise the error event if we failed to reconnect connection.OnError(exception); Reconnect(connection, data, disconnectToken); } } requestDisposer.Dispose(); } else { IResponse response = task.Result; Stream stream = response.GetResponseStream(); var eventSource = new EventSourceStreamReader(stream); bool retry = true; var esCancellationRegistration = disconnectToken.SafeRegister(es => { retry = false; es.Close(); }, eventSource); eventSource.Opened = () => { if (!reconnecting) { callbackInvoker.Invoke(initializeCallback); } else if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected)) { // Raise the reconnect event if the connection comes back up connection.OnReconnected(); } }; eventSource.Message = sseEvent => { if (sseEvent.EventType == EventType.Data) { if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase)) { return; } bool timedOut; bool disconnected; TransportHelper.ProcessResponse(connection, sseEvent.Data, out timedOut, out disconnected); if (disconnected) { retry = false; connection.Disconnect(); } } }; eventSource.Closed = exception => { bool isRequestAborted = false; if (exception != null) { // Check if the request is aborted isRequestAborted = ExceptionHelper.IsRequestAborted(exception); if (!isRequestAborted) { // Don't raise exceptions if the request was aborted (connection was stopped). connection.OnError(exception); } } // Skip reconnect attempt for aborted requests if (!isRequestAborted && retry) { Reconnect(connection, data, disconnectToken); } }; // See http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.close.aspx eventSource.Disabled = () => { requestDisposer.Dispose(); esCancellationRegistration.Dispose(); response.Close(); }; eventSource.Start(); } }); var requestCancellationRegistration = disconnectToken.SafeRegister(req => { if (req != null) { // This will no-op if the request is already finished. req.Abort(); } if (errorCallback != null) { callbackInvoker.Invoke((cb, token) => { #if NET35 || WINDOWS_PHONE cb(new OperationCanceledException(Resources.Error_ConnectionCancelled)); #else cb(new OperationCanceledException(Resources.Error_ConnectionCancelled, token)); #endif }, errorCallback, disconnectToken); } }, request); requestDisposer.Set(requestCancellationRegistration); if (errorCallback != null) { TaskAsyncHelper.Delay(ConnectionTimeout).Then(() => { callbackInvoker.Invoke((conn, cb) => { // Abort the request before cancelling request.Abort(); // Connection timeout occurred cb(new TimeoutException()); }, connection, errorCallback); }); } }
protected virtual void InitializePersistentState() { _hostShutdownToken = _context.HostShutdownToken(); Completed = new TaskCompletionSource<object>(); // Create a token that represents the end of this connection's life _connectionEndTokenSource = new SafeCancellationTokenSource(); _connectionEndToken = _connectionEndTokenSource.Token; // Handle the shutdown token's callback so we can end our token if it trips _hostRegistration = _hostShutdownToken.SafeRegister(state => { state.Cancel(); }, _connectionEndTokenSource); }
private void OpenConnection(IConnection connection, string data, CancellationToken disconnectToken, Action initializeCallback, Action<Exception> errorCallback) { // If we're reconnecting add /connect to the url bool reconnecting = initializeCallback == null; var callbackInvoker = new ThreadSafeInvoker(); var requestDisposer = new Disposer(); Action initializeInvoke = () => { callbackInvoker.Invoke(initializeCallback); }; var url = connection.Url + (reconnecting ? "reconnect" : "connect") + GetReceiveQueryString(connection, data); connection.Trace(TraceLevels.Events, "SSE: GET {0}", url); HttpClient.Get(url, req => { _request = req; _request.Accept = "text/event-stream"; connection.PrepareRequest(_request); }, isLongRunning: true).ContinueWith(task => { if (task.IsFaulted || task.IsCanceled) { Exception exception; if (task.IsCanceled) { exception = new OperationCanceledException(Resources.Error_TaskCancelledException); } else { exception = task.Exception.Unwrap(); } if (errorCallback != null) { callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception); } else if (!_stop && reconnecting) { // Only raise the error event if we failed to reconnect connection.OnError(exception); Reconnect(connection, data, disconnectToken); } requestDisposer.Dispose(); } else { // If the disconnect token is canceled the response to the task doesn't matter. if (disconnectToken.IsCancellationRequested) { return; } var response = task.Result; Stream stream = response.GetStream(); var eventSource = new EventSourceStreamReader(connection, stream); var esCancellationRegistration = disconnectToken.SafeRegister(state => { _stop = true; ((IRequest)state).Abort(); }, _request); eventSource.Opened = () => { // This will noop if we're not in the reconnecting state if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected)) { // Raise the reconnect event if the connection comes back up connection.OnReconnected(); } }; eventSource.Message = sseEvent => { if (sseEvent.EventType == EventType.Data) { if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase)) { return; } bool shouldReconnect; bool disconnected; TransportHelper.ProcessResponse(connection, sseEvent.Data, out shouldReconnect, out disconnected, initializeInvoke); if (disconnected) { _stop = true; connection.Disconnect(); } } }; eventSource.Closed = exception => { if (exception != null) { // Check if the request is aborted bool isRequestAborted = ExceptionHelper.IsRequestAborted(exception); if (!isRequestAborted) { // Don't raise exceptions if the request was aborted (connection was stopped). connection.OnError(exception); } } requestDisposer.Dispose(); esCancellationRegistration.Dispose(); response.Dispose(); if (_stop) { AbortHandler.CompleteAbort(); } else if (AbortHandler.TryCompleteAbort()) { // Abort() was called, so don't reconnect } else { Reconnect(connection, data, disconnectToken); } }; eventSource.Start(); } }); var requestCancellationRegistration = disconnectToken.SafeRegister(state => { if (state != null) { // This will no-op if the request is already finished. ((IRequest)state).Abort(); } if (errorCallback != null) { callbackInvoker.Invoke((cb, token) => { #if !NET35 cb(new OperationCanceledException(Resources.Error_ConnectionCancelled, token)); #else cb(new OperationCanceledException(Resources.Error_ConnectionCancelled)); #endif }, errorCallback, disconnectToken); } }, _request); requestDisposer.Set(requestCancellationRegistration); }
private void PollingSetup(IConnection connection, string data, CancellationToken disconnectToken, PollingRequestHandler requestHandler, Action onInitialized) { // reconnectInvoker is created new on each poll var reconnectInvoker = new ThreadSafeInvoker(); var disconnectRegistration = disconnectToken.SafeRegister(state => { reconnectInvoker.Invoke(); requestHandler.Stop(); }, null); requestHandler.ResolveUrl = () => { var url = connection.Url; if (connection.MessageId == null) { url += "connect"; connection.Trace(TraceLevels.Events, "LP Connect: {0}", url); } else if (IsReconnecting(connection)) { url += "reconnect"; connection.Trace(TraceLevels.Events, "LP Reconnect: {0}", url); } else { url += "poll"; connection.Trace(TraceLevels.Events, "LP Poll: {0}", url); } url += GetReceiveQueryString(connection, data); return url; }; requestHandler.PrepareRequest += req => { connection.PrepareRequest(req); }; requestHandler.OnMessage += message => { var shouldReconnect = false; var disconnectedReceived = false; connection.Trace(TraceLevels.Messages, "LP: OnMessage({0})", message); TransportHelper.ProcessResponse(connection, message, out shouldReconnect, out disconnectedReceived, onInitialized); if (IsReconnecting(connection)) { // If the timeout for the reconnect hasn't fired as yet just fire the // event here before any incoming messages are processed TryReconnect(connection, reconnectInvoker); } if (shouldReconnect) { // Transition into reconnecting state connection.EnsureReconnecting(); } if (disconnectedReceived) { connection.Disconnect(); } }; requestHandler.OnError += exception => { reconnectInvoker.Invoke(); // Transition into reconnecting state connection.EnsureReconnecting(); // Sometimes a connection might have been closed by the server before we get to write anything // so just try again and raise OnError. if (!ExceptionHelper.IsRequestAborted(exception) && !(exception is IOException)) { connection.OnError(exception); } else { requestHandler.Stop(); } }; requestHandler.OnPolling += () => { // Capture the cleanup within a closure so it can persist through multiple requests TryDelayedReconnect(connection, reconnectInvoker); }; requestHandler.OnAfterPoll = exception => { if (AbortHandler.TryCompleteAbort()) { // Abort() was called, so don't reconnect requestHandler.Stop(); } else { reconnectInvoker = new ThreadSafeInvoker(); if (exception != null) { // Delay polling by the error delay return TaskAsyncHelper.Delay(ErrorDelay); } } return TaskAsyncHelper.Empty; }; requestHandler.OnAbort += _ => { disconnectRegistration.Dispose(); // Complete any ongoing calls to Abort() // If someone calls Abort() later, have it no-op AbortHandler.CompleteAbort(); }; }
protected virtual void InitializePersistentState() { _hostShutdownToken = _context.HostShutdownToken(); _requestLifeTime = new HttpRequestLifeTime(WriteQueue, Trace, ConnectionId); // Create a token that represents the end of this connection's life _connectionEndTokenSource = new SafeCancellationTokenSource(); _connectionEndToken = _connectionEndTokenSource.Token; // Handle the shutdown token's callback so we can end our token if it trips _hostRegistration = _hostShutdownToken.SafeRegister(state => { ((SafeCancellationTokenSource)state).Cancel(); }, _connectionEndTokenSource); // When the connection ends release the request _connectionEndRegistration = CancellationToken.SafeRegister(state => { ((HttpRequestLifeTime)state).Complete(); }, _requestLifeTime); }