public async Task <bool> InitAsync() { if (await ParseSubscriptionOptionsAsync() == false) { return(false); } if (_logger.IsInfoEnabled) { _logger.Info($"Subscription connection for subscription ID: {SubscriptionId} received from {TcpConnection.TcpClient.Client.RemoteEndPoint}"); } try { TcpConnection.DocumentDatabase.SubscriptionStorage.AssertSubscriptionIdExists(SubscriptionId); } catch (SubscriptionDoesNotExistException e) { if (_logger.IsInfoEnabled) { _logger.Info("Subscription does not exist", e); } await WriteJsonAsync(new DynamicJsonValue { ["Type"] = "CoonectionStatus", ["Status"] = "NotFound", ["FreeText"] = e.ToString() }); return(false); } _state = TcpConnection.DocumentDatabase.SubscriptionStorage.OpenSubscription(this); var timeout = 0; while (true) { try { DisposeOnDisconnect = await _state.RegisterSubscriptionConnection(this, timeout); await WriteJsonAsync(new DynamicJsonValue { ["Type"] = "CoonectionStatus", ["Status"] = "Accepted" }); Stats.ConnectedAt = DateTime.UtcNow; return(true); } catch (TimeoutException) { if (timeout == 0 && _logger.IsInfoEnabled) { _logger.Info( $"Subscription Id {SubscriptionId} from IP {TcpConnection.TcpClient.Client.RemoteEndPoint} starts to wait until previous connection from {_state.Connection.TcpConnection.TcpClient.Client.RemoteEndPoint} is released"); } timeout = Math.Max(250, _options.TimeToWaitBeforeConnectionRetryMilliseconds / 2); await SendHeartBeat(); } catch (SubscriptionInUseException) { if (timeout == 0 && _logger.IsInfoEnabled) { _logger.Info( $"Subscription Id {SubscriptionId} from IP {TcpConnection.TcpClient.Client.RemoteEndPoint} with connection strategy {Strategy} was rejected because previous connection from {_state.Connection.TcpConnection.TcpClient.Client.RemoteEndPoint} has stronger connection strategy ({_state.Connection.Strategy})"); } await WriteJsonAsync(new DynamicJsonValue { ["Type"] = "CoonectionStatus", ["Status"] = "InUse" }); return(false); } } }