|
| 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 System; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using Microsoft.AspNetCore.NodeServices.Npm; |
| 8 | +using System.Text.RegularExpressions; |
| 9 | +using Microsoft.Extensions.Logging; |
| 10 | +using Microsoft.Extensions.DependencyInjection; |
| 11 | +using Microsoft.Extensions.Logging.Console; |
| 12 | +using System.Net.Sockets; |
| 13 | +using System.Net; |
| 14 | +using System.IO; |
| 15 | +using Microsoft.AspNetCore.NodeServices.Util; |
| 16 | + |
| 17 | +namespace Microsoft.AspNetCore.SpaServices.AngularCli |
| 18 | +{ |
| 19 | + internal static class AngularCliMiddleware |
| 20 | + { |
| 21 | + private const string LogCategoryName = "Microsoft.AspNetCore.SpaServices"; |
| 22 | + private static TimeSpan RegexMatchTimeout = TimeSpan.FromSeconds(5); // This is a development-time only feature, so a very long timeout is fine |
| 23 | + 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 |
| 24 | + |
| 25 | + public static void Attach( |
| 26 | + ISpaBuilder spaBuilder, |
| 27 | + string npmScriptName) |
| 28 | + { |
| 29 | + var sourcePath = spaBuilder.Options.SourcePath; |
| 30 | + if (string.IsNullOrEmpty(sourcePath)) |
| 31 | + { |
| 32 | + throw new ArgumentException("Cannot be null or empty", nameof(sourcePath)); |
| 33 | + } |
| 34 | + |
| 35 | + if (string.IsNullOrEmpty(npmScriptName)) |
| 36 | + { |
| 37 | + throw new ArgumentException("Cannot be null or empty", nameof(npmScriptName)); |
| 38 | + } |
| 39 | + |
| 40 | + // Start Angular CLI and attach to middleware pipeline |
| 41 | + var appBuilder = spaBuilder.ApplicationBuilder; |
| 42 | + var logger = GetOrCreateLogger(appBuilder); |
| 43 | + var angularCliServerInfoTask = StartAngularCliServerAsync(sourcePath, npmScriptName, logger); |
| 44 | + |
| 45 | + // Everything we proxy is hardcoded to target http://localhost because: |
| 46 | + // - the requests are always from the local machine (we're not accepting remote |
| 47 | + // requests that go directly to the Angular CLI middleware server) |
| 48 | + // - given that, there's no reason to use https, and we couldn't even if we |
| 49 | + // wanted to, because in general the Angular CLI server has no certificate |
| 50 | + var targetUriTask = angularCliServerInfoTask.ContinueWith( |
| 51 | + task => new UriBuilder("http", "localhost", task.Result.Port).Uri); |
| 52 | + |
| 53 | + SpaProxyingExtensions.UseProxyToSpaDevelopmentServer(spaBuilder, targetUriTask); |
| 54 | + } |
| 55 | + |
| 56 | + internal static ILogger GetOrCreateLogger(IApplicationBuilder appBuilder) |
| 57 | + { |
| 58 | + // If the DI system gives us a logger, use it. Otherwise, set up a default one. |
| 59 | + var loggerFactory = appBuilder.ApplicationServices.GetService<ILoggerFactory>(); |
| 60 | + var logger = loggerFactory != null |
| 61 | + ? loggerFactory.CreateLogger(LogCategoryName) |
| 62 | + : new ConsoleLogger(LogCategoryName, null, false); |
| 63 | + return logger; |
| 64 | + } |
| 65 | + |
| 66 | + private static async Task<AngularCliServerInfo> StartAngularCliServerAsync( |
| 67 | + string sourcePath, string npmScriptName, ILogger logger) |
| 68 | + { |
| 69 | + var portNumber = FindAvailablePort(); |
| 70 | + logger.LogInformation($"Starting @angular/cli on port {portNumber}..."); |
| 71 | + |
| 72 | + var npmScriptRunner = new NpmScriptRunner( |
| 73 | + sourcePath, npmScriptName, $"--port {portNumber}"); |
| 74 | + npmScriptRunner.AttachToLogger(logger); |
| 75 | + |
| 76 | + Match openBrowserLine; |
| 77 | + using (var stdErrReader = new EventedStreamStringReader(npmScriptRunner.StdErr)) |
| 78 | + { |
| 79 | + try |
| 80 | + { |
| 81 | + openBrowserLine = await npmScriptRunner.StdOut.WaitForMatch( |
| 82 | + new Regex("open your browser on (http\\S+)", RegexOptions.None, RegexMatchTimeout), |
| 83 | + StartupTimeout); |
| 84 | + } |
| 85 | + catch (EndOfStreamException ex) |
| 86 | + { |
| 87 | + throw new InvalidOperationException( |
| 88 | + $"The NPM script '{npmScriptName}' exited without indicating that the " + |
| 89 | + $"Angular CLI was listening for requests. The error output was: " + |
| 90 | + $"{stdErrReader.ReadAsString()}", ex); |
| 91 | + } |
| 92 | + catch (TaskCanceledException ex) |
| 93 | + { |
| 94 | + throw new InvalidOperationException( |
| 95 | + $"The Angular CLI process did not start listening for requests " + |
| 96 | + $"within the timeout period of {StartupTimeout.Seconds} seconds. " + |
| 97 | + $"Check the log output for error information.", ex); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + var uri = new Uri(openBrowserLine.Groups[1].Value); |
| 102 | + var serverInfo = new AngularCliServerInfo { Port = uri.Port }; |
| 103 | + |
| 104 | + // Even after the Angular CLI claims to be listening for requests, there's a short |
| 105 | + // period where it will give an error if you make a request too quickly. Give it |
| 106 | + // a moment to finish starting up. |
| 107 | + await Task.Delay(500); |
| 108 | + |
| 109 | + return serverInfo; |
| 110 | + } |
| 111 | + |
| 112 | + private static int FindAvailablePort() |
| 113 | + { |
| 114 | + var listener = new TcpListener(IPAddress.Loopback, 0); |
| 115 | + listener.Start(); |
| 116 | + try |
| 117 | + { |
| 118 | + return ((IPEndPoint)listener.LocalEndpoint).Port; |
| 119 | + } |
| 120 | + finally |
| 121 | + { |
| 122 | + listener.Stop(); |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + class AngularCliServerInfo |
| 127 | + { |
| 128 | + public int Port { get; set; } |
| 129 | + } |
| 130 | + } |
| 131 | +} |
0 commit comments