private async Task ReceiveHandshakeResponseAsync()

in src/Microsoft.Azure.SignalR.Common/ServiceConnections/ServiceConnectionBase.cs [544:604]


    private async Task<bool> ReceiveHandshakeResponseAsync(PipeReader input, CancellationToken token)
    {
        while (true)
        {
            var result = await input.ReadAsync(token);

            var buffer = result.Buffer;
            var consumed = buffer.Start;
            var examined = buffer.End;

            try
            {
                if (result.IsCanceled)
                {
                    throw new InvalidOperationException("Connection cancelled before handshake complete.");
                }

                if (!buffer.IsEmpty)
                {
                    if (ServiceProtocol.TryParseMessage(ref buffer, out var message))
                    {
                        consumed = buffer.Start;
                        examined = consumed;

                        if (message is not HandshakeResponseMessage handshakeResponse)
                        {
                            throw new InvalidDataException(
                                $"{message.GetType().Name} received when waiting for handshake response.");
                        }

                        if (string.IsNullOrEmpty(handshakeResponse.ErrorMessage))
                        {
                            return true;
                        }

                        // Handshake error. Will stop reconnect.
                        if (_connectionType == ServiceConnectionType.OnDemand)
                        {
                            // Handshake errors on on-demand connections are acceptable.
                            Log.OnDemandConnectionHandshakeResponse(Logger, handshakeResponse.ErrorMessage);
                        }
                        else
                        {
                            Log.HandshakeError(Logger, _endpointName, handshakeResponse.ErrorMessage, ConnectionId);
                        }
                        return false;
                    }
                }

                if (result.IsCompleted)
                {
                    // Not enough data, and we won't be getting any more data.
                    throw new InvalidOperationException("Service disconnected before sending a handshake response.");
                }
            }
            finally
            {
                input.AdvanceTo(consumed, examined);
            }
        }
    }