Switch to using DI to acquire Node instances. Bump versions to alpha2.

This commit is contained in:
SteveSandersonMS
2015-11-02 13:35:14 -08:00
parent 301657a207
commit de991b9858
23 changed files with 103 additions and 92 deletions

View File

@@ -20,8 +20,6 @@ namespace Microsoft.AspNet.NodeServices.Angular
const string PrerenderModuleAttributeName = "aspnet-ng2-prerender-module"; const string PrerenderModuleAttributeName = "aspnet-ng2-prerender-module";
const string PrerenderExportAttributeName = "aspnet-ng2-prerender-export"; const string PrerenderExportAttributeName = "aspnet-ng2-prerender-export";
private static NodeInstance nodeInstance = new NodeInstance();
[HtmlAttributeName(PrerenderModuleAttributeName)] [HtmlAttributeName(PrerenderModuleAttributeName)]
public string ModuleName { get; set; } public string ModuleName { get; set; }
@@ -29,15 +27,17 @@ namespace Microsoft.AspNet.NodeServices.Angular
public string ExportName { get; set; } public string ExportName { get; set; }
private IHttpContextAccessor contextAccessor; private IHttpContextAccessor contextAccessor;
private INodeServices nodeServices;
public AngularRunAtServerTagHelper(IHttpContextAccessor contextAccessor) public AngularRunAtServerTagHelper(INodeServices nodeServices, IHttpContextAccessor contextAccessor)
{ {
this.contextAccessor = contextAccessor; this.contextAccessor = contextAccessor;
this.nodeServices = nodeServices;
} }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{ {
var result = await nodeInstance.InvokeExport(nodeScript.FileName, "renderComponent", new { var result = await this.nodeServices.InvokeExport(nodeScript.FileName, "renderComponent", new {
componentModule = this.ModuleName, componentModule = this.ModuleName,
componentExport = this.ExportName, componentExport = this.ExportName,
tagName = output.TagName, tagName = output.TagName,

View File

@@ -1,5 +1,5 @@
{ {
"version": "1.0.0-alpha1", "version": "1.0.0-alpha2",
"description": "Microsoft.AspNet.NodeServices.Angular Class Library", "description": "Microsoft.AspNet.NodeServices.Angular Class Library",
"authors": [ "authors": [
"Microsoft" "Microsoft"
@@ -25,7 +25,7 @@
} }
}, },
"dependencies": { "dependencies": {
"Microsoft.AspNet.NodeServices": "1.0.0-alpha1", "Microsoft.AspNet.NodeServices": "1.0.0-alpha2",
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta8" "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta8"
}, },
"resource": [ "resource": [

View File

@@ -5,7 +5,6 @@ namespace Microsoft.AspNet.NodeServices.React
public static class ReactRenderer public static class ReactRenderer
{ {
private static StringAsTempFile nodeScript; private static StringAsTempFile nodeScript;
private static NodeInstance nodeInstance = new NodeInstance();
static ReactRenderer() { static ReactRenderer() {
// Consider populating this lazily // Consider populating this lazily
@@ -13,8 +12,8 @@ namespace Microsoft.AspNet.NodeServices.React
nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit nodeScript = new StringAsTempFile(script); // Will be cleaned up on process exit
} }
public static async Task<string> RenderToString(string moduleName, string exportName, string baseUrl) { public static async Task<string> RenderToString(INodeServices nodeServices, string moduleName, string exportName, string baseUrl) {
return await nodeInstance.InvokeExport(nodeScript.FileName, "renderToString", new { return await nodeServices.InvokeExport(nodeScript.FileName, "renderToString", new {
moduleName, moduleName,
exportName, exportName,
baseUrl baseUrl

View File

@@ -1,5 +1,5 @@
{ {
"version": "1.0.0-alpha1", "version": "1.0.0-alpha2",
"description": "Microsoft.AspNet.NodeServices.React Class Library", "description": "Microsoft.AspNet.NodeServices.React Class Library",
"authors": [ "authors": [
"Microsoft" "Microsoft"
@@ -25,7 +25,7 @@
} }
}, },
"dependencies": { "dependencies": {
"Microsoft.AspNet.NodeServices": "1.0.0-alpha1" "Microsoft.AspNet.NodeServices": "1.0.0-alpha2"
}, },
"resource": [ "resource": [
"Content/**/*" "Content/**/*"

View File

@@ -0,0 +1,24 @@
using Microsoft.Framework.DependencyInjection;
namespace Microsoft.AspNet.NodeServices {
public static class Configuration {
public static void AddNodeServices(this IServiceCollection serviceCollection, NodeHostingModel hostingModel = NodeHostingModel.Http) {
serviceCollection.AddSingleton(typeof(INodeServices), (serviceProvider) => {
return CreateNodeServices(hostingModel);
});
}
private static INodeServices CreateNodeServices(NodeHostingModel hostingModel)
{
switch (hostingModel)
{
case NodeHostingModel.Http:
return new HttpNodeInstance();
case NodeHostingModel.InputOutputStream:
return new InputOutputStreamNodeInstance();
default:
throw new System.ArgumentException("Unknown hosting model: " + hostingModel.ToString());
}
}
}
}

View File

@@ -6,7 +6,7 @@ using Newtonsoft.Json;
using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Serialization;
namespace Microsoft.AspNet.NodeServices { namespace Microsoft.AspNet.NodeServices {
internal class HttpNodeHost : OutOfProcessNodeRunner { internal class HttpNodeInstance : OutOfProcessNodeInstance {
private readonly static Regex PortMessageRegex = new Regex(@"^\[Microsoft.AspNet.NodeServices.HttpNodeHost:Listening on port (\d+)\]$"); private readonly static Regex PortMessageRegex = new Regex(@"^\[Microsoft.AspNet.NodeServices.HttpNodeHost:Listening on port (\d+)\]$");
private readonly static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings { private readonly static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings {
@@ -15,8 +15,8 @@ namespace Microsoft.AspNet.NodeServices {
private int _portNumber; private int _portNumber;
public HttpNodeHost(int port = 0) public HttpNodeInstance(int port = 0)
: base(EmbeddedResourceReader.Read(typeof(HttpNodeHost), "/Content/Node/entrypoint-http.js"), port.ToString()) : base(EmbeddedResourceReader.Read(typeof(HttpNodeInstance), "/Content/Node/entrypoint-http.js"), port.ToString())
{ {
} }

View File

@@ -15,7 +15,7 @@ namespace Microsoft.AspNet.NodeServices {
// Instead of directly using stdin/stdout, we could use either regular sockets (TCP) or use named pipes // 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 // 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. // requests, associating them with responses, and scheduling use of the comms channel.
internal class InputOutputStreamNodeHost : OutOfProcessNodeRunner internal class InputOutputStreamNodeInstance : OutOfProcessNodeInstance
{ {
private SemaphoreSlim _invocationSemaphore = new SemaphoreSlim(1); private SemaphoreSlim _invocationSemaphore = new SemaphoreSlim(1);
private TaskCompletionSource<string> _currentInvocationResult; private TaskCompletionSource<string> _currentInvocationResult;
@@ -24,8 +24,8 @@ namespace Microsoft.AspNet.NodeServices {
ContractResolver = new CamelCasePropertyNamesContractResolver() ContractResolver = new CamelCasePropertyNamesContractResolver()
}; };
public InputOutputStreamNodeHost() public InputOutputStreamNodeInstance()
: base(EmbeddedResourceReader.Read(typeof(InputOutputStreamNodeHost), "/Content/Node/entrypoint-stream.js")) : base(EmbeddedResourceReader.Read(typeof(InputOutputStreamNodeInstance), "/Content/Node/entrypoint-stream.js"))
{ {
} }

View File

@@ -1,10 +0,0 @@
using System.Threading.Tasks;
namespace Microsoft.AspNet.NodeServices {
public abstract class NodeHost : System.IDisposable
{
public abstract Task<string> Invoke(NodeInvocationInfo invocationInfo);
public abstract void Dispose();
}
}

View File

@@ -8,7 +8,7 @@ namespace Microsoft.AspNet.NodeServices {
* Class responsible for launching the Node child process, determining when it is ready to accept invocations, * 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. * and finally killing it when the parent process exits. Also it restarts the child process if it dies.
*/ */
internal abstract class OutOfProcessNodeRunner : NodeHost { public abstract class OutOfProcessNodeInstance : INodeServices {
private object _childProcessLauncherLock; private object _childProcessLauncherLock;
private bool disposed; private bool disposed;
private StringAsTempFile _entryPointScript; private StringAsTempFile _entryPointScript;
@@ -18,19 +18,33 @@ namespace Microsoft.AspNet.NodeServices {
protected Process NodeProcess { protected Process NodeProcess {
get { get {
// This is only exposed to support the UnreliableStreamNodeHost, which is just to verify that // 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. // other hosting/transport mechanisms are possible. This shouldn't really be exposed.
return this._nodeProcess; return this._nodeProcess;
} }
} }
public OutOfProcessNodeRunner(string entryPointScript, string commandLineArguments = null) public OutOfProcessNodeInstance(string entryPointScript, string commandLineArguments = null)
{ {
this._childProcessLauncherLock = new object(); this._childProcessLauncherLock = new object();
this._entryPointScript = new StringAsTempFile(entryPointScript); this._entryPointScript = new StringAsTempFile(entryPointScript);
this._commandLineArguments = commandLineArguments ?? string.Empty; this._commandLineArguments = commandLineArguments ?? string.Empty;
} }
public abstract Task<string> Invoke(NodeInvocationInfo invocationInfo);
public Task<string> Invoke(string moduleName, params object[] args) {
return this.InvokeExport(moduleName, null, args);
}
public async Task<string> InvokeExport(string moduleName, string exportedFunctionName, params object[] args) {
return await this.Invoke(new NodeInvocationInfo {
ModuleName = moduleName,
ExportedFunctionName = exportedFunctionName,
Args = args
});
}
protected async Task EnsureReady() { protected async Task EnsureReady() {
lock (this._childProcessLauncherLock) { lock (this._childProcessLauncherLock) {
if (this._nodeProcess == null || this._nodeProcess.HasExited) { if (this._nodeProcess == null || this._nodeProcess.HasExited) {
@@ -104,8 +118,8 @@ namespace Microsoft.AspNet.NodeServices {
protected virtual void OnErrorDataReceived(string errorData) { protected virtual void OnErrorDataReceived(string errorData) {
Console.WriteLine("[Node] " + errorData); Console.WriteLine("[Node] " + errorData);
} }
public override void Dispose() public void Dispose()
{ {
Dispose(true); Dispose(true);
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
@@ -125,8 +139,8 @@ namespace Microsoft.AspNet.NodeServices {
disposed = true; disposed = true;
} }
} }
~OutOfProcessNodeRunner() { ~OutOfProcessNodeInstance() {
Dispose (false); Dispose (false);
} }
} }

View File

@@ -0,0 +1,10 @@
using System;
using System.Threading.Tasks;
namespace Microsoft.AspNet.NodeServices {
public interface INodeServices : IDisposable {
Task<string> Invoke(string moduleName, params object[] args);
Task<string> InvokeExport(string moduleName, string exportedFunctionName, params object[] args);
}
}

View File

@@ -1,38 +0,0 @@
using System;
using System.Threading.Tasks;
namespace Microsoft.AspNet.NodeServices {
public class NodeInstance : IDisposable {
private readonly NodeHost _nodeHost;
public NodeInstance(NodeHostingModel hostingModel = NodeHostingModel.Http) {
switch (hostingModel) {
case NodeHostingModel.Http:
this._nodeHost = new HttpNodeHost();
break;
case NodeHostingModel.InputOutputStream:
this._nodeHost = new InputOutputStreamNodeHost();
break;
default:
throw new ArgumentException("Unknown hosting model: " + hostingModel.ToString());
}
}
public Task<string> Invoke(string moduleName, params object[] args) {
return this.InvokeExport(moduleName, null, args);
}
public async Task<string> InvokeExport(string moduleName, string exportedFunctionName, params object[] args) {
return await this._nodeHost.Invoke(new NodeInvocationInfo {
ModuleName = moduleName,
ExportedFunctionName = exportedFunctionName,
Args = args
});
}
public void Dispose()
{
this._nodeHost.Dispose();
}
}
}

View File

@@ -1,5 +1,5 @@
{ {
"version": "1.0.0-alpha1", "version": "1.0.0-alpha2",
"description": "Microsoft.AspNet.NodeServices", "description": "Microsoft.AspNet.NodeServices",
"authors": [ "Microsoft" ], "authors": [ "Microsoft" ],
"tags": [""], "tags": [""],
@@ -8,7 +8,8 @@
"dependencies": { "dependencies": {
"System.Net.Http": "4.0.1-beta-23409", "System.Net.Http": "4.0.1-beta-23409",
"Newtonsoft.Json": "8.0.1-beta1" "Newtonsoft.Json": "8.0.1-beta1",
"Microsoft.Framework.DependencyInjection": "1.0.0-beta8"
}, },
"frameworks": { "frameworks": {

View File

@@ -79,6 +79,9 @@ namespace MusicStore
Mapper.CreateMap<ArtistResultDto, Artist>(); Mapper.CreateMap<ArtistResultDto, Artist>();
Mapper.CreateMap<Genre, GenreResultDto>(); Mapper.CreateMap<Genre, GenreResultDto>();
Mapper.CreateMap<GenreResultDto, Genre>(); Mapper.CreateMap<GenreResultDto, Genre>();
// Enable Node Services
services.AddNodeServices();
} }
// Configure is called after ConfigureServices is called. // Configure is called after ConfigureServices is called.
@@ -108,17 +111,6 @@ namespace MusicStore
app.UseExceptionHandler("/Home/Error"); app.UseExceptionHandler("/Home/Error");
} }
var nodeInstance = new NodeInstance();
app.Use(async (context, next) => {
if (context.Request.Path.Value.EndsWith(".less")) {
// Note: check for directory traversal
var output = await nodeInstance.Invoke("lessCompiler.js", env.WebRootPath + context.Request.Path.Value);
await context.Response.WriteAsync(output);
} else {
await next();
}
});
// Add static files to the request pipeline. // Add static files to the request pipeline.
app.UseStaticFiles(); app.UseStaticFiles();

View File

@@ -19,7 +19,7 @@
"EntityFramework.SQLite": "7.0.0-beta8", "EntityFramework.SQLite": "7.0.0-beta8",
"Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta8", "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta8",
"AutoMapper": "4.0.0-alpha1", "AutoMapper": "4.0.0-alpha1",
"Microsoft.AspNet.NodeServices.Angular": "1.0.0-alpha1" "Microsoft.AspNet.NodeServices.Angular": "1.0.0-alpha2"
}, },
"commands": { "commands": {
"web": "Microsoft.AspNet.Server.Kestrel" "web": "Microsoft.AspNet.Server.Kestrel"

View File

@@ -5,7 +5,7 @@ namespace ES2015Example.Controllers
{ {
public class HomeController : Controller public class HomeController : Controller
{ {
public async Task<IActionResult> Index(int pageIndex) public IActionResult Index(int pageIndex)
{ {
return View(); return View();
} }

View File

@@ -6,13 +6,17 @@ namespace ES2015Example.Controllers
{ {
public class ScriptController : Controller public class ScriptController : Controller
{ {
private static NodeInstance nodeInstance = new NodeInstance(); private INodeServices nodeServices;
public ScriptController(INodeServices nodeServices) {
this.nodeServices = nodeServices;
}
public async Task<ContentResult> Transpile(string filename) public async Task<ContentResult> Transpile(string filename)
{ {
// TODO: Don't hard-code wwwroot; use proper path conversions // TODO: Don't hard-code wwwroot; use proper path conversions
var fileContents = System.IO.File.ReadAllText("wwwroot/" + filename); var fileContents = System.IO.File.ReadAllText("wwwroot/" + filename);
var transpiledResult = await nodeInstance.Invoke("transpilation.js", fileContents, Request.Path.Value); var transpiledResult = await this.nodeServices.Invoke("transpilation.js", fileContents, Request.Path.Value);
return Content(transpiledResult, "application/javascript"); return Content(transpiledResult, "application/javascript");
} }
} }

View File

@@ -5,6 +5,7 @@ using Microsoft.Dnx.Runtime;
using Microsoft.Framework.Configuration; using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging; using Microsoft.Framework.Logging;
using Microsoft.AspNet.NodeServices;
namespace ES2015Example namespace ES2015Example
{ {
@@ -27,6 +28,9 @@ namespace ES2015Example
{ {
// Add MVC services to the services container. // Add MVC services to the services container.
services.AddMvc(); services.AddMvc();
// Enable Node Services
services.AddNodeServices();
} }
// Configure is called after ConfigureServices is called. // Configure is called after ConfigureServices is called.

View File

@@ -16,7 +16,7 @@
"Microsoft.Framework.Logging": "1.0.0-beta8", "Microsoft.Framework.Logging": "1.0.0-beta8",
"Microsoft.Framework.Logging.Console": "1.0.0-beta8", "Microsoft.Framework.Logging.Console": "1.0.0-beta8",
"Microsoft.Framework.Logging.Debug": "1.0.0-beta8", "Microsoft.Framework.Logging.Debug": "1.0.0-beta8",
"Microsoft.AspNet.NodeServices": "1.0.0-alpha1" "Microsoft.AspNet.NodeServices": "1.0.0-alpha2"
}, },
"commands": { "commands": {
"web": "Microsoft.AspNet.Server.Kestrel" "web": "Microsoft.AspNet.Server.Kestrel"

View File

@@ -1,14 +1,21 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.NodeServices;
using Microsoft.AspNet.NodeServices.React; using Microsoft.AspNet.NodeServices.React;
namespace ReactExample.Controllers namespace ReactExample.Controllers
{ {
public class HomeController : Controller public class HomeController : Controller
{ {
private INodeServices nodeServices;
public HomeController(INodeServices nodeServices) {
this.nodeServices = nodeServices;
}
public async Task<IActionResult> Index(int pageIndex) public async Task<IActionResult> Index(int pageIndex)
{ {
ViewData["ReactOutput"] = await ReactRenderer.RenderToString( ViewData["ReactOutput"] = await ReactRenderer.RenderToString(this.nodeServices,
moduleName: "ReactApp/components/ReactApp.jsx", moduleName: "ReactApp/components/ReactApp.jsx",
exportName: "ReactApp", exportName: "ReactApp",
baseUrl: Request.Path baseUrl: Request.Path

View File

@@ -1,5 +1,6 @@
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.NodeServices;
using Microsoft.Dnx.Runtime; using Microsoft.Dnx.Runtime;
using Microsoft.Framework.Configuration; using Microsoft.Framework.Configuration;
using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.DependencyInjection;
@@ -26,6 +27,9 @@ namespace ReactExample
{ {
// Add MVC services to the services container. // Add MVC services to the services container.
services.AddMvc(); services.AddMvc();
// Enable Node Services
services.AddNodeServices();
} }
// Configure is called after ConfigureServices is called. // Configure is called after ConfigureServices is called.

View File

@@ -16,7 +16,7 @@
"Microsoft.Framework.Logging": "1.0.0-beta8", "Microsoft.Framework.Logging": "1.0.0-beta8",
"Microsoft.Framework.Logging.Console": "1.0.0-beta8", "Microsoft.Framework.Logging.Console": "1.0.0-beta8",
"Microsoft.Framework.Logging.Debug": "1.0.0-beta8", "Microsoft.Framework.Logging.Debug": "1.0.0-beta8",
"Microsoft.AspNet.NodeServices.React": "1.0.0-alpha1" "Microsoft.AspNet.NodeServices.React": "1.0.0-alpha2"
}, },
"commands": { "commands": {
"web": "Microsoft.AspNet.Server.Kestrel" "web": "Microsoft.AspNet.Server.Kestrel"