Skip to content

Commit 0bc38a2

Browse files
authored
Merge pull request #142 from EvotecIT/feature/script-execution-options
Create Jint engines through a configuration service
2 parents f84f18d + 25dc67b commit 0bc38a2

6 files changed

Lines changed: 226 additions & 15 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
- Fixed background thread leaks when worker construction is rejected
44
- Fixed canonical DOM node identity and concrete prototypes through `DomSameObject` getters (#140)
5+
- Added `JsScriptingOptions.EngineCreator` to create a configured Jint engine before any page script runs
56

67
# 1.1.0
78

‎README.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,29 @@ var config = Configuration.Default
4646
});
4747
```
4848

49+
Register an `EngineCreator` service to configure Jint before inline page scripts run:
50+
51+
```cs
52+
using Jint;
53+
using AngleSharp.Js;
54+
55+
var config = Configuration.Default
56+
.With(new EngineCreator((window, options) => new Engine(options
57+
.MaxStatements(100_000)
58+
.TimeoutInterval(TimeSpan.FromSeconds(5))
59+
.LimitMemory(16 * 1024 * 1024))))
60+
.WithJs();
61+
```
62+
63+
The factory runs once for each window and must return a fresh engine using the supplied options.
64+
Those options contain AngleSharp's DOM module loader, object wrapper, and call stack guard.
65+
DOM bindings are installed after the factory returns. Configure the engine and host globals
66+
in the factory, then access DOM objects and evaluate page scripts through the document.
67+
Jint controls the scope and reset behavior of its constraints.
68+
Any state captured by the service remains owned by the host.
69+
Hosts sharing one configuration across windows must make
70+
their captured state safe for that use.
71+
4972
You can also use this part with a console for logging. The call for this is `WithConsoleLogger`, e.g.,
5073

5174
```cs
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
namespace AngleSharp.Js.Tests
2+
{
3+
using AngleSharp.Dom;
4+
using AngleSharp.Io;
5+
using AngleSharp.Js.Tests.Mocks;
6+
using AngleSharp.Scripting;
7+
using Jint;
8+
using Jint.Runtime;
9+
using NUnit.Framework;
10+
using System;
11+
using System.Collections.Concurrent;
12+
using System.Threading;
13+
using System.Threading.Tasks;
14+
15+
public class EngineConfigurationTests
16+
{
17+
[Test]
18+
public async Task ConstraintsAreInstalledBeforeInlineScriptsRun()
19+
{
20+
var config = Configuration.Default
21+
.With(new EngineCreator((window, options) => new Engine(options.MaxStatements(64))))
22+
.WithJs()
23+
.WithEventLoop();
24+
25+
using (var context = BrowsingContext.New(config))
26+
{
27+
var document = await context.OpenAsync(request => request.Content(
28+
"<div id='result'>before</div><script>for (var i = 0; i < 1000; i++) {} " +
29+
"document.getElementById('result').textContent = 'after';</script>")).ConfigureAwait(false);
30+
31+
Assert.AreEqual("before", document.QuerySelector("#result").TextContent);
32+
Assert.Throws<StatementsCountOverflowException>(() => document.ExecuteScript(
33+
"for (var i = 0; i < 1000; i++) {}"));
34+
Assert.AreEqual("before", document.ExecuteScript("document.getElementById('result').textContent"));
35+
}
36+
}
37+
38+
[Test]
39+
public async Task CreatorServiceCanBeCreatedForEachBrowsingContext()
40+
{
41+
var services = 0;
42+
Func<IBrowsingContext, EngineCreator> createService = _ =>
43+
{
44+
services++;
45+
var limit = services == 1 ? 64 : 2000;
46+
return (window, options) => new Engine(options.MaxStatements(limit));
47+
};
48+
var config = Configuration.Default.With(createService).WithJs().WithEventLoop();
49+
50+
using (var first = BrowsingContext.New(config))
51+
using (var second = BrowsingContext.New(config))
52+
{
53+
var firstDocument = await first.OpenNewAsync().ConfigureAwait(false);
54+
var secondDocument = await second.OpenNewAsync().ConfigureAwait(false);
55+
Assert.Throws<StatementsCountOverflowException>(() => firstDocument.ExecuteScript(
56+
"for (var i = 0; i < 1000; i++) {}"));
57+
Assert.AreEqual(100, secondDocument.ExecuteScript("var i = 0; for (; i < 100; i++) {} i;"));
58+
Assert.AreEqual(2, services);
59+
}
60+
}
61+
62+
[Test]
63+
public async Task CreatorRunsOncePerWindowAndRetainsDomWrapping()
64+
{
65+
var calls = 0;
66+
var windows = new ConcurrentQueue<IWindow>();
67+
var config = Configuration.Default.With(new EngineCreator((window, options) =>
68+
{
69+
calls++;
70+
windows.Enqueue(window);
71+
return new Engine(options.MaxStatements(1000));
72+
})).WithJs().WithEventLoop();
73+
74+
using (var firstContext = BrowsingContext.New(config))
75+
using (var secondContext = BrowsingContext.New(config))
76+
{
77+
var first = await firstContext.OpenAsync(request => request.Content("<p>first</p>")).ConfigureAwait(false);
78+
var second = await secondContext.OpenAsync(request => request.Content("<p>second</p>")).ConfigureAwait(false);
79+
80+
Assert.AreEqual("first", first.ExecuteScript("document.querySelector('p').textContent"));
81+
Assert.AreEqual("first", first.ExecuteScript("document.querySelector('p').textContent"));
82+
Assert.AreEqual("second", second.ExecuteScript("document.querySelector('p').textContent"));
83+
Assert.AreEqual(2, calls);
84+
CollectionAssert.AreEqual(new[] { first.DefaultView, second.DefaultView }, windows.ToArray());
85+
}
86+
}
87+
88+
[Test]
89+
public async Task CreatorReturnsTheEngineUsedForInlineScriptsAndDomBindings()
90+
{
91+
Engine created = null;
92+
var config = Configuration.Default.With(new EngineCreator((window, options) =>
93+
{
94+
created = new Engine(options.Configure(engine => engine.SetValue("hostValue", "configured")));
95+
return created;
96+
})).WithJs().WithEventLoop();
97+
98+
using (var context = BrowsingContext.New(config))
99+
{
100+
var document = await context.OpenAsync(request => request.Content(
101+
"<p>before</p><script>document.querySelector('p').textContent = hostValue;</script>")).ConfigureAwait(false);
102+
Assert.AreEqual("configured", document.QuerySelector("p").TextContent);
103+
Assert.AreSame(created, context.GetService<JsScriptingService>().GetOrCreateJint(document));
104+
created.SetValue("hostNode", document.QuerySelector("p"));
105+
Assert.AreEqual(true, document.ExecuteScript("hostNode === document.querySelector('p')"));
106+
}
107+
}
108+
109+
[TestCase(false)]
110+
[TestCase(true)]
111+
public async Task WorkersInheritTheEngineCreatorService(Boolean contextFactory)
112+
{
113+
var services = 0;
114+
var windows = new ConcurrentQueue<IWindow>();
115+
EngineCreator CreateEngine(String hostValue) => (window, options) =>
116+
{
117+
windows.Enqueue(window);
118+
return new Engine(options.MaxStatements(256)
119+
.Configure(engine => engine.SetValue("hostValue", hostValue)));
120+
};
121+
Object registration = contextFactory
122+
? (Object)new Func<IBrowsingContext, EngineCreator>(_ => CreateEngine("context-" + Interlocked.Increment(ref services)))
123+
: CreateEngine("configured");
124+
var config = Configuration.Default
125+
.With(registration)
126+
.WithJs()
127+
.WithEventLoop()
128+
.With(new DelayedRequester(0, "self.__host = hostValue; for (var i = 0; i < 10000; i++) {} self.__after = true;"))
129+
.WithDefaultLoader(new LoaderOptions { IsResourceLoadingEnabled = true });
130+
131+
using (var context = BrowsingContext.New(config))
132+
{
133+
var document = await context.OpenNewAsync().ConfigureAwait(false);
134+
Assert.AreEqual(contextFactory ? "context-1" : "configured", document.ExecuteScript("hostValue"));
135+
var worker = new Dom.Worker(document.DefaultView, "https://example.com/worker.js");
136+
137+
try
138+
{
139+
for (var retries = 200; retries > 0 && !worker.IsInitialized && worker.StartupError is null; retries--)
140+
{
141+
await Task.Delay(10).ConfigureAwait(false);
142+
}
143+
144+
Assert.IsInstanceOf<StatementsCountOverflowException>(worker.StartupError);
145+
Assert.AreEqual(contextFactory ? "context-2" : "configured", worker.EvaluateInWorker("self.__host"));
146+
Assert.AreEqual("undefined", worker.EvaluateInWorker("typeof self.__after"));
147+
var createdWindows = windows.ToArray();
148+
Assert.AreEqual(2, createdWindows.Length);
149+
Assert.AreSame(document.DefaultView, createdWindows[0]);
150+
Assert.AreNotSame(document.DefaultView, createdWindows[1]);
151+
Assert.AreNotSame(context, createdWindows[1].Document.Context);
152+
Assert.AreSame(createdWindows[1], createdWindows[1].Document.DefaultView);
153+
if (contextFactory)
154+
{
155+
Assert.AreEqual(2, services);
156+
}
157+
}
158+
finally
159+
{
160+
worker.Terminate();
161+
}
162+
}
163+
}
164+
}
165+
}

