Compare commits

...

22 Commits

Author SHA1 Message Date
Jarred Sumner
039b4a31ac Add test-http-server-response-standalone and fix ServerResponse.end 2025-05-29 15:46:01 -07:00
Meghan Denny
576f66c149 fix test-net-server-drop-connections.js (#19995) 2025-05-29 13:55:25 -07:00
Ashcon Partovi
cd0756c95c Revert "ci: Fix build image step with cross-compiled zig"
This reverts commit c92f3f7b72.
2025-05-29 12:44:43 -07:00
Ashcon Partovi
c92f3f7b72 ci: Fix build image step with cross-compiled zig 2025-05-29 12:43:29 -07:00
190n
f1226c9767 ci: fix machine.mjs for Windows instances (#20021)
Co-authored-by: 190n <7763597+190n@users.noreply.github.com>
2025-05-29 12:04:10 -07:00
Meghan Denny
b111e6db02 fix test-net-connect-handle-econnrefused.js (#19993) 2025-05-29 11:32:54 -07:00
Meghan Denny
ffffb634c6 fix test-net-bytes-stats.js (#20003) 2025-05-29 11:32:13 -07:00
Meghan Denny
d109183d3e fix test-net-better-error-messages-port.js (#20008) 2025-05-29 11:31:53 -07:00
Meghan Denny
14c9165d6f fix test-net-socket-local-address.js (#20010) 2025-05-29 11:31:26 -07:00
wldfngrs
c42539b0bf Fix parse segfault #18888 (#19817)
Co-authored-by: Dylan Conway <dylan.conway567@gmail.com>
2025-05-29 08:44:19 -07:00
Meghan Denny
022a567af0 tidy from 19970 (#20002) 2025-05-29 00:31:44 -07:00
Jarred Sumner
cfb8956ac5 Cursor config 2025-05-28 23:09:16 -07:00
190n
2bb36ca6b4 Fix crash initializing process stdio streams while process is overridden (#19978) 2025-05-28 22:57:59 -07:00
Jarred Sumner
24b3de1bc3 Fix net close event and add reconnect test (#19975)
Co-authored-by: Meghan Denny <meghan@bun.sh>
2025-05-28 22:27:52 -07:00
Jarred Sumner
b01ffe6da8 Fix pauseOnConnect semantics for node:net server (#19987) 2025-05-28 22:23:57 -07:00
Kai Tamkun
579f2ecd51 Add node:vm leak tests (#19947)
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
2025-05-28 22:23:30 -07:00
Jarred Sumner
627b0010e0 Fix Node net bytesWritten with pending strings (#19962)
Co-authored-by: Meghan Denny <meghan@bun.sh>
2025-05-28 22:21:28 -07:00
Jarred Sumner
3369e25a70 Update environment.json 2025-05-28 22:04:38 -07:00
Jarred Sumner
06a40f0b29 Configure cursor 2025-05-28 21:55:08 -07:00
Jarred Sumner
7989352b39 Add node server close test (#19972)
Co-authored-by: Meghan Denny <meghan@bun.sh>
2025-05-28 21:38:52 -07:00
Jarred Sumner
e1ab6fe36b Add net autoselectfamily default test (#19970)
Co-authored-by: Jarred-Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2025-05-28 21:30:22 -07:00
Jarred Sumner
14f59568cc Fix net.listen backlog arg & add Node test (#19966)
Co-authored-by: Meghan Denny <meghan@bun.sh>
2025-05-28 21:23:35 -07:00
25 changed files with 951 additions and 65 deletions

3
.cursor/environment.json Normal file
View File

@@ -0,0 +1,3 @@
{
"terminals": []
}

View File

@@ -1,27 +1,13 @@
---
description: How to build Bun
globs:
globs:
alwaysApply: false
---
# How to build Bun
## CMake
Run:
Bun is built using CMake, which you can find in `CMakeLists.txt` and in the `cmake/` directory.
* `CMakeLists.txt`
* `cmake/`
* `Globals.cmake` - macros and functions used by all the other files
* `Options.cmake` - build options for configuring the build (e.g. debug/release mode)
* `CompilerFlags.cmake` - compiler and linker flags used by all the targets
* `tools/` - setup scripts for various build tools (e.g. llvm, zig, webkit, rust, etc.)
* `targets/` - targets for bun and its dependencies (e.g. brotli, boringssl, libuv, etc.)
## How to
There are `package.json` scripts that make it easy to build Bun without calling CMake directly, for example:
```sh
bun run build # builds a debug build: `build/debug/bun-debug`
bun run build:release # builds a release build: `build/release/bun`
bun run build:assert # builds a release build with debug assertions: `build/assert/bun`
```bash
bun bd
```

View File

@@ -858,7 +858,8 @@ function getSshKeys() {
const sshFiles = readdirSync(sshPath, { withFileTypes: true, encoding: "utf-8" });
const publicPaths = sshFiles
.filter(entry => entry.isFile() && entry.name.endsWith(".pub"))
.map(({ name }) => join(sshPath, name));
.map(({ name }) => join(sshPath, name))
.filter(path => !readFile(path, { cache: true }).startsWith("ssh-ed25519"));
sshKeys.push(
...publicPaths.map(publicPath => ({

View File

@@ -2030,13 +2030,14 @@ enum class BunProcessStdinFdType : int32_t {
extern "C" BunProcessStdinFdType Bun__Process__getStdinFdType(void*, int fd);
extern "C" void Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(JSC::JSGlobalObject*, JSC::EncodedJSValue);
static JSValue constructStdioWriteStream(JSC::JSGlobalObject* globalObject, int fd)
static JSValue constructStdioWriteStream(JSC::JSGlobalObject* globalObject, JSC::JSObject* processObject, int fd)
{
auto& vm = JSC::getVM(globalObject);
auto scope = DECLARE_CATCH_SCOPE(vm);
JSC::JSFunction* getStdioWriteStream = JSC::JSFunction::create(vm, globalObject, processObjectInternalsGetStdioWriteStreamCodeGenerator(vm), globalObject);
JSC::MarkedArgumentBuffer args;
args.append(processObject);
args.append(JSC::jsNumber(fd));
args.append(jsBoolean(bun_stdio_tty[fd]));
BunProcessStdinFdType fdType = Bun__Process__getStdinFdType(Bun::vm(vm), fd);
@@ -2045,8 +2046,11 @@ static JSValue constructStdioWriteStream(JSC::JSGlobalObject* globalObject, int
JSC::CallData callData = JSC::getCallData(getStdioWriteStream);
auto result = JSC::profiledCall(globalObject, ProfilingReason::API, getStdioWriteStream, callData, globalObject->globalThis(), args);
scope.assertNoExceptionExceptTermination();
CLEAR_AND_RETURN_IF_EXCEPTION(scope, jsUndefined());
if (auto* exception = scope.exception()) {
Zig::GlobalObject::reportUncaughtExceptionAtEventLoop(globalObject, exception);
scope.clearException();
return jsUndefined();
}
ASSERT_WITH_MESSAGE(JSC::isJSArray(result), "Expected an array from getStdioWriteStream");
JSC::JSArray* resultObject = JSC::jsCast<JSC::JSArray*>(result);
@@ -2077,12 +2081,12 @@ static JSValue constructStdioWriteStream(JSC::JSGlobalObject* globalObject, int
static JSValue constructStdout(VM& vm, JSObject* processObject)
{
return constructStdioWriteStream(processObject->globalObject(), 1);
return constructStdioWriteStream(processObject->globalObject(), processObject, 1);
}
static JSValue constructStderr(VM& vm, JSObject* processObject)
{
return constructStdioWriteStream(processObject->globalObject(), 2);
return constructStdioWriteStream(processObject->globalObject(), processObject, 2);
}
#if OS(WINDOWS)
@@ -2092,17 +2096,22 @@ static JSValue constructStderr(VM& vm, JSObject* processObject)
static JSValue constructStdin(VM& vm, JSObject* processObject)
{
auto* globalObject = processObject->globalObject();
auto scope = DECLARE_THROW_SCOPE(vm);
JSC::JSFunction* getStdioWriteStream = JSC::JSFunction::create(vm, globalObject, processObjectInternalsGetStdinStreamCodeGenerator(vm), globalObject);
auto scope = DECLARE_CATCH_SCOPE(vm);
JSC::JSFunction* getStdinStream = JSC::JSFunction::create(vm, globalObject, processObjectInternalsGetStdinStreamCodeGenerator(vm), globalObject);
JSC::MarkedArgumentBuffer args;
args.append(processObject);
args.append(JSC::jsNumber(STDIN_FILENO));
args.append(jsBoolean(bun_stdio_tty[STDIN_FILENO]));
BunProcessStdinFdType fdType = Bun__Process__getStdinFdType(Bun::vm(vm), STDIN_FILENO);
args.append(jsNumber(static_cast<int32_t>(fdType)));
JSC::CallData callData = JSC::getCallData(getStdioWriteStream);
JSC::CallData callData = JSC::getCallData(getStdinStream);
auto result = JSC::profiledCall(globalObject, ProfilingReason::API, getStdioWriteStream, callData, globalObject, args);
RETURN_IF_EXCEPTION(scope, {});
auto result = JSC::profiledCall(globalObject, ProfilingReason::API, getStdinStream, callData, globalObject, args);
if (auto* exception = scope.exception()) {
Zig::GlobalObject::reportUncaughtExceptionAtEventLoop(globalObject, exception);
scope.clearException();
return jsUndefined();
}
return result;
}

View File

@@ -30,8 +30,13 @@ const enum BunProcessStdinFdType {
socket = 2,
}
export function getStdioWriteStream(fd, isTTY: boolean, _fdType: BunProcessStdinFdType) {
$assert(typeof fd === "number", `Expected fd to be a number, got ${typeof fd}`);
export function getStdioWriteStream(
process: typeof globalThis.process,
fd: number,
isTTY: boolean,
_fdType: BunProcessStdinFdType,
) {
$assert(fd === 1 || fd === 2, `Expected fd to be 1 or 2, got ${fd}`);
let stream;
if (isTTY) {
@@ -74,9 +79,14 @@ export function getStdioWriteStream(fd, isTTY: boolean, _fdType: BunProcessStdin
return [stream, underlyingSink];
}
export function getStdinStream(fd, isTTY: boolean, fdType: BunProcessStdinFdType) {
export function getStdinStream(
process: typeof globalThis.process,
fd: number,
isTTY: boolean,
fdType: BunProcessStdinFdType,
) {
$assert(fd === 0);
const native = Bun.stdin.stream();
// @ts-expect-error
const source = native.$bunNativePtr;
var reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
@@ -246,7 +256,12 @@ export function getStdinStream(fd, isTTY: boolean, fdType: BunProcessStdinFdType
return stream;
}
export function initializeNextTickQueue(process, nextTickQueue, drainMicrotasksFn, reportUncaughtExceptionFn) {
export function initializeNextTickQueue(
process: typeof globalThis.process,
nextTickQueue,
drainMicrotasksFn,
reportUncaughtExceptionFn,
) {
var queue;
var process;
var nextTickQueue = nextTickQueue;

View File

@@ -231,9 +231,54 @@ const ServerResponsePrototype = {
}
if (!handle) {
if ($isCallable(callback)) {
process.nextTick(callback);
if (!this.socket) {
if ($isCallable(callback)) {
process.nextTick(callback);
}
return this;
}
this._implicitHeader();
if (chunk) {
OutgoingMessagePrototype._send.$call(this, chunk, encoding, null);
} else {
OutgoingMessagePrototype._send.$call(this, kEmptyBuffer, encoding, null);
}
const socket = this.socket;
this.detachSocket(socket);
this.finished = true;
process.nextTick(self => {
self._ended = true;
}, this);
this.emit("prefinish");
this._callPendingCallbacks();
if (callback) {
process.nextTick(
function (callback, self) {
self.emit("finish");
try {
callback();
} catch (err) {
self.emit("error", err);
}
process.nextTick(emitCloseNT, self);
},
callback,
this,
);
} else {
process.nextTick(function (self) {
self.emit("finish");
process.nextTick(emitCloseNT, self);
}, this);
}
socket.end(Buffer.alloc(0));
return this;
}

View File

@@ -88,7 +88,6 @@ function isIP(s): 0 | 4 | 6 {
}
const bunTlsSymbol = Symbol.for("::buntls::");
const bunSocketServerConnections = Symbol.for("::bunnetserverconnections::");
const bunSocketServerOptions = Symbol.for("::bunnetserveroptions::");
const owner_symbol = Symbol("owner_symbol");
@@ -118,11 +117,7 @@ function endNT(socket, callback, err) {
callback(err);
}
function emitCloseNT(self, hasError) {
if (hasError) {
self.emit("close", hasError);
} else {
self.emit("close");
}
self.emit("close", hasError);
}
function detachSocket(self) {
if (!self) self = this;
@@ -233,6 +228,7 @@ const SocketHandlers: SocketHandler = {
self[kwriteCallback] = null;
callback(error);
}
self.emit("error", error);
},
open(socket) {
@@ -342,7 +338,7 @@ const ServerHandlers: SocketHandler = {
const data = this.data;
if (!data) return;
data.server[bunSocketServerConnections]--;
data.server._connections--;
{
if (!data[kclosed]) {
data[kclosed] = true;
@@ -388,7 +384,7 @@ const ServerHandlers: SocketHandler = {
return;
}
}
if (self.maxConnections && self[bunSocketServerConnections] >= self.maxConnections) {
if (self.maxConnections != null && self._connections >= self.maxConnections) {
const data = {
localAddress: _socket.localAddress,
localPort: _socket.localPort || this.localPort,
@@ -407,7 +403,11 @@ const ServerHandlers: SocketHandler = {
const bunTLS = _socket[bunTlsSymbol];
const isTLS = typeof bunTLS === "function";
self[bunSocketServerConnections]++;
self._connections++;
if (pauseOnConnect) {
_socket.pause();
}
if (typeof connectionListener === "function") {
this.pauseOnConnect = pauseOnConnect;
@@ -463,7 +463,9 @@ const ServerHandlers: SocketHandler = {
// after secureConnection event we emmit secure and secureConnect
self.emit("secure", self);
self.emit("secureConnect", verifyError);
if (!server.pauseOnConnect) {
if (server.pauseOnConnect) {
self.pause();
} else {
self.resume();
}
},
@@ -517,6 +519,9 @@ const SocketHandlers2: SocketHandler<SocketHandleData> = {
$debug("self[kupgraded]", String(self[kupgraded]));
if (!self[kupgraded]) req!.oncomplete(0, self._handle, req, true, true);
socket.data.req = undefined;
if (self.pauseOnConnect) {
self.pause();
}
if (self[kupgraded]) {
self.connecting = false;
const options = self[bunTLSConnectOptions];
@@ -724,6 +729,8 @@ function Socket(options?) {
this[kclosed] = false;
this[kended] = false;
this.connecting = false;
this._host = undefined;
this._port = undefined;
this[bunTLSConnectOptions] = null;
this.timeout = 0;
this[kwriteCallback] = undefined;
@@ -839,7 +846,9 @@ Object.defineProperty(Socket.prototype, "bytesWritten", {
else bytes += Buffer.byteLength(chunk.chunk, chunk.encoding);
}
} else if (data) {
bytes += data.byteLength;
// Writes are either a string or a Buffer.
if (typeof data !== "string") bytes += data.length;
else bytes += Buffer.byteLength(data, this._pendingEncoding || "utf8");
}
return bytes;
},
@@ -857,7 +866,7 @@ Socket.prototype[kAttach] = function (port, socket) {
}
if (this[kSetKeepAlive]) {
socket.setKeepAlive(true, self[kSetKeepAliveInitialDelay]);
socket.setKeepAlive(true, this[kSetKeepAliveInitialDelay]);
}
if (!this[kupgraded]) {
@@ -899,12 +908,14 @@ Socket.prototype.connect = function connect(...args) {
}).catch(error => {
if (!this.destroyed) {
this.emit("error", error);
this.emit("close");
this.emit("close", true);
}
});
}
this.pauseOnConnect = pauseOnConnect;
if (!pauseOnConnect) {
if (pauseOnConnect) {
this.pause();
} else {
process.nextTick(() => {
this.resume();
});
@@ -1151,7 +1162,7 @@ Socket.prototype._destroy = function _destroy(err, callback) {
callback(err);
} else {
callback(err);
process.nextTick(emitCloseNT, this);
process.nextTick(emitCloseNT, this, false);
}
};
@@ -1546,6 +1557,7 @@ function lookupAndConnect(self, options) {
$debug("connect: find host", host, addressType);
$debug("connect: dns options", dnsopts);
self._host = host;
self._port = port;
const lookup = options.lookup || dns.lookup;
if (dnsopts.family !== 4 && dnsopts.family !== 6 && !localAddress && autoSelectFamily) {
@@ -2062,7 +2074,6 @@ function Server(options?, connectionListener?) {
// https://nodejs.org/api/net.html#netcreateserveroptions-connectionlistener
const {
maxConnections, //
allowHalfOpen = false,
keepAlive = false,
keepAliveInitialDelay = 0,
@@ -2079,7 +2090,6 @@ function Server(options?, connectionListener?) {
this._unref = false;
this.listeningId = 1;
this[bunSocketServerConnections] = 0;
this[bunSocketServerOptions] = undefined;
this.allowHalfOpen = allowHalfOpen;
this.keepAlive = keepAlive;
@@ -2087,7 +2097,6 @@ function Server(options?, connectionListener?) {
this.highWaterMark = highWaterMark;
this.pauseOnConnect = Boolean(pauseOnConnect);
this.noDelay = noDelay;
this.maxConnections = Number.isSafeInteger(maxConnections) && maxConnections > 0 ? maxConnections : 0;
options.connectionListener = connectionListener;
this[bunSocketServerOptions] = options;
@@ -2150,7 +2159,7 @@ Server.prototype[Symbol.asyncDispose] = function () {
};
Server.prototype._emitCloseIfDrained = function _emitCloseIfDrained() {
if (this._handle || this[bunSocketServerConnections] > 0) {
if (this._handle || this._connections > 0) {
return;
}
process.nextTick(() => {
@@ -2179,12 +2188,13 @@ Server.prototype.getConnections = function getConnections(callback) {
//in Bun case we will never error on getConnections
//node only errors if in the middle of the couting the server got disconnected, what never happens in Bun
//if disconnected will only pass null as well and 0 connected
callback(null, this._handle ? this[bunSocketServerConnections] : 0);
callback(null, this._handle ? this._connections : 0);
}
return this;
};
Server.prototype.listen = function listen(port, hostname, onListen) {
const argsLength = arguments.length;
if (typeof port === "string") {
const numPort = Number(port);
if (!Number.isNaN(numPort)) port = numPort;
@@ -2212,9 +2222,15 @@ Server.prototype.listen = function listen(port, hostname, onListen) {
hostname = undefined;
port = undefined;
} else {
if (typeof hostname === "function") {
if (typeof hostname === "number") {
backlog = hostname;
hostname = undefined;
} else if (typeof hostname === "function") {
onListen = hostname;
hostname = undefined;
} else if (typeof hostname === "string" && typeof onListen === "number") {
backlog = onListen;
onListen = argsLength > 3 ? arguments[3] : undefined;
}
if (typeof port === "function") {
@@ -2231,6 +2247,7 @@ Server.prototype.listen = function listen(port, hostname, onListen) {
ipv6Only = options.ipv6Only;
allowHalfOpen = options.allowHalfOpen;
reusePort = options.reusePort;
backlog = options.backlog;
if (typeof options.fd === "number" && options.fd >= 0) {
fd = options.fd;
@@ -2424,7 +2441,7 @@ function emitErrorNextTick(self, error) {
function emitErrorAndCloseNextTick(self, error) {
self.emit("error", error);
self.emit("close");
self.emit("close", true);
}
function addServerAbortSignalOption(self, options) {

View File

@@ -7671,7 +7671,15 @@ fn NewParser_(
ifStmtScopeIndex = try p.pushScopeForParsePass(js_ast.Scope.Kind.block, loc);
}
const scopeIndex = try p.pushScopeForParsePass(js_ast.Scope.Kind.function_args, p.lexer.loc());
var scopeIndex: usize = 0;
var pushedScopeForFunctionArgs = false;
// Push scope if the current lexer token is an open parenthesis token.
// That is, the parser is about parsing function arguments
if (p.lexer.token == .t_open_paren) {
scopeIndex = try p.pushScopeForParsePass(js_ast.Scope.Kind.function_args, p.lexer.loc());
pushedScopeForFunctionArgs = true;
}
var func = try p.parseFn(name, FnOrArrowDataParse{
.needs_async_loc = loc,
.async_range = asyncRange orelse logger.Range.None,
@@ -7687,7 +7695,7 @@ fn NewParser_(
if (comptime is_typescript_enabled) {
// Don't output anything if it's just a forward declaration of a function
if (opts.is_typescript_declare or func.flags.contains(.is_forward_declaration)) {
if ((opts.is_typescript_declare or func.flags.contains(.is_forward_declaration)) and pushedScopeForFunctionArgs) {
p.popAndDiscardScope(scopeIndex);
// Balance the fake block scope introduced above
@@ -7703,7 +7711,9 @@ fn NewParser_(
}
}
p.popScope();
if (pushedScopeForFunctionArgs) {
p.popScope();
}
// Only declare the function after we know if it had a body or not. Otherwise
// TypeScript code such as this will double-declare the symbol:
@@ -12605,14 +12615,19 @@ fn NewParser_(
p.allow_in = true;
const loc = p.lexer.loc();
_ = try p.pushScopeForParsePass(Scope.Kind.function_body, p.lexer.loc());
defer p.popScope();
var pushedScopeForFunctionBody = false;
if (p.lexer.token == .t_open_brace) {
_ = try p.pushScopeForParsePass(Scope.Kind.function_body, p.lexer.loc());
pushedScopeForFunctionBody = true;
}
try p.lexer.expect(.t_open_brace);
var opts = ParseStatementOptions{};
const stmts = try p.parseStmtsUpTo(.t_close_brace, &opts);
try p.lexer.next();
if (pushedScopeForFunctionBody) p.popScope();
p.allow_in = oldAllowIn;
p.fn_or_arrow_data_parse = oldFnOrArrowData;
return G.FnBody{ .loc = loc, .stmts = stmts };

View File

@@ -3462,6 +3462,18 @@ describe("await can only be used inside an async function message", () => {
});
});
describe("malformed function definition does not crash due to invalid scope initialization", () => {
it("fails with a parse error and exits cleanly", async () => {
const tests = ["function:", "function a() {function:}"];
for (const code of tests) {
for (const loader of ["js", "ts"]) {
const transpiler = new Bun.Transpiler({ loader });
expect(() => transpiler.transformSync(code)).toThrow("Parse error");
}
}
});
});
it("does not crash with 9 comments and typescript type skipping", () => {
const cmd = [bunExe(), "build", "--minify-identifiers", join(import.meta.dir, "fixtures", "9-comments.ts")];
const { stdout, stderr, exitCode } = Bun.spawnSync({

View File

@@ -1114,3 +1114,20 @@ it("should handle user assigned `default` properties", async () => {
await promise;
});
it.each(["stdin", "stdout", "stderr"])("%s stream accessor should handle exceptions without crashing", stream => {
expect([
/* js */ `
const old = process;
process = null;
try {
old.${stream};
} catch {}
if (typeof old.${stream} !== "undefined") {
console.log("wrong");
}
`,
"",
1,
]).toRunInlineFixture();
});

View File

@@ -0,0 +1,38 @@
const common = require('../common');
const { ServerResponse } = require('http');
const { Writable } = require('stream');
const assert = require('assert');
// Check that ServerResponse can be used without a proper Socket
// Refs: https://github.com/nodejs/node/issues/14386
// Refs: https://github.com/nodejs/node/issues/14381
const res = new ServerResponse({
method: 'GET',
httpVersionMajor: 1,
httpVersionMinor: 1
});
let firstChunk = true;
const ws = new Writable({
write: common.mustCall((chunk, encoding, callback) => {
if (firstChunk) {
assert(chunk.toString().endsWith('hello world'));
firstChunk = false;
} else {
assert.strictEqual(chunk.length, 0);
}
setImmediate(callback);
}, 2)
});
res.assignSocket(ws);
assert.throws(function() {
res.assignSocket(ws);
}, {
code: 'ERR_HTTP_SOCKET_ASSIGNED'
});
res.end('hello world');

View File

@@ -0,0 +1,83 @@
'use strict';
const common = require('../common');
const { createMockedLookup } = require('../common/dns');
const assert = require('assert');
const { createConnection, createServer, setDefaultAutoSelectFamily } = require('net');
const autoSelectFamilyAttemptTimeout = common.defaultAutoSelectFamilyAttemptTimeout;
// Test that IPV4 is reached by default if IPV6 is not reachable and the default is enabled
{
const ipv4Server = createServer((socket) => {
socket.on('data', common.mustCall(() => {
socket.write('response-ipv4');
socket.end();
}));
});
ipv4Server.listen(0, '127.0.0.1', common.mustCall(() => {
setDefaultAutoSelectFamily(true);
const connection = createConnection({
host: 'example.org',
port: ipv4Server.address().port,
lookup: createMockedLookup('::1', '127.0.0.1'),
autoSelectFamilyAttemptTimeout,
});
let response = '';
connection.setEncoding('utf-8');
connection.on('data', (chunk) => {
response += chunk;
});
connection.on('end', common.mustCall(() => {
assert.strictEqual(response, 'response-ipv4');
ipv4Server.close();
}));
connection.write('request');
}));
}
// Test that IPV4 is not reached by default if IPV6 is not reachable and the default is disabled
{
const ipv4Server = createServer((socket) => {
socket.on('data', common.mustCall(() => {
socket.write('response-ipv4');
socket.end();
}));
});
ipv4Server.listen(0, '127.0.0.1', common.mustCall(() => {
setDefaultAutoSelectFamily(false);
const port = ipv4Server.address().port;
const connection = createConnection({
host: 'example.org',
port,
lookup: createMockedLookup('::1', '127.0.0.1'),
});
connection.on('ready', common.mustNotCall());
connection.on('error', common.mustCall((error) => {
if (common.hasIPv6) {
assert.strictEqual(error.code, 'ECONNREFUSED');
assert.strictEqual(error.message, `connect ECONNREFUSED ::1:${port}`);
} else if (error.code === 'EAFNOSUPPORT') {
assert.strictEqual(error.message, `connect EAFNOSUPPORT ::1:${port} - Local (undefined:undefined)`);
} else if (error.code === 'EUNATCH') {
assert.strictEqual(error.message, `connect EUNATCH ::1:${port} - Local (:::0)`);
} else {
assert.strictEqual(error.code, 'EADDRNOTAVAIL');
assert.strictEqual(error.message, `connect EADDRNOTAVAIL ::1:${port} - Local (:::0)`);
}
ipv4Server.close();
}));
}));
}

View File

@@ -0,0 +1,78 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
require('../common');
const assert = require('assert');
const net = require('net');
let bytesRead = 0;
let bytesWritten = 0;
let count = 0;
const tcp = net.Server(function(s) {
console.log('tcp server connection');
// trigger old mode.
s.resume();
s.on('end', function() {
bytesRead += s.bytesRead;
console.log(`tcp socket disconnect #${count}`);
});
});
tcp.listen(0, function doTest() {
console.error('listening');
const socket = net.createConnection(this.address().port);
socket.on('connect', function() {
count++;
console.error('CLIENT connect #%d', count);
socket.write('foo', function() {
console.error('CLIENT: write cb');
socket.end('bar');
});
});
socket.on('finish', function() {
bytesWritten += socket.bytesWritten;
console.error('CLIENT end event #%d', count);
});
socket.on('close', function() {
console.error('CLIENT close event #%d', count);
console.log(`Bytes read: ${bytesRead}`);
console.log(`Bytes written: ${bytesWritten}`);
if (count < 2) {
console.error('RECONNECTING');
socket.connect(tcp.address().port);
} else {
tcp.close();
}
});
});
process.on('exit', function() {
assert.strictEqual(bytesRead, 12);
assert.strictEqual(bytesWritten, 12);
});

View File

@@ -0,0 +1,77 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
const tcp = net.Server(common.mustCall((s) => {
tcp.close();
let buf = '';
s.setEncoding('utf8');
s.on('data', function(d) {
buf += d;
});
s.on('end', common.mustCall(function() {
console.error('SERVER: end', buf);
assert.strictEqual(buf, "L'État, c'est moi");
s.end();
}));
}));
tcp.listen(0, common.mustCall(function() {
const socket = net.Stream({ highWaterMark: 0 });
let connected = false;
assert.strictEqual(socket.pending, true);
socket.connect(this.address().port, common.mustCall(() => connected = true));
assert.strictEqual(socket.pending, true);
assert.strictEqual(socket.connecting, true);
assert.strictEqual(socket.readyState, 'opening');
// Write a string that contains a multi-byte character sequence to test that
// `bytesWritten` is incremented with the # of bytes, not # of characters.
const a = "L'État, c'est ";
const b = 'moi';
// We're still connecting at this point so the datagram is first pushed onto
// the connect queue. Make sure that it's not added to `bytesWritten` again
// when the actual write happens.
const r = socket.write(a, common.mustCall((er) => {
console.error('write cb');
assert.ok(connected);
assert.strictEqual(socket.bytesWritten, Buffer.from(a + b).length);
assert.strictEqual(socket.pending, false);
}));
socket.on('close', common.mustCall(() => {
assert.strictEqual(socket.pending, true);
}));
assert.strictEqual(socket.bytesWritten, Buffer.from(a).length);
assert.strictEqual(r, false);
socket.end(b);
assert.strictEqual(socket.readyState, 'opening');
}));

View File

@@ -0,0 +1,56 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
const tcp = net.Server(common.mustCall((s) => {
tcp.close();
let buf = '';
s.setEncoding('utf8');
s.on('data', function(d) {
buf += d;
});
s.on('end', common.mustCall(function() {
console.error('SERVER: end', buf);
assert.strictEqual(buf, "L'État, c'est moi");
s.end();
}));
}));
tcp.listen(0, common.mustCall(function() {
const socket = net.Stream({ highWaterMark: 0 });
let connected = false;
assert.strictEqual(socket.pending, true);
socket.connect(this.address().port, common.mustCall(() => connected = true));
assert.strictEqual(socket.pending, true);
assert.strictEqual(socket.connecting, true);
assert.strictEqual(socket.readyState, 'opening');
// Write a string that contains a multi-byte character sequence to test that
// `bytesWritten` is incremented with the # of bytes, not # of characters.
const a = "L'État, c'est ";
const b = 'moi';
// We're still connecting at this point so the datagram is first pushed onto
// the connect queue. Make sure that it's not added to `bytesWritten` again
// when the actual write happens.
const r = socket.write(a, common.mustCall((er) => {
console.error('write cb');
assert.ok(connected);
assert.strictEqual(socket.bytesWritten, Buffer.from(a + b).length);
assert.strictEqual(socket.pending, false);
}));
socket.on('close', common.mustCall(() => {
assert.strictEqual(socket.pending, true);
}));
assert.strictEqual(socket.bytesWritten, Buffer.from(a).length);
assert.strictEqual(r, false);
socket.end(b);
assert.strictEqual(socket.readyState, 'opening');
}));

View File

@@ -0,0 +1,88 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
require('../common');
const assert = require('assert');
const net = require('net');
const N = 50;
let client_recv_count = 0;
let client_end_count = 0;
let disconnect_count = 0;
const server = net.createServer(function(socket) {
console.error('SERVER: got socket connection');
socket.resume();
console.error('SERVER connect, writing');
socket.write('hello\r\n');
socket.on('end', () => {
console.error('SERVER socket end, calling end()');
socket.end();
});
socket.on('close', (had_error) => {
console.log(`SERVER had_error: ${JSON.stringify(had_error)}`);
assert.strictEqual(had_error, false);
});
});
server.listen(0, function() {
console.log('SERVER listening');
const client = net.createConnection(this.address().port);
client.setEncoding('UTF8');
client.on('connect', () => {
console.error('CLIENT connected', client._writableState);
});
client.on('data', function(chunk) {
client_recv_count += 1;
console.log(`client_recv_count ${client_recv_count}`);
assert.strictEqual(chunk, 'hello\r\n');
console.error('CLIENT: calling end', client._writableState);
client.end();
});
client.on('end', () => {
console.error('CLIENT end');
client_end_count++;
});
client.on('close', (had_error) => {
console.log('CLIENT disconnect');
assert.strictEqual(had_error, false);
if (disconnect_count++ < N)
client.connect(server.address().port); // reconnect
else
server.close();
});
});
process.on('exit', () => {
assert.strictEqual(disconnect_count, N + 1);
assert.strictEqual(client_recv_count, N + 1);
assert.strictEqual(client_end_count, N + 1);
});

View File

@@ -0,0 +1,45 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
const sockets = [];
const server = net.createServer(function(c) {
c.on('close', common.mustCall());
sockets.push(c);
if (sockets.length === 2) {
assert.strictEqual(server.close(), server);
sockets.forEach((c) => c.destroy());
}
});
server.on('close', common.mustCall());
assert.strictEqual(server, server.listen(0, () => {
net.createConnection(server.address().port);
net.createConnection(server.address().port);
}));

View File

@@ -0,0 +1,41 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
let firstSocket;
const dormantServer = net.createServer(common.mustNotCall());
const server = net.createServer(common.mustCall((socket) => {
firstSocket = socket;
}));
dormantServer.maxConnections = 0;
server.maxConnections = 1;
dormantServer.on('drop', common.mustCall((data) => {
assert.strictEqual(!!data.localAddress, true);
assert.strictEqual(!!data.localPort, true);
assert.strictEqual(!!data.remoteAddress, true);
assert.strictEqual(!!data.remotePort, true);
assert.strictEqual(!!data.remoteFamily, true);
dormantServer.close();
}));
server.on('drop', common.mustCall((data) => {
assert.strictEqual(!!data.localAddress, true);
assert.strictEqual(!!data.localPort, true);
assert.strictEqual(!!data.remoteAddress, true);
assert.strictEqual(!!data.remotePort, true);
assert.strictEqual(!!data.remoteFamily, true);
firstSocket.destroy();
server.close();
}));
dormantServer.listen(0, () => {
net.createConnection(dormantServer.address().port);
});
server.listen(0, () => {
net.createConnection(server.address().port);
net.createConnection(server.address().port);
});

View File

@@ -0,0 +1,49 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
const msg = 'test';
let stopped = true;
let server1Sock;
const server1ConnHandler = (socket) => {
socket.on('data', function(data) {
if (stopped) {
assert.fail('data event should not have happened yet');
}
assert.strictEqual(data.toString(), msg);
socket.end();
server1.close();
});
server1Sock = socket;
};
const server1 = net.createServer({ pauseOnConnect: true }, server1ConnHandler);
const server2ConnHandler = (socket) => {
socket.on('data', function(data) {
assert.strictEqual(data.toString(), msg);
socket.end();
server2.close();
assert.strictEqual(server1Sock.bytesRead, 0);
server1Sock.resume();
stopped = false;
});
};
const server2 = net.createServer({ pauseOnConnect: false }, server2ConnHandler);
server1.listen(0, function() {
const clientHandler = common.mustCall(function() {
server2.listen(0, function() {
net.createConnection({ port: this.address().port }).write(msg);
});
});
net.createConnection({ port: this.address().port }).write(msg, clientHandler);
});
process.on('exit', function() {
assert.strictEqual(stopped, false);
});

View File

@@ -0,0 +1,41 @@
'use strict';
const common = require('../common');
// Skip test in FreeBSD jails
if (common.inFreeBSDJail)
common.skip('In a FreeBSD jail');
const assert = require('assert');
const net = require('net');
let conns = 0;
const clientLocalPorts = [];
const serverRemotePorts = [];
const client = new net.Socket();
const server = net.createServer((socket) => {
serverRemotePorts.push(socket.remotePort);
socket.end();
});
server.on('close', common.mustCall(() => {
// Client and server should agree on the ports used
assert.deepStrictEqual(serverRemotePorts, clientLocalPorts);
assert.strictEqual(conns, 2);
}));
server.listen(0, common.localhostIPv4, connect);
function connect() {
if (conns === 2) {
server.close();
return;
}
conns++;
client.once('close', connect);
assert.strictEqual(
client,
client.connect(server.address().port, common.localhostIPv4, () => {
clientLocalPorts.push(client.localPort);
})
);
}

View File

@@ -0,0 +1,17 @@
'use strict';
const common = require('../common');
const net = require('net');
const assert = require('assert');
const c = net.createConnection(common.PORT);
c.on('connect', common.mustNotCall());
c.on('error', common.mustCall(function(error) {
// Family autoselection might be skipped if only a single address is returned by DNS.
const failedAttempt = Array.isArray(error.errors) ? error.errors[0] : error;
assert.strictEqual(failedAttempt.code, 'ECONNREFUSED');
assert.strictEqual(failedAttempt.port, common.PORT);
assert.match(failedAttempt.address, /^(127\.0\.0\.1|::1)$/);
}));

View File

@@ -0,0 +1,32 @@
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const net = require('net');
const assert = require('assert');
const c = net.createConnection(common.PORT);
c.on('connect', common.mustNotCall());
c.on('error', common.mustCall((e) => {
assert.strictEqual(c.connecting, false);
assert.strictEqual(e.code, 'ECONNREFUSED');
}));

View File

@@ -0,0 +1,64 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const net = require('net');
// With only a callback, server should get a port assigned by the OS
{
const server = net.createServer(common.mustNotCall());
server.listen(common.mustCall(function() {
assert.ok(server.address().port > 100);
server.close();
}));
}
// No callback to listen(), assume we can bind in 100 ms
{
const server = net.createServer(common.mustNotCall());
server.listen(common.PORT);
setTimeout(function() {
const address = server.address();
assert.strictEqual(address.port, common.PORT);
if (address.family === 'IPv6')
assert.strictEqual(server._connectionKey, `6::::${address.port}`);
else
assert.strictEqual(server._connectionKey, `4:0.0.0.0:${address.port}`);
server.close();
}, 100);
}
// Callback to listen()
{
const server = net.createServer(common.mustNotCall());
server.listen(common.PORT + 1, common.mustCall(function() {
assert.strictEqual(server.address().port, common.PORT + 1);
server.close();
}));
}
// Backlog argument
{
const server = net.createServer(common.mustNotCall());
server.listen(common.PORT + 2, '0.0.0.0', 127, common.mustCall(function() {
assert.strictEqual(server.address().port, common.PORT + 2);
server.close();
}));
}
// Backlog argument without host argument
{
const server = net.createServer(common.mustNotCall());
server.listen(common.PORT + 3, 127, common.mustCall(function() {
assert.strictEqual(server.address().port, common.PORT + 3);
server.close();
}));
}

View File

@@ -0,0 +1,27 @@
const vm = require("vm");
const { describe, it, expect } = require("bun:test");
describe("vm.Script", () => {
it("shouldn't leak memory", () => {
const initialUsage = process.memoryUsage.rss();
{
const source = `/*\n${Buffer.alloc(10000, " * aaaaa\n").toString("utf8")}\n*/ Buffer.alloc(10, 'hello');`;
function go(i) {
const script = new vm.Script(source + "//" + i);
script.runInThisContext();
}
for (let i = 0; i < 10000; ++i) {
go(i);
}
}
Bun.gc(true);
const finalUsage = process.memoryUsage.rss();
const megabytes = Math.round(((finalUsage - initialUsage) / 1024 / 1024) * 100) / 100;
expect(megabytes).toBeLessThan(200);
});
});

View File

@@ -0,0 +1,30 @@
const vm = require("vm");
const { describe, it, expect } = require("bun:test");
describe("vm.SourceTextModule", () => {
it("shouldn't leak memory", async () => {
const initialUsage = process.memoryUsage.rss();
{
const source = `/*\n${Buffer.alloc(50_000, " * aaaaa\n").toString("utf8")}\n*/ Buffer.alloc(10, 'hello');`;
async function go(i) {
const mod = new vm.SourceTextModule(source + "//" + i, {
identifier: Buffer.alloc(64, i.toString()).toString("utf8"),
});
await mod.link(() => {});
await mod.evaluate();
}
for (let i = 0; i < 50_000; ++i) {
await go(i);
}
}
Bun.gc(true);
const finalUsage = process.memoryUsage.rss();
const megabytes = Math.round(((finalUsage - initialUsage) / 1024 / 1024) * 100) / 100;
expect(megabytes).toBeLessThan(3000);
});
});