Skip to content

Commit 1fd6b65

Browse files
fix(worker): route worker_threads errors like the web surface, and fire once listeners once (#2089)
* fix(worker): route parentPort listener throws and handled Node-style errors like the web surface A parentPort listener that threw was dispatched without rethrowing, so the error went to the uncaught-error reporter and never reached the worker's onerror or its parent. The relay now dispatches the way worker-global message delivery does. The worker_threads Worker's onerror handler returned nothing, so an error its 'error' listeners took was also reported to the parent's global scope as unhandled. It returns whether a listener ran, which cancels the event. * fix(worker): fire a worker_threads once listener at most once under a reentrant emit An earlier listener that emitted the same event again let the nested emit fire and remove a later once listener, and the outer emit then called it a second time from its snapshot. A once registration now records that it fired, as Node's once wrapper does. * fix(worker): hand worker_threads 'error' listeners an Error rebuilt from the thrown value A worker_threads 'error' listener received the runtime's ErrorEvent, not an Error, and the message it carried was V8's "Uncaught Error: ..." text. The worker now reads the thrown value's name and message and forwards them with the error payload. The parent rebuilds an Error from them with the worker's stack, using the built-in constructor the name belongs to, and the parent's global error event carries that same Error when nothing handled it. The Worker shim cancels an error its listeners took with preventDefault() rather than through the truthy-return contract of onerror. * fix(worker): keep a forwarded worker error exact when its stack getter throws Reading the stack of the error a worker's onerror threw could run a `stack` getter, and a getter that threw replaced that error in the TryCatch holding it, so the parent rebuilt the getter's error instead. The stack read now runs under its own TryCatch. The thrown value's name and message travel to the parent as UTF-16, so an unpaired surrogate arrives as thrown rather than as U+FFFD. ArgConverter::ConvertToString copies by length, so an embedded NUL no longer cuts a converted string short. * docs(worker): match the #reportExit comment to iOS Co-authored-by: Adrian Niculescu <15037449+adrian-niculescu@users.noreply.github.com>
1 parent fef72d5 commit 1fd6b65

18 files changed

Lines changed: 362 additions & 76 deletions

‎docs/ns-builtin-modules.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -732,12 +732,13 @@ resolvers read the same table differently:
732732
Seven rows are public today: `ns:module`, `ns:runtime`, `ns:util`,
733733
`node:module`, `node:url`, `node:util`, `node:worker_threads`.
734734
- The **internal require** builtins receive (previous section) is the only
735-
thing that can name an internal-only row. Five rows are marked that way:
735+
thing that can name an internal-only row. Six rows are marked that way:
736736
`internal/broadcast-channel`, `internal/dom-exception`, `internal/events`,
737-
`internal/message-channel`, `internal/message-event`. Their exports carry
738-
capabilities app code must not hold — listener-accounting hook keys, the
739-
error-reporter setter, base classes that must be the runtime's own rather
740-
than whatever a global currently names.
737+
`internal/message-channel`, `internal/message-event`,
738+
`internal/worker-events`. Their exports carry capabilities app code must not
739+
hold — listener-accounting hook keys, the error-reporter setter, the key a
740+
worker's rebuilt error travels under, base classes that must be the
741+
runtime's own rather than whatever a global currently names.
741742
- Builtins with **no row at all** (the intrinsics snapshot, the require
742743
factory, the console formatter) are invoked straight from their native call
743744
sites. There is no specifier that could reach them and nothing to mark.

‎docs/worker-threads.md‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ means deliberately unsupported.
5454
| `threadName` | shim | Always `undefined`. |
5555
| `workerData` | shim | Always `null` — see below. |
5656
| `parentPort` | shim | `null` on the main isolate. Inside a worker, a `MessagePort`-shaped `EventTarget` over the worker's existing parent channel: `postMessage` forwards to the global `postMessage`, `message`/`messageerror` are re-dispatched from the worker global scope, `start()` and `close()` are no-ops. It is **not** a real port: not transferable, no queue of its own. |
57-
| `Worker` | shim | A class over the runtime's global `Worker` with a small Node-style emitter (`on`/`once`/`off`/`removeListener`) for `message`, `messageerror`, `error`, `online` and `exit`. `postMessage(value, transfer)` and `terminate()` forward. `online` is emitted off a microtask after construction, not from the thread. `exit` (always code `0`) fires exactly once, when the thread has ended, whether the worker was terminated or ended by its own `close()`; `terminate()` resolves at the same point. Unsupported options throw a `TypeError` naming the option: `workerData`, `env`, `eval`, `transferList`, and `stdin`/`stdout`/`stderr` when explicitly truthy. The runtime's own `Worker` options (`androidPriority`) ride along untouched — the native constructor ignores keys it does not know. |
57+
| `Worker` | shim | A class over the runtime's global `Worker` with a small Node-style emitter (`on`/`once`/`off`/`removeListener`) for `message`, `messageerror`, `error`, `online` and `exit`. An `error` listener receives the worker's error rebuilt as an `Error` (see below). `postMessage(value, transfer)` and `terminate()` forward. `online` is emitted off a microtask after construction, not from the thread. `exit` (always code `0`) fires exactly once, when the thread has ended, whether the worker was terminated or ended by its own `close()`; `terminate()` resolves at the same point. Unsupported options throw a `TypeError` naming the option: `workerData`, `env`, `eval`, `transferList`, and `stdin`/`stdout`/`stderr` when explicitly truthy. The runtime's own `Worker` options (`androidPriority`) ride along untouched — the native constructor ignores keys it does not know. |
5858
| `postMessageToThread` | throws | `Error: postMessageToThread is not supported in this runtime`. |
5959
| `moveMessagePortToContext` | throws | `Error: moveMessagePortToContext is not supported in this runtime`. |
6060
| `locks` | absent | Web Locks are not implemented; the property does not exist. |
@@ -83,6 +83,22 @@ the code is `0` whichever way the worker ended — `terminate()`, its own
8383
delivers the notification, so a `terminate()` awaited from a dying isolate
8484
stays pending, as it does in Node when the parent process exits.
8585

86+
### An `error` listener receives a rebuilt `Error`
87+
88+
Node hands an `error` listener the worker's error deserialized on the parent.
89+
Only strings cross the isolate boundary here, so the parent rebuilds it from
90+
the thrown value's `name` and `message`, with the worker's stack as its
91+
`stack`. A built-in name (`TypeError`, `RangeError`, …) rebuilds with that
92+
constructor, so `instanceof` holds; any other name, a subclass's or a
93+
`DOMException`'s, is an own `name` on an `Error`. Other properties, such as a
94+
`code` or a `cause`, are not carried. A thrown value with no string `message`,
95+
such as a string or a number, arrives as an `Error` whose message is its string
96+
form, where Node hands over the value itself.
97+
98+
Once an `error` listener has received it, the error counts as handled and is
99+
not reported on the parent's global scope. With no `error` listener, the
100+
parent's global `error` event carries the same rebuilt `Error`.
101+
86102
### A worker error carries no `error` object, and the worker scope's `onerror` is not an event
87103

88104
An error the worker scope leaves unhandled reaches the parent as a real

‎eslint.config.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ const capturedStatics = [
3232

3333
// Captured constructors. A destructure from `primordials` shadows the global,
3434
// so these only fire on the unguarded reference.
35-
const restrictedGlobals = ['Date', 'FinalizationRegistry', 'Map', 'Number', 'Promise', 'Proxy', 'RangeError', 'Set', 'String', 'TypeError', 'Uint8Array', 'Uint32Array', 'WeakRef', 'WeakSet'].map((name) => ({
35+
const restrictedGlobals = ['Date', 'EvalError', 'FinalizationRegistry', 'Map', 'Number', 'Promise', 'Proxy', 'RangeError', 'ReferenceError', 'Set', 'String', 'SyntaxError', 'TypeError', 'Uint8Array', 'Uint32Array', 'URIError', 'WeakRef', 'WeakSet'].map((name) => ({
3636
name,
3737
message: `Destructure ${name} from primordials — builtins must not read intrinsics off globals user code can replace.`,
3838
}));
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
throw new DOMException("aborted in a worker", "AbortError");
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// The scope's onerror throws an error whose message holds a NUL and an
2+
// unpaired surrogate, and whose stack getter throws.
3+
onerror = function () {
4+
var error = new TypeError("before\0after \uD800");
5+
Object.defineProperty(error, "stack", {
6+
get: function () { throw new RangeError("thrown by the stack getter"); }
7+
});
8+
throw error;
9+
};
10+
onmessage = function () {
11+
throw new Error("thrown by onmessage");
12+
};
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
var parentPort = require("node:worker_threads").parentPort;
2+
parentPort.on("message", function () {
3+
throw new TypeError("thrown by a parentPort listener");
4+
});

‎test-app/app/src/main/assets/app/tests/testMessaging.js‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,7 @@ describe("Messaging runtime edges", function () {
355355
expect(seen.length).toBe(1);
356356
expect(seen[0].message).toContain("boom from worker");
357357
expect(seen[0].error instanceof Error).toBe(true);
358+
expect(seen[0].error.message).toBe("boom from worker");
358359
worker.terminate();
359360
done();
360361
};
@@ -378,6 +379,94 @@ describe("Messaging runtime edges", function () {
378379
}
379380
};
380381
});
382+
383+
it("lets a node:worker_threads 'error' listener consume the error", function (done) {
384+
var wt = require("node:worker_threads");
385+
var globalErrors = [];
386+
var listener = function (event) {
387+
globalErrors.push(event.message);
388+
event.preventDefault();
389+
};
390+
addEventListener("error", listener);
391+
var worker = new wt.Worker("~/tests/messaging/throwingWorker.js");
392+
worker.on("error", function (error) {
393+
setTimeout(function () {
394+
removeEventListener("error", listener);
395+
expect(error instanceof Error).toBe(true);
396+
expect(error.name).toBe("Error");
397+
expect(error.message).toBe("boom from worker");
398+
expect(error.stack).toContain("boom from worker");
399+
expect(globalErrors).toEqual([]);
400+
worker.terminate();
401+
done();
402+
}, SETTLE);
403+
});
404+
});
405+
406+
it("hands a node:worker_threads 'error' listener a thrown DOMException's name and message", function (done) {
407+
var wt = require("node:worker_threads");
408+
var worker = new wt.Worker("~/tests/messaging/domExceptionThrowingWorker.js");
409+
worker.on("error", function (error) {
410+
expect(error instanceof Error).toBe(true);
411+
expect(error.name).toBe("AbortError");
412+
expect(error.message).toBe("aborted in a worker");
413+
worker.terminate();
414+
done();
415+
});
416+
});
417+
418+
it("rebuilds the error a worker's onerror threw exactly, even when its stack getter throws", function (done) {
419+
var wt = require("node:worker_threads");
420+
var worker = new wt.Worker("~/tests/messaging/onerrorRethrowingWorker.js");
421+
worker.on("error", function (error) {
422+
expect(error instanceof TypeError).toBe(true);
423+
expect(error.message).toBe("before\0after \uD800");
424+
worker.terminate();
425+
done();
426+
});
427+
worker.postMessage("go");
428+
});
429+
430+
it("calls a node:worker_threads once listener once when an earlier listener emits again", function () {
431+
var wt = require("node:worker_threads");
432+
var worker = new wt.Worker("~/tests/eventLoopEchoWorker.js");
433+
var calls = 0;
434+
var nested = false;
435+
worker.on("probe", function () {
436+
if (!nested) {
437+
nested = true;
438+
worker.emit("probe");
439+
}
440+
});
441+
worker.once("probe", function () { calls++; });
442+
worker.emit("probe");
443+
worker.terminate();
444+
expect(calls).toBe(1);
445+
});
446+
447+
it("routes a throw from a parentPort listener to the parent's 'error' listeners", function (done) {
448+
var wt = require("node:worker_threads");
449+
var worker = new wt.Worker("~/tests/messaging/parentPortThrowingWorker.js");
450+
var errors = [];
451+
var finish = function () {
452+
expect(errors.length).toBe(1);
453+
expect(errors[0] instanceof TypeError).toBe(true);
454+
expect(errors[0].name).toBe("TypeError");
455+
expect(errors[0].message).toBe("thrown by a parentPort listener");
456+
worker.terminate();
457+
done();
458+
};
459+
// Nothing else settles the spec when the error never arrives.
460+
var guard = setTimeout(finish, 10000);
461+
worker.on("error", function (error) {
462+
errors.push(error);
463+
if (errors.length === 1) {
464+
clearTimeout(guard);
465+
setTimeout(finish, SETTLE);
466+
}
467+
});
468+
worker.postMessage("go");
469+
});
381470
});
382471

383472
describe("AbortSignal handler attribute accounting", function () {

‎test-app/runtime/src/main/cpp/ArgConverter.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ class ArgConverter {
6060
} else {
6161
auto isolate = v8::Isolate::GetCurrent();
6262
v8::String::Utf8Value str(isolate, s);
63-
return {*str};
63+
return {*str, static_cast<size_t>(str.length())};
6464
}
6565
}
6666

‎test-app/runtime/src/main/cpp/CallbackHandlers.cpp‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1837,6 +1837,9 @@ static void ExtractTryCatchInfo(Isolate *isolate, Local<Context> context, TryCat
18371837
}
18381838
}
18391839

1840+
// `stack` may be an accessor. One that throws only costs the stack: caught
1841+
// here, its exception cannot replace the one `tc` holds.
1842+
TryCatch stackTc(isolate);
18401843
Local<Value> outStackTrace = tc.StackTrace(context).FromMaybe(Local<Value>());
18411844
if (!outStackTrace.IsEmpty()) {
18421845
Local<String> stackTraceStr =
@@ -1897,14 +1900,16 @@ void CallbackHandlers::CallWorkerScopeOnErrorHandle(Isolate *isolate, TryCatch &
18971900
// parent sees the handler's own error, and only that one.
18981901
if (innerTc.HasCaught()) {
18991902
ExtractTryCatchInfo(isolate, context, innerTc, message, source, stackTrace, lineno);
1900-
wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno);
1903+
wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno,
1904+
innerTc.Exception());
19011905
return;
19021906
}
19031907

19041908
// Unhandled at the worker scope - including when there is no scope
19051909
// handler at all - so it becomes the parent's error event.
19061910
ExtractTryCatchInfo(isolate, context, tc, message, source, stackTrace, lineno);
1907-
wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno);
1911+
wrapper->PassUncaughtExceptionFromWorkerToParent(message, source, stackTrace, lineno,
1912+
tc.Exception());
19081913
} catch (NativeScriptException &ex) {
19091914
ex.ReThrowToV8();
19101915
} catch (std::exception e) {

‎test-app/runtime/src/main/cpp/NativeScriptException.cpp‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -918,7 +918,9 @@ void PromiseRejectionTracker::Drain() {
918918
!workerWrapper->IsTerminating() && !workerWrapper->IsDisposed()) {
919919
string forwarded = message;
920920
string forwardedStack = stackTrace;
921+
Local<Value> forwardedValue = reason;
921922
if (!thrown.IsEmpty()) {
923+
forwardedValue = thrown;
922924
forwarded = ToDetailString(isolate, thrown);
923925
// The handler's own stack replaces the reason's; an accessor
924926
// that throws costs the stack, never the forward.
@@ -930,7 +932,7 @@ void PromiseRejectionTracker::Drain() {
930932
}
931933
}
932934
workerWrapper->PassUncaughtExceptionFromWorkerToParent(
933-
forwarded, "", forwardedStack, 0);
935+
forwarded, "", forwardedStack, 0, forwardedValue);
934936
}
935937
}
936938
} else {

0 commit comments

Comments
 (0)