Skip to content

Backport Blazor Server Add Console Warning if Long Polling (#36764) #36886

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Components/Web.JS/dist/Release/blazor.server.js

Large diffs are not rendered by default.

18 changes: 17 additions & 1 deletion src/Components/Web.JS/src/Boot.Server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DotNet } from '@microsoft/dotnet-js-interop';
import { Blazor } from './GlobalExports';
import { HubConnectionBuilder, HubConnection } from '@microsoft/signalr';
import { HubConnectionBuilder, HubConnection, HttpTransportType } from '@microsoft/signalr';
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack';
import { showErrorNotification } from './BootErrors';
import { shouldAutoStart } from './BootCommon';
Expand Down Expand Up @@ -147,6 +147,22 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger
} else {
showErrorNotification();
}

if (ex.innerErrors) {
if (ex.innerErrors.some(e => e.errorType === 'UnsupportedTransportError' && e.transport === HttpTransportType.WebSockets)) {
logger.log(LogLevel.Error, 'Unable to connect, please ensure you are using an updated browser that supports WebSockets.');
} else if (ex.innerErrors.some(e => e.errorType === 'FailedToStartTransportError' && e.transport === HttpTransportType.WebSockets)) {
logger.log(LogLevel.Error, 'Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection.');
} else if (ex.innerErrors.some(e => e.errorType === 'DisabledTransportError' && e.transport === HttpTransportType.LongPolling)) {
logger.log(LogLevel.Error, 'Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit https://aka.ms/blazor-server-websockets-error.');
}
}
}

// Check if the connection is established using the long polling transport,
// using the `features.inherentKeepAlive` property only present with long polling.
if ((connection as any).connection?.features?.inherentKeepAlive) {
logger.log(LogLevel.Warning, 'Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit https://aka.ms/blazor-server-using-fallback-long-polling.');
}