‎src/AngleSharp.Js/Dom/Worker.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,15 @@ public Worker(IWindow window, String source)
7272
var workerConfig = Configuration.Default
7373
.With(_scripting)
7474
.WithOnly(_workerLoop);
75+
76+
foreach (var service in parentContext.OriginalServices)
77+
{
78+
if (service is EngineCreator || service is Func<IBrowsingContext, EngineCreator>)
79+
{
80+
workerConfig = workerConfig.With(service);
81+
}
82+
}
83+
7584
_workerContext = BrowsingContext.New(workerConfig);
7685

7786
Enqueue(_workerLoop, TaskPriority.Critical, () =>

‎src/AngleSharp.Js/EngineCreator.cs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
namespace AngleSharp.Js
2+
{
3+
using AngleSharp.Dom;
4+
5+
/// <summary>
6+
/// Creates a window's Jint engine. Register this service with the configuration
7+
/// to customize engine creation before page scripts run.
8+
/// </summary>
9+
/// <param name="window">The window whose engine is being created.</param>
10+
/// <param name="options">Options containing the DOM wrapper, module loader, and stack guard.</param>
11+
/// <returns>A fresh engine constructed with the supplied options.</returns>
12+
/// <remarks>
13+
/// DOM bindings are installed after this delegate returns. Configure the engine
14+
/// and host globals here; access DOM objects and run page scripts afterwards.
15+
/// </remarks>
16+
public delegate Jint.Engine EngineCreator(IWindow window, Jint.Options options);
17+
}

‎src/AngleSharp.Js/EngineInstance.cs‎

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -37,21 +37,17 @@ sealed class EngineInstance
3737
public EngineInstance(IWindow window, IDictionary<String, Object> assignments, IEnumerable<Assembly> libs, JsScriptingOptions options)
3838
{
3939
_importMap = new JsImportMap();
40-
41-
_engine = new Engine((o) =>
42-
{
43-
o.EnableModules(new JsModuleLoader(this, window.Document, false));
44-
// The handler answers out of the caches assigned right below, which only exist
45-
// once this constructor returns. Jint wraps nothing while it is configuring
46-
// itself, so that is safe - and Engine.Options is internal, so registering the
47-
// handler afterwards is not an option.
48-
o.SetWrapObjectHandler(WrapObject);
49-
// Left alone, the JS call stack is the native one, and a script recursing
50-
// deeper than it holds takes the whole process down - a StackOverflowException
51-
// cannot be caught. Guarded, the engine continues on a fresh stack and finally
52-
// reports an ordinary "Maximum call stack size exceeded" error instead.
53-
o.Constraints.MaxExecutionStackCount = options.MaxCallStackDepth > 0 ? options.MaxCallStackDepth : StackGuardDisabled;
54-
});
40+
var engineOptions = new Options();
41+
engineOptions.EnableModules(new JsModuleLoader(this, window.Document, false));
42+
// The handler uses the caches initialized below. The creator must return the
43+
// engine before DOM objects are wrapped or page scripts are evaluated.
44+
engineOptions.SetWrapObjectHandler(WrapObject);
45+
// Left alone, the JS call stack is the native one, and a runaway recursion
46+
// takes the process down with an uncatchable StackOverflowException.
47+
engineOptions.Constraints.MaxExecutionStackCount = options.MaxCallStackDepth > 0 ? options.MaxCallStackDepth : StackGuardDisabled;
48+
var creator = window.Document.Context.GetService<EngineCreator>();
49+
_engine = (creator is null ? new Engine(engineOptions) : creator.Invoke(window, engineOptions))
50+
?? throw new InvalidOperationException("The engine creator must return a Jint engine.");
5551
_libs = new LibrarySet(libs);
5652
_prototypes = new PrototypeCache(_engine, _libs);
5753
_references = new ReferenceCache();

0 commit comments

Comments
 (0)