Skip to content

Commit 5f473af

Browse files
hborchardtjkrems
authored andcommitted
fix(@angular/build): avoid race condition in sass importer
On slow systems, a race condition can lead to the sass worker thread being notified to wake up before a message is posted. This causes the build to be aborted because the searched file is not found. Waiting twice for a non-zero number in the signal handles this race correctly, and the second wait should be a noop in the usual case. Fixes #27167
1 parent d8ab36b commit 5f473af

File tree

1 file changed

+19
-0
lines changed
  • packages/angular/build/src/tools/sass

1 file changed

+19
-0
lines changed

packages/angular/build/src/tools/sass/worker.ts

+19
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,25 @@ export default async function renderSassStylesheet(
106106
containingUrl: containingUrl ? fileURLToPath(containingUrl) : null,
107107
},
108108
});
109+
// Wait for the main thread to set the signal to 1 and notify, which tells
110+
// us that a message can be received on the port.
111+
// If the main thread is fast, the signal will already be set to 1, and no
112+
// sleep/notify is necessary.
113+
// However, there can be a race condition here:
114+
// - the main thread sets the signal to 1, but does not get to the notify instruction yet
115+
// - the worker does not pause because the signal is set to 1
116+
// - the worker very soon enters this method again
117+
// - this method sets the signal to 0 and sends the message
118+
// - the signal is 0 and so the `Atomics.wait` call blocks
119+
// - only now the main thread runs the `notify` from the first invocation, so the
120+
// worker continues.
121+
// - but there is no message yet in the port, because the thread should not have been
122+
// waken up yet.
123+
// To combat this, wait for a non-0 value _twice_.
124+
// Almost every time, this immediately continues with "not-equal", because
125+
// the signal is still set to 1, except during the race condition, when the second
126+
// wait will wait for the correct notify.
127+
Atomics.wait(importerChannel.signal, 0, 0);
109128
Atomics.wait(importerChannel.signal, 0, 0);
110129

111130
const result = receiveMessageOnPort(importerChannel.port)?.message as string | null;

0 commit comments

Comments
 (0)