DotNet.attachDispatcher({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;
using System.Threading;
using BasicTestApp;
using BasicTestApp.Reconnection;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;
using Microsoft.AspNetCore.E2ETesting;
using OpenQA.Selenium;
using TestServer;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests
{
public class ServerTransportsTest : ServerTestBase<BasicTestAppServerSiteFixture<TransportsServerStartup>>
{
public ServerTransportsTest(
BrowserFixture browserFixture,
BasicTestAppServerSiteFixture<TransportsServerStartup> serverFixture,
ITestOutputHelper output)
: base(browserFixture, serverFixture, output)
{
}

[Fact]
public void DefaultTransportsWorks_WithWebSockets()
{
Navigate("/defaultTransport/Transports");

Browser.Exists(By.Id("startBlazorServerBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Starting up Blazor server-side application.",
"WebSocket connected to ws://",
"Received render batch with",
"The HttpConnection connected successfully.",
"Blazor server-side application started.");

AssertGlobalErrorState(hasGlobalError: false);
}

[Fact]
public void ErrorIfClientAttemptsLongPolling_WithServerOnWebSockets()
{
Navigate("/webSockets/Transports");

Browser.Exists(By.Id("startWithLongPollingBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Information: Starting up Blazor server-side application.",
"Skipping transport 'WebSockets' because it was disabled by the client",
"Failed to start the connection: Error: Unable to connect to the server with any of the available transports.",
"Failed to start the circuit.");

AssertGlobalErrorState(hasGlobalError: true);
}

[Fact]
public void WebSocketsConnectionIsRejected_FallbackToLongPolling()
{
Navigate("/defaultTransport/Transports");

Browser.Exists(By.Id("startAndRejectWebSocketConnectionBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Information: Starting up Blazor server-side application.",
"Selecting transport 'LongPolling'",
"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit",
"Blazor server-side application started.");

AssertGlobalErrorState(hasGlobalError: false);
}

[Fact]
public void ErrorIfWebSocketsConnectionIsRejected_WithServerOnWebSockets()
{
Navigate("/webSockets/Transports");

Browser.Exists(By.Id("startAndRejectWebSocketConnectionBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Information: Starting up Blazor server-side application.",
"Selecting transport 'WebSockets'.",
"Error: Failed to start the transport 'WebSockets': Error: Don't allow Websockets.",
"Error: Failed to start the connection: Error: Unable to connect to the server with any of the available transports. Error: WebSockets failed: Error: Don't allow Websockets.",
"Failed to start the circuit.");

AssertGlobalErrorState(hasGlobalError: true);
}

[Fact]
public void ServerOnlySupportsLongPolling_FallbackToLongPolling()
{
Navigate("/longPolling/Transports");

Browser.Exists(By.Id("startBlazorServerBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Starting up Blazor server-side application.",
"Selecting transport 'LongPolling'.",
"Failed to connect via WebSockets, using the Long Polling fallback transport. This may be due to a VPN or proxy blocking the connection. To troubleshoot this, visit",
"Blazor server-side application started.");

AssertGlobalErrorState(hasGlobalError: false);
}

[Fact]
public void ErrorIfClientDisablesLongPolling_WithServerOnLongPolling()
{
Navigate("/longPolling/Transports");

Browser.Exists(By.Id("startWithWebSocketsBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Starting up Blazor server-side application.",
"Unable to connect to the server with any of the available transports. LongPolling failed: Error: 'LongPolling' is disabled by the client.",
"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. For additional details, visit");

AssertGlobalErrorState(hasGlobalError: true);
}

void AssertLogContainsMessages(params string[] messages)
{
var log = Browser.Manage().Logs.GetLog(LogType.Browser);
foreach (var message in messages)
{
Assert.Contains(log, entry =>
{
return entry.Message.Contains(message, StringComparison.InvariantCulture);
});
}
}

void AssertGlobalErrorState(bool hasGlobalError)
{
var globalErrorUi = Browser.Exists(By.Id("blazor-error-ui"));
Browser.Equal(hasGlobalError ? "block" : "none", () => globalErrorUi.GetCssValue("display"));
}
}
}
79 changes: 79 additions & 0 deletions src/Components/test/testassets/TestServer/Pages/Transports.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
@page
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"

<!DOCTYPE html>
<html>
<head>
<title>Transports Tests</title>
<base href="~/" />

<link href="style.css" rel="stylesheet" />
</head>
<body>

<root><component type="typeof(BasicTestApp.Index)" render-mode="Server" /></root>

<div id="blazor-error-ui">
An unhandled exception has occurred. See browser dev tools for details.
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>

<button id="startBlazorServerBtn" onclick="startBlazorServer()">Start Normally</button>
<button id="startWithLongPollingBtn" onclick="startWithLongPolling()">Start with Long Polling</button>
<button id="startWithWebSocketsBtn" onclick="startWithWebSockets()">Start with Web Sockets</button>
<button id="startAndRejectWebSocketConnectionBtn" onclick="startAndRejectWebSocketConnection()">Start with WebSockets and Reject Connection</button>

<script src="_framework/blazor.server.js" autostart="false"></script>
<script src="js/jsRootComponentInitializers.js"></script>
<script>
console.log('Blazor server-side');
function startBlazorServer() {
Blazor.start({
logLevel: 1, // LogLevel.Debug
configureSignalR: builder => {
builder.configureLogging("debug") // LogLevel.Debug
}
}).then(function () {
window['__aspnetcore__testing__blazor__start__script__executed__'] = true;
});
}
function startWithLongPolling() {
Blazor.start({
logLevel: 1, // LogLevel.Debug
configureSignalR: builder => {
builder.configureLogging("debug") // LogLevel.Debug
.withUrl('_blazor', 4) // Long Polling (4)
}
}).then(function () {
window['__aspnetcore__testing__blazor__start__script__executed__'] = true;
});
}
function startWithWebSockets() {
Blazor.start({
logLevel: 1, // LogLevel.Debug
configureSignalR: builder => {
builder.configureLogging("debug") // LogLevel.Debug
.withUrl('_blazor', 1) // Web Sockets (1)
}
}).then(function () {
window['__aspnetcore__testing__blazor__start__script__executed__'] = true;
});
}
function WebSocketNotAllowed() { throw new Error("Don't allow Websockets."); }
function startAndRejectWebSocketConnection() {
Blazor.start({
logLevel: 1, // LogLevel.Debug
configureSignalR: builder => {
builder.configureLogging("debug") // LogLevel.Debug
.withUrl('_blazor', {
WebSocket: WebSocketNotAllowed
})
}
}).then(function () {
window['__aspnetcore__testing__blazor__start__script__executed__'] = true;
});
}
</script>
</body>
</html>
2 changes: 1 addition & 1 deletion src/Components/test/testassets/TestServer/ServerStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public void ConfigureServices(IServiceCollection services)
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ResourceRequestLog resourceRequestLog)
public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env, ResourceRequestLog resourceRequestLog)
{
var enUs = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = enUs;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Globalization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace TestServer
{
public class TransportsServerStartup : ServerStartup
{
public TransportsServerStartup(IConfiguration configuration)
: base (configuration)
{
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env, ResourceRequestLog resourceRequestLog)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.Map("/defaultTransport", app =>
{
app.UseStaticFiles();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_ServerHost");
});
});

app.Map("/longPolling", app =>
{
app.UseStaticFiles();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub(configureOptions: options =>
{
options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.LongPolling;
});
endpoints.MapFallbackToPage("/_ServerHost");
});
});

app.Map("/webSockets", app =>
{
app.UseStaticFiles();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub(configureOptions: options =>
{
options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.WebSockets;
});
endpoints.MapFallbackToPage("/_ServerHost");
});
});
}
}
}