mirror of
https://github.com/aspnet/JavaScriptServices.git
synced 2025-12-24 10:40:23 +00:00
refactor: apply default vs transform to xproj
refactor(spa-services): clean code refactor(node-services): clean code, extract classes nto separate files refactor(angular-services): prime cache cleanup
This commit is contained in:
@@ -7,66 +7,90 @@ using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices {
|
||||
internal class HttpNodeInstance : OutOfProcessNodeInstance {
|
||||
private readonly static Regex PortMessageRegex = new Regex(@"^\[Microsoft.AspNetCore.NodeServices.HttpNodeHost:Listening on port (\d+)\]$");
|
||||
namespace Microsoft.AspNetCore.NodeServices
|
||||
{
|
||||
internal class HttpNodeInstance : OutOfProcessNodeInstance
|
||||
{
|
||||
private static readonly Regex PortMessageRegex =
|
||||
new Regex(@"^\[Microsoft.AspNetCore.NodeServices.HttpNodeHost:Listening on port (\d+)\]$");
|
||||
|
||||
private readonly static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings {
|
||||
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
||||
};
|
||||
|
||||
private int _portNumber;
|
||||
|
||||
public HttpNodeInstance(string projectPath, int port = 0, string[] watchFileExtensions = null)
|
||||
: base(EmbeddedResourceReader.Read(typeof(HttpNodeInstance), "/Content/Node/entrypoint-http.js"), projectPath, MakeCommandLineOptions(port, watchFileExtensions))
|
||||
public HttpNodeInstance(string projectPath, int port = 0, string[] watchFileExtensions = null)
|
||||
: base(
|
||||
EmbeddedResourceReader.Read(
|
||||
typeof(HttpNodeInstance),
|
||||
"/Content/Node/entrypoint-http.js"),
|
||||
projectPath,
|
||||
MakeCommandLineOptions(port, watchFileExtensions))
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static string MakeCommandLineOptions(int port, string[] watchFileExtensions) {
|
||||
var result = "--port " + port.ToString();
|
||||
if (watchFileExtensions != null && watchFileExtensions.Length > 0) {
|
||||
private static string MakeCommandLineOptions(int port, string[] watchFileExtensions)
|
||||
{
|
||||
var result = "--port " + port;
|
||||
if (watchFileExtensions != null && watchFileExtensions.Length > 0)
|
||||
{
|
||||
result += " --watch " + string.Join(",", watchFileExtensions);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public override async Task<T> Invoke<T>(NodeInvocationInfo invocationInfo) {
|
||||
await this.EnsureReady();
|
||||
public override async Task<T> Invoke<T>(NodeInvocationInfo invocationInfo)
|
||||
{
|
||||
await EnsureReady();
|
||||
|
||||
using (var client = new HttpClient()) {
|
||||
using (var client = new HttpClient())
|
||||
{
|
||||
// TODO: Use System.Net.Http.Formatting (PostAsJsonAsync etc.)
|
||||
var payloadJson = JsonConvert.SerializeObject(invocationInfo, jsonSerializerSettings);
|
||||
var payloadJson = JsonConvert.SerializeObject(invocationInfo, JsonSerializerSettings);
|
||||
var payload = new StringContent(payloadJson, Encoding.UTF8, "application/json");
|
||||
var response = await client.PostAsync("http://localhost:" + this._portNumber, payload);
|
||||
var response = await client.PostAsync("http://localhost:" + _portNumber, payload);
|
||||
var responseString = await response.Content.ReadAsStringAsync();
|
||||
|
||||
if (!response.IsSuccessStatusCode) {
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw new Exception("Call to Node module failed with error: " + responseString);
|
||||
}
|
||||
|
||||
var responseIsJson = response.Content.Headers.ContentType.MediaType == "application/json";
|
||||
if (responseIsJson) {
|
||||
if (responseIsJson)
|
||||
{
|
||||
return JsonConvert.DeserializeObject<T>(responseString);
|
||||
} else if (typeof(T) != typeof(string)) {
|
||||
throw new System.ArgumentException("Node module responded with non-JSON string. This cannot be converted to the requested generic type: " + typeof(T).FullName);
|
||||
} else {
|
||||
return (T)(object)responseString;
|
||||
}
|
||||
if (typeof(T) != typeof(string))
|
||||
{
|
||||
throw new ArgumentException(
|
||||
"Node module responded with non-JSON string. This cannot be converted to the requested generic type: " +
|
||||
typeof(T).FullName);
|
||||
}
|
||||
return (T)(object)responseString;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnOutputDataReceived(string outputData) {
|
||||
var match = this._portNumber != 0 ? null : PortMessageRegex.Match(outputData);
|
||||
if (match != null && match.Success) {
|
||||
this._portNumber = int.Parse(match.Groups[1].Captures[0].Value);
|
||||
} else {
|
||||
protected override void OnOutputDataReceived(string outputData)
|
||||
{
|
||||
var match = _portNumber != 0 ? null : PortMessageRegex.Match(outputData);
|
||||
if (match != null && match.Success)
|
||||
{
|
||||
_portNumber = int.Parse(match.Groups[1].Captures[0].Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
base.OnOutputDataReceived(outputData);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnBeforeLaunchProcess() {
|
||||
protected override void OnBeforeLaunchProcess()
|
||||
{
|
||||
// Prepare to receive a new port number
|
||||
this._portNumber = 0;
|
||||
_portNumber = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,55 +4,72 @@ using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices {
|
||||
// This is just to demonstrate that other transports are possible. This implementation is extremely
|
||||
// dubious - if the Node-side code fails to conform to the expected protocol in any way (e.g., has an
|
||||
// error), then it will just hang forever. So don't use this.
|
||||
//
|
||||
// But it's fast - the communication round-trip time is about 0.2ms (tested on OS X on a recent machine),
|
||||
// versus 2-3ms for the HTTP transport.
|
||||
//
|
||||
// Instead of directly using stdin/stdout, we could use either regular sockets (TCP) or use named pipes
|
||||
// on Windows and domain sockets on Linux / OS X, but either way would need a system for framing the
|
||||
// requests, associating them with responses, and scheduling use of the comms channel.
|
||||
namespace Microsoft.AspNetCore.NodeServices
|
||||
{
|
||||
/// <summary>
|
||||
/// This is just to demonstrate that other transports are possible. This implementation is extremely
|
||||
/// dubious - if the Node-side code fails to conform to the expected protocol in any way (e.g., has an
|
||||
/// error), then it will just hang forever. So don't use this.
|
||||
///
|
||||
/// But it's fast - the communication round-trip time is about 0.2ms (tested on OS X on a recent machine),
|
||||
/// versus 2-3ms for the HTTP transport.
|
||||
///
|
||||
/// Instead of directly using stdin/stdout, we could use either regular sockets (TCP) or use named pipes
|
||||
/// on Windows and domain sockets on Linux / OS X, but either way would need a system for framing the
|
||||
/// requests, associating them with responses, and scheduling use of the comms channel.
|
||||
/// </summary>
|
||||
/// <seealso cref="Microsoft.AspNetCore.NodeServices.OutOfProcessNodeInstance" />
|
||||
internal class InputOutputStreamNodeInstance : OutOfProcessNodeInstance
|
||||
{
|
||||
private SemaphoreSlim _invocationSemaphore = new SemaphoreSlim(1);
|
||||
private TaskCompletionSource<string> _currentInvocationResult;
|
||||
|
||||
private readonly static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings {
|
||||
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
|
||||
{
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
||||
};
|
||||
|
||||
public InputOutputStreamNodeInstance(string projectPath)
|
||||
: base(EmbeddedResourceReader.Read(typeof(InputOutputStreamNodeInstance), "/Content/Node/entrypoint-stream.js"), projectPath)
|
||||
private TaskCompletionSource<string> _currentInvocationResult;
|
||||
private readonly SemaphoreSlim _invocationSemaphore = new SemaphoreSlim(1);
|
||||
|
||||
public InputOutputStreamNodeInstance(string projectPath)
|
||||
: base(
|
||||
EmbeddedResourceReader.Read(
|
||||
typeof(InputOutputStreamNodeInstance),
|
||||
"/Content/Node/entrypoint-stream.js"),
|
||||
projectPath)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task<T> Invoke<T>(NodeInvocationInfo invocationInfo) {
|
||||
await this._invocationSemaphore.WaitAsync();
|
||||
try {
|
||||
await this.EnsureReady();
|
||||
public override async Task<T> Invoke<T>(NodeInvocationInfo invocationInfo)
|
||||
{
|
||||
await _invocationSemaphore.WaitAsync();
|
||||
try
|
||||
{
|
||||
await EnsureReady();
|
||||
|
||||
var payloadJson = JsonConvert.SerializeObject(invocationInfo, jsonSerializerSettings);
|
||||
var nodeProcess = this.NodeProcess;
|
||||
this._currentInvocationResult = new TaskCompletionSource<string>();
|
||||
var payloadJson = JsonConvert.SerializeObject(invocationInfo, JsonSerializerSettings);
|
||||
var nodeProcess = NodeProcess;
|
||||
_currentInvocationResult = new TaskCompletionSource<string>();
|
||||
nodeProcess.StandardInput.Write("\ninvoke:");
|
||||
nodeProcess.StandardInput.WriteLine(payloadJson); // WriteLineAsync isn't supported cross-platform
|
||||
var resultString = await this._currentInvocationResult.Task;
|
||||
var resultString = await _currentInvocationResult.Task;
|
||||
return JsonConvert.DeserializeObject<T>(resultString);
|
||||
} finally {
|
||||
this._invocationSemaphore.Release();
|
||||
this._currentInvocationResult = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_invocationSemaphore.Release();
|
||||
_currentInvocationResult = null;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnOutputDataReceived(string outputData) {
|
||||
if (this._currentInvocationResult != null) {
|
||||
this._currentInvocationResult.SetResult(outputData);
|
||||
} else {
|
||||
protected override void OnOutputDataReceived(string outputData)
|
||||
{
|
||||
if (_currentInvocationResult != null)
|
||||
{
|
||||
_currentInvocationResult.SetResult(outputData);
|
||||
}
|
||||
else
|
||||
{
|
||||
base.OnOutputDataReceived(outputData);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
namespace Microsoft.AspNetCore.NodeServices {
|
||||
namespace Microsoft.AspNetCore.NodeServices
|
||||
{
|
||||
public class NodeInvocationInfo
|
||||
{
|
||||
public string ModuleName;
|
||||
public string ExportedFunctionName;
|
||||
public object[] Args;
|
||||
public string ModuleName { get; set; }
|
||||
public string ExportedFunctionName { get; set; }
|
||||
public object[] Args { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,126 +3,42 @@ using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Microsoft.AspNetCore.NodeServices {
|
||||
/**
|
||||
* Class responsible for launching the Node child process, determining when it is ready to accept invocations,
|
||||
* and finally killing it when the parent process exits. Also it restarts the child process if it dies.
|
||||
*/
|
||||
public abstract class OutOfProcessNodeInstance : INodeServices {
|
||||
private object _childProcessLauncherLock;
|
||||
private bool disposed;
|
||||
private StringAsTempFile _entryPointScript;
|
||||
private string _projectPath;
|
||||
private string _commandLineArguments;
|
||||
private Process _nodeProcess;
|
||||
namespace Microsoft.AspNetCore.NodeServices
|
||||
{
|
||||
/// <summary>
|
||||
/// Class responsible for launching the Node child process, determining when it is ready to accept invocations,
|
||||
/// and finally killing it when the parent process exits. Also it restarts the child process if it dies.
|
||||
/// </summary>
|
||||
/// <seealso cref="Microsoft.AspNetCore.NodeServices.INodeServices" />
|
||||
public abstract class OutOfProcessNodeInstance : INodeServices
|
||||
{
|
||||
private readonly object _childProcessLauncherLock;
|
||||
private readonly string _commandLineArguments;
|
||||
private readonly StringAsTempFile _entryPointScript;
|
||||
private TaskCompletionSource<bool> _nodeProcessIsReadySource;
|
||||
|
||||
protected Process NodeProcess {
|
||||
get {
|
||||
// This is only exposed to support the unreliable OutOfProcessNodeRunner, which is just to verify that
|
||||
// other hosting/transport mechanisms are possible. This shouldn't really be exposed.
|
||||
return this._nodeProcess;
|
||||
}
|
||||
}
|
||||
private readonly string _projectPath;
|
||||
private bool _disposed;
|
||||
|
||||
public OutOfProcessNodeInstance(string entryPointScript, string projectPath, string commandLineArguments = null)
|
||||
{
|
||||
this._childProcessLauncherLock = new object();
|
||||
this._entryPointScript = new StringAsTempFile(entryPointScript);
|
||||
this._projectPath = projectPath;
|
||||
this._commandLineArguments = commandLineArguments ?? string.Empty;
|
||||
_childProcessLauncherLock = new object();
|
||||
_entryPointScript = new StringAsTempFile(entryPointScript);
|
||||
_projectPath = projectPath;
|
||||
_commandLineArguments = commandLineArguments ?? string.Empty;
|
||||
}
|
||||
|
||||
public abstract Task<T> Invoke<T>(NodeInvocationInfo invocationInfo);
|
||||
protected Process NodeProcess { get; private set; }
|
||||
|
||||
public Task<T> Invoke<T>(string moduleName, params object[] args) {
|
||||
return this.InvokeExport<T>(moduleName, null, args);
|
||||
}
|
||||
public Task<T> Invoke<T>(string moduleName, params object[] args)
|
||||
=> InvokeExport<T>(moduleName, null, args);
|
||||
|
||||
public async Task<T> InvokeExport<T>(string moduleName, string exportedFunctionName, params object[] args) {
|
||||
return await this.Invoke<T>(new NodeInvocationInfo {
|
||||
public Task<T> InvokeExport<T>(string moduleName, string exportedFunctionName, params object[] args)
|
||||
=> Invoke<T>(new NodeInvocationInfo
|
||||
{
|
||||
ModuleName = moduleName,
|
||||
ExportedFunctionName = exportedFunctionName,
|
||||
Args = args
|
||||
});
|
||||
}
|
||||
|
||||
protected async Task EnsureReady() {
|
||||
lock (this._childProcessLauncherLock) {
|
||||
if (this._nodeProcess == null || this._nodeProcess.HasExited) {
|
||||
var startInfo = new ProcessStartInfo("node") {
|
||||
Arguments = "\"" + this._entryPointScript.FileName + "\" " + this._commandLineArguments,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardInput = true,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
WorkingDirectory = this._projectPath
|
||||
};
|
||||
|
||||
// Append projectPath to NODE_PATH so it can locate node_modules
|
||||
var existingNodePath = Environment.GetEnvironmentVariable("NODE_PATH") ?? string.Empty;
|
||||
if (existingNodePath != string.Empty) {
|
||||
existingNodePath += ":";
|
||||
}
|
||||
|
||||
var nodePathValue = existingNodePath + Path.Combine(this._projectPath, "node_modules");
|
||||
#if NET451
|
||||
startInfo.EnvironmentVariables.Add("NODE_PATH", nodePathValue);
|
||||
#else
|
||||
startInfo.Environment.Add("NODE_PATH", nodePathValue);
|
||||
#endif
|
||||
|
||||
this.OnBeforeLaunchProcess();
|
||||
this._nodeProcess = Process.Start(startInfo);
|
||||
this.ConnectToInputOutputStreams();
|
||||
}
|
||||
}
|
||||
|
||||
var task = this._nodeProcessIsReadySource.Task;
|
||||
var initializationSucceeded = await task;
|
||||
|
||||
if (!initializationSucceeded) {
|
||||
throw new InvalidOperationException("The Node.js process failed to initialize", task.Exception);
|
||||
}
|
||||
}
|
||||
|
||||
private void ConnectToInputOutputStreams() {
|
||||
var initializationIsCompleted = false; // TODO: Make this thread-safe? (Interlocked.Exchange etc.)
|
||||
this._nodeProcessIsReadySource = new TaskCompletionSource<bool>();
|
||||
|
||||
this._nodeProcess.OutputDataReceived += (sender, evt) => {
|
||||
if (evt.Data == "[Microsoft.AspNetCore.NodeServices:Listening]" && !initializationIsCompleted) {
|
||||
this._nodeProcessIsReadySource.SetResult(true);
|
||||
initializationIsCompleted = true;
|
||||
} else if (evt.Data != null) {
|
||||
this.OnOutputDataReceived(evt.Data);
|
||||
}
|
||||
};
|
||||
|
||||
this._nodeProcess.ErrorDataReceived += (sender, evt) => {
|
||||
if (evt.Data != null) {
|
||||
this.OnErrorDataReceived(evt.Data);
|
||||
if (!initializationIsCompleted) {
|
||||
this._nodeProcessIsReadySource.SetResult(false);
|
||||
initializationIsCompleted = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
this._nodeProcess.BeginOutputReadLine();
|
||||
this._nodeProcess.BeginErrorReadLine();
|
||||
}
|
||||
|
||||
protected virtual void OnBeforeLaunchProcess() {
|
||||
}
|
||||
|
||||
protected virtual void OnOutputDataReceived(string outputData) {
|
||||
Console.WriteLine("[Node] " + outputData);
|
||||
}
|
||||
|
||||
protected virtual void OnErrorDataReceived(string errorData) {
|
||||
Console.WriteLine("[Node] " + errorData);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
@@ -130,23 +46,124 @@ namespace Microsoft.AspNetCore.NodeServices {
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
public abstract Task<T> Invoke<T>(NodeInvocationInfo invocationInfo);
|
||||
|
||||
protected async Task EnsureReady()
|
||||
{
|
||||
if (!disposed) {
|
||||
if (disposing) {
|
||||
this._entryPointScript.Dispose();
|
||||
}
|
||||
lock (_childProcessLauncherLock)
|
||||
{
|
||||
if (NodeProcess == null || NodeProcess.HasExited)
|
||||
{
|
||||
var startInfo = new ProcessStartInfo("node")
|
||||
{
|
||||
Arguments = "\"" + _entryPointScript.FileName + "\" " + _commandLineArguments,
|
||||
UseShellExecute = false,
|
||||
RedirectStandardInput = true,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
WorkingDirectory = _projectPath
|
||||
};
|
||||
|
||||
if (this._nodeProcess != null && !this._nodeProcess.HasExited) {
|
||||
this._nodeProcess.Kill(); // TODO: Is there a more graceful way to end it? Or does this still let it perform any cleanup?
|
||||
}
|
||||
// Append projectPath to NODE_PATH so it can locate node_modules
|
||||
var existingNodePath = Environment.GetEnvironmentVariable("NODE_PATH") ?? string.Empty;
|
||||
if (existingNodePath != string.Empty)
|
||||
{
|
||||
existingNodePath += ":";
|
||||
}
|
||||
|
||||
disposed = true;
|
||||
var nodePathValue = existingNodePath + Path.Combine(_projectPath, "node_modules");
|
||||
#if NET451
|
||||
startInfo.EnvironmentVariables.Add("NODE_PATH", nodePathValue);
|
||||
#else
|
||||
startInfo.Environment.Add("NODE_PATH", nodePathValue);
|
||||
#endif
|
||||
|
||||
OnBeforeLaunchProcess();
|
||||
NodeProcess = Process.Start(startInfo);
|
||||
ConnectToInputOutputStreams();
|
||||
}
|
||||
}
|
||||
|
||||
var task = _nodeProcessIsReadySource.Task;
|
||||
var initializationSucceeded = await task;
|
||||
|
||||
if (!initializationSucceeded)
|
||||
{
|
||||
throw new InvalidOperationException("The Node.js process failed to initialize", task.Exception);
|
||||
}
|
||||
}
|
||||
|
||||
~OutOfProcessNodeInstance() {
|
||||
Dispose (false);
|
||||
private void ConnectToInputOutputStreams()
|
||||
{
|
||||
var initializationIsCompleted = false; // TODO: Make this thread-safe? (Interlocked.Exchange etc.)
|
||||
_nodeProcessIsReadySource = new TaskCompletionSource<bool>();
|
||||
|
||||
NodeProcess.OutputDataReceived += (sender, evt) =>
|
||||
{
|
||||
if (evt.Data == "[Microsoft.AspNetCore.NodeServices:Listening]" && !initializationIsCompleted)
|
||||
{
|
||||
_nodeProcessIsReadySource.SetResult(true);
|
||||
initializationIsCompleted = true;
|
||||
}
|
||||
else if (evt.Data != null)
|
||||
{
|
||||
OnOutputDataReceived(evt.Data);
|
||||
}
|
||||
};
|
||||
|
||||
NodeProcess.ErrorDataReceived += (sender, evt) =>
|
||||
{
|
||||
if (evt.Data != null)
|
||||
{
|
||||
OnErrorDataReceived(evt.Data);
|
||||
if (!initializationIsCompleted)
|
||||
{
|
||||
_nodeProcessIsReadySource.SetResult(false);
|
||||
initializationIsCompleted = true;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
NodeProcess.BeginOutputReadLine();
|
||||
NodeProcess.BeginErrorReadLine();
|
||||
}
|
||||
|
||||
protected virtual void OnBeforeLaunchProcess()
|
||||
{
|
||||
}
|
||||
|
||||
protected virtual void OnOutputDataReceived(string outputData)
|
||||
{
|
||||
Console.WriteLine("[Node] " + outputData);
|
||||
}
|
||||
|
||||
protected virtual void OnErrorDataReceived(string errorData)
|
||||
{
|
||||
Console.WriteLine("[Node] " + errorData);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_entryPointScript.Dispose();
|
||||
}
|
||||
|
||||
if (NodeProcess != null && !NodeProcess.HasExited)
|
||||
{
|
||||
NodeProcess.Kill();
|
||||
// TODO: Is there a more graceful way to end it? Or does this still let it perform any cleanup?
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
~OutOfProcessNodeInstance()
|
||||
{
|
||||
Dispose(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user