dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.37k stars 9.99k forks source link

React + ASPNET Core + Prerendering: An attempt was made to access a socket in a way forbidden by its access permissions #5255

Closed dfenske closed 5 years ago

dfenske commented 6 years ago

(Also posted on Stack Overflow)

I have a .NET Core + React app using aspnet-prerendering. I created the app using dotnet new reactredux. I published this to Azure, and routed to that app using AWS CloudFront.

The app has worked in all environments (locally, CI, prestaging...) but when I deployed it to production, it worked for a few days and then I started getting a lot of An attempt was made to access a socket in a way forbidden by its access permissions errors. This is happening when a POST is made to 127.0.0.1:<randomPort>. I do not make this POST in my code, and I've been told it has to do with how react is prerendered. These errors usually only start about 1-2 days after deploying. So when I first deploy, everything looks good, but then when the errors start, they continue until I re-deploy or restart the app in Azure.


Things I've tried:


A sample list of the ports that fail vs. succeed (seemingly random...?):

success count_  data
FALSE   3493    http://127.0.0.1:53571
FALSE   1353    http://127.0.0.1:49988
FALSE   535     http://127.0.0.1:55453
FALSE   484     http://127.0.0.1:53144
FALSE   13      http://127.0.0.1:52428
FALSE   7       http://127.0.0.1:49583
TRUE    11247   http://127.0.0.1:56790
TRUE    10960   http://127.0.0.1:55806
TRUE    10920   http://127.0.0.1:55227
TRUE    9300    http://127.0.0.1:55453
TRUE    8472    http://127.0.0.1:51734
TRUE    5602    http://127.0.0.1:53571
TRUE    5429    http://127.0.0.1:56860

Code snippets:

Startup:

public void ConfigureServices(IServiceCollection services)
    {    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // In production, the React files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/build";
        });
        …
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true,
                ReactHotModuleReplacement = true,
                // This configuration suppresses the warnings that the server code doesn't match the client code, which happens on reload.
                HotModuleReplacementClientOptions = new Dictionary<string, string>()
                {
                    { "warn", "false" }
                }
            });
        }
        else
        {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
        }

        //app.UseHttpsRedirection();
        app.UseStaticFiles();
        …
    }

Index.cshtml

@using Microsoft.Extensions.Configuration
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv
@inject IConfiguration Configuration

<script>
    window.data = @Html.Raw(Json.Serialize(@Model));
</script>

<div id="col-app"
     asp-prerender-module="./wwwroot/cost-of-living-calculator/dist/main-server"
     asp-prerender-webpack-config="webpack.config.server.js"
     asp-prerender-data="@Model">Loading...</div>

@if (hostingEnv.EnvironmentName == "Production")
{
    <script src="/cost-of-living-calculator/dist/main.min.js" asp-append-version="true"></script>
}
else
{
    <script src="/cost-of-living-calculator/dist/main.js" asp-append-version="true"></script>
}

Package.json

...
"aspnet-prerendering": "3.0.1",
"aspnet-webpack": "3.0.0",
"aspnet-webpack-react": "3.0.0",
...

NOTE: I have a boot-server and a boot-client, as well as a server webpack config and a client webpack config. This is due to differing needs for server/client compilation.

Boot-server.js

import React from 'react';
import { createServerRenderer } from 'aspnet-prerendering';
import { renderToString } from 'react-dom/server';
import App from './App';

export default createServerRenderer(
  params =>
    new Promise((resolve, reject) => {
      const data = params.data;
      const result = renderToString(React.createElement(App, data));

      resolve({ html: result });
    })
);

Boot-client.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

const element = document.getElementById('col-app');
ReactDOM.render(<App {...window.data} />, element);

// This is required to trigger the hot reloading functionality
if (module.hot) {
  module.hot.accept('./App', () => {
    const NewApp = require('./App').default;
    ReactDOM.render(<NewApp {...window.data} />, element);
  });
}

Webpack.config.js

var path = require('path');
var webpack = require('webpack'); 
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const isDevelopment = process.env.ASPNETCORE_ENVIRONMENT === 'Development';

module.exports = () => {
  return {
    devtool: 'inline-source-map',
    entry: {
    'main': ['babel-polyfill', './ClientApp/boot-client.js', './ClientApp/index.scss'],
},
optimization: {
  minimizer: [
    new UglifyJsPlugin({
      cache: true,
      parallel: true,
      sourceMap: true // set to true if you want JS source maps
    }),
    new OptimizeCSSAssetsPlugin({})
  ]
},
output: {
  path: path.join(__dirname, './wwwroot/cost-of-living-calculator/dist'),
  publicPath: '/cost-of-living-calculator/dist/',
  filename: isDevelopment ? "[name].js" : "[name].min.js"
},
plugins: [
  new MiniCssExtractPlugin({
    // Options similar to the same options in webpackOptions.output
    // both options are optional
    filename: "[name].css",
    chunkFilename: "[id].css"
  })
],
module: {
  rules: [
    {
      // JavaScript files, which will be transpiled
      // based on .babelrc
      test: /\.(js|jsx)$/,
      exclude: [/node_modules/],
      loader: ['babel-loader', 'source-map-loader']
    },
    {
      test: /\.s?css$/,
      use: isDevelopment ? [
        'style-loader',
        'css-loader',
        'sass-loader',
      ] : [
        MiniCssExtractPlugin.loader,
        'css-loader',
        'sass-loader'
      ]
    }
  ]
},
mode: isDevelopment ? 'development' : 'production'
  }
};

Webpack.config.server.js

var path = require('path');
const isDevelopment = process.env.ASPNETCORE_ENVIRONMENT === 'Development';

module.exports = () => {
  return {
    devtool: 'inline-source-map',
    entry: {
      'main-server': ['babel-polyfill', './ClientApp/boot-server.js']
    },
    output: {
      path: path.join(__dirname, './wwwroot/cost-of-living-calculator/dist'),
      publicPath: '/cost-of-living-calculator/dist/',
      filename: "[name].js",
      // commonjs is required for server-side compilation
      libraryTarget: 'commonjs'
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: [/node_modules/],
          loader: ['babel-loader', 'source-map-loader']
        }
      ]
    },
    target: 'node',
    mode: isDevelopment ? 'development' : 'production'
  }
};

My question is - Why is this happening? How do I prevent it?

ccpu commented 5 years ago

Can you please tell me if you have found any solution to this problem, I am facing the same problem.

ccpu commented 5 years ago

firewall was the cause of my problem.

dfenske commented 5 years ago

No solution for me yet. I don't think firewall is an issue for me either.

Vetsoo commented 5 years ago

My team is also having this issue. Is is possible there might be a problem with disposing sockets? From what I have found, there is a limit on sockets you can open, so if a socket is disposed but there is a problem and another one is opened, after a few days, you reach the limit of sockets and errors occur. Just an hypothesis, nothing for sure.

If anyone finds a solution, would be great :)

mkArtakMSFT commented 5 years ago

Thanks for contacting us. We're closing this issue as this doesn't align with our long-term plans in this area. You can read more details about our vision for this area at https://github.com/aspnet/AspNetCore/issues/12890.