Skip to content
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

process: add multipleResolves event #22218

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions doc/api/process.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,60 @@ the child process.
The message goes through serialization and parsing. The resulting message might
not be the same as what is originally sent.

### Event: 'multipleResolves'
<!-- YAML
added: REPLACEME
-->

* `type` {string} The error type. One of `'resolveAfterResolved'` or
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could just call type 'resolve' or 'reject'

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see that this could be sufficient but I personally like the very explicit nature here. If you feel strongly about it, I'll change it, otherwise I would rather keep it as is.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know which is best but my instincts tell me that it should be named "resolvedAfterResolved" or "resolveAfterResolved"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

current naming is correct, there was a resolve after the promise resolved.

Copy link
Member

@targos targos Sep 19, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, you're right. I didn't know "resolve" was also a noun.

`'rejectAfterResolved'`.
* `promise` {Promise} The promise that resolved or rejected more than once.
* `value` {any} The value with which the promise was either resolved or
rejected after the original resolve.
* `message` {string} A short description of what happened.

The `'multipleResolves'` event is emitted whenever a `Promise` has been either:

* Resolved more than once.
* Rejected after resolve.

This is useful for tracking errors in your application while using the promise
constructor. Otherwise such mistakes are silently swallowed due to being in a
dead zone.

It is recommended to end the process on such errors, since the process could be
in an undefined state.

```js
process.on('multipleResolves', (type, promise, reason, message) => {
console.error(`${type}: ${message}`);
console.error(promise, reason);
process.exit(1);
});

async function main() {
try {
return await new Promise((resolve, reject) => {
resolve('First call');
resolve('Swallowed resolve');
reject(new Error('Swallowed reject'));
});
} catch {
throw new Error('Failed');
}
}

main().then(console.log);
// resolveAfterResolved: Resolve was called more than once.
// Promise { 'First call' } 'Swallowed resolve'
// rejectAfterResolved: Reject was called after resolve.
// Promise { 'First call' } Error: Swallowed reject
// at Promise (*)
// at new Promise (<anonymous>)
// at main (*)
// First call
```

### Event: 'rejectionHandled'
<!-- YAML
added: v1.4.1
Expand Down
40 changes: 26 additions & 14 deletions lib/internal/process/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,35 @@ const { safeToString } = internalBinding('util');
const maybeUnhandledPromises = new WeakMap();
const pendingUnhandledRejections = [];
const asyncHandledRejections = [];
const promiseRejectEvents = {};
let lastPromiseId = 0;

exports.setup = setupPromises;

function setupPromises(_setupPromises) {
_setupPromises(unhandledRejection, handledRejection);
_setupPromises(handler, promiseRejectEvents);
return emitPromiseRejectionWarnings;
}

function handler(type, promise, reason) {
switch (type) {
case promiseRejectEvents.kPromiseRejectWithNoHandler:
return unhandledRejection(promise, reason);
case promiseRejectEvents.kPromiseHandlerAddedAfterReject:
return handledRejection(promise);
case promiseRejectEvents.kPromiseResolveAfterResolved:
return resolveError('resolveAfterResolved', promise, reason,
'Resolve was called more than once.');
case promiseRejectEvents.kPromiseRejectAfterResolved:
return resolveError('rejectAfterResolved', promise, reason,
'Reject was called after resolve.');
}
}

function resolveError(type, promise, reason, message) {
process.emit('multipleResolves', type, promise, reason, message);
}

