|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using Microsoft.AspNetCore.Builder; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using Microsoft.AspNetCore.NodeServices.Npm; |
| 7 | +using Microsoft.AspNetCore.NodeServices.Util; |
| 8 | +using Microsoft.AspNetCore.SpaServices.Util; |
| 9 | +using System; |
| 10 | +using System.IO; |
| 11 | +using System.Collections.Generic; |
| 12 | +using System.Text.RegularExpressions; |
| 13 | +using System.Threading.Tasks; |
| 14 | + |
| 15 | +namespace Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer |
| 16 | +{ |
| 17 | + internal static class ReactDevelopmentServerMiddleware |
| 18 | + { |
| 19 | + private const string LogCategoryName = "Microsoft.AspNetCore.SpaServices"; |
| 20 | + private static TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine |
| 21 | + private static TimeSpan StartupTimeout = TimeSpan.FromSeconds(50); // Note that the HTTP request itself by default times out after 60s, so you only get useful error information if this is shorter |
| 22 | + |
| 23 | + public static void Attach( |
| 24 | + ISpaBuilder spaBuilder, |
| 25 | + string npmScriptName) |
| 26 | + { |
| 27 | + var sourcePath = spaBuilder.Options.SourcePath; |
| 28 | + if (string.IsNullOrEmpty(sourcePath)) |
| 29 | + { |
| 30 | + throw new ArgumentException("Cannot be null or empty", nameof(sourcePath)); |
| 31 | + } |
| 32 | + |
| 33 | + if (string.IsNullOrEmpty(npmScriptName)) |
| 34 | + { |
| 35 | + throw new ArgumentException("Cannot be null or empty", nameof(npmScriptName)); |
| 36 | + } |
| 37 | + |
| 38 | + // Start create-react-app and attach to middleware pipeline |
| 39 | + var appBuilder = spaBuilder.ApplicationBuilder; |
| 40 | + var logger = LoggerFinder.GetOrCreateLogger(appBuilder, LogCategoryName); |
| 41 | + var portTask = StartCreateReactAppServerAsync(sourcePath, npmScriptName, logger); |
| 42 | + |
| 43 | + // Everything we proxy is hardcoded to target http://localhost because: |
| 44 | + // - the requests are always from the local machine (we're not accepting remote |
| 45 | + // requests that go directly to the create-react-app server) |
| 46 | + // - given that, there's no reason to use https, and we couldn't even if we |
| 47 | + // wanted to, because in general the create-react-app server has no certificate |
| 48 | + var targetUriTask = portTask.ContinueWith( |
| 49 | + task => new UriBuilder("http", "localhost", task.Result).Uri); |
| 50 | + |
| 51 | + SpaProxyingExtensions.UseProxyToSpaDevelopmentServer(spaBuilder, targetUriTask); |
| 52 | + } |
| 53 | + |
| 54 | + private static async Task<int> StartCreateReactAppServerAsync( |
| 55 | + string sourcePath, string npmScriptName, ILogger logger) |
| 56 | + { |
| 57 | + var portNumber = TcpPortFinder.FindAvailablePort(); |
| 58 | + logger.LogInformation($"Starting create-react-app server on port {portNumber}..."); |
| 59 | + |
| 60 | + var envVars = new Dictionary<string, string> |
| 61 | + { |
| 62 | + { "PORT", portNumber.ToString() } |
| 63 | + }; |
| 64 | + var npmScriptRunner = new NpmScriptRunner( |
| 65 | + sourcePath, npmScriptName, null, envVars); |
| 66 | + npmScriptRunner.AttachToLogger(logger); |
| 67 | + |
| 68 | + Match openBrowserLine; |
| 69 | + using (var stdErrReader = new EventedStreamStringReader(npmScriptRunner.StdErr)) |
| 70 | + { |
| 71 | + try |
| 72 | + { |
| 73 | + openBrowserLine = await npmScriptRunner.StdOut.WaitForMatch( |
| 74 | + new Regex("Local:\\s*(http\\S+)", RegexOptions.None, RegexMatchTimeout), |
| 75 | + StartupTimeout); |
| 76 | + } |
| 77 | + catch (EndOfStreamException ex) |
| 78 | + { |
| 79 | + throw new InvalidOperationException( |
| 80 | + $"The NPM script '{npmScriptName}' exited without indicating that the " + |
| 81 | + $"create-react-app server was listening for requests. The error output was: " + |
| 82 | + $"{stdErrReader.ReadAsString()}", ex); |
| 83 | + } |
| 84 | + catch (TaskCanceledException ex) |
| 85 | + { |
| 86 | + throw new InvalidOperationException( |
| 87 | + $"The create-react-app server did not start listening for requests " + |
| 88 | + $"within the timeout period of {StartupTimeout.Seconds} seconds. " + |
| 89 | + $"Check the log output for error information.", ex); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + var uri = new Uri(openBrowserLine.Groups[1].Value); |
| 94 | + return uri.Port; |
| 95 | + } |
| 96 | + } |
| 97 | +} |
0 commit comments