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

zlib: remove usage of require('util') #27180

Closed
wants to merge 15 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 3 additions & 1 deletion benchmark/http/headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ function main({ len, n }) {
'Transfer-Encoding': 'chunked',
};

const Is = [ ...Array(n / len).keys() ];
// TODO(BridgeAR): Change this benchmark to use grouped arguments when
// implemented. https://github.com/nodejs/node/issues/26425
const Is = [ ...Array(Math.max(n / len, 1)).keys() ];
const Js = [ ...Array(len).keys() ];
for (const i of Is) {
headers[`foo${i}`] = Js.map(() => `some header value ${i}`);
Expand Down
4 changes: 3 additions & 1 deletion benchmark/misc/freelist.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ const bench = common.createBenchmark(main, {
});

function main({ n }) {
const { FreeList } = require('internal/freelist');
let FreeList = require('internal/freelist');
if (FreeList.FreeList)
FreeList = FreeList.FreeList;
const poolSize = 1000;
const list = new FreeList('test', poolSize, Object);
var j;
Expand Down
4 changes: 2 additions & 2 deletions lib/_http_client.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ const {
ERR_UNESCAPED_CHARACTERS
} = require('internal/errors').codes;
const { getTimerDuration } = require('internal/timers');
const is_reused_symbol = require('internal/freelist').symbols.is_reused_symbol;
const {
DTRACE_HTTP_CLIENT_REQUEST,
DTRACE_HTTP_CLIENT_RESPONSE
Expand Down Expand Up @@ -631,10 +630,11 @@ function emitFreeNT(socket) {
}

function tickOnSocket(req, socket) {
const isParserReused = parsers.hasItems();
const parser = parsers.alloc();
req.socket = socket;
req.connection = socket;
parser.reinitialize(HTTPParser.RESPONSE, parser[is_reused_symbol]);
parser.reinitialize(HTTPParser.RESPONSE, isParserReused);
parser.socket = socket;
parser.outgoing = req;
req.parser = parser;
Expand Down
2 changes: 1 addition & 1 deletion lib/_http_common.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const { methods, HTTPParser } =
getOptionValue('--http-parser') === 'legacy' ?
internalBinding('http_parser') : internalBinding('http_parser_llhttp');

const { FreeList } = require('internal/freelist');
const FreeList = require('internal/freelist');
const { ondrain } = require('internal/http');
const incoming = require('_http_incoming');
const {
Expand Down
4 changes: 2 additions & 2 deletions lib/_http_server.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ const {
defaultTriggerAsyncIdScope,
getOrSetAsyncId
} = require('internal/async_hooks');
const is_reused_symbol = require('internal/freelist').symbols.is_reused_symbol;
const { IncomingMessage } = require('_http_incoming');
const {
ERR_HTTP_HEADERS_SENT,
Expand Down Expand Up @@ -348,8 +347,9 @@ function connectionListenerInternal(server, socket) {
socket.setTimeout(server.timeout);
socket.on('timeout', socketOnTimeout);

const isParserReused = parsers.hasItems();
const parser = parsers.alloc();
parser.reinitialize(HTTPParser.REQUEST, parser[is_reused_symbol]);
parser.reinitialize(HTTPParser.REQUEST, isParserReused);
parser.socket = socket;

// We are starting to wait for our headers.
Expand Down
6 changes: 1 addition & 5 deletions lib/_stream_readable.js
Original file line number Diff line number Diff line change
Expand Up @@ -521,11 +521,7 @@ function onEofChunk(stream, state) {
state.emittedReadable = true;
// We have to emit readable now that we are EOF. Modules
// in the ecosystem (e.g. dicer) rely on this event being sync.
if (state.ended) {
emitReadable_(stream);
} else {
process.nextTick(emitReadable_, stream);
}
emitReadable_(stream);
}
}

Expand Down
5 changes: 5 additions & 0 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,11 @@ function checkIsPromise(obj) {
// Accept native ES6 promises and promises that are implemented in a similar
// way. Do not accept thenables that use a function as `obj` and that have no
// `catch` handler.

// TODO: thenables are checked up until they have the correct methods,
// but according to documentation, the `then` method should receive
// the `fulfill` and `reject` arguments as well or it may be never resolved.

return isPromise(obj) ||
obj !== null && typeof obj === 'object' &&
typeof obj.then === 'function' &&
Expand Down
25 changes: 9 additions & 16 deletions lib/internal/freelist.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const is_reused_symbol = Symbol('isReused');
const { Reflect } = primordials;

class FreeList {
constructor(name, max, ctor) {
Expand All @@ -10,16 +10,14 @@ class FreeList {
this.list = [];
}

hasItems() {
return this.list.length > 0;
}

alloc() {
let item;
if (this.list.length > 0) {
item = this.list.pop();
item[is_reused_symbol] = true;
} else {
item = this.ctor.apply(this, arguments);
item[is_reused_symbol] = false;
}
return item;
return this.list.length > 0 ?
this.list.pop() :
Reflect.apply(this.ctor, this, arguments);
}

free(obj) {
Expand All @@ -31,9 +29,4 @@ class FreeList {
}
}

module.exports = {
FreeList,
symbols: {
is_reused_symbol
}
};
module.exports = FreeList;
2 changes: 1 addition & 1 deletion lib/internal/modules/esm/create_dynamic_module.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const { ArrayPrototype } = primordials;

const { ModuleWrap, callbackMap } = internalBinding('module_wrap');
const debug = require('util').debuglog('esm');
const debug = require('internal/util/debuglog').debuglog('esm');

const createDynamicModule = (exports, url = '', evaluate) => {
debug('creating ESM facade for %s with exports: %j', url, exports);
Expand Down
2 changes: 1 addition & 1 deletion lib/internal/modules/esm/module_job.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const {
SafePromise
} = primordials;

const { decorateErrorStack } = require('internal/util');
const { decorateErrorStack } = require('internal/util/decorateErrorStack').decorateErrorStack;
const assert = require('internal/assert');
const resolvedPromise = SafePromise.resolve();

Expand Down
2 changes: 1 addition & 1 deletion lib/internal/process/execution.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function tryGetCwd() {
}

function evalModule(source) {
const { decorateErrorStack } = require('internal/util');
const { decorateErrorStack } = require('internal/util/decorateErrorStack').decorateErrorStack;
const asyncESM = require('internal/process/esm_loader');
asyncESM.loaderPromise.then(async (loader) => {
const { result } = await loader.eval(source);
Expand Down
6 changes: 2 additions & 4 deletions lib/internal/process/report.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
'use strict';
const { convertToValidSignal } = require('internal/util');
const {
ERR_INVALID_ARG_TYPE,
ERR_SYNTHETIC
} = require('internal/errors').codes;
const { validateString } = require('internal/validators');
const { validateSignalName, validateString } = require('internal/validators');
const nr = internalBinding('report');
const report = {
writeReport(file, err) {
Expand Down Expand Up @@ -47,8 +46,7 @@ const report = {
return nr.getSignal();
},
set signal(sig) {
validateString(sig, 'signal');
convertToValidSignal(sig); // Validate that the signal is recognized.
validateSignalName(sig, 'signal');
removeSignalHandler();
addSignalHandler(sig);
nr.setSignal(sig);
Expand Down
27 changes: 2 additions & 25 deletions lib/internal/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ const {
arrow_message_private_symbol: kArrowMessagePrivateSymbolIndex,
decorated_private_symbol: kDecoratedPrivateSymbolIndex
} = internalBinding('util');
const { isNativeError } = internalBinding('types');

const noCrypto = !process.versions.openssl;

Expand All @@ -26,13 +25,6 @@ function removeColors(str) {
return str.replace(colorRegExp, '');
}

function isError(e) {
// An error could be an instance of Error while not being a native error
// or could be from a different realm and not be instance of Error but still
// be a native error.
return isNativeError(e) || e instanceof Error;
}

function objectToString(o) {
return Object.prototype.toString.call(o);
}
Expand Down Expand Up @@ -83,19 +75,6 @@ function deprecate(fn, msg, code) {
return deprecated;
}

function decorateErrorStack(err) {
if (!(isError(err) && err.stack) ||
getHiddenValue(err, kDecoratedPrivateSymbolIndex) === true)
return;

const arrow = getHiddenValue(err, kArrowMessagePrivateSymbolIndex);

if (arrow) {
err.stack = arrow + err.stack;
setHiddenValue(err, kDecoratedPrivateSymbolIndex, true);
}
}

function assertCrypto() {
if (noCrypto)
throw new ERR_NO_CRYPTO();
Expand Down Expand Up @@ -391,14 +370,12 @@ module.exports = {
assertCrypto,
cachedResult,
convertToValidSignal,
createClassWrapper,
decorateErrorStack,
createClassWrapper,
deprecate,
emitExperimentalWarning,
filterDuplicateStrings,
getConstructorOf,
getSystemErrorName,
isError,
getSystemErrorName,
isInsideNodeModules,
join,
normalizeEncoding,
Expand Down
18 changes: 18 additions & 0 deletions lib/internal/util/decorateErrorStack.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

function decorateErrorStack(err) {
if (!(isError(err) && err.stack) ||
getHiddenValue(err, kDecoratedPrivateSymbolIndex) === true)
return;

const arrow = getHiddenValue(err, kArrowMessagePrivateSymbolIndex);

if (arrow) {
err.stack = arrow + err.stack;
setHiddenValue(err, kDecoratedPrivateSymbolIndex, true);
}
}

module.exports = {
decorateErrorStack
}
14 changes: 14 additions & 0 deletions lib/internal/util/isError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
'use strict';

const { isNativeError } = internalBinding('types');

function isError(e) {
// An error could be an instance of Error while not being a native error
// or could be from a different realm and not be instance of Error but still
// be a native error.
return isNativeError(e) || e instanceof Error;
}

module.exports = {
isError
}
21 changes: 19 additions & 2 deletions lib/internal/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@ const {
codes: {
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_OUT_OF_RANGE
ERR_OUT_OF_RANGE,
ERR_UNKNOWN_SIGNAL
}
} = require('internal/errors');
const {
isArrayBufferView
} = require('internal/util/types');
const { signals } = internalBinding('constants').os;

function isInt32(value) {
return value === (value | 0);
Expand Down Expand Up @@ -110,6 +112,20 @@ function validateNumber(value, name) {
throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
}

function validateSignalName(signal, name = 'signal') {
if (typeof signal !== 'string')
throw new ERR_INVALID_ARG_TYPE(name, 'string', signal);

if (signals[signal] === undefined) {
if (signals[signal.toUpperCase()] !== undefined) {
throw new ERR_UNKNOWN_SIGNAL(signal +
' (signals must use all capital letters)');
}

throw new ERR_UNKNOWN_SIGNAL(signal);
}
}

// TODO(BridgeAR): We have multiple validation functions that call
// `require('internal/utils').toBuf()` before validating for array buffer views.
// Those should likely also be consolidated in here.
Expand All @@ -130,5 +146,6 @@ module.exports = {
validateInt32,
validateUint32,
validateString,
validateNumber
validateNumber,
validateSignalName
};
14 changes: 2 additions & 12 deletions lib/net.js
Original file line number Diff line number Diff line change
Expand Up @@ -541,19 +541,9 @@ function onReadableStreamEnd() {
if (this.writable)
this.end();
}
maybeDestroy(this);
}


// Call whenever we set writable=false or readable=false
function maybeDestroy(socket) {
if (!socket.readable &&
!socket.writable &&
!socket.destroyed &&
!socket.connecting &&
!socket.writableLength) {
socket.destroy();
}
if (!this.destroyed && !this.writable && !this.writableLength)
this.destroy();
}


Expand Down
4 changes: 2 additions & 2 deletions lib/repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ const {
isIdentifierChar
} = require('internal/deps/acorn/acorn/dist/acorn');
const {
decorateErrorStack,
isError,
deprecate
} = require('internal/util');
const { isError } = require('internal/util/isError').isError;
const { decorateErrorStack } = require('internal/util/decorateErrorStack').decorateErrorStack;
const { inspect } = require('internal/util/inspect');
const Stream = require('stream');
const vm = require('vm');
Expand Down
2 changes: 1 addition & 1 deletion lib/zlib.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const {
isAnyArrayBuffer,
isArrayBufferView
}
} = require('util');
} = require('internal/util');
const binding = internalBinding('zlib');
const assert = require('internal/assert');
const {
Expand Down
Loading