-
Notifications
You must be signed in to change notification settings - Fork 12k
perf(@angular-devkit/build-angular): execute dart-sass in a worker #20740
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
205 changes: 205 additions & 0 deletions
205
packages/angular_devkit/build_angular/src/sass/sass-service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,205 @@ | ||
/** | ||
* @license | ||
* Copyright Google LLC All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
import { Importer, ImporterReturnType, Options, Result, SassException } from 'sass'; | ||
import { MessageChannel, Worker } from 'worker_threads'; | ||
|
||
/** | ||
* The callback type for the `dart-sass` asynchronous render function. | ||
*/ | ||
type RenderCallback = (error?: SassException, result?: Result) => void; | ||
|
||
/** | ||
* An object containing the contextual information for a specific render request. | ||
*/ | ||
interface RenderRequest { | ||
id: number; | ||
callback: RenderCallback; | ||
importers?: Importer[]; | ||
} | ||
|
||
/** | ||
* A response from the Sass render Worker containing the result of the operation. | ||
*/ | ||
interface RenderResponseMessage { | ||
id: number; | ||
error?: SassException; | ||
result?: Result; | ||
} | ||
|
||
/** | ||
* A Sass renderer implementation that provides an interface that can be used by Webpack's | ||
* `sass-loader`. The implementation uses a Worker thread to perform the Sass rendering | ||
* with the `dart-sass` package. The `dart-sass` synchronous render function is used within | ||
* the worker which can be up to two times faster than the asynchronous variant. | ||
*/ | ||
export class SassWorkerImplementation { | ||
private worker?: Worker; | ||
private readonly requests = new Map<number, RenderRequest>(); | ||
private idCounter = 1; | ||
|
||
/** | ||
* Provides information about the Sass implementation. | ||
* This mimics enough of the `dart-sass` value to be used with the `sass-loader`. | ||
*/ | ||
get info(): string { | ||
return 'dart-sass\tworker'; | ||
} | ||
|
||
/** | ||
* The synchronous render function is not used by the `sass-loader`. | ||
*/ | ||
renderSync(): never { | ||
throw new Error('Sass renderSync is not supported.'); | ||
} | ||
|
||
/** | ||
* Asynchronously request a Sass stylesheet to be renderered. | ||
* | ||
* @param options The `dart-sass` options to use when rendering the stylesheet. | ||
* @param callback The function to execute when the rendering is complete. | ||
*/ | ||
render(options: Options, callback: RenderCallback): void { | ||
// The `functions` and `importer` options are JavaScript functions that cannot be transferred. | ||
// If any additional function options are added in the future, they must be excluded as well. | ||
const { functions, importer, ...serializableOptions } = options; | ||
|
||
// The CLI's configuration does not use or expose the ability to defined custom Sass functions | ||
if (functions && Object.keys(functions).length > 0) { | ||
throw new Error('Sass custom functions are not supported.'); | ||
} | ||
|
||
if (!this.worker) { | ||
this.worker = this.createWorker(); | ||
} | ||
|
||
const request = this.createRequest(callback, importer); | ||
this.requests.set(request.id, request); | ||
|
||
this.worker.postMessage({ | ||
id: request.id, | ||
hasImporter: !!importer, | ||
options: serializableOptions, | ||
}); | ||
} | ||
|
||
/** | ||
* Shutdown the Sass render worker. | ||
* Executing this method will stop any pending render requests. | ||
* | ||
* The worker is unreferenced upon creation and will not block application exit. This method | ||
* is only needed if early cleanup is needed. | ||
*/ | ||
close(): void { | ||
this.worker?.terminate(); | ||
this.requests.clear(); | ||
} | ||
|
||
private createWorker(): Worker { | ||
const { port1: mainImporterPort, port2: workerImporterPort } = new MessageChannel(); | ||
const importerSignal = new Int32Array(new SharedArrayBuffer(4)); | ||
|
||
const workerPath = require.resolve('./worker'); | ||
const worker = new Worker(workerPath, { | ||
workerData: { workerImporterPort, importerSignal }, | ||
transferList: [workerImporterPort], | ||
}); | ||
|
||
worker.on('message', (response: RenderResponseMessage) => { | ||
const request = this.requests.get(response.id); | ||
if (!request) { | ||
return; | ||
} | ||
|
||
this.requests.delete(response.id); | ||
|
||
if (response.result) { | ||
// The results are expected to be Node.js `Buffer` objects but will each be transferred as | ||
// a Uint8Array that does not have the expected `toString` behavior of a `Buffer`. | ||
const { css, map, stats } = response.result; | ||
const result: Result = { | ||
// This `Buffer.from` override will use the memory directly and avoid making a copy | ||
css: Buffer.from(css.buffer, css.byteOffset, css.byteLength), | ||
stats, | ||
}; | ||
if (map) { | ||
// This `Buffer.from` override will use the memory directly and avoid making a copy | ||
result.map = Buffer.from(map.buffer, map.byteOffset, map.byteLength); | ||
} | ||
request.callback(undefined, result); | ||
} else { | ||
request.callback(response.error); | ||
} | ||
}); | ||
|
||
mainImporterPort.on( | ||
'message', | ||
({ id, url, prev }: { id: number; url: string; prev: string }) => { | ||
const request = this.requests.get(id); | ||
if (!request?.importers) { | ||
mainImporterPort.postMessage(null); | ||
Atomics.store(importerSignal, 0, 1); | ||
Atomics.notify(importerSignal, 0); | ||
|
||
return; | ||
} | ||
|
||
this.processImporters(request.importers, url, prev) | ||
.then((result) => { | ||
mainImporterPort.postMessage(result); | ||
}) | ||
.catch((error) => { | ||
mainImporterPort.postMessage(error); | ||
}) | ||
.finally(() => { | ||
Atomics.store(importerSignal, 0, 1); | ||
Atomics.notify(importerSignal, 0); | ||
}); | ||
}, | ||
); | ||
|
||
worker.unref(); | ||
mainImporterPort.unref(); | ||
|
||
return worker; | ||
} | ||
|
||
private async processImporters( | ||
importers: Iterable<Importer>, | ||
url: string, | ||
prev: string, | ||
): Promise<ImporterReturnType> { | ||
let result = null; | ||
for (const importer of importers) { | ||
result = await new Promise<ImporterReturnType>((resolve) => { | ||
// Importers can be both sync and async | ||
const innerResult = importer(url, prev, resolve); | ||
if (innerResult !== undefined) { | ||
resolve(innerResult); | ||
} | ||
}); | ||
|
||
if (result) { | ||
break; | ||
} | ||
} | ||
|
||
return result; | ||
} | ||
|
||
private createRequest( | ||
callback: RenderCallback, | ||
importer: Importer | Importer[] | undefined, | ||
): RenderRequest { | ||
return { | ||
id: this.idCounter++, | ||
callback, | ||
importers: !importer || Array.isArray(importer) ? importer : [importer], | ||
}; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
/** | ||
* @license | ||
* Copyright Google LLC All Rights Reserved. | ||
* | ||
* Use of this source code is governed by an MIT-style license that can be | ||
* found in the LICENSE file at https://angular.io/license | ||
*/ | ||
|
||
import { ImporterReturnType, Options, renderSync } from 'sass'; | ||
import { MessagePort, parentPort, receiveMessageOnPort, workerData } from 'worker_threads'; | ||
|
||
/** | ||
* A request to render a Sass stylesheet using the supplied options. | ||
*/ | ||
interface RenderRequestMessage { | ||
/** | ||
* The unique request identifier that links the render action with a callback and optional | ||
* importer on the main thread. | ||
*/ | ||
id: number; | ||
/** | ||
* The Sass options to provide to the `dart-sass` render function. | ||
*/ | ||
options: Options; | ||
/** | ||
* Indicates the request has a custom importer function on the main thread. | ||
*/ | ||
hasImporter: boolean; | ||
} | ||
|
||
if (!parentPort || !workerData) { | ||
throw new Error('Sass worker must be executed as a Worker.'); | ||
} | ||
|
||
// The importer variables are used to proxy import requests to the main thread | ||
const { workerImporterPort, importerSignal } = workerData as { | ||
workerImporterPort: MessagePort; | ||
importerSignal: Int32Array; | ||
}; | ||
|
||
parentPort.on('message', ({ id, hasImporter, options }: RenderRequestMessage) => { | ||
try { | ||
if (hasImporter) { | ||
// When a custom importer function is present, the importer request must be proxied | ||
// back to the main thread where it can be executed. | ||
// This process must be synchronous from the perspective of dart-sass. The `Atomics` | ||
// functions combined with the shared memory `importSignal` and the Node.js | ||
// `receiveMessageOnPort` function are used to ensure synchronous behavior. | ||
options.importer = (url, prev) => { | ||
Atomics.store(importerSignal, 0, 0); | ||
workerImporterPort.postMessage({ id, url, prev }); | ||
Atomics.wait(importerSignal, 0, 0); | ||
|
||
return receiveMessageOnPort(workerImporterPort)?.message as ImporterReturnType; | ||
}; | ||
} | ||
|
||
// The synchronous Sass render function can be up to two times faster than the async variant | ||
const result = renderSync(options); | ||
|
||
parentPort?.postMessage({ id, result }); | ||
} catch (error) { | ||
parentPort?.postMessage({ id, error }); | ||
} | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clever way, to make the importer sync 👍