function unhandledRejection(promise, reason) {
maybeUnhandledPromises.set(promise, {
reason,
Expand Down Expand Up @@ -46,16 +66,6 @@ function handledRejection(promise) {

const unhandledRejectionErrName = 'UnhandledPromiseRejectionWarning';
function emitWarning(uid, reason) {
try {
if (reason instanceof Error) {
process.emitWarning(reason.stack, unhandledRejectionErrName);
} else {
process.emitWarning(safeToString(reason), unhandledRejectionErrName);
}
} catch (e) {
// ignored
}

// eslint-disable-next-line no-restricted-syntax
const warning = new Error(
'Unhandled promise rejection. This error originated either by ' +
Expand All @@ -67,10 +77,12 @@ function emitWarning(uid, reason) {
try {
if (reason instanceof Error) {
warning.stack = reason.stack;
process.emitWarning(reason.stack, unhandledRejectionErrName);
} else {
process.emitWarning(safeToString(reason), unhandledRejectionErrName);
}
} catch (err) {
// ignored
}
} catch {}

process.emitWarning(warning);
emitDeprecationWarning();
}
Expand Down
55 changes: 36 additions & 19 deletions src/bootstrapper.cc
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,13 @@ using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::kPromiseHandlerAddedAfterReject;
using v8::kPromiseRejectAfterResolved;
using v8::kPromiseRejectWithNoHandler;
using v8::kPromiseResolveAfterResolved;
using v8::Local;
using v8::MaybeLocal;
using v8::Number;
using v8::Object;
using v8::Promise;
using v8::PromiseRejectEvent;
Expand Down Expand Up @@ -67,34 +72,40 @@ void PromiseRejectCallback(PromiseRejectMessage message) {
PromiseRejectEvent event = message.GetEvent();

Environment* env = Environment::GetCurrent(isolate);

if (env == nullptr) return;
Local<Function> callback;

Local<Function> callback = env->promise_handler_function();
Local<Value> value;
Local<Value> type = Number::New(env->isolate(), event);

if (event == v8::kPromiseRejectWithNoHandler) {
callback = env->promise_reject_unhandled_function();
if (event == kPromiseRejectWithNoHandler) {
value = message.GetValue();

if (value.IsEmpty())
value = Undefined(isolate);

unhandledRejections++;
} else if (event == v8::kPromiseHandlerAddedAfterReject) {
callback = env->promise_reject_handled_function();
TRACE_COUNTER2(TRACING_CATEGORY_NODE2(promises, rejections),
"rejections",
"unhandled", unhandledRejections,
"handledAfter", rejectionsHandledAfter);
} else if (event == kPromiseHandlerAddedAfterReject) {
value = Undefined(isolate);

rejectionsHandledAfter++;
TRACE_COUNTER2(TRACING_CATEGORY_NODE2(promises, rejections),
"rejections",
"unhandled", unhandledRejections,
"handledAfter", rejectionsHandledAfter);
} else if (event == kPromiseResolveAfterResolved) {
value = message.GetValue();
} else if (event == kPromiseRejectAfterResolved) {
value = message.GetValue();
} else {
return;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this UNREACHABLE?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but I was asked to keep the return: #22218 (comment)

}

TRACE_COUNTER2(TRACING_CATEGORY_NODE2(promises, rejections),
"rejections",
"unhandled", unhandledRejections,
"handledAfter", rejectionsHandledAfter);

if (value.IsEmpty()) {
value = Undefined(isolate);
}

Local<Value> args[] = { promise, value };
Local<Value> args[] = { type, promise, value };
MaybeLocal<Value> ret = callback->Call(env->context(),
Undefined(isolate),
arraysize(args),
Expand All @@ -109,11 +120,17 @@ void SetupPromises(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = env->isolate();

CHECK(args[0]->IsFunction());
CHECK(args[1]->IsFunction());
CHECK(args[1]->IsObject());

Local<Object> constants = args[1].As<Object>();

NODE_DEFINE_CONSTANT(constants, kPromiseRejectWithNoHandler);
NODE_DEFINE_CONSTANT(constants, kPromiseHandlerAddedAfterReject);
NODE_DEFINE_CONSTANT(constants, kPromiseResolveAfterResolved);
NODE_DEFINE_CONSTANT(constants, kPromiseRejectAfterResolved);

isolate->SetPromiseRejectCallback(PromiseRejectCallback);
env->set_promise_reject_unhandled_function(args[0].As<Function>());
env->set_promise_reject_handled_function(args[1].As<Function>());
env->set_promise_handler_function(args[0].As<Function>());
}

#define BOOTSTRAP_METHOD(name, fn) env->SetMethod(bootstrapper, #name, fn)
Expand Down
3 changes: 1 addition & 2 deletions src/env.h
Original file line number Diff line number Diff line change
Expand Up @@ -340,8 +340,7 @@ struct PackageConfig {
V(performance_entry_callback, v8::Function) \
V(performance_entry_template, v8::Function) \
V(process_object, v8::Object) \
V(promise_reject_handled_function, v8::Function) \
V(promise_reject_unhandled_function, v8::Function) \
V(promise_handler_function, v8::Function) \
V(promise_wrap_template, v8::ObjectTemplate) \
V(push_values_to_array_function, v8::Function) \
V(sab_lifetimepartner_constructor_template, v8::FunctionTemplate) \
Expand Down
1 change: 1 addition & 0 deletions test/message/unhandled_promise_trace_warnings.out
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
at *
(node:*) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1)
at handledRejection (internal/process/promises.js:*)
at handler (internal/process/promises.js:*)
at Promise.then *
at Promise.catch *
at Immediate.setImmediate (*test*message*unhandled_promise_trace_warnings.js:*)
Expand Down
32 changes: 32 additions & 0 deletions test/parallel/test-promise-swallowed-event.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
'use strict';

const common = require('../common');
const assert = require('assert');

const resolveMessage = 'First call';
const swallowedResolve = 'Swallowed resolve';
const rejection = new Error('Swallowed reject');

const expected = [
'resolveAfterResolved',
swallowedResolve,
'Resolve was called more than once.',
'rejectAfterResolved',
rejection,
'Reject was called after resolve.'
];

function handler(type, p, reason, message) {
assert.strictEqual(type, expected.shift());
assert.deepStrictEqual(p, Promise.resolve(resolveMessage));
assert.strictEqual(reason, expected.shift());
assert.strictEqual(message, expected.shift());
}

process.on('multipleResolves', common.mustCall(handler, 2));

new Promise((resolve, reject) => {
resolve(resolveMessage);
resolve(swallowedResolve);
reject(rejection);
});