forked from reactjs/React.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaScriptEngineFactory.cs
More file actions
329 lines (309 loc) · 9.05 KB
/
JavaScriptEngineFactory.cs
File metadata and controls
329 lines (309 loc) · 9.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using JavaScriptEngineSwitcher.Core;
using JavaScriptEngineSwitcher.Msie;
using JavaScriptEngineSwitcher.V8;
using JSPool;
using React.Exceptions;
namespace React
{
/// <summary>
/// Handles creation of JavaScript engines. All methods are thread-safe.
/// </summary>
public class JavaScriptEngineFactory : IDisposable, IJavaScriptEngineFactory
{
/// <summary>
/// React configuration for the current site
/// </summary>
protected readonly IReactSiteConfiguration _config;
/// <summary>
/// File system wrapper
/// </summary>
protected readonly IFileSystem _fileSystem;
/// <summary>
/// Function used to create new JavaScript engine instances.
/// </summary>
protected readonly Func<IJsEngine> _factory;
/// <summary>
/// Contains all current JavaScript engine instances. One per thread, keyed on thread ID.
/// </summary>
protected readonly ConcurrentDictionary<int, IJsEngine> _engines
= new ConcurrentDictionary<int, IJsEngine>();
/// <summary>
/// Pool of JavaScript engines to use
/// </summary>
protected IJsPool _pool;
/// <summary>
/// Whether this class has been disposed.
/// </summary>
protected bool _disposed;
/// <summary>
/// Initializes a new instance of the <see cref="JavaScriptEngineFactory"/> class.
/// </summary>
public JavaScriptEngineFactory(
IEnumerable<Registration> availableFactories,
IReactSiteConfiguration config,
IFileSystem fileSystem
)
{
_config = config;
_fileSystem = fileSystem;
_factory = GetFactory(availableFactories, config.AllowMsieEngine);
if (_config.ReuseJavaScriptEngines)
{
_pool = CreatePool();
}
}
/// <summary>
/// Creates a new JavaScript engine pool.
/// </summary>
protected virtual IJsPool CreatePool()
{
var allFiles = _config.Scripts
.Concat(_config.ScriptsWithoutTransform)
.Select(_fileSystem.MapPath);
var poolConfig = new JsPoolConfig
{
EngineFactory = _factory,
Initializer = InitialiseEngine,
WatchPath = _fileSystem.MapPath("~/"),
WatchFiles = allFiles
};
if (_config.MaxEngines != null)
{
poolConfig.MaxEngines = _config.MaxEngines.Value;
}
if (_config.StartEngines != null)
{
poolConfig.StartEngines = _config.StartEngines.Value;
}
return new JsPool(poolConfig);
}
/// <summary>
/// Loads standard React and JSXTransformer scripts into the engine.
/// </summary>
protected virtual void InitialiseEngine(IJsEngine engine)
{
var thisAssembly = typeof(ReactEnvironment).Assembly;
engine.ExecuteResource("React.Resources.shims.js", thisAssembly);
if (_config.LoadReact)
{
engine.ExecuteResource("React.Resources.react-with-addons.js", thisAssembly);
engine.Execute("React = global.React");
engine.ExecuteResource("React.Resources.JSXTransformer.js", thisAssembly);
}
LoadUserScripts(engine);
if (!_config.LoadReact)
{
// We expect to user to have loaded their own versino of React in the scripts that
// were loaded above, let's ensure that's the case.
EnsureReactLoaded(engine);
}
}
/// <summary>
/// Loads any user-provided scripts. Only scripts that don't need JSX transformation can
/// run immediately here. JSX files are loaded in ReactEnvironment.
/// </summary>
/// <param name="engine">Engine to load scripts into</param>
private void LoadUserScripts(IJsEngine engine)
{
foreach (var file in _config.ScriptsWithoutTransform)
{
try
{
var contents = _fileSystem.ReadAsString(file);
engine.Execute(contents);
}
catch (JsRuntimeException ex)
{
throw new ReactScriptLoadException(string.Format(
"Error while loading \"{0}\": {1}\r\nLine: {2}\r\nColumn: {3}",
file,
ex.Message,
ex.LineNumber,
ex.ColumnNumber
));
}
}
}
/// <summary>
/// Ensures that React has been correctly loaded into the specified engine.
/// </summary>
/// <param name="engine">Engine to check</param>
private static void EnsureReactLoaded(IJsEngine engine)
{
var result = engine.CallFunction<bool>("ReactNET_initReact");
if (!result)
{
throw new ReactNotInitialisedException(
"React has not been loaded correctly. Please expose your version of React as a global " +
"variable named 'React', or enable the 'LoadReact' configuration option to " +
"use the built-in version of React."
);
}
}
/// <summary>
/// Gets the JavaScript engine for the current thread. It is recommended to use
/// <see cref="GetEngine"/> instead, which will pool/reuse engines.
/// </summary>
/// <returns>The JavaScript engine</returns>
public virtual IJsEngine GetEngineForCurrentThread()
{
EnsureNotDisposed();
return _engines.GetOrAdd(Thread.CurrentThread.ManagedThreadId, id =>
{
var engine = _factory();
InitialiseEngine(engine);
return engine;
});
}
/// <summary>
/// Disposes the JavaScript engine for the current thread.
/// </summary>
public virtual void DisposeEngineForCurrentThread()
{
IJsEngine engine;
if (_engines.TryRemove(Thread.CurrentThread.ManagedThreadId, out engine))
{
if (engine != null)
{
engine.Dispose();
}
}
}
/// <summary>
/// Gets a JavaScript engine from the pool.
/// </summary>
/// <returns>The JavaScript engine</returns>
public virtual IJsEngine GetEngine()
{
EnsureNotDisposed();
return _pool.GetEngine();
}
/// <summary>
/// Returns an engine to the pool so it can be reused
/// </summary>
/// <param name="engine">Engine to return</param>
public virtual void ReturnEngineToPool(IJsEngine engine)
{
// This could be called from ReactEnvironment.Dispose if that class is disposed after
// this class. Let's just ignore this if it's disposed.
if (!_disposed)
{
_pool.ReturnEngineToPool(engine);
}
}
/// <summary>
/// Gets a factory for the most appropriate JavaScript engine for the current environment.
/// The first functioning JavaScript engine with the lowest priority will be used.
/// </summary>
/// <returns>Function to create JavaScript engine</returns>
private static Func<IJsEngine> GetFactory(IEnumerable<Registration> availableFactories, bool allowMsie)
{
var availableEngineFactories = availableFactories
.OrderBy(x => x.Priority)
.Select(x => x.Factory);
foreach (var engineFactory in availableEngineFactories)
{
IJsEngine engine = null;
try
{
engine = engineFactory();
if (EngineIsUsable(engine, allowMsie))
{
// Success! Use this one.
return engineFactory;
}
}
catch (Exception ex)
{
// This engine threw an exception, try the next one
Trace.WriteLine(string.Format("Error initialising {0}: {1}", engineFactory, ex));
}
finally
{
if (engine != null)
{
engine.Dispose();
}
}
}
// Epic fail, none of the engines worked. Nothing we can do now.
// Throw an error relevant to the engine they should be able to use.
if (JavaScriptEngineUtils.EnvironmentSupportsClearScript())
{
JavaScriptEngineUtils.EnsureEngineFunctional<V8JsEngine, ClearScriptV8InitialisationException>(
ex => new ClearScriptV8InitialisationException(ex)
);
}
else if (JavaScriptEngineUtils.EnvironmentSupportsVroomJs())
{
JavaScriptEngineUtils.EnsureEngineFunctional<VroomJsEngine, VroomJsInitialisationException>(
ex => new VroomJsInitialisationException(ex.Message)
);
}
throw new ReactEngineNotFoundException();
}
/// <summary>
/// Performs a sanity check to ensure the specified engine type is usable.
/// </summary>
/// <param name="engine">Engine to test</param>
/// <param name="allowMsie">Whether the MSIE engine can be used</param>
/// <returns></returns>
private static bool EngineIsUsable(IJsEngine engine, bool allowMsie)
{
// Perform a sanity test to ensure this engine is usable
var isUsable = engine.Evaluate<int>("1 + 1") == 2;
var isMsie = engine is MsieJsEngine;
return isUsable && (!isMsie || allowMsie);
}
/// <summary>
/// Clean up all engines
/// </summary>
public virtual void Dispose()
{
_disposed = true;
foreach (var engine in _engines)
{
if (engine.Value != null)
{
engine.Value.Dispose();
}
}
if (_pool != null)
{
_pool.Dispose();
_pool = null;
}
}
/// <summary>
/// Ensures that this object has not been disposed.
/// </summary>
public void EnsureNotDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
}
/// <summary>
/// Represents a factory for a supported JavaScript engine.
/// </summary>
public class Registration
{
/// <summary>
/// Gets or sets the factory for this JavaScript engine
/// </summary>
public Func<IJsEngine> Factory { get; set; }
/// <summary>
/// Gets or sets the priority for this JavaScript engine. Engines with lower priority
/// are preferred.
/// </summary>
public int Priority { get; set; }
}
}
}