Skip to content

Commit cc7f75f

Browse files
clydinalan-agius4
authored andcommitted
perf(@angular-devkit/build-angular): execute dart-sass in a worker
The dart-sass Sass implementation will now be executed in a separate worker thread. The wrapper worker implementation provides an interface that can be directly used by Webpack's `sass-loader`. The worker implementation allows dart-sass to be executed in its synchronous mode which can be up to two times faster than its asynchronous mode. The worker thread also allows Webpack to continue other bundling tasks while the Sass stylesheets are being processed.
1 parent e37a96a commit cc7f75f

File tree

6 files changed

+283
-1
lines changed

6 files changed

+283
-1
lines changed

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@
119119
"@types/progress": "^2.0.3",
120120
"@types/resolve": "^1.17.1",
121121
"@types/rimraf": "^3.0.0",
122+
"@types/sass": "^1.16.0",
122123
"@types/semver": "^7.0.0",
123124
"@types/text-table": "^0.2.1",
124125
"@types/uuid": "^8.0.0",

packages/angular_devkit/build_angular/BUILD.bazel

+1
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ ts_library(
132132
"@npm//@types/parse5-html-rewriting-stream",
133133
"@npm//@types/postcss-preset-env",
134134
"@npm//@types/rimraf",
135+
"@npm//@types/sass",
135136
"@npm//@types/semver",
136137
"@npm//@types/text-table",
137138
"@npm//@types/webpack-dev-server",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import { Importer, ImporterReturnType, Options, Result, SassException } from 'sass';
10+
import { MessageChannel, Worker } from 'worker_threads';
11+
12+
/**
13+
* The callback type for the `dart-sass` asynchronous render function.
14+
*/
15+
type RenderCallback = (error?: SassException, result?: Result) => void;
16+
17+
/**
18+
* An object containing the contextual information for a specific render request.
19+
*/
20+
interface RenderRequest {
21+
id: number;
22+
callback: RenderCallback;
23+
importers?: Importer[];
24+
}
25+
26+
/**
27+
* A response from the Sass render Worker containing the result of the operation.
28+
*/
29+
interface RenderResponseMessage {
30+
id: number;
31+
error?: SassException;
32+
result?: Result;
33+
}
34+
35+
/**
36+
* A Sass renderer implementation that provides an interface that can be used by Webpack's
37+
* `sass-loader`. The implementation uses a Worker thread to perform the Sass rendering
38+
* with the `dart-sass` package. The `dart-sass` synchronous render function is used within
39+
* the worker which can be up to two times faster than the asynchronous variant.
40+
*/
41+
export class SassWorkerImplementation {
42+
private worker?: Worker;
43+
private readonly requests = new Map<number, RenderRequest>();
44+
private idCounter = 1;
45+
46+
/**
47+
* Provides information about the Sass implementation.
48+
* This mimics enough of the `dart-sass` value to be used with the `sass-loader`.
49+
*/
50+
get info(): string {
51+
return 'dart-sass\tworker';
52+
}
53+
54+
/**
55+
* The synchronous render function is not used by the `sass-loader`.
56+
*/
57+
renderSync(): never {
58+
throw new Error('Sass renderSync is not supported.');
59+
}
60+
61+
/**
62+
* Asynchronously request a Sass stylesheet to be renderered.
63+
*
64+
* @param options The `dart-sass` options to use when rendering the stylesheet.
65+
* @param callback The function to execute when the rendering is complete.
66+
*/
67+
render(options: Options, callback: RenderCallback): void {
68+
// The `functions` and `importer` options are JavaScript functions that cannot be transferred.
69+
// If any additional function options are added in the future, they must be excluded as well.
70+
const { functions, importer, ...serializableOptions } = options;
71+
72+
// The CLI's configuration does not use or expose the ability to defined custom Sass functions
73+
if (functions && Object.keys(functions).length > 0) {
74+
throw new Error('Sass custom functions are not supported.');
75+
}
76+
77+
if (!this.worker) {
78+
this.worker = this.createWorker();
79+
}
80+
81+
const request = this.createRequest(callback, importer);
82+
this.requests.set(request.id, request);
83+
84+
this.worker.postMessage({
85+
id: request.id,
86+
hasImporter: !!importer,
87+
options: serializableOptions,
88+
});
89+
}
90+
91+
/**
92+
* Shutdown the Sass render worker.
93+
* Executing this method will stop any pending render requests.
94+
*
95+
* The worker is unreferenced upon creation and will not block application exit. This method
96+
* is only needed if early cleanup is needed.
97+
*/
98+
close(): void {
99+
this.worker?.terminate();
100+
this.requests.clear();
101+
}
102+
103+
private createWorker(): Worker {
104+
const { port1: mainImporterPort, port2: workerImporterPort } = new MessageChannel();
105+
const importerSignal = new Int32Array(new SharedArrayBuffer(4));
106+
107+
const workerPath = require.resolve('./worker');
108+
const worker = new Worker(workerPath, {
109+
workerData: { workerImporterPort, importerSignal },
110+
transferList: [workerImporterPort],
111+
});
112+
113+
worker.on('message', (response: RenderResponseMessage) => {
114+
const request = this.requests.get(response.id);
115+
if (!request) {
116+
return;
117+
}
118+
119+
this.requests.delete(response.id);
120+
121+
if (response.result) {
122+
// The results are expected to be Node.js `Buffer` objects but will each be transferred as
123+
// a Uint8Array that does not have the expected `toString` behavior of a `Buffer`.
124+
const { css, map, stats } = response.result;
125+
const result: Result = {
126+
// This `Buffer.from` override will use the memory directly and avoid making a copy
127+
css: Buffer.from(css.buffer, css.byteOffset, css.byteLength),
128+
stats,
129+
};
130+
if (map) {
131+
// This `Buffer.from` override will use the memory directly and avoid making a copy
132+
result.map = Buffer.from(map.buffer, map.byteOffset, map.byteLength);
133+
}
134+
request.callback(undefined, result);
135+
} else {
136+
request.callback(response.error);
137+
}
138+
});
139+
140+
mainImporterPort.on(
141+
'message',
142+
({ id, url, prev }: { id: number; url: string; prev: string }) => {
143+
const request = this.requests.get(id);
144+
if (!request?.importers) {
145+
mainImporterPort.postMessage(null);
146+
Atomics.store(importerSignal, 0, 1);
147+
Atomics.notify(importerSignal, 0);
148+
149+
return;
150+
}
151+
152+
this.processImporters(request.importers, url, prev)
153+
.then((result) => {
154+
mainImporterPort.postMessage(result);
155+
})
156+
.catch((error) => {
157+
mainImporterPort.postMessage(error);
158+
})
159+
.finally(() => {
160+
Atomics.store(importerSignal, 0, 1);
161+
Atomics.notify(importerSignal, 0);
162+
});
163+
},
164+
);
165+
166+
worker.unref();
167+
mainImporterPort.unref();
168+
169+
return worker;
170+
}
171+
172+
private async processImporters(
173+
importers: Iterable<Importer>,
174+
url: string,
175+
prev: string,
176+
): Promise<ImporterReturnType> {
177+
let result = null;
178+
for (const importer of importers) {
179+
result = await new Promise<ImporterReturnType>((resolve) => {
180+
// Importers can be both sync and async
181+
const innerResult = importer(url, prev, resolve);
182+
if (innerResult !== undefined) {
183+
resolve(innerResult);
184+
}
185+
});
186+
187+
if (result) {
188+
break;
189+
}
190+
}
191+
192+
return result;
193+
}
194+
195+
private createRequest(
196+
callback: RenderCallback,
197+
importer: Importer | Importer[] | undefined,
198+
): RenderRequest {
199+
return {
200+
id: this.idCounter++,
201+
callback,
202+
importers: !importer || Array.isArray(importer) ? importer : [importer],
203+
};
204+
}
205+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.io/license
7+
*/
8+
9+
import { ImporterReturnType, Options, renderSync } from 'sass';
10+
import { MessagePort, parentPort, receiveMessageOnPort, workerData } from 'worker_threads';
11+
12+
/**
13+
* A request to render a Sass stylesheet using the supplied options.
14+
*/
15+
interface RenderRequestMessage {
16+
/**
17+
* The unique request identifier that links the render action with a callback and optional
18+
* importer on the main thread.
19+
*/
20+
id: number;
21+
/**
22+
* The Sass options to provide to the `dart-sass` render function.
23+
*/
24+
options: Options;
25+
/**
26+
* Indicates the request has a custom importer function on the main thread.
27+
*/
28+
hasImporter: boolean;
29+
}
30+
31+
if (!parentPort || !workerData) {
32+
throw new Error('Sass worker must be executed as a Worker.');
33+
}
34+
35+
// The importer variables are used to proxy import requests to the main thread
36+
const { workerImporterPort, importerSignal } = workerData as {
37+
workerImporterPort: MessagePort;
38+
importerSignal: Int32Array;
39+
};
40+
41+
parentPort.on('message', ({ id, hasImporter, options }: RenderRequestMessage) => {
42+
try {
43+
if (hasImporter) {
44+
// When a custom importer function is present, the importer request must be proxied
45+
// back to the main thread where it can be executed.
46+
// This process must be synchronous from the perspective of dart-sass. The `Atomics`
47+
// functions combined with the shared memory `importSignal` and the Node.js
48+
// `receiveMessageOnPort` function are used to ensure synchronous behavior.
49+
options.importer = (url, prev) => {
50+
Atomics.store(importerSignal, 0, 0);
51+
workerImporterPort.postMessage({ id, url, prev });
52+
Atomics.wait(importerSignal, 0, 0);
53+
54+
return receiveMessageOnPort(workerImporterPort)?.message as ImporterReturnType;
55+
};
56+
}
57+
58+
// The synchronous Sass render function can be up to two times faster than the async variant
59+
const result = renderSync(options);
60+
61+
parentPort?.postMessage({ id, result });
62+
} catch (error) {
63+
parentPort?.postMessage({ id, error });
64+
}
65+
});

packages/angular_devkit/build_angular/src/webpack/configs/styles.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import * as fs from 'fs';
1010
import * as path from 'path';
1111
import * as webpack from 'webpack';
1212
import { ExtraEntryPoint } from '../../browser/schema';
13+
import { SassWorkerImplementation } from '../../sass/sass-service';
1314
import { BuildBrowserFeatures } from '../../utils/build-browser-features';
1415
import { WebpackConfigOptions } from '../../utils/build-options';
1516
import {
@@ -114,7 +115,7 @@ export function getStylesConfig(wco: WebpackConfigOptions): webpack.Configuratio
114115
`To opt-out of the deprecated behaviour and start using 'sass' uninstall 'node-sass'.`,
115116
);
116117
} catch {
117-
sassImplementation = require('sass');
118+
sassImplementation = new SassWorkerImplementation();
118119
}
119120

120121
const assetNameTemplate = assetNameTemplateFactory(hashFormat);
@@ -288,6 +289,8 @@ export function getStylesConfig(wco: WebpackConfigOptions): webpack.Configuratio
288289
implementation: sassImplementation,
289290
sourceMap: true,
290291
sassOptions: {
292+
// Prevent use of `fibers` package as it no longer works in newer Node.js versions
293+
fiber: false,
291294
// bootstrap-sass requires a minimum precision of 8
292295
precision: 8,
293296
includePaths,

yarn.lock

+7
Original file line numberDiff line numberDiff line change
@@ -1842,6 +1842,13 @@
18421842
"@types/glob" "*"
18431843
"@types/node" "*"
18441844

1845+
"@types/sass@^1.16.0":
1846+
version "1.16.0"
1847+
resolved "https://registry.yarnpkg.com/@types/sass/-/sass-1.16.0.tgz#b41ac1c17fa68ffb57d43e2360486ef526b3d57d"
1848+
integrity sha512-2XZovu4NwcqmtZtsBR5XYLw18T8cBCnU2USFHTnYLLHz9fkhnoEMoDsqShJIOFsFhn5aJHjweiUUdTrDGujegA==
1849+
dependencies:
1850+
"@types/node" "*"
1851+
18451852
"@types/selenium-webdriver@^3.0.0":
18461853
version "3.0.17"
18471854
resolved "https://registry.yarnpkg.com/@types/selenium-webdriver/-/selenium-webdriver-3.0.17.tgz#50bea0c3c2acc31c959c5b1e747798b3b3d06d4b"

0 commit comments

Comments
 (0)