From 4654a8a886334f4851797b6769d863720d2bafca Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Mon, 8 Sep 2025 15:28:35 -0700 Subject: [PATCH 01/59] dont override this let it use binded value --- src/sql/mysql/MySQLConnection.zig | 2 +- src/sql/postgres/PostgresSQLConnection.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 82bce2824e56..9dd70556e788 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -378,7 +378,7 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { defer loop.exit(); _ = on_close.call( this.globalObject, - this.js_value, + .js_undefined, &[_]JSValue{ value, this.getQueriesArray(), diff --git a/src/sql/postgres/PostgresSQLConnection.zig b/src/sql/postgres/PostgresSQLConnection.zig index a7422f532f76..725dacddff09 100644 --- a/src/sql/postgres/PostgresSQLConnection.zig +++ b/src/sql/postgres/PostgresSQLConnection.zig @@ -324,7 +324,7 @@ pub fn failWithJSValue(this: *PostgresSQLConnection, value: JSValue) void { defer loop.exit(); _ = on_close.call( this.globalObject, - this.js_value, + .js_undefined, &[_]JSValue{ value, this.getQueriesArray(), From 8bf8b8e32f086619204230c31548182624a53ad2 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Mon, 8 Sep 2025 17:29:01 -0700 Subject: [PATCH 02/59] test --- src/js/internal/sql/mysql.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index 8e4702944eeb..2ec1c0d8e755 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -396,15 +396,19 @@ class PooledMySQLConnection { this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; - // notify all queries that the connection is closed - for (const onClose of queries) { - onClose(err); - } - const onFinish = this.onFinish; - if (onFinish) { - onFinish(err); + try { + // notify all queries that the connection is closed + for (const onClose of queries) { + onClose(err); + } + const onFinish = this.onFinish; + if (onFinish) { + onFinish(err); + } + } catch (e) { + console.log("onClose error", e, this instanceof PooledMySQLConnection, this); + throw e; } - this.adapter.release(this, true); } From 3be879682ee4cd23b141b1bb656a0d3622b763aa Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Mon, 8 Sep 2025 18:28:10 -0700 Subject: [PATCH 03/59] wip --- src/js/internal/sql/mysql.ts | 20 ++++++++------------ src/sql/mysql/protocol/ErrorPacket.zig | 2 +- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index 2ec1c0d8e755..8e4702944eeb 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -396,19 +396,15 @@ class PooledMySQLConnection { this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; - try { - // notify all queries that the connection is closed - for (const onClose of queries) { - onClose(err); - } - const onFinish = this.onFinish; - if (onFinish) { - onFinish(err); - } - } catch (e) { - console.log("onClose error", e, this instanceof PooledMySQLConnection, this); - throw e; + // notify all queries that the connection is closed + for (const onClose of queries) { + onClose(err); } + const onFinish = this.onFinish; + if (onFinish) { + onFinish(err); + } + this.adapter.release(this, true); } diff --git a/src/sql/mysql/protocol/ErrorPacket.zig b/src/sql/mysql/protocol/ErrorPacket.zig index 5e16c7c97f61..6fb6ef9b3791 100644 --- a/src/sql/mysql/protocol/ErrorPacket.zig +++ b/src/sql/mysql/protocol/ErrorPacket.zig @@ -19,7 +19,7 @@ pub fn createMySQLError( message: []const u8, options: MySQLErrorOptions, ) bun.JSError!JSValue { - const opts_obj = JSValue.createEmptyObject(globalObject, 18); + const opts_obj = JSValue.createEmptyObject(globalObject, 0); opts_obj.ensureStillAlive(); opts_obj.put(globalObject, JSC.ZigString.static("code"), try bun.String.createUTF8ForJS(globalObject, options.code)); if (options.errno) |errno| { From edec93a475fc4b96f8a21784d1a7d4774872bc6c Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Mon, 8 Sep 2025 19:25:15 -0700 Subject: [PATCH 04/59] test --- src/js/internal/sql/mysql.ts | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index 8e4702944eeb..f41cb3c221a8 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -396,13 +396,19 @@ class PooledMySQLConnection { this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; - // notify all queries that the connection is closed - for (const onClose of queries) { - onClose(err); - } - const onFinish = this.onFinish; - if (onFinish) { - onFinish(err); + try { + // notify all queries that the connection is closed + for (const onClose of queries) { + onClose(err); + } + const onFinish = this.onFinish; + if (onFinish) { + onFinish(err); + } + } catch (e) { + console.log("onClose error", e, this instanceof PooledMySQLConnection, this, this.queries); + console.log("error", err); + throw e; } this.adapter.release(this, true); From 6f125e0375098541292ef3be090d5541fe8d2a95 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Mon, 8 Sep 2025 19:43:40 -0700 Subject: [PATCH 05/59] toError --- src/sql/mysql/MySQLConnection.zig | 2 +- src/sql/mysql/MySQLQuery.zig | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 9dd70556e788..094fe9411a90 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -380,7 +380,7 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { this.globalObject, .js_undefined, &[_]JSValue{ - value, + value.toError() orelse value, this.getQueriesArray(), }, ) catch |e| this.globalObject.reportActiveExceptionAsUnhandled(e); diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index 5072018601f2..029274385924 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -95,9 +95,7 @@ pub fn onWriteFail( const event_loop = vm.eventLoop(); event_loop.runCallback(function, globalObject, thisValue, &.{ targetValue, - // TODO: add mysql error to JS - // postgresErrorToJS(globalObject, null, err), - instance, + instance.toError() orelse instance, queries_array, }); } @@ -178,7 +176,7 @@ pub fn onJSError(this: *@This(), err: jsc.JSValue, globalObject: *jsc.JSGlobalOb const function = vm.rareData().mysql_context.onQueryRejectFn.get().?; const event_loop = vm.eventLoop(); event_loop.runCallback(function, globalObject, thisValue, &.{ - targetValue, + targetValue.toError() orelse targetValue, err, }); } From b809cd297e69e55efea5a6b7b7469187ed8be646 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Mon, 8 Sep 2025 20:50:40 -0700 Subject: [PATCH 06/59] test --- src/js/internal/sql/mysql.ts | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index f41cb3c221a8..d9f025ee6926 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -396,19 +396,13 @@ class PooledMySQLConnection { this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; - try { - // notify all queries that the connection is closed - for (const onClose of queries) { - onClose(err); - } - const onFinish = this.onFinish; - if (onFinish) { - onFinish(err); - } - } catch (e) { - console.log("onClose error", e, this instanceof PooledMySQLConnection, this, this.queries); - console.log("error", err); - throw e; + // notify all queries that the connection is closed + for (const onClose of queries) { + onClose(err); + } + const onFinish = this.onFinish; + if (onFinish) { + onFinish(err); } this.adapter.release(this, true); @@ -425,7 +419,7 @@ class PooledMySQLConnection { this.connection = await PooledMySQLConnection.createConnection( this.connectionInfo, this.#onConnected.bind(this), - this.#onClose.bind(this), + (...args) => this.#onClose(...args), ); } From 7eecefecf00e634efc7ba1048bf803b5e0663704 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Mon, 8 Sep 2025 20:51:17 -0700 Subject: [PATCH 07/59] test --- src/js/internal/sql/mysql.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index d9f025ee6926..4173620c2f7d 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -418,7 +418,7 @@ class PooledMySQLConnection { async #startConnection() { this.connection = await PooledMySQLConnection.createConnection( this.connectionInfo, - this.#onConnected.bind(this), + (...args) => this.#onConnected(...args), (...args) => this.#onClose(...args), ); } From 413dd86bf8c23f4864c5f60cc437aa2a91458894 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Mon, 8 Sep 2025 21:48:37 -0700 Subject: [PATCH 08/59] test --- src/js/internal/sql/mysql.ts | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index 4173620c2f7d..ac50d14e5a50 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -378,31 +378,33 @@ class PooledMySQLConnection { } #onClose(err) { - if (err) { - err = wrapError(err); - } - const connectionInfo = this.connectionInfo; - if (connectionInfo?.onclose) { - connectionInfo.onclose(err); - } + let wrappedErr = err; this.state = PooledConnectionState.closed; this.connection = null; - this.storedError = err; - - // remove from ready connections if its there this.adapter.readyConnections.delete(this); const queries = new Set(this.queries); this.queries?.clear?.(); this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; + const connectionInfo = this.connectionInfo; + + if (err) { + wrappedErr = wrapError(err); + } + + this.storedError = wrappedErr; // notify all queries that the connection is closed for (const onClose of queries) { - onClose(err); + onClose(wrappedErr); } const onFinish = this.onFinish; if (onFinish) { - onFinish(err); + onFinish(wrappedErr); + } + + if (connectionInfo?.onclose) { + connectionInfo.onclose(wrappedErr); } this.adapter.release(this, true); From becf7777ef35fffbfffd9e4fceacadb22899b47d Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Mon, 8 Sep 2025 21:49:07 -0700 Subject: [PATCH 09/59] test --- src/js/internal/sql/mysql.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index ac50d14e5a50..935effb7a868 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -383,7 +383,7 @@ class PooledMySQLConnection { this.connection = null; this.adapter.readyConnections.delete(this); const queries = new Set(this.queries); - this.queries?.clear?.(); + this.queries.clear(); this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; const connectionInfo = this.connectionInfo; From 07ca61f8141f7457a6be31448d8d591eaf6c8e15 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 13:23:28 -0700 Subject: [PATCH 10/59] a --- src/js/internal/sql/mysql.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index 935effb7a868..f6180488228f 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -386,6 +386,7 @@ class PooledMySQLConnection { this.queries.clear(); this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; + const onFinish = this.onFinish; const connectionInfo = this.connectionInfo; if (err) { @@ -398,7 +399,7 @@ class PooledMySQLConnection { for (const onClose of queries) { onClose(wrappedErr); } - const onFinish = this.onFinish; + if (onFinish) { onFinish(wrappedErr); } From f424308a316123359f3937d20fb122ec3b4e5b6b Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 13:49:39 -0700 Subject: [PATCH 11/59] fix disconnect inside finalie --- src/sql/mysql/MySQLConnection.zig | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 094fe9411a90..8753fec3fc54 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -264,13 +264,37 @@ fn drainInternal(this: *@This()) void { } } } + pub fn finalize(this: *MySQLConnection) void { this.stopTimers(); debug("MySQLConnection finalize", .{}); // Ensure we disconnect before finalizing if (this.status != .disconnected) { - this.disconnect(); + // delay disconnecting to avoid calling JS code inside the finalizer + const DisconnectTask = struct { + connection: *MySQLConnection, + task: jsc.AnyTask, + + fn run(ctx: *@This()) void { + ctx.connection.disconnect(); + + ctx.connection.deref(); + bun.default_allocator.destroy(ctx); + } + + pub fn enqueue(connection: *MySQLConnection) void { + const holder = bun.handleOom(bun.default_allocator.create(@This())); + holder.* = .{ + .connection = connection, + .task = jsc.AnyTask.New(@This(), @This().run).init(holder), + }; + connection.ref(); + connection.vm.enqueueTask(jsc.Task.init(&holder.task)); + } + }; + + DisconnectTask.enqueue(this); } this.js_value = .zero; From edeca4602d88c05164e4c608a886e52075d26a22 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 15:00:02 -0700 Subject: [PATCH 12/59] dont pass zero --- src/sql/mysql/MySQLConnection.zig | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 8753fec3fc54..acbc27fd9978 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -376,7 +376,10 @@ pub fn stopTimers(this: *@This()) void { } pub fn getQueriesArray(this: *const @This()) JSValue { - return js.queriesGetCached(this.js_value) orelse .zero; + if (this.js_value == .zero) { + return .js_undefined; + } + return js.queriesGetCached(this.js_value) orelse .js_undefined; } pub fn failFmt(this: *@This(), error_code: AnyMySQLError.Error, comptime fmt: [:0]const u8, args: anytype) void { const message = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, fmt, args)); @@ -1294,6 +1297,9 @@ fn handleHandshakeDecodePublicKey(this: *MySQLConnection, comptime Context: type pub fn consumeOnConnectCallback(this: *const @This(), globalObject: *jsc.JSGlobalObject) ?jsc.JSValue { debug("consumeOnConnectCallback", .{}); + if (this.js_value == .zero) { + return null; + } const on_connect = js.onconnectGetCached(this.js_value) orelse return null; debug("consumeOnConnectCallback exists", .{}); @@ -1303,6 +1309,9 @@ pub fn consumeOnConnectCallback(this: *const @This(), globalObject: *jsc.JSGloba pub fn consumeOnCloseCallback(this: *const @This(), globalObject: *jsc.JSGlobalObject) ?jsc.JSValue { debug("consumeOnCloseCallback", .{}); + if (this.js_value == .zero) { + return null; + } const on_close = js.oncloseGetCached(this.js_value) orelse return null; debug("consumeOnCloseCallback exists", .{}); js.oncloseSetCached(this.js_value, globalObject, .zero); @@ -1320,8 +1329,12 @@ pub fn setStatus(this: *@This(), status: ConnectionState) void { switch (status) { .connected => { const on_connect = this.consumeOnConnectCallback(this.globalObject) orelse return; - const js_value = this.js_value; - js_value.ensureStillAlive(); + var js_value = this.js_value; + if (js_value == .zero) { + js_value = .js_undefined; + } else { + js_value.ensureStillAlive(); + } this.globalObject.queueMicrotask(on_connect, &[_]JSValue{ JSValue.jsNull(), js_value }); this.poll_ref.unref(this.vm); }, @@ -1898,7 +1911,7 @@ pub fn handleResultSet(this: *MySQLConnection, comptime Context: type, reader: N var cached_structure: ?CachedStructure = null; switch (request.flags.result_mode) { .objects => { - cached_structure = statement.structure(this.js_value, this.globalObject); + cached_structure = if (this.js_value == .zero) null else statement.structure(this.js_value, this.globalObject); structure = cached_structure.?.jsValue() orelse .js_undefined; }, .raw, .values => { From b3d46fa99a20c99e6ebe834eb90218b0301a4716 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 15:01:11 -0700 Subject: [PATCH 13/59] check that --- src/js/internal/sql/mysql.ts | 63 ++++++++++++++++++++++++++---------- 1 file changed, 46 insertions(+), 17 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index f6180488228f..b14749d8fed3 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -378,34 +378,63 @@ class PooledMySQLConnection { } #onClose(err) { - let wrappedErr = err; + // let wrappedErr = err; + // this.state = PooledConnectionState.closed; + // this.connection = null; + // this.adapter.readyConnections.delete(this); + // const queries = new Set(this.queries); + // this.queries.clear(); + // this.queryCount = 0; + // this.flags &= ~PooledConnectionFlags.reserved; + // const onFinish = this.onFinish; + // const connectionInfo = this.connectionInfo; + + // if (err) { + // wrappedErr = wrapError(err); + // } + + // this.storedError = wrappedErr; + + // // notify all queries that the connection is closed + // for (const onClose of queries) { + // onClose(wrappedErr); + // } + + // if (onFinish) { + // onFinish(wrappedErr); + // } + + // if (connectionInfo?.onclose) { + // connectionInfo.onclose(wrappedErr); + // } + + // this.adapter.release(this, true); + + if (err) { + err = wrapError(err); + } + const connectionInfo = this.connectionInfo; + if (connectionInfo?.onclose) { + connectionInfo.onclose(err); + } this.state = PooledConnectionState.closed; this.connection = null; + this.storedError = err; + + // remove from ready connections if its there this.adapter.readyConnections.delete(this); const queries = new Set(this.queries); - this.queries.clear(); + this.queries?.clear?.(); this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; - const onFinish = this.onFinish; - const connectionInfo = this.connectionInfo; - - if (err) { - wrappedErr = wrapError(err); - } - - this.storedError = wrappedErr; // notify all queries that the connection is closed for (const onClose of queries) { - onClose(wrappedErr); + onClose(err); } - + const onFinish = this.onFinish; if (onFinish) { - onFinish(wrappedErr); - } - - if (connectionInfo?.onclose) { - connectionInfo.onclose(wrappedErr); + onFinish(err); } this.adapter.release(this, true); From 173309ba956049d8a5f4ff37eea03aedbe867dc9 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 15:04:28 -0700 Subject: [PATCH 14/59] fix test --- test/js/sql/sql-mysql.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/js/sql/sql-mysql.test.ts b/test/js/sql/sql-mysql.test.ts index cdce28948200..611805d88db8 100644 --- a/test/js/sql/sql-mysql.test.ts +++ b/test/js/sql/sql-mysql.test.ts @@ -880,7 +880,7 @@ if (docker) { } catch (e) { expect(e).toBeInstanceOf(Error); expect(e.code).toBe("ERR_MYSQL_CONNECTION_TIMEOUT"); - expect(e.message).toMatch(/Connection timed out after 200ms/); + expect(e.message).toMatch(/Connection timeout after 200ms/); } finally { sql.close(); server.close(); From 3d053712d49eca8650e65d2a3253bdbe495f68ae Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 15:06:12 -0700 Subject: [PATCH 15/59] more consistent --- src/sql/mysql/MySQLConnection.zig | 4 ++-- src/sql/postgres/PostgresSQLConnection.zig | 2 +- test/js/sql/sql.test.ts | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index acbc27fd9978..0727741e8f6a 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -232,7 +232,7 @@ pub fn onConnectionTimeout(this: *@This()) bun.api.Timer.EventLoopTimer.Arm { .authenticating, .authentication_awaiting_pk, => { - this.failFmt(error.ConnectionTimedOut, "Connection timed out after {} (during authentication)", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.connection_timeout_ms) *| std.time.ns_per_ms)}); + this.failFmt(error.ConnectionTimedOut, "Connection ttimeout after {} (during authentication)", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.connection_timeout_ms) *| std.time.ns_per_ms)}); }, } return .disarm; @@ -774,7 +774,7 @@ fn SocketHandler(comptime ssl: bool) type { } pub fn onTimeout(this: *MySQLConnection) void { - this.fail("Connection timed out", error.ConnectionTimedOut); + this.fail("Connection timeout", error.ConnectionTimedOut); } pub fn onDrain(this: *MySQLConnection) void { diff --git a/src/sql/postgres/PostgresSQLConnection.zig b/src/sql/postgres/PostgresSQLConnection.zig index 725dacddff09..6689d044ae16 100644 --- a/src/sql/postgres/PostgresSQLConnection.zig +++ b/src/sql/postgres/PostgresSQLConnection.zig @@ -219,7 +219,7 @@ pub fn onConnectionTimeout(this: *PostgresSQLConnection) bun.api.Timer.EventLoop this.failFmt("ERR_POSTGRES_CONNECTION_TIMEOUT", "Connection timeout after {}", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.connection_timeout_ms) *| std.time.ns_per_ms)}); }, .sent_startup_message => { - this.failFmt("ERR_POSTGRES_CONNECTION_TIMEOUT", "Connection timed out after {} (sent startup message, but never received response)", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.connection_timeout_ms) *| std.time.ns_per_ms)}); + this.failFmt("ERR_POSTGRES_CONNECTION_TIMEOUT", "Connection timeout after {} (sent startup message, but never received response)", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.connection_timeout_ms) *| std.time.ns_per_ms)}); }, } return .disarm; diff --git a/test/js/sql/sql.test.ts b/test/js/sql/sql.test.ts index 57740fa7ebfb..7b7c7abce42e 100644 --- a/test/js/sql/sql.test.ts +++ b/test/js/sql/sql.test.ts @@ -2630,7 +2630,7 @@ if (isDockerEnabled()) { expect(e).toBeInstanceOf(SQL.SQLError); expect(e).toBeInstanceOf(SQL.PostgresError); expect(e.code).toBe("ERR_POSTGRES_CONNECTION_TIMEOUT"); - expect(e.message).toMatch(/Connection timed out after 200ms/); + expect(e.message).toMatch(/Connection timeout after 200ms/); } finally { sql.close(); server.close(); From 60d4f924911ce9c119c978fe3f84472cad2eba0b Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 15:14:10 -0700 Subject: [PATCH 16/59] enable more --- src/codegen/bundle-modules.ts | 12 ++++++++++-- src/js/internal/sql/mysql.ts | 2 +- src/js/internal/sql/postgres.ts | 2 +- src/js/internal/sql/sqlite.ts | 3 ++- test/harness.ts | 7 +------ 5 files changed, 15 insertions(+), 11 deletions(-) diff --git a/src/codegen/bundle-modules.ts b/src/codegen/bundle-modules.ts index a7645c162590..46a99d44ac45 100644 --- a/src/codegen/bundle-modules.ts +++ b/src/codegen/bundle-modules.ts @@ -98,8 +98,8 @@ for (let i = 0; i < nativeStartIndex; i++) { // TODO: there is no reason this cannot be converted automatically. // import { ... } from '...' -> `const { ... } = require('...')` - const scannedImports = t.scanImports(input); - for (const imp of scannedImports) { + const scannedImports = t.scan(input); + for (const imp of scannedImports.imports) { if (imp.kind === "import-statement") { var isBuiltin = true; try { @@ -120,6 +120,14 @@ for (let i = 0; i < nativeStartIndex; i++) { } } + if (scannedImports.exports.includes("default") && scannedImports.exports.length > 1) { + const err = new Error( + `Using \`export default\` AND named exports together in builtin modules is unsupported. See src/js/README.md (from ${moduleList[i]})`, + ); + err.name = "BunError"; + err.fileName = moduleList[i]; + throw err; + } let importStatements: string[] = []; const processed = sliceSourceCode( diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index b14749d8fed3..c4e4e5a748ab 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -516,7 +516,7 @@ class PooledMySQLConnection { } } -export class MySQLAdapter +class MySQLAdapter implements DatabaseAdapter { diff --git a/src/js/internal/sql/postgres.ts b/src/js/internal/sql/postgres.ts index 9dbb3f30fd40..42d7143211f6 100644 --- a/src/js/internal/sql/postgres.ts +++ b/src/js/internal/sql/postgres.ts @@ -501,7 +501,7 @@ class PooledPostgresConnection { } } -export class PostgresAdapter +class PostgresAdapter implements DatabaseAdapter< PooledPostgresConnection, diff --git a/src/js/internal/sql/sqlite.ts b/src/js/internal/sql/sqlite.ts index 11304a7e879c..60aa190d797e 100644 --- a/src/js/internal/sql/sqlite.ts +++ b/src/js/internal/sql/sqlite.ts @@ -293,7 +293,7 @@ function parseSQLQuery(query: string): SQLParsedInfo { return { command, firstKeyword, hasReturning }; } -export class SQLiteQueryHandle implements BaseQueryHandle { +class SQLiteQueryHandle implements BaseQueryHandle { private mode = SQLQueryResultMode.objects; private readonly sql: string; @@ -807,4 +807,5 @@ export default { SQLCommand, commandToString, parseSQLQuery, + SQLiteQueryHandle, }; diff --git a/test/harness.ts b/test/harness.ts index 01b5e7937331..78bf54af83dc 100644 --- a/test/harness.ts +++ b/test/harness.ts @@ -863,11 +863,6 @@ export function isDockerEnabled(): boolean { return false; } - // TODO: investigate why its not starting on Linux arm64 - if ((isLinux && process.arch === "arm64") || isMacOS) { - return false; - } - try { const info = execSync(`${dockerCLI} info`, { stdio: ["ignore", "pipe", "inherit"] }); return info.toString().indexOf("Server Version:") !== -1; @@ -925,7 +920,7 @@ export async function describeWithContainer( return; } const { arch, platform } = process; - if ((archs && !archs?.includes(arch)) || platform === "win32" || platform === "darwin") { + if ((archs && !archs?.includes(arch)) || platform === "win32") { test.skip(`docker image is not supported on ${platform}/${arch}, skipped: ${image}`, () => {}); return false; } From 7c30edd20ea29c6fa2456a46015079aa49778c71 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 15:15:09 -0700 Subject: [PATCH 17/59] opsie --- src/js/internal/sql/sqlite.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/js/internal/sql/sqlite.ts b/src/js/internal/sql/sqlite.ts index 60aa190d797e..8e1c944438ff 100644 --- a/src/js/internal/sql/sqlite.ts +++ b/src/js/internal/sql/sqlite.ts @@ -380,9 +380,7 @@ class SQLiteQueryHandle implements BaseQueryHandle { } } -export class SQLiteAdapter - implements DatabaseAdapter -{ +class SQLiteAdapter implements DatabaseAdapter { public readonly connectionInfo: Bun.SQL.__internal.DefinedSQLiteOptions; public db: BunSQLiteModule.Database | null = null; public storedError: Error | null = null; From c5fbe102e2d0a5a1c5a6eb9025a49aa2a2a32a0e Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 15:16:39 -0700 Subject: [PATCH 18/59] opsie --- src/sql/mysql/MySQLConnection.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 0727741e8f6a..43be7196d599 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -232,7 +232,7 @@ pub fn onConnectionTimeout(this: *@This()) bun.api.Timer.EventLoopTimer.Arm { .authenticating, .authentication_awaiting_pk, => { - this.failFmt(error.ConnectionTimedOut, "Connection ttimeout after {} (during authentication)", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.connection_timeout_ms) *| std.time.ns_per_ms)}); + this.failFmt(error.ConnectionTimedOut, "Connection timeout after {} (during authentication)", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.connection_timeout_ms) *| std.time.ns_per_ms)}); }, } return .disarm; From b79f0d1e395709a5c8df71caff64dae0ca1a14b5 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 16:00:37 -0700 Subject: [PATCH 19/59] tst --- test/js/sql/sql-mysql.test.ts | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/test/js/sql/sql-mysql.test.ts b/test/js/sql/sql-mysql.test.ts index 611805d88db8..ff2e85d175db 100644 --- a/test/js/sql/sql-mysql.test.ts +++ b/test/js/sql/sql-mysql.test.ts @@ -612,23 +612,23 @@ if (docker) { expect(e.message).toBe("password error"); } }); - test("Support dynamic async password function that throws", async () => { - await using sql = new SQL({ - ...options, - max: 1, - password: async () => { - await Bun.sleep(10); - throw new Error("password error"); - }, - }); - try { - await sql`select true as x`; - expect.unreachable(); - } catch (e: any) { - expect(e).toBeInstanceOf(Error); - expect(e.message).toBe("password error"); - } - }); + // test("Support dynamic async password function that throws", async () => { + // await using sql = new SQL({ + // ...options, + // max: 1, + // password: async () => { + // await Bun.sleep(10); + // throw new Error("password error"); + // }, + // }); + // try { + // await sql`select true as x`; + // expect.unreachable(); + // } catch (e: any) { + // expect(e).toBeInstanceOf(Error); + // expect(e.message).toBe("password error"); + // } + // }); test("sql file", async () => { await using sql = new SQL(options); expect((await sql.file(rel("select.sql")))[0].x).toBe(1); From 7753820bd6e0dbb012b32d2e22bf428ab2129f34 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 16:23:21 -0700 Subject: [PATCH 20/59] delay clos --- src/js/internal/sql/mysql.ts | 16 ++++++++-------- src/sql/mysql/MySQLConnection.zig | 10 ++-------- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index c4e4e5a748ab..7d9612faef4b 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -346,10 +346,13 @@ class PooledMySQLConnection { /// queryCount is used to indicate the number of queries using the connection, if a connection is reserved or if its a transaction queryCount will be 1 independently of the number of queries queryCount: number = 0; - #onConnected(err, _) { + #onConnected(err, connection) { if (err) { err = wrapError(err); + } else { + this.connection = connection; } + const connectionInfo = this.connectionInfo; if (connectionInfo?.onconnect) { connectionInfo.onconnect(err); @@ -388,6 +391,7 @@ class PooledMySQLConnection { // this.flags &= ~PooledConnectionFlags.reserved; // const onFinish = this.onFinish; // const connectionInfo = this.connectionInfo; + // const adapter = this.adapter; // if (err) { // wrappedErr = wrapError(err); @@ -408,7 +412,7 @@ class PooledMySQLConnection { // connectionInfo.onclose(wrappedErr); // } - // this.adapter.release(this, true); + // adapter.release(this, true); if (err) { err = wrapError(err); @@ -447,12 +451,8 @@ class PooledMySQLConnection { this.#startConnection(); } - async #startConnection() { - this.connection = await PooledMySQLConnection.createConnection( - this.connectionInfo, - (...args) => this.#onConnected(...args), - (...args) => this.#onClose(...args), - ); + #startConnection() { + PooledMySQLConnection.createConnection(this.connectionInfo, this.#onConnected.bind(this), this.#onClose.bind(this)); } onClose(onClose: (err: Error) => void) { diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 43be7196d599..55ae71f553ab 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -403,14 +403,8 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { const loop = this.vm.eventLoop(); loop.enter(); defer loop.exit(); - _ = on_close.call( - this.globalObject, - .js_undefined, - &[_]JSValue{ - value.toError() orelse value, - this.getQueriesArray(), - }, - ) catch |e| this.globalObject.reportActiveExceptionAsUnhandled(e); + + this.globalObject.queueMicrotask(on_close, &[_]JSValue{ value.toError() orelse value, this.getQueriesArray() }); } pub fn fail(this: *MySQLConnection, message: []const u8, err: AnyMySQLError.Error) void { From 3e84a2964da73a1f04041b7a82fe89a9580ef9c5 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 16:30:54 -0700 Subject: [PATCH 21/59] ensureStillAlive --- src/sql/mysql/MySQLConnection.zig | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 55ae71f553ab..8904f965c5bf 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -404,7 +404,11 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { loop.enter(); defer loop.exit(); - this.globalObject.queueMicrotask(on_close, &[_]JSValue{ value.toError() orelse value, this.getQueriesArray() }); + const js_error = value.toError() orelse value; + js_error.ensureStillAlive(); + const queries_array = this.getQueriesArray(); + queries_array.ensureStillAlive(); + this.globalObject.queueMicrotask(on_close, &[_]JSValue{ js_error, queries_array }); } pub fn fail(this: *MySQLConnection, message: []const u8, err: AnyMySQLError.Error) void { From b778121cf17c6f17f287fc9c0ce97f2fea908a12 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 16:50:12 -0700 Subject: [PATCH 22/59] ok --- src/sql/mysql/MySQLConnection.zig | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 8904f965c5bf..4ad2c8ce3878 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -389,15 +389,19 @@ pub fn failFmt(this: *@This(), error_code: AnyMySQLError.Error, comptime fmt: [: this.failWithJSValue(err); } pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { - defer this.updateHasPendingActivity(); - this.stopTimers(); if (this.status == .failed) return; - this.setStatus(.failed); + this.stopTimers(); this.ref(); - defer this.deref(); - // we defer the refAndClose so the on_close will be called first before we reject the pending requests - defer this.refAndClose(value); + defer { + // we defer the refAndClose so the on_close will be called first before we reject the pending requests + this.refAndClose(value); + this.updateHasPendingActivity(); + this.deref(); + } + + this.setStatus(.failed); + const on_close = this.consumeOnCloseCallback(this.globalObject) orelse return; const loop = this.vm.eventLoop(); @@ -418,8 +422,7 @@ pub fn fail(this: *MySQLConnection, message: []const u8, err: AnyMySQLError.Erro } pub fn onClose(this: *MySQLConnection) void { - var vm = this.vm; - defer vm.drainMicrotasks(); + defer this.deref(); this.fail("Connection closed", error.ConnectionClosed); } @@ -1025,6 +1028,7 @@ pub fn onOpen(this: *MySQLConnection, socket: Socket) void { this.setupMaxLifetimeTimerIfNecessary(); this.resetConnectionTimeout(); this.socket = socket; + this.ref(); // one ref for the socket if (socket == .SocketTCP) { // when upgrading to TLS the onOpen callback will be called again and at this moment we dont wanna to change the status to handshaking this.setStatus(.handshaking); From f1a52633a358da572c9e62c27a02a71e594507ee Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 16:56:59 -0700 Subject: [PATCH 23/59] opsie --- src/sql/mysql/MySQLConnection.zig | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 4ad2c8ce3878..61bb5e78bb0f 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -421,11 +421,18 @@ pub fn fail(this: *MySQLConnection, message: []const u8, err: AnyMySQLError.Erro this.failWithJSValue(instance); } -pub fn onClose(this: *MySQLConnection) void { +pub fn onEnd(this: *MySQLConnection) void { + // no more socket defer this.deref(); this.fail("Connection closed", error.ConnectionClosed); } +pub fn onClose(this: *MySQLConnection) void { + // no more socket + defer this.deref(); + this.onEnd(); +} + fn refAndClose(this: *@This(), js_reason: ?jsc.JSValue) void { // refAndClose is always called when we wanna to disconnect or when we are closed @@ -749,7 +756,7 @@ fn SocketHandler(comptime ssl: bool) type { pub fn onEnd(this: *MySQLConnection, socket: SocketType) void { _ = socket; - this.onClose(); + this.onEnd(); } pub fn onConnectError(this: *MySQLConnection, socket: SocketType, _: i32) void { From fa0febc520ab0cc02c90622b9e45e9addd28efcd Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 17:02:30 -0700 Subject: [PATCH 24/59] opsie --- src/sql/mysql/MySQLConnection.zig | 1 - 1 file changed, 1 deletion(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 61bb5e78bb0f..cf28e9f54d15 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -423,7 +423,6 @@ pub fn fail(this: *MySQLConnection, message: []const u8, err: AnyMySQLError.Erro pub fn onEnd(this: *MySQLConnection) void { // no more socket - defer this.deref(); this.fail("Connection closed", error.ConnectionClosed); } From c4996b2d996ec6706983eaf05c30f8ced18e0c2e Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 17:30:24 -0700 Subject: [PATCH 25/59] more --- src/sql/mysql/MySQLConnection.zig | 35 ++++--------------------------- 1 file changed, 4 insertions(+), 31 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index cf28e9f54d15..c275a8eaeeab 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -128,7 +128,7 @@ pub fn hasPendingActivity(this: *MySQLConnection) bool { fn updateHasPendingActivity(this: *MySQLConnection) void { const a: u32 = if (this.requests.readableLength() > 0) 1 else 0; - const b: u32 = if (this.status != .disconnected) 1 else 0; + const b: u32 = if (this.status != .disconnected and this.status != .failed) 1 else 0; this.pending_activity_count.store(a + b, .release); } @@ -269,34 +269,6 @@ pub fn finalize(this: *MySQLConnection) void { this.stopTimers(); debug("MySQLConnection finalize", .{}); - // Ensure we disconnect before finalizing - if (this.status != .disconnected) { - // delay disconnecting to avoid calling JS code inside the finalizer - const DisconnectTask = struct { - connection: *MySQLConnection, - task: jsc.AnyTask, - - fn run(ctx: *@This()) void { - ctx.connection.disconnect(); - - ctx.connection.deref(); - bun.default_allocator.destroy(ctx); - } - - pub fn enqueue(connection: *MySQLConnection) void { - const holder = bun.handleOom(bun.default_allocator.create(@This())); - holder.* = .{ - .connection = connection, - .task = jsc.AnyTask.New(@This(), @This().run).init(holder), - }; - connection.ref(); - connection.vm.enqueueTask(jsc.Task.init(&holder.task)); - } - }; - - DisconnectTask.enqueue(this); - } - this.js_value = .zero; this.deref(); } @@ -389,6 +361,7 @@ pub fn failFmt(this: *@This(), error_code: AnyMySQLError.Error, comptime fmt: [: this.failWithJSValue(err); } pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { + defer this.updateHasPendingActivity(); if (this.status == .failed) return; this.stopTimers(); @@ -760,7 +733,7 @@ fn SocketHandler(comptime ssl: bool) type { pub fn onConnectError(this: *MySQLConnection, socket: SocketType, _: i32) void { _ = socket; - this.onClose(); + this.onEnd(); } pub fn onTimeout(this: *MySQLConnection, socket: SocketType) void { @@ -1034,10 +1007,10 @@ pub fn onOpen(this: *MySQLConnection, socket: Socket) void { this.setupMaxLifetimeTimerIfNecessary(); this.resetConnectionTimeout(); this.socket = socket; - this.ref(); // one ref for the socket if (socket == .SocketTCP) { // when upgrading to TLS the onOpen callback will be called again and at this moment we dont wanna to change the status to handshaking this.setStatus(.handshaking); + this.ref(); // keep a ref for the socket } this.poll_ref.ref(this.vm); this.updateHasPendingActivity(); From 08f32702037f598a1a44b401bde296d3384c4ffd Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 17:38:00 -0700 Subject: [PATCH 26/59] dont timeout when disconnected --- src/sql/mysql/MySQLConnection.zig | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index c275a8eaeeab..2854b1453f2e 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -225,7 +225,7 @@ pub fn onConnectionTimeout(this: *@This()) bun.api.Timer.EventLoopTimer.Arm { .connected => { this.failFmt(error.IdleTimeout, "Idle timeout reached after {}", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.idle_timeout_interval_ms) *| std.time.ns_per_ms)}); }, - else => { + .connecting => { this.failFmt(error.ConnectionTimedOut, "Connection timeout after {}", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.connection_timeout_ms) *| std.time.ns_per_ms)}); }, .handshaking, @@ -234,6 +234,7 @@ pub fn onConnectionTimeout(this: *@This()) bun.api.Timer.EventLoopTimer.Arm { => { this.failFmt(error.ConnectionTimedOut, "Connection timeout after {} (during authentication)", .{bun.fmt.fmtDurationOneDecimal(@as(u64, this.connection_timeout_ms) *| std.time.ns_per_ms)}); }, + .disconnected, .failed => {}, } return .disarm; } @@ -362,9 +363,9 @@ pub fn failFmt(this: *@This(), error_code: AnyMySQLError.Error, comptime fmt: [: } pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { defer this.updateHasPendingActivity(); + this.stopTimers(); if (this.status == .failed) return; - this.stopTimers(); this.ref(); defer { // we defer the refAndClose so the on_close will be called first before we reject the pending requests @@ -408,15 +409,15 @@ pub fn onClose(this: *MySQLConnection) void { fn refAndClose(this: *@This(), js_reason: ?jsc.JSValue) void { // refAndClose is always called when we wanna to disconnect or when we are closed + // cleanup requests + this.cleanUpRequests(js_reason); + if (!this.socket.isClosed()) { // event loop need to be alive to close the socket this.poll_ref.ref(this.vm); // will unref on socket close this.socket.close(); } - - // cleanup requests - this.cleanUpRequests(js_reason); } pub fn disconnect(this: *@This()) void { From f763180b95fc541f50185e0ac27e70e73cd64e63 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 18:28:30 -0700 Subject: [PATCH 27/59] test --- src/js/internal/sql/mysql.ts | 67 ++++++++++------------------------- test/js/sql/sql-mysql.test.ts | 34 +++++++++--------- 2 files changed, 36 insertions(+), 65 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index 7d9612faef4b..0969f1c2434a 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -381,67 +381,38 @@ class PooledMySQLConnection { } #onClose(err) { - // let wrappedErr = err; - // this.state = PooledConnectionState.closed; - // this.connection = null; - // this.adapter.readyConnections.delete(this); - // const queries = new Set(this.queries); - // this.queries.clear(); - // this.queryCount = 0; - // this.flags &= ~PooledConnectionFlags.reserved; - // const onFinish = this.onFinish; - // const connectionInfo = this.connectionInfo; - // const adapter = this.adapter; - - // if (err) { - // wrappedErr = wrapError(err); - // } - - // this.storedError = wrappedErr; - - // // notify all queries that the connection is closed - // for (const onClose of queries) { - // onClose(wrappedErr); - // } - - // if (onFinish) { - // onFinish(wrappedErr); - // } - - // if (connectionInfo?.onclose) { - // connectionInfo.onclose(wrappedErr); - // } - - // adapter.release(this, true); - - if (err) { - err = wrapError(err); - } - const connectionInfo = this.connectionInfo; - if (connectionInfo?.onclose) { - connectionInfo.onclose(err); - } + let wrappedErr = err; this.state = PooledConnectionState.closed; this.connection = null; - this.storedError = err; - - // remove from ready connections if its there this.adapter.readyConnections.delete(this); const queries = new Set(this.queries); - this.queries?.clear?.(); + this.queries.clear(); this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; + const onFinish = this.onFinish; + const connectionInfo = this.connectionInfo; + const adapter = this.adapter; + + if (err) { + wrappedErr = wrapError(err); + } + + this.storedError = wrappedErr; // notify all queries that the connection is closed for (const onClose of queries) { - onClose(err); + onClose(wrappedErr); } - const onFinish = this.onFinish; + if (onFinish) { - onFinish(err); + onFinish(wrappedErr); } - this.adapter.release(this, true); + if (connectionInfo?.onclose) { + connectionInfo.onclose(wrappedErr); + } + + adapter.release(this, true); } constructor(connectionInfo: Bun.SQL.__internal.DefinedMySQLOptions, adapter: MySQLAdapter) { diff --git a/test/js/sql/sql-mysql.test.ts b/test/js/sql/sql-mysql.test.ts index ff2e85d175db..611805d88db8 100644 --- a/test/js/sql/sql-mysql.test.ts +++ b/test/js/sql/sql-mysql.test.ts @@ -612,23 +612,23 @@ if (docker) { expect(e.message).toBe("password error"); } }); - // test("Support dynamic async password function that throws", async () => { - // await using sql = new SQL({ - // ...options, - // max: 1, - // password: async () => { - // await Bun.sleep(10); - // throw new Error("password error"); - // }, - // }); - // try { - // await sql`select true as x`; - // expect.unreachable(); - // } catch (e: any) { - // expect(e).toBeInstanceOf(Error); - // expect(e.message).toBe("password error"); - // } - // }); + test("Support dynamic async password function that throws", async () => { + await using sql = new SQL({ + ...options, + max: 1, + password: async () => { + await Bun.sleep(10); + throw new Error("password error"); + }, + }); + try { + await sql`select true as x`; + expect.unreachable(); + } catch (e: any) { + expect(e).toBeInstanceOf(Error); + expect(e.message).toBe("password error"); + } + }); test("sql file", async () => { await using sql = new SQL(options); expect((await sql.file(rel("select.sql")))[0].x).toBe(1); From 38a798baa8483af9efc90d4a56cdfb93eb7c07fb Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 19:40:27 -0700 Subject: [PATCH 28/59] maybe --- src/sql/mysql/MySQLConnection.zig | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 2854b1453f2e..97b5fe896ccd 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -370,11 +370,10 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { defer { // we defer the refAndClose so the on_close will be called first before we reject the pending requests this.refAndClose(value); - this.updateHasPendingActivity(); this.deref(); } - this.setStatus(.failed); + this.status = .failed; const on_close = this.consumeOnCloseCallback(this.globalObject) orelse return; From 054de551c2d0e321efc8faec9d165e6f748c6dfd Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 19:42:46 -0700 Subject: [PATCH 29/59] maybe2 --- src/sql/mysql/MySQLConnection.zig | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 97b5fe896ccd..728896aa769c 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -422,7 +422,8 @@ fn refAndClose(this: *@This(), js_reason: ?jsc.JSValue) void { pub fn disconnect(this: *@This()) void { this.stopTimers(); if (this.status == .connected) { - this.setStatus(.disconnected); + defer this.updateHasPendingActivity(); + this.status = .disconnected; this.poll_ref.disable(); const requests = this.requests.readableSlice(0); @@ -945,7 +946,6 @@ pub fn call(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JS } } ptr.setStatus(.connecting); - ptr.updateHasPendingActivity(); ptr.resetConnectionTimeout(); ptr.poll_ref.ref(vm); const js_value = ptr.toJS(globalObject); @@ -1009,7 +1009,7 @@ pub fn onOpen(this: *MySQLConnection, socket: Socket) void { this.socket = socket; if (socket == .SocketTCP) { // when upgrading to TLS the onOpen callback will be called again and at this moment we dont wanna to change the status to handshaking - this.setStatus(.handshaking); + this.status = .handshaking; this.ref(); // keep a ref for the socket } this.poll_ref.ref(this.vm); From ec1fc80111aa450f025c857c15284c82777d96b3 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 20:24:01 -0700 Subject: [PATCH 30/59] use bool instead of i32 here --- src/sql/mysql/MySQLConnection.zig | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 728896aa769c..c4331ed963ee 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -21,7 +21,7 @@ poll_ref: bun.Async.KeepAlive = .{}, globalObject: *jsc.JSGlobalObject, vm: *jsc.VirtualMachine, -pending_activity_count: std.atomic.Value(u32) = std.atomic.Value(u32).init(0), +has_pending_activity: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), js_value: JSValue = .js_undefined, server_version: bun.ByteList = .{}, @@ -123,13 +123,19 @@ pub const AuthState = union(enum) { }; pub fn hasPendingActivity(this: *MySQLConnection) bool { - return this.pending_activity_count.load(.acquire) > 0; + return this.has_pending_activity.load(.acquire); } fn updateHasPendingActivity(this: *MySQLConnection) void { - const a: u32 = if (this.requests.readableLength() > 0) 1 else 0; - const b: u32 = if (this.status != .disconnected and this.status != .failed) 1 else 0; - this.pending_activity_count.store(a + b, .release); + if (this.requests.readableLength() > 0) { + this.has_pending_activity.store(true, .release); + return; + } + if (this.status != .disconnected and this.status != .failed) { + this.has_pending_activity.store(true, .release); + return; + } + this.has_pending_activity.store(false, .release); } fn hasDataToSend(this: *@This()) bool { @@ -1325,7 +1331,7 @@ pub fn setStatus(this: *@This(), status: ConnectionState) void { pub fn updateRef(this: *@This()) void { this.updateHasPendingActivity(); - if (this.pending_activity_count.raw > 0) { + if (this.has_pending_activity.raw) { this.poll_ref.ref(this.vm); } else { this.poll_ref.unref(this.vm); From 1c0ae142392cd660ff8eb2222100d390ee9b40d0 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 21:08:38 -0700 Subject: [PATCH 31/59] lets go back and test it again --- src/js/internal/sql/mysql.ts | 67 ++++++++++++++++++++++++++---------- 1 file changed, 48 insertions(+), 19 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index 0969f1c2434a..7d9612faef4b 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -381,38 +381,67 @@ class PooledMySQLConnection { } #onClose(err) { - let wrappedErr = err; + // let wrappedErr = err; + // this.state = PooledConnectionState.closed; + // this.connection = null; + // this.adapter.readyConnections.delete(this); + // const queries = new Set(this.queries); + // this.queries.clear(); + // this.queryCount = 0; + // this.flags &= ~PooledConnectionFlags.reserved; + // const onFinish = this.onFinish; + // const connectionInfo = this.connectionInfo; + // const adapter = this.adapter; + + // if (err) { + // wrappedErr = wrapError(err); + // } + + // this.storedError = wrappedErr; + + // // notify all queries that the connection is closed + // for (const onClose of queries) { + // onClose(wrappedErr); + // } + + // if (onFinish) { + // onFinish(wrappedErr); + // } + + // if (connectionInfo?.onclose) { + // connectionInfo.onclose(wrappedErr); + // } + + // adapter.release(this, true); + + if (err) { + err = wrapError(err); + } + const connectionInfo = this.connectionInfo; + if (connectionInfo?.onclose) { + connectionInfo.onclose(err); + } this.state = PooledConnectionState.closed; this.connection = null; + this.storedError = err; + + // remove from ready connections if its there this.adapter.readyConnections.delete(this); const queries = new Set(this.queries); - this.queries.clear(); + this.queries?.clear?.(); this.queryCount = 0; this.flags &= ~PooledConnectionFlags.reserved; - const onFinish = this.onFinish; - const connectionInfo = this.connectionInfo; - const adapter = this.adapter; - - if (err) { - wrappedErr = wrapError(err); - } - - this.storedError = wrappedErr; // notify all queries that the connection is closed for (const onClose of queries) { - onClose(wrappedErr); + onClose(err); } - + const onFinish = this.onFinish; if (onFinish) { - onFinish(wrappedErr); + onFinish(err); } - if (connectionInfo?.onclose) { - connectionInfo.onclose(wrappedErr); - } - - adapter.release(this, true); + this.adapter.release(this, true); } constructor(connectionInfo: Bun.SQL.__internal.DefinedMySQLOptions, adapter: MySQLAdapter) { From 09099b3747d90beb2036ae592dbdbaffd74266b8 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 21:10:40 -0700 Subject: [PATCH 32/59] test without microtask --- src/sql/mysql/MySQLConnection.zig | 13 +++++++++-- test/js/sql/sql-mysql.test.ts | 38 +++++++++++++++++-------------- 2 files changed, 32 insertions(+), 19 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index c4331ed963ee..8deaf3aff9a5 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -382,7 +382,7 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { this.status = .failed; const on_close = this.consumeOnCloseCallback(this.globalObject) orelse return; - + on_close.ensureStillAlive(); const loop = this.vm.eventLoop(); loop.enter(); defer loop.exit(); @@ -391,7 +391,15 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { js_error.ensureStillAlive(); const queries_array = this.getQueriesArray(); queries_array.ensureStillAlive(); - this.globalObject.queueMicrotask(on_close, &[_]JSValue{ js_error, queries_array }); + // this.globalObject.queueMicrotask(on_close, &[_]JSValue{ js_error, queries_array }); + _ = on_close.call( + this.globalObject, + .js_undefined, + &[_]JSValue{ + value.toError() orelse value, + this.getQueriesArray(), + }, + ) catch |e| this.globalObject.reportActiveExceptionAsUnhandled(e); } pub fn fail(this: *MySQLConnection, message: []const u8, err: AnyMySQLError.Error) void { @@ -1316,6 +1324,7 @@ pub fn setStatus(this: *@This(), status: ConnectionState) void { switch (status) { .connected => { const on_connect = this.consumeOnConnectCallback(this.globalObject) orelse return; + on_connect.ensureStillAlive(); var js_value = this.js_value; if (js_value == .zero) { js_value = .js_undefined; diff --git a/test/js/sql/sql-mysql.test.ts b/test/js/sql/sql-mysql.test.ts index 611805d88db8..41c7c3fb3970 100644 --- a/test/js/sql/sql-mysql.test.ts +++ b/test/js/sql/sql-mysql.test.ts @@ -612,23 +612,27 @@ if (docker) { expect(e.message).toBe("password error"); } }); - test("Support dynamic async password function that throws", async () => { - await using sql = new SQL({ - ...options, - max: 1, - password: async () => { - await Bun.sleep(10); - throw new Error("password error"); - }, + + for (let i = 0; i < 10000; i++) { + test.only("Support dynamic async password function that throws" + i, async () => { + await using sql = new SQL({ + ...options, + max: 1, + password: async () => { + await Bun.sleep(10); + throw new Error("password error"); + }, + }); + try { + await sql`select true as x`; + expect.unreachable(); + } catch (e: any) { + expect(e).toBeInstanceOf(Error); + expect(e.message).toBe("password error"); + } }); - try { - await sql`select true as x`; - expect.unreachable(); - } catch (e: any) { - expect(e).toBeInstanceOf(Error); - expect(e.message).toBe("password error"); - } - }); + } + test("sql file", async () => { await using sql = new SQL(options); expect((await sql.file(rel("select.sql")))[0].x).toBe(1); @@ -880,7 +884,7 @@ if (docker) { } catch (e) { expect(e).toBeInstanceOf(Error); expect(e.code).toBe("ERR_MYSQL_CONNECTION_TIMEOUT"); - expect(e.message).toMatch(/Connection timeout after 200ms/); + expect(e.message).toMatch(/Connection timeut after 200ms/); } finally { sql.close(); server.close(); From 6d789e2eb79b435150053fcee1875469f60a1152 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 21:11:23 -0700 Subject: [PATCH 33/59] opsie --- src/sql/mysql/MySQLConnection.zig | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 8deaf3aff9a5..89bd96bd33c2 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -396,8 +396,8 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { this.globalObject, .js_undefined, &[_]JSValue{ - value.toError() orelse value, - this.getQueriesArray(), + js_error, + queries_array, }, ) catch |e| this.globalObject.reportActiveExceptionAsUnhandled(e); } From 75fde6ce453bd04cc630e6dc66049622d87625bd Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 21:48:55 -0700 Subject: [PATCH 34/59] more --- src/sql/mysql/MySQLConnection.zig | 14 ++++++++++++-- src/sql/mysql/MySQLQuery.zig | 9 +++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 89bd96bd33c2..69a3f0e836dc 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -358,7 +358,13 @@ pub fn getQueriesArray(this: *const @This()) JSValue { if (this.js_value == .zero) { return .js_undefined; } - return js.queriesGetCached(this.js_value) orelse .js_undefined; + if (js.queriesGetCached(this.js_value)) |value| { + if (value == .zero) { + return .js_undefined; + } + return value; + } + return .js_undefined; } pub fn failFmt(this: *@This(), error_code: AnyMySQLError.Error, comptime fmt: [:0]const u8, args: anytype) void { const message = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, fmt, args)); @@ -387,8 +393,12 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { loop.enter(); defer loop.exit(); - const js_error = value.toError() orelse value; + var js_error = value.toError() orelse value; + if (js_error == .zero) { + js_error = AnyMySQLError.mysqlErrorToJS(this.globalObject, "Connection closed", error.ConnectionClosed); + } js_error.ensureStillAlive(); + const queries_array = this.getQueriesArray(); queries_array.ensureStillAlive(); // this.globalObject.queueMicrotask(on_close, &[_]JSValue{ js_error, queries_array }); diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index 029274385924..0fe8cd608895 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -175,9 +175,14 @@ pub fn onJSError(this: *@This(), err: jsc.JSValue, globalObject: *jsc.JSGlobalOb var vm = jsc.VirtualMachine.get(); const function = vm.rareData().mysql_context.onQueryRejectFn.get().?; const event_loop = vm.eventLoop(); + var js_error = err.toError() orelse err; + if (js_error == .zero) { + js_error = AnyMySQLError.mysqlErrorToJS(globalObject, "Query failed", err); + } + js_error.ensureStillAlive(); event_loop.runCallback(function, globalObject, thisValue, &.{ - targetValue.toError() orelse targetValue, - err, + targetValue, + js_error, }); } pub fn getTarget(this: *@This(), globalObject: *jsc.JSGlobalObject, clean_target: bool) jsc.JSValue { From bca76bf37888af2ffdda5ab0030d658c4cfbe92c Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 21:57:03 -0700 Subject: [PATCH 35/59] opsie --- src/sql/mysql/MySQLQuery.zig | 2 +- src/sql/mysql/protocol/AnyMySQLError.zig | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index 0fe8cd608895..da1b634a167a 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -177,7 +177,7 @@ pub fn onJSError(this: *@This(), err: jsc.JSValue, globalObject: *jsc.JSGlobalOb const event_loop = vm.eventLoop(); var js_error = err.toError() orelse err; if (js_error == .zero) { - js_error = AnyMySQLError.mysqlErrorToJS(globalObject, "Query failed", err); + js_error = AnyMySQLError.mysqlErrorToJS(globalObject, "Query failed", error.UnknownError); } js_error.ensureStillAlive(); event_loop.runCallback(function, globalObject, thisValue, &.{ diff --git a/src/sql/mysql/protocol/AnyMySQLError.zig b/src/sql/mysql/protocol/AnyMySQLError.zig index 2bcea88279d3..66e5b6aa2650 100644 --- a/src/sql/mysql/protocol/AnyMySQLError.zig +++ b/src/sql/mysql/protocol/AnyMySQLError.zig @@ -33,6 +33,7 @@ pub const Error = error{ InvalidErrorPacket, UnexpectedPacket, ShortRead, + UnknownError, }; pub fn mysqlErrorToJS(globalObject: *jsc.JSGlobalObject, message: ?[]const u8, err: Error) JSValue { @@ -64,6 +65,7 @@ pub fn mysqlErrorToJS(globalObject: *jsc.JSGlobalObject, message: ?[]const u8, e error.MissingAuthData => "ERR_MYSQL_MISSING_AUTH_DATA", error.FailedToEncryptPassword => "ERR_MYSQL_FAILED_TO_ENCRYPT_PASSWORD", error.InvalidPublicKey => "ERR_MYSQL_INVALID_PUBLIC_KEY", + error.UnknownError => "ERR_MYSQL_UNKNOWN_ERROR", error.JSError => { return globalObject.takeException(error.JSError); }, From 32d5797866e97698eefb5b840549aa20a88cba52 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 22:20:18 -0700 Subject: [PATCH 36/59] opsie --- test/js/sql/sql-mysql.test.ts | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/test/js/sql/sql-mysql.test.ts b/test/js/sql/sql-mysql.test.ts index 41c7c3fb3970..ad5d40f602f1 100644 --- a/test/js/sql/sql-mysql.test.ts +++ b/test/js/sql/sql-mysql.test.ts @@ -613,25 +613,23 @@ if (docker) { } }); - for (let i = 0; i < 10000; i++) { - test.only("Support dynamic async password function that throws" + i, async () => { - await using sql = new SQL({ - ...options, - max: 1, - password: async () => { - await Bun.sleep(10); - throw new Error("password error"); - }, - }); - try { - await sql`select true as x`; - expect.unreachable(); - } catch (e: any) { - expect(e).toBeInstanceOf(Error); - expect(e.message).toBe("password error"); - } + test("Support dynamic async password function that throws", async () => { + await using sql = new SQL({ + ...options, + max: 1, + password: async () => { + await Bun.sleep(10); + throw new Error("password error"); + }, }); - } + try { + await sql`select true as x`; + expect.unreachable(); + } catch (e: any) { + expect(e).toBeInstanceOf(Error); + expect(e.message).toBe("password error"); + } + }); test("sql file", async () => { await using sql = new SQL(options); From e557195dde8e1fdc97db6dc38116363ef32af736 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 22:22:39 -0700 Subject: [PATCH 37/59] opsie --- test/js/sql/sql-mysql.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/js/sql/sql-mysql.test.ts b/test/js/sql/sql-mysql.test.ts index ad5d40f602f1..ef3301d71167 100644 --- a/test/js/sql/sql-mysql.test.ts +++ b/test/js/sql/sql-mysql.test.ts @@ -882,7 +882,7 @@ if (docker) { } catch (e) { expect(e).toBeInstanceOf(Error); expect(e.code).toBe("ERR_MYSQL_CONNECTION_TIMEOUT"); - expect(e.message).toMatch(/Connection timeut after 200ms/); + expect(e.message).toMatch(/Connection timeout after 200ms/); } finally { sql.close(); server.close(); From 7d7c3daccf1fc5bf18314c4adf0aaff7788b7614 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 22:49:40 -0700 Subject: [PATCH 38/59] more --- src/js/internal/sql/mysql.ts | 33 ------------------------------- src/sql/mysql/MySQLConnection.zig | 10 +--------- 2 files changed, 1 insertion(+), 42 deletions(-) diff --git a/src/js/internal/sql/mysql.ts b/src/js/internal/sql/mysql.ts index 7d9612faef4b..a0f0cdad17ef 100644 --- a/src/js/internal/sql/mysql.ts +++ b/src/js/internal/sql/mysql.ts @@ -381,39 +381,6 @@ class PooledMySQLConnection { } #onClose(err) { - // let wrappedErr = err; - // this.state = PooledConnectionState.closed; - // this.connection = null; - // this.adapter.readyConnections.delete(this); - // const queries = new Set(this.queries); - // this.queries.clear(); - // this.queryCount = 0; - // this.flags &= ~PooledConnectionFlags.reserved; - // const onFinish = this.onFinish; - // const connectionInfo = this.connectionInfo; - // const adapter = this.adapter; - - // if (err) { - // wrappedErr = wrapError(err); - // } - - // this.storedError = wrappedErr; - - // // notify all queries that the connection is closed - // for (const onClose of queries) { - // onClose(wrappedErr); - // } - - // if (onFinish) { - // onFinish(wrappedErr); - // } - - // if (connectionInfo?.onclose) { - // connectionInfo.onclose(wrappedErr); - // } - - // adapter.release(this, true); - if (err) { err = wrapError(err); } diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 69a3f0e836dc..120d17aa1359 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -401,15 +401,7 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { const queries_array = this.getQueriesArray(); queries_array.ensureStillAlive(); - // this.globalObject.queueMicrotask(on_close, &[_]JSValue{ js_error, queries_array }); - _ = on_close.call( - this.globalObject, - .js_undefined, - &[_]JSValue{ - js_error, - queries_array, - }, - ) catch |e| this.globalObject.reportActiveExceptionAsUnhandled(e); + this.globalObject.queueMicrotask(on_close, &[_]JSValue{ js_error, queries_array }); } pub fn fail(this: *MySQLConnection, message: []const u8, err: AnyMySQLError.Error) void { From 2cc90a7615f1a884328812c0aa2779dfad37a338 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 22:53:29 -0700 Subject: [PATCH 39/59] more --- src/sql/mysql/MySQLQuery.zig | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index da1b634a167a..2fb9a5e8402d 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -241,13 +241,19 @@ pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalOb const function = vm.rareData().mysql_context.onQueryResolveFn.get().?; const event_loop = vm.eventLoop(); const tag: CommandTag = .{ .SELECT = result_count }; + var queries_array = if (connection == .zero) .js_undefined else MySQLConnection.js.queriesGetCached(connection) orelse .js_undefined; + if (queries_array == .zero) { + queries_array = .js_undefined; + } else { + queries_array.ensureStillAlive(); + } event_loop.runCallback(function, globalObject, thisValue, &.{ targetValue, consumePendingValue(thisValue, globalObject) orelse .js_undefined, tag.toJSTag(globalObject), tag.toJSNumber(), - if (connection == .zero) .js_undefined else MySQLConnection.js.queriesGetCached(connection) orelse .js_undefined, + queries_array, JSValue.jsBoolean(is_last), JSValue.jsNumber(last_insert_id), JSValue.jsNumber(affected_rows), From 8eb6b933b6744639d73c7b683e56b8ee3d7d5026 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Tue, 9 Sep 2025 22:56:10 -0700 Subject: [PATCH 40/59] revert this --- src/sql/mysql/MySQLConnection.zig | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 120d17aa1359..c412e768ea4d 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -401,7 +401,14 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { const queries_array = this.getQueriesArray(); queries_array.ensureStillAlive(); - this.globalObject.queueMicrotask(on_close, &[_]JSValue{ js_error, queries_array }); + _ = on_close.call( + this.globalObject, + .js_undefined, + &[_]JSValue{ + js_error, + queries_array, + }, + ) catch |e| this.globalObject.reportActiveExceptionAsUnhandled(e); } pub fn fail(this: *MySQLConnection, message: []const u8, err: AnyMySQLError.Error) void { From 477aa56aa474088dd23d07c3f00379127eece280 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 16:20:51 -0700 Subject: [PATCH 41/59] Ciro/fix onclose refactor (#22556) ### What does this PR do? ### How did you verify your code works? --- src/bun.js/api/server.zig | 9 +- src/bun.js/api/server/RequestContext.zig | 2 +- src/bun.js/api/sql.classes.ts | 3 +- src/bun.js/bindings/JSRef.zig | 43 ++++++++-- src/js/bun/sql.ts | 30 +++---- src/sql/mysql/MySQLConnection.zig | 105 +++++++++++------------ src/sql/mysql/MySQLQuery.zig | 48 ++++------- src/sql/mysql/protocol/AnyMySQLError.zig | 2 + src/sql/postgres/PostgresSQLQuery.zig | 34 +++----- src/sql/shared/ObjectIterator.zig | 4 + 10 files changed, 139 insertions(+), 141 deletions(-) diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index f26f45525813..bf75c92b1a5c 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -627,8 +627,8 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d } pub fn jsValueAssertAlive(server: *ThisServer) jsc.JSValue { - // With JSRef, we can safely access the JS value even after stop() via weak reference - return server.js_value.get(); + bun.assert(server.js_value.isNotEmpty()); + return server.js_value.tryGet().?; } pub fn requestIP(this: *ThisServer, request: *jsc.WebCore.Request) bun.JSError!jsc.JSValue { @@ -1124,7 +1124,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d this.onReloadFromZig(&new_config, globalThis); - return this.js_value.get(); + return this.js_value.tryGet() orelse .js_undefined; } pub fn onFetch(this: *ThisServer, ctx: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!jsc.JSValue { @@ -1539,8 +1539,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d } pub fn stop(this: *ThisServer, abrupt: bool) void { - const current_value = this.js_value.get(); - this.js_value.setWeak(current_value); + this.js_value.downgrade(); if (this.config.allow_hot and this.config.id.len > 0) { if (this.globalThis.bunVM().hotMap()) |hot| { diff --git a/src/bun.js/api/server/RequestContext.zig b/src/bun.js/api/server/RequestContext.zig index e1c0097107d3..aab5b503f2fe 100644 --- a/src/bun.js/api/server/RequestContext.zig +++ b/src/bun.js/api/server/RequestContext.zig @@ -1981,7 +1981,7 @@ pub fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, this.flags.has_called_error_handler = true; const result = server.config.onError.call( server.globalThis, - server.js_value.get(), + server.js_value.tryGet() orelse .js_undefined, &.{value}, ) catch |err| server.globalThis.takeException(err); defer result.ensureStillAlive(); diff --git a/src/bun.js/api/sql.classes.ts b/src/bun.js/api/sql.classes.ts index db29a3dc1f61..14d7b5bca3f9 100644 --- a/src/bun.js/api/sql.classes.ts +++ b/src/bun.js/api/sql.classes.ts @@ -9,7 +9,7 @@ for (const type of types) { construct: true, finalize: true, configurable: false, - hasPendingActivity: true, + hasPendingActivity: type === "PostgresSQL", klass: { // escapeString: { // fn: "escapeString", @@ -60,7 +60,6 @@ for (const type of types) { construct: true, finalize: true, configurable: false, - JSType: "0b11101110", klass: {}, proto: { diff --git a/src/bun.js/bindings/JSRef.zig b/src/bun.js/bindings/JSRef.zig index a4f079b98db9..46555db798b6 100644 --- a/src/bun.js/bindings/JSRef.zig +++ b/src/bun.js/bindings/JSRef.zig @@ -8,6 +8,7 @@ pub const JSRef = union(enum) { } pub fn initStrong(value: jsc.JSValue, globalThis: *jsc.JSGlobalObject) @This() { + bun.assert(value != .zero); return .{ .strong = .create(value, globalThis) }; } @@ -15,15 +16,7 @@ pub const JSRef = union(enum) { return .{ .weak = .zero }; } - pub fn get(this: *@This()) jsc.JSValue { - return switch (this.*) { - .weak => this.weak, - .strong => this.strong.get() orelse .zero, - .finalized => .zero, - }; - } - - pub fn tryGet(this: *@This()) ?jsc.JSValue { + pub fn tryGet(this: *const @This()) ?jsc.JSValue { return switch (this.*) { .weak => if (this.weak != .zero) this.weak else null, .strong => this.strong.get(), @@ -44,6 +37,7 @@ pub const JSRef = union(enum) { } pub fn setStrong(this: *@This(), value: jsc.JSValue, globalThis: *jsc.JSGlobalObject) void { + bun.assert(value != .zero); if (this.* == .strong) { this.strong.set(globalThis, value); return; @@ -64,6 +58,37 @@ pub const JSRef = union(enum) { } } + pub fn downgrade(this: *@This()) void { + switch (this.*) { + .weak => {}, + .strong => |*strong| { + const value = strong.get() orelse .zero; + value.ensureStillAlive(); + strong.deinit(); + this.* = .{ .weak = value }; + }, + .finalized => { + bun.debugAssert(false); + }, + } + } + + pub fn isEmpty(this: *const @This()) bool { + return switch (this.*) { + .weak => this.weak == .zero, + .strong => !this.strong.has(), + .finalized => true, + }; + } + + pub fn isNotEmpty(this: *const @This()) bool { + return switch (this.*) { + .weak => this.weak != .zero, + .strong => this.strong.has(), + .finalized => false, + }; + } + pub fn deinit(this: *@This()) void { switch (this.*) { .weak => { diff --git a/src/js/bun/sql.ts b/src/js/bun/sql.ts index db7b0eb87109..dc063c0a1ae1 100644 --- a/src/js/bun/sql.ts +++ b/src/js/bun/sql.ts @@ -291,7 +291,7 @@ const SQL: typeof Bun.SQL = function SQL( reserved_sql.connect = () => { if (state.connectionState & ReservedConnectionState.closed) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } return Promise.$resolve(reserved_sql); }; @@ -322,7 +322,7 @@ const SQL: typeof Bun.SQL = function SQL( reserved_sql.beginDistributed = (name: string, fn: TransactionCallback) => { // begin is allowed the difference is that we need to make sure to use the same connection and never release it if (state.connectionState & ReservedConnectionState.closed) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } let callback = fn; @@ -346,7 +346,7 @@ const SQL: typeof Bun.SQL = function SQL( state.connectionState & ReservedConnectionState.closed || !(state.connectionState & ReservedConnectionState.acceptQueries) ) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } let callback = fn; let options: string | undefined = options_or_fn as unknown as string; @@ -369,7 +369,7 @@ const SQL: typeof Bun.SQL = function SQL( reserved_sql.flush = () => { if (state.connectionState & ReservedConnectionState.closed) { - throw this.connectionClosedError(); + throw pool.connectionClosedError(); } // Use pooled connection's flush if available, otherwise use adapter's flush if (pooledConnection.flush) { @@ -429,7 +429,7 @@ const SQL: typeof Bun.SQL = function SQL( state.connectionState & ReservedConnectionState.closed || !(state.connectionState & ReservedConnectionState.acceptQueries) ) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } // just release the connection back to the pool state.connectionState |= ReservedConnectionState.closed; @@ -552,7 +552,7 @@ const SQL: typeof Bun.SQL = function SQL( function run_internal_transaction_sql(string) { if (state.connectionState & ReservedConnectionState.closed) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } return unsafeQueryFromTransaction(string, [], pooledConnection, state.queries); } @@ -564,7 +564,7 @@ const SQL: typeof Bun.SQL = function SQL( state.connectionState & ReservedConnectionState.closed || !(state.connectionState & ReservedConnectionState.acceptQueries) ) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } if ($isArray(strings)) { // detect if is tagged template @@ -593,7 +593,7 @@ const SQL: typeof Bun.SQL = function SQL( transaction_sql.connect = () => { if (state.connectionState & ReservedConnectionState.closed) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } return Promise.$resolve(transaction_sql); @@ -732,7 +732,7 @@ const SQL: typeof Bun.SQL = function SQL( state.connectionState & ReservedConnectionState.closed || !(state.connectionState & ReservedConnectionState.acceptQueries) ) { - throw this.connectionClosedError(); + throw pool.connectionClosedError(); } if ($isCallable(name)) { @@ -816,7 +816,7 @@ const SQL: typeof Bun.SQL = function SQL( sql.reserve = () => { if (pool.closed) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } // Check if adapter supports reserved connections @@ -831,7 +831,7 @@ const SQL: typeof Bun.SQL = function SQL( }; sql.rollbackDistributed = async function (name: string) { if (pool.closed) { - throw this.connectionClosedError(); + throw pool.connectionClosedError(); } if (!pool.getRollbackDistributedSQL) { @@ -844,7 +844,7 @@ const SQL: typeof Bun.SQL = function SQL( sql.commitDistributed = async function (name: string) { if (pool.closed) { - throw this.connectionClosedError(); + throw pool.connectionClosedError(); } if (!pool.getCommitDistributedSQL) { @@ -857,7 +857,7 @@ const SQL: typeof Bun.SQL = function SQL( sql.beginDistributed = (name: string, fn: TransactionCallback) => { if (pool.closed) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } let callback = fn; @@ -876,7 +876,7 @@ const SQL: typeof Bun.SQL = function SQL( sql.begin = (options_or_fn: string | TransactionCallback, fn?: TransactionCallback) => { if (pool.closed) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } let callback = fn; let options: string | undefined = options_or_fn as unknown as string; @@ -896,7 +896,7 @@ const SQL: typeof Bun.SQL = function SQL( }; sql.connect = () => { if (pool.closed) { - return Promise.$reject(this.connectionClosedError()); + return Promise.$reject(pool.connectionClosedError()); } if (pool.isConnected()) { diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 64e98b11b329..bb66decc9497 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -21,8 +21,7 @@ poll_ref: bun.Async.KeepAlive = .{}, globalObject: *jsc.JSGlobalObject, vm: *jsc.VirtualMachine, -has_pending_activity: std.atomic.Value(bool) = std.atomic.Value(bool).init(false), -js_value: JSValue = .js_undefined, +js_value: jsc.JSRef = jsc.JSRef.empty(), server_version: bun.ByteList = .{}, connection_id: u32 = 0, @@ -122,20 +121,14 @@ pub const AuthState = union(enum) { }; }; -pub fn hasPendingActivity(this: *MySQLConnection) bool { - return this.has_pending_activity.load(.acquire); -} - -fn updateHasPendingActivity(this: *MySQLConnection) void { - if (this.requests.readableLength() > 0) { - this.has_pending_activity.store(true, .release); - return; - } - if (this.status != .disconnected and this.status != .failed) { - this.has_pending_activity.store(true, .release); - return; +fn updateReferenceType(this: *MySQLConnection) void { + if (this.js_value.isNotEmpty()) { + if (this.requests.readableLength() > 0 or (this.status != .disconnected and this.status != .failed)) { + this.js_value.upgrade(this.globalObject); + return; + } + this.js_value.downgrade(); } - this.has_pending_activity.store(false, .release); } fn hasDataToSend(this: *@This()) bool { @@ -276,19 +269,19 @@ pub fn finalize(this: *MySQLConnection) void { this.stopTimers(); debug("MySQLConnection finalize", .{}); - this.js_value = .zero; + this.js_value.deinit(); this.deref(); } pub fn doRef(this: *@This(), _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { this.poll_ref.ref(this.vm); - this.updateHasPendingActivity(); + this.updateReferenceType(); return .js_undefined; } pub fn doUnref(this: *@This(), _: *jsc.JSGlobalObject, _: *jsc.CallFrame) bun.JSError!JSValue { this.poll_ref.unref(this.vm); - this.updateHasPendingActivity(); + this.updateReferenceType(); return .js_undefined; } @@ -355,8 +348,10 @@ pub fn stopTimers(this: *@This()) void { } pub fn getQueriesArray(this: *const @This()) JSValue { - if (this.js_value == .zero) return .js_undefined; - return js.queriesGetCached(this.js_value) orelse .js_undefined; + if (this.js_value.tryGet()) |value| { + return js.queriesGetCached(value) orelse .js_undefined; + } + return .js_undefined; } pub fn failFmt(this: *@This(), error_code: AnyMySQLError.Error, comptime fmt: [:0]const u8, args: anytype) void { const message = bun.handleOom(std.fmt.allocPrint(bun.default_allocator, fmt, args)); @@ -366,7 +361,7 @@ pub fn failFmt(this: *@This(), error_code: AnyMySQLError.Error, comptime fmt: [: this.failWithJSValue(err); } pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { - defer this.updateHasPendingActivity(); + defer this.updateReferenceType(); this.stopTimers(); if (this.status == .failed) return; @@ -437,7 +432,7 @@ fn refAndClose(this: *@This(), js_reason: ?jsc.JSValue) void { pub fn disconnect(this: *@This()) void { this.stopTimers(); if (this.status == .connected) { - defer this.updateHasPendingActivity(); + defer this.updateReferenceType(); this.status = .disconnected; this.poll_ref.disable(); @@ -965,7 +960,7 @@ pub fn call(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JS ptr.poll_ref.ref(vm); const js_value = ptr.toJS(globalObject); js_value.ensureStillAlive(); - ptr.js_value = js_value; + ptr.js_value.setStrong(js_value, globalObject); js.onconnectSetCached(js_value, globalObject, on_connect); js.oncloseSetCached(js_value, globalObject, on_close); @@ -1028,7 +1023,7 @@ pub fn onOpen(this: *MySQLConnection, socket: Socket) void { this.ref(); // keep a ref for the socket } this.poll_ref.ref(this.vm); - this.updateHasPendingActivity(); + this.updateReferenceType(); } pub fn onHandshake(this: *MySQLConnection, success: i32, ssl_error: uws.us_bun_verify_error_t) void { @@ -1166,11 +1161,12 @@ pub fn processPackets(this: *MySQLConnection, comptime Context: type, reader: Ne // Read packet header const header = PacketHeader.decode(reader.peek()) orelse return AnyMySQLError.Error.ShortRead; const header_length = header.length; + const packet_length: usize = header_length + PacketHeader.size; debug("sequence_id: {d} header: {d}", .{ this.sequence_id, header_length }); // Ensure we have the full packet - reader.ensureCapacity(header_length + PacketHeader.size) catch return AnyMySQLError.Error.ShortRead; + reader.ensureCapacity(packet_length) catch return AnyMySQLError.Error.ShortRead; // always skip the full packet, we dont care about padding or unreaded bytes - defer reader.setOffsetFromStart(header_length + PacketHeader.size); + defer reader.setOffsetFromStart(packet_length); reader.skip(PacketHeader.size); // Update sequence id @@ -1293,30 +1289,35 @@ fn handleHandshakeDecodePublicKey(this: *MySQLConnection, comptime Context: type pub fn consumeOnConnectCallback(this: *const @This(), globalObject: *jsc.JSGlobalObject) ?jsc.JSValue { debug("consumeOnConnectCallback", .{}); - if (this.js_value == .zero) { - return null; + if (this.js_value.tryGet()) |value| { + const on_connect = js.onconnectGetCached(value) orelse return null; + debug("consumeOnConnectCallback exists", .{}); + js.onconnectSetCached(value, globalObject, .zero); + if (on_connect == .zero) { + return null; + } + return on_connect; } - const on_connect = js.onconnectGetCached(this.js_value) orelse return null; - debug("consumeOnConnectCallback exists", .{}); - - js.onconnectSetCached(this.js_value, globalObject, .zero); - return on_connect; + return null; } pub fn consumeOnCloseCallback(this: *const @This(), globalObject: *jsc.JSGlobalObject) ?jsc.JSValue { debug("consumeOnCloseCallback", .{}); - if (this.js_value == .zero) { - return null; + if (this.js_value.tryGet()) |value| { + const on_close = js.oncloseGetCached(value) orelse return null; + debug("consumeOnCloseCallback exists", .{}); + js.oncloseSetCached(value, globalObject, .zero); + if (on_close == .zero) { + return null; + } + return on_close; } - const on_close = js.oncloseGetCached(this.js_value) orelse return null; - debug("consumeOnCloseCallback exists", .{}); - js.oncloseSetCached(this.js_value, globalObject, .zero); - return on_close; + return null; } pub fn setStatus(this: *@This(), status: ConnectionState) void { if (this.status == status) return; - defer this.updateHasPendingActivity(); + defer this.updateReferenceType(); this.status = status; this.resetConnectionTimeout(); @@ -1326,12 +1327,8 @@ pub fn setStatus(this: *@This(), status: ConnectionState) void { .connected => { const on_connect = this.consumeOnConnectCallback(this.globalObject) orelse return; on_connect.ensureStillAlive(); - var js_value = this.js_value; - if (js_value == .zero) { - js_value = .js_undefined; - } else { - js_value.ensureStillAlive(); - } + var js_value = this.js_value.tryGet() orelse .js_undefined; + js_value.ensureStillAlive(); this.globalObject.queueMicrotask(on_connect, &[_]JSValue{ JSValue.jsNull(), js_value }); this.poll_ref.unref(this.vm); }, @@ -1340,8 +1337,8 @@ pub fn setStatus(this: *@This(), status: ConnectionState) void { } pub fn updateRef(this: *@This()) void { - this.updateHasPendingActivity(); - if (this.has_pending_activity.raw) { + this.updateReferenceType(); + if (this.js_value == .strong) { this.poll_ref.ref(this.vm); } else { this.poll_ref.unref(this.vm); @@ -1799,7 +1796,7 @@ fn handleResultSetOK(this: *MySQLConnection, request: *MySQLQuery, statement: *M request.onResult( statement.result_count, this.globalObject, - this.js_value, + this.js_value.tryGet() orelse .js_undefined, this.flags.is_ready_for_query, last_insert_id, affected_rows, @@ -1908,7 +1905,7 @@ pub fn handleResultSet(this: *MySQLConnection, comptime Context: type, reader: N var cached_structure: ?CachedStructure = null; switch (request.flags.result_mode) { .objects => { - cached_structure = if (this.js_value == .zero) null else statement.structure(this.js_value, this.globalObject); + cached_structure = if (this.js_value.tryGet()) |value| statement.structure(value, this.globalObject) else null; structure = cached_structure.?.jsValue() orelse .js_undefined; }, .raw, .values => { @@ -1918,7 +1915,7 @@ pub fn handleResultSet(this: *MySQLConnection, comptime Context: type, reader: N defer row.deinit(allocator); try row.decode(allocator, reader); - const pending_value = MySQLQuery.js.pendingValueGetCached(request.thisValue.get()) orelse .zero; + const pending_value = (if (request.thisValue.tryGet()) |value| MySQLQuery.js.pendingValueGetCached(value) else .js_undefined) orelse .js_undefined; // Process row data const row_value = row.toJS( @@ -1936,8 +1933,10 @@ pub fn handleResultSet(this: *MySQLConnection, comptime Context: type, reader: N } statement.result_count += 1; - if (pending_value == .zero) { - MySQLQuery.js.pendingValueSetCached(request.thisValue.get(), this.globalObject, row_value); + if (pending_value.isEmptyOrUndefinedOrNull()) { + if (request.thisValue.tryGet()) |value| { + MySQLQuery.js.pendingValueSetCached(value, this.globalObject, row_value); + } } } }, diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index 2fb9a5e8402d..2388240c9dd4 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -1,5 +1,5 @@ const MySQLQuery = @This(); -const RefCount = bun.ptr.ThreadSafeRefCount(@This(), "ref_count", deinit, .{}); +const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); statement: ?*MySQLStatement = null, query: bun.String = bun.String.empty, @@ -42,10 +42,6 @@ pub const Status = enum(u8) { } }; -pub fn hasPendingActivity(this: *@This()) bool { - return this.ref_count.load(.monotonic) > 1; -} - pub fn deinit(this: *@This()) void { this.thisValue.deinit(); if (this.statement) |statement| { @@ -66,11 +62,7 @@ pub fn finalize(this: *@This()) void { this.statement = null; } - if (this.thisValue == .weak) { - // clean up if is a weak reference, if is a strong reference we need to wait until the query is done - // if we are a strong reference, here is probably a bug because GC'd should not happen - this.thisValue.weak = .zero; - } + this.thisValue.deinit(); this.deref(); } @@ -81,12 +73,9 @@ pub fn onWriteFail( queries_array: JSValue, ) void { this.status = .fail; - const thisValue = this.thisValue.get(); + const thisValue = this.thisValue.tryGet() orelse return; defer this.thisValue.deinit(); - const targetValue = this.getTarget(globalObject, true); - if (thisValue == .zero or targetValue == .zero) { - return; - } + const targetValue = this.getTarget(globalObject, true) orelse return; const instance = AnyMySQLError.mysqlErrorToJS(globalObject, "Failed to bind query", err); @@ -122,9 +111,9 @@ pub fn bindAndExecute(this: *MySQLQuery, writer: anytype, statement: *MySQLState } fn bind(this: *MySQLQuery, execute: *PreparedStatement.Execute, globalObject: *jsc.JSGlobalObject) AnyMySQLError.Error!void { - const thisValue = this.thisValue.get(); - const binding_value = js.bindingGetCached(thisValue) orelse .zero; - const columns_value = js.columnsGetCached(thisValue) orelse .zero; + const thisValue = this.thisValue.tryGet() orelse return error.InvalidState; + const binding_value = js.bindingGetCached(thisValue) orelse .js_undefined; + const columns_value = js.columnsGetCached(thisValue) orelse .js_undefined; var iter = try QueryBindingIterator.init(binding_value, columns_value, globalObject); @@ -165,12 +154,9 @@ pub fn onJSError(this: *@This(), err: jsc.JSValue, globalObject: *jsc.JSGlobalOb this.ref(); defer this.deref(); this.status = .fail; - const thisValue = this.thisValue.get(); + const thisValue = this.thisValue.tryGet() orelse return; defer this.thisValue.deinit(); - const targetValue = this.getTarget(globalObject, true); - if (thisValue == .zero or targetValue == .zero) { - return; - } + const targetValue = this.getTarget(globalObject, true) orelse return; var vm = jsc.VirtualMachine.get(); const function = vm.rareData().mysql_context.onQueryRejectFn.get().?; @@ -185,9 +171,9 @@ pub fn onJSError(this: *@This(), err: jsc.JSValue, globalObject: *jsc.JSGlobalOb js_error, }); } -pub fn getTarget(this: *@This(), globalObject: *jsc.JSGlobalObject, clean_target: bool) jsc.JSValue { - const thisValue = this.thisValue.tryGet() orelse return .zero; - const target = js.targetGetCached(thisValue) orelse return .zero; +pub fn getTarget(this: *@This(), globalObject: *jsc.JSGlobalObject, clean_target: bool) ?jsc.JSValue { + const thisValue = this.thisValue.tryGet() orelse return null; + const target = js.targetGetCached(thisValue) orelse return null; if (clean_target) { js.targetSetCached(thisValue, globalObject, .zero); } @@ -222,20 +208,18 @@ pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalOb this.ref(); defer this.deref(); - const thisValue = this.thisValue.get(); - const targetValue = this.getTarget(globalObject, is_last); if (is_last) { this.status = .success; } else { this.status = .partial_response; } + const thisValue = this.thisValue.tryGet() orelse return; + defer if (is_last) { allowGC(thisValue, globalObject); this.thisValue.deinit(); }; - if (thisValue == .zero or targetValue == .zero) { - return; - } + const targetValue = this.getTarget(globalObject, is_last) orelse return; const vm = jsc.VirtualMachine.get(); const function = vm.rareData().mysql_context.onQueryResolveFn.get().?; @@ -373,7 +357,7 @@ pub fn doRun(this: *MySQLQuery, globalObject: *jsc.JSGlobalObject, callframe: *j return globalObject.throw("connection must be a MySQLConnection", .{}); }; - connection.poll_ref.ref(globalObject.bunVM()); + defer connection.updateRef(); var query = arguments[1]; if (!query.isObject()) { diff --git a/src/sql/mysql/protocol/AnyMySQLError.zig b/src/sql/mysql/protocol/AnyMySQLError.zig index 66e5b6aa2650..f93a28f3836d 100644 --- a/src/sql/mysql/protocol/AnyMySQLError.zig +++ b/src/sql/mysql/protocol/AnyMySQLError.zig @@ -34,6 +34,7 @@ pub const Error = error{ UnexpectedPacket, ShortRead, UnknownError, + InvalidState, }; pub fn mysqlErrorToJS(globalObject: *jsc.JSGlobalObject, message: ?[]const u8, err: Error) JSValue { @@ -66,6 +67,7 @@ pub fn mysqlErrorToJS(globalObject: *jsc.JSGlobalObject, message: ?[]const u8, e error.FailedToEncryptPassword => "ERR_MYSQL_FAILED_TO_ENCRYPT_PASSWORD", error.InvalidPublicKey => "ERR_MYSQL_INVALID_PUBLIC_KEY", error.UnknownError => "ERR_MYSQL_UNKNOWN_ERROR", + error.InvalidState => "ERR_MYSQL_INVALID_STATE", error.JSError => { return globalObject.takeException(error.JSError); }, diff --git a/src/sql/postgres/PostgresSQLQuery.zig b/src/sql/postgres/PostgresSQLQuery.zig index 9860b0273a53..12e3dd4fb33b 100644 --- a/src/sql/postgres/PostgresSQLQuery.zig +++ b/src/sql/postgres/PostgresSQLQuery.zig @@ -1,5 +1,5 @@ const PostgresSQLQuery = @This(); -const RefCount = bun.ptr.ThreadSafeRefCount(@This(), "ref_count", deinit, .{}); +const RefCount = bun.ptr.RefCount(@This(), "ref_count", deinit, .{}); statement: ?*PostgresSQLStatement = null, query: bun.String = bun.String.empty, cursor_name: bun.String = bun.String.empty, @@ -23,9 +23,9 @@ flags: packed struct(u8) { pub const ref = RefCount.ref; pub const deref = RefCount.deref; -pub fn getTarget(this: *PostgresSQLQuery, globalObject: *jsc.JSGlobalObject, clean_target: bool) jsc.JSValue { - const thisValue = this.thisValue.tryGet() orelse return .zero; - const target = js.targetGetCached(thisValue) orelse return .zero; +pub fn getTarget(this: *PostgresSQLQuery, globalObject: *jsc.JSGlobalObject, clean_target: bool) ?jsc.JSValue { + const thisValue = this.thisValue.tryGet() orelse return null; + const target = js.targetGetCached(thisValue) orelse return null; if (clean_target) { js.targetSetCached(thisValue, globalObject, .zero); } @@ -51,10 +51,6 @@ pub const Status = enum(u8) { } }; -pub fn hasPendingActivity(this: *@This()) bool { - return this.ref_count.get() > 1; -} - pub fn deinit(this: *@This()) void { this.thisValue.deinit(); if (this.statement) |statement| { @@ -84,12 +80,9 @@ pub fn onWriteFail( this.ref(); defer this.deref(); this.status = .fail; - const thisValue = this.thisValue.get(); + const thisValue = this.thisValue.tryGet() orelse return; defer this.thisValue.deinit(); - const targetValue = this.getTarget(globalObject, true); - if (thisValue == .zero or targetValue == .zero) { - return; - } + const targetValue = this.getTarget(globalObject, true) orelse return; const vm = jsc.VirtualMachine.get(); const function = vm.rareData().postgresql_context.onQueryRejectFn.get().?; @@ -105,12 +98,9 @@ pub fn onJSError(this: *@This(), err: jsc.JSValue, globalObject: *jsc.JSGlobalOb this.ref(); defer this.deref(); this.status = .fail; - const thisValue = this.thisValue.get(); + const thisValue = this.thisValue.tryGet() orelse return; defer this.thisValue.deinit(); - const targetValue = this.getTarget(globalObject, true); - if (thisValue == .zero or targetValue == .zero) { - return; - } + const targetValue = this.getTarget(globalObject, true) orelse return; var vm = jsc.VirtualMachine.get(); const function = vm.rareData().postgresql_context.onQueryRejectFn.get().?; @@ -145,21 +135,17 @@ fn consumePendingValue(thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject pub fn onResult(this: *@This(), command_tag_str: []const u8, globalObject: *jsc.JSGlobalObject, connection: jsc.JSValue, is_last: bool) void { this.ref(); defer this.deref(); - - const thisValue = this.thisValue.get(); - const targetValue = this.getTarget(globalObject, is_last); if (is_last) { this.status = .success; } else { this.status = .partial_response; } + const thisValue = this.thisValue.tryGet() orelse return; defer if (is_last) { allowGC(thisValue, globalObject); this.thisValue.deinit(); }; - if (thisValue == .zero or targetValue == .zero) { - return; - } + const targetValue = this.getTarget(globalObject, is_last) orelse return; const vm = jsc.VirtualMachine.get(); const function = vm.rareData().postgresql_context.onQueryResolveFn.get().?; diff --git a/src/sql/shared/ObjectIterator.zig b/src/sql/shared/ObjectIterator.zig index 1e3fbb6de57b..fb5f7eeb299c 100644 --- a/src/sql/shared/ObjectIterator.zig +++ b/src/sql/shared/ObjectIterator.zig @@ -11,6 +11,10 @@ array_length: usize = 0, any_failed: bool = false, pub fn next(this: *ObjectIterator) ?jsc.JSValue { + if (this.array.isEmptyOrUndefinedOrNull() or this.columns.isEmptyOrUndefinedOrNull()) { + this.any_failed = true; + return null; + } if (this.row_i >= this.array_length) { return null; } From 8a64dd86c60dbac4ce9006b07a1b74d86418e62e Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 17:04:41 -0700 Subject: [PATCH 42/59] more --- src/sql/postgres/PostgresSQLConnection.zig | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/sql/postgres/PostgresSQLConnection.zig b/src/sql/postgres/PostgresSQLConnection.zig index 445c25e6aa5a..0d2445a5ff82 100644 --- a/src/sql/postgres/PostgresSQLConnection.zig +++ b/src/sql/postgres/PostgresSQLConnection.zig @@ -311,7 +311,7 @@ pub fn failWithJSValue(this: *PostgresSQLConnection, value: JSValue) void { this.stopTimers(); if (this.status == .failed) return; - this.setStatus(.failed); + this.status = .failed; this.ref(); defer this.deref(); @@ -321,12 +321,17 @@ pub fn failWithJSValue(this: *PostgresSQLConnection, value: JSValue) void { const loop = this.vm.eventLoop(); loop.enter(); + var js_error = value.toError() orelse value; + if (js_error == .zero) { + js_error = postgresErrorToJS(this.globalObject, "Connection closed", error.ConnectionClosed); + } + js_error.ensureStillAlive(); defer loop.exit(); _ = on_close.call( this.globalObject, .js_undefined, &[_]JSValue{ - value.toError() orelse value, + js_error, this.getQueriesArray(), }, ) catch |e| this.globalObject.reportActiveExceptionAsUnhandled(e); @@ -1350,6 +1355,9 @@ fn advance(this: *PostgresSQLConnection) void { } pub fn getQueriesArray(this: *const PostgresSQLConnection) JSValue { + if (this.js_value.isEmptyOrUndefinedOrNull()) { + return .js_undefined; + } return js.queriesGetCached(this.js_value) orelse .js_undefined; } From 07631e0742f6d82733d7f6959bf2dd15984bfc6c Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 19:18:19 -0700 Subject: [PATCH 43/59] test --- src/bun.js/bindings/ZigGlobalObject.cpp | 16 +++++++++++-- src/bun.js/bindings/bindings.cpp | 30 +++++++++++++++++++++---- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/bun.js/bindings/ZigGlobalObject.cpp b/src/bun.js/bindings/ZigGlobalObject.cpp index fc584871ca05..64d6ccc0d287 100644 --- a/src/bun.js/bindings/ZigGlobalObject.cpp +++ b/src/bun.js/bindings/ZigGlobalObject.cpp @@ -1548,10 +1548,16 @@ JSC_DEFINE_HOST_FUNCTION(functionQueueMicrotask, auto* globalObject = defaultGlobalObject(lexicalGlobalObject); JSC::JSValue asyncContext = globalObject->m_asyncContextData.get()->getInternalField(0); + auto function = globalObject->performMicrotaskFunction(); +#if ASSERT_ENABLED + ASSERT_WITH_MESSAGE(function, "Invalid microtask function"); + ASSERT_WITH_MESSAGE(asyncContext.isEmpty(), "Invalid microtask context"); + ASSERT_WITH_MESSAGE(callback.isEmpty(), "Invalid microtask callback"); +#endif // This is a JSC builtin function - lexicalGlobalObject->queueMicrotask(globalObject->performMicrotaskFunction(), callback, asyncContext, - JSC::JSValue {}, JSC::JSValue {}); + lexicalGlobalObject->queueMicrotask(function, callback, asyncContext, + JSC::jsUndefined(), JSC::jsUndefined()); return JSC::JSValue::encode(JSC::jsUndefined()); } @@ -4147,6 +4153,12 @@ extern "C" void JSC__JSGlobalObject__queueMicrotaskCallback(Zig::GlobalObject* g { JSFunction* function = globalObject->nativeMicrotaskTrampoline(); +#if ASSERT_ENABLED + ASSERT_WITH_MESSAGE(function, "Invalid microtask function"); + ASSERT_WITH_MESSAGE(ptr, "Invalid microtask context"); + ASSERT_WITH_MESSAGE(callback, "Invalid microtask callback"); +#endif + // Do not use JSCell* here because the GC will try to visit it. globalObject->queueMicrotask(function, JSValue(std::bit_cast(reinterpret_cast(ptr))), JSValue(std::bit_cast(reinterpret_cast(callback))), jsUndefined(), jsUndefined()); } diff --git a/src/bun.js/bindings/bindings.cpp b/src/bun.js/bindings/bindings.cpp index 6d6b51321169..4220f04d463a 100644 --- a/src/bun.js/bindings/bindings.cpp +++ b/src/bun.js/bindings/bindings.cpp @@ -3453,6 +3453,7 @@ void JSC__JSPromise__rejectOnNextTickWithHandled(JSC::JSPromise* promise, JSC::J JSC::EncodedJSValue encoedValue, bool handled) { JSC::JSValue value = JSC::JSValue::decode(encoedValue); + auto& vm = JSC::getVM(lexicalGlobalObject); auto scope = DECLARE_THROW_SCOPE(vm); uint32_t flags = promise->internalField(JSC::JSPromise::Field::Flags).get().asUInt32(); @@ -3463,10 +3464,29 @@ void JSC__JSPromise__rejectOnNextTickWithHandled(JSC::JSPromise* promise, JSC::J promise->internalField(JSC::JSPromise::Field::Flags).set(vm, promise, jsNumber(flags | JSC::JSPromise::isFirstResolvingFunctionCalledFlag)); auto* globalObject = jsCast(promise->globalObject()); + auto microtaskFunction = globalObject->performMicrotaskFunction(); + auto rejectPromiseFunction = globalObject->rejectPromiseFunction(); + + auto asyncContext = globalObject->m_asyncContextData.get()->getInternalField(0); + +#if ASSERT_ENABLED + ASSERT_WITH_MESSAGE(microtaskFunction, "Invalid microtask function"); + ASSERT_WITH_MESSAGE(asyncContext.isEmpty(), "Invalid microtask context"); + ASSERT_WITH_MESSAGE(rejectPromiseFunction, "Invalid microtask callback"); + ASSERT_WITH_MESSAGE(value.isEmpty(), "Invalid microtask value"); +#endif + + if (asyncContext.isEmpty()) { + asyncContext = jsUndefined(); + } + + if (value.isEmpty()) { + value = jsUndefined(); + } globalObject->queueMicrotask( - globalObject->performMicrotaskFunction(), - globalObject->rejectPromiseFunction(), + microtaskFunction, + rejectPromiseFunction, globalObject->m_asyncContextData.get()->getInternalField(0), promise, value); @@ -6121,8 +6141,9 @@ extern "C" void JSC__JSGlobalObject__queueMicrotaskJob(JSC::JSGlobalObject* arg0 if (microtaskArgs[3].isEmpty()) { microtaskArgs[3] = jsUndefined(); } - + auto microTaskFunction = globalObject->performMicrotaskFunction(); #if ASSERT_ENABLED + ASSERT_WITH_MESSAGE(microTaskFunction, "Invalid microtask function"); auto& vm = globalObject->vm(); if (microtaskArgs[0].isCell()) { JSC::Integrity::auditCellFully(vm, microtaskArgs[0].asCell()); @@ -6139,10 +6160,11 @@ extern "C" void JSC__JSGlobalObject__queueMicrotaskJob(JSC::JSGlobalObject* arg0 if (microtaskArgs[3].isCell()) { JSC::Integrity::auditCellFully(vm, microtaskArgs[3].asCell()); } + #endif globalObject->queueMicrotask( - globalObject->performMicrotaskFunction(), + microTaskFunction, WTFMove(microtaskArgs[0]), WTFMove(microtaskArgs[1]), WTFMove(microtaskArgs[2]), From 00ce0847d984ecec4e43798350983cbcaf84a0ba Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 19:48:16 -0700 Subject: [PATCH 44/59] opsie --- src/bun.js/bindings/ZigGlobalObject.cpp | 8 ++++++-- src/bun.js/bindings/bindings.cpp | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/bun.js/bindings/ZigGlobalObject.cpp b/src/bun.js/bindings/ZigGlobalObject.cpp index 64d6ccc0d287..36720bdec1bf 100644 --- a/src/bun.js/bindings/ZigGlobalObject.cpp +++ b/src/bun.js/bindings/ZigGlobalObject.cpp @@ -1551,10 +1551,14 @@ JSC_DEFINE_HOST_FUNCTION(functionQueueMicrotask, auto function = globalObject->performMicrotaskFunction(); #if ASSERT_ENABLED ASSERT_WITH_MESSAGE(function, "Invalid microtask function"); - ASSERT_WITH_MESSAGE(asyncContext.isEmpty(), "Invalid microtask context"); - ASSERT_WITH_MESSAGE(callback.isEmpty(), "Invalid microtask callback"); + ASSERT_WITH_MESSAGE(!asyncContext.isEmpty(), "Invalid microtask context"); + ASSERT_WITH_MESSAGE(!callback.isEmpty(), "Invalid microtask callback"); #endif + if (asyncContext.isEmpty()) { + asyncContext = JSC::jsUndefined(); + } + // This is a JSC builtin function lexicalGlobalObject->queueMicrotask(function, callback, asyncContext, JSC::jsUndefined(), JSC::jsUndefined()); diff --git a/src/bun.js/bindings/bindings.cpp b/src/bun.js/bindings/bindings.cpp index 4220f04d463a..750704fedcfd 100644 --- a/src/bun.js/bindings/bindings.cpp +++ b/src/bun.js/bindings/bindings.cpp @@ -3471,9 +3471,9 @@ void JSC__JSPromise__rejectOnNextTickWithHandled(JSC::JSPromise* promise, JSC::J #if ASSERT_ENABLED ASSERT_WITH_MESSAGE(microtaskFunction, "Invalid microtask function"); - ASSERT_WITH_MESSAGE(asyncContext.isEmpty(), "Invalid microtask context"); + ASSERT_WITH_MESSAGE(!asyncContext.isEmpty(), "Invalid microtask context"); ASSERT_WITH_MESSAGE(rejectPromiseFunction, "Invalid microtask callback"); - ASSERT_WITH_MESSAGE(value.isEmpty(), "Invalid microtask value"); + ASSERT_WITH_MESSAGE(!value.isEmpty(), "Invalid microtask value"); #endif if (asyncContext.isEmpty()) { From bb85cc40a7a7e5f79486263172b0cd175eae2724 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 20:08:39 -0700 Subject: [PATCH 45/59] allow no asyncContext --- src/bun.js/bindings/ZigGlobalObject.cpp | 1 - src/bun.js/bindings/bindings.cpp | 1 - 2 files changed, 2 deletions(-) diff --git a/src/bun.js/bindings/ZigGlobalObject.cpp b/src/bun.js/bindings/ZigGlobalObject.cpp index 36720bdec1bf..0b5d9cf96c3a 100644 --- a/src/bun.js/bindings/ZigGlobalObject.cpp +++ b/src/bun.js/bindings/ZigGlobalObject.cpp @@ -1551,7 +1551,6 @@ JSC_DEFINE_HOST_FUNCTION(functionQueueMicrotask, auto function = globalObject->performMicrotaskFunction(); #if ASSERT_ENABLED ASSERT_WITH_MESSAGE(function, "Invalid microtask function"); - ASSERT_WITH_MESSAGE(!asyncContext.isEmpty(), "Invalid microtask context"); ASSERT_WITH_MESSAGE(!callback.isEmpty(), "Invalid microtask callback"); #endif diff --git a/src/bun.js/bindings/bindings.cpp b/src/bun.js/bindings/bindings.cpp index 750704fedcfd..03eb92288656 100644 --- a/src/bun.js/bindings/bindings.cpp +++ b/src/bun.js/bindings/bindings.cpp @@ -3471,7 +3471,6 @@ void JSC__JSPromise__rejectOnNextTickWithHandled(JSC::JSPromise* promise, JSC::J #if ASSERT_ENABLED ASSERT_WITH_MESSAGE(microtaskFunction, "Invalid microtask function"); - ASSERT_WITH_MESSAGE(!asyncContext.isEmpty(), "Invalid microtask context"); ASSERT_WITH_MESSAGE(rejectPromiseFunction, "Invalid microtask callback"); ASSERT_WITH_MESSAGE(!value.isEmpty(), "Invalid microtask value"); #endif From e5cc5d5b4bfc914582087a734fe448b15e1d8400 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 20:53:15 -0700 Subject: [PATCH 46/59] fix test-queue-microtask --- src/bun.js/bindings/ZigGlobalObject.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bun.js/bindings/ZigGlobalObject.cpp b/src/bun.js/bindings/ZigGlobalObject.cpp index 0b5d9cf96c3a..653f70761344 100644 --- a/src/bun.js/bindings/ZigGlobalObject.cpp +++ b/src/bun.js/bindings/ZigGlobalObject.cpp @@ -1560,7 +1560,7 @@ JSC_DEFINE_HOST_FUNCTION(functionQueueMicrotask, // This is a JSC builtin function lexicalGlobalObject->queueMicrotask(function, callback, asyncContext, - JSC::jsUndefined(), JSC::jsUndefined()); + JSC::JSValue {}, JSC::JSValue {}); return JSC::JSValue::encode(JSC::jsUndefined()); } From 019ccc338d1be57b79cffc9c9dc400cbc0f2983b Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 21:18:02 -0700 Subject: [PATCH 47/59] queueMicrotask again --- src/sql/mysql/MySQLConnection.zig | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index bb66decc9497..f6d73664d479 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -388,14 +388,7 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { const queries_array = this.getQueriesArray(); queries_array.ensureStillAlive(); - _ = on_close.call( - this.globalObject, - .js_undefined, - &[_]JSValue{ - js_error, - queries_array, - }, - ) catch |e| this.globalObject.reportActiveExceptionAsUnhandled(e); + this.globalObject.queueMicrotask(on_close, &[_]JSValue{ js_error, queries_array }); } pub fn fail(this: *MySQLConnection, message: []const u8, err: AnyMySQLError.Error) void { From 324c72c537b11228804ba83be5fdde8df4d26d96 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 21:29:22 -0700 Subject: [PATCH 48/59] more --- src/bun.js/api/server.zig | 2 +- src/bun.js/bindings/JSRef.zig | 5 +++++ src/sql/mysql/MySQLConnection.zig | 2 +- src/sql/mysql/MySQLQuery.zig | 29 +++++++++++++++++---------- src/sql/postgres/PostgresSQLQuery.zig | 13 ++++-------- 5 files changed, 29 insertions(+), 22 deletions(-) diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index bf75c92b1a5c..a29342e6a1a3 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -1426,7 +1426,7 @@ pub fn NewServer(protocol_enum: enum { http, https }, development_kind: enum { d pub fn finalize(this: *ThisServer) void { httplog("finalize", .{}); - this.js_value.deinit(); + this.js_value.finalize(); this.flags.has_js_deinited = true; this.deinitIfWeCan(); } diff --git a/src/bun.js/bindings/JSRef.zig b/src/bun.js/bindings/JSRef.zig index 46555db798b6..ee8f697f388c 100644 --- a/src/bun.js/bindings/JSRef.zig +++ b/src/bun.js/bindings/JSRef.zig @@ -100,6 +100,11 @@ pub const JSRef = union(enum) { .finalized => {}, } } + + pub fn finalize(this: *@This()) void { + this.deinit(); + this.* = .{ .finalized = {} }; + } }; const bun = @import("bun"); diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index f6d73664d479..8dddb303e867 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -269,7 +269,7 @@ pub fn finalize(this: *MySQLConnection) void { this.stopTimers(); debug("MySQLConnection finalize", .{}); - this.js_value.deinit(); + this.js_value.finalize(); this.deref(); } diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index 2388240c9dd4..45e6d4936dc4 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -43,7 +43,6 @@ pub const Status = enum(u8) { }; pub fn deinit(this: *@This()) void { - this.thisValue.deinit(); if (this.statement) |statement| { statement.deref(); } @@ -62,7 +61,7 @@ pub fn finalize(this: *@This()) void { this.statement = null; } - this.thisValue.deinit(); + this.thisValue.finalize(); this.deref(); } @@ -74,18 +73,23 @@ pub fn onWriteFail( ) void { this.status = .fail; const thisValue = this.thisValue.tryGet() orelse return; - defer this.thisValue.deinit(); + defer this.thisValue.downgrade(); const targetValue = this.getTarget(globalObject, true) orelse return; const instance = AnyMySQLError.mysqlErrorToJS(globalObject, "Failed to bind query", err); - + const js_err = instance.toError() orelse instance; + bun.assertf(js_err != .zero, "js_err is zero", .{}); + js_err.ensureStillAlive(); const vm = jsc.VirtualMachine.get(); - const function = vm.rareData().mysql_context.onQueryRejectFn.get().?; + const function = vm.rareData().mysql_context.onQueryRejectFn.get() orelse return; + bun.assertf(function.isCallable(), "onQueryRejectFn is not callable"); const event_loop = vm.eventLoop(); + const js_array = if (queries_array == .zero) .js_undefined else queries_array; + js_array.ensureStillAlive(); event_loop.runCallback(function, globalObject, thisValue, &.{ targetValue, - instance.toError() orelse instance, - queries_array, + js_err, + js_array, }); } @@ -155,11 +159,12 @@ pub fn onJSError(this: *@This(), err: jsc.JSValue, globalObject: *jsc.JSGlobalOb defer this.deref(); this.status = .fail; const thisValue = this.thisValue.tryGet() orelse return; - defer this.thisValue.deinit(); + defer this.thisValue.downgrade(); const targetValue = this.getTarget(globalObject, true) orelse return; var vm = jsc.VirtualMachine.get(); - const function = vm.rareData().mysql_context.onQueryRejectFn.get().?; + const function = vm.rareData().mysql_context.onQueryRejectFn.get() orelse return; + bun.assertf(function.isCallable(), "onQueryRejectFn is not callable", .{}); const event_loop = vm.eventLoop(); var js_error = err.toError() orelse err; if (js_error == .zero) { @@ -217,12 +222,14 @@ pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalOb defer if (is_last) { allowGC(thisValue, globalObject); - this.thisValue.deinit(); + this.thisValue.downgrade(); }; const targetValue = this.getTarget(globalObject, is_last) orelse return; const vm = jsc.VirtualMachine.get(); - const function = vm.rareData().mysql_context.onQueryResolveFn.get().?; + const function = vm.rareData().mysql_context.onQueryResolveFn.get() orelse return; + bun.assertf(function.isCallable(), "onQueryResolveFn is not callable", .{}); + const event_loop = vm.eventLoop(); const tag: CommandTag = .{ .SELECT = result_count }; var queries_array = if (connection == .zero) .js_undefined else MySQLConnection.js.queriesGetCached(connection) orelse .js_undefined; diff --git a/src/sql/postgres/PostgresSQLQuery.zig b/src/sql/postgres/PostgresSQLQuery.zig index 12e3dd4fb33b..a8a399362f9c 100644 --- a/src/sql/postgres/PostgresSQLQuery.zig +++ b/src/sql/postgres/PostgresSQLQuery.zig @@ -52,7 +52,6 @@ pub const Status = enum(u8) { }; pub fn deinit(this: *@This()) void { - this.thisValue.deinit(); if (this.statement) |statement| { statement.deref(); } @@ -63,11 +62,7 @@ pub fn deinit(this: *@This()) void { pub fn finalize(this: *@This()) void { debug("PostgresSQLQuery finalize", .{}); - if (this.thisValue == .weak) { - // clean up if is a weak reference, if is a strong reference we need to wait until the query is done - // if we are a strong reference, here is probably a bug because GC'd should not happen - this.thisValue.weak = .zero; - } + this.finalize(); this.deref(); } @@ -81,7 +76,7 @@ pub fn onWriteFail( defer this.deref(); this.status = .fail; const thisValue = this.thisValue.tryGet() orelse return; - defer this.thisValue.deinit(); + defer this.thisValue.downgrade(); const targetValue = this.getTarget(globalObject, true) orelse return; const vm = jsc.VirtualMachine.get(); @@ -99,7 +94,7 @@ pub fn onJSError(this: *@This(), err: jsc.JSValue, globalObject: *jsc.JSGlobalOb defer this.deref(); this.status = .fail; const thisValue = this.thisValue.tryGet() orelse return; - defer this.thisValue.deinit(); + defer this.thisValue.downgrade(); const targetValue = this.getTarget(globalObject, true) orelse return; var vm = jsc.VirtualMachine.get(); @@ -143,7 +138,7 @@ pub fn onResult(this: *@This(), command_tag_str: []const u8, globalObject: *jsc. const thisValue = this.thisValue.tryGet() orelse return; defer if (is_last) { allowGC(thisValue, globalObject); - this.thisValue.deinit(); + this.thisValue.downgrade(); }; const targetValue = this.getTarget(globalObject, is_last) orelse return; From 5ddc772c50baa1521edc9a283b7537ac979cb7f6 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 21:31:11 -0700 Subject: [PATCH 49/59] opsie --- src/sql/mysql/MySQLQuery.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index 45e6d4936dc4..4621acc36dc4 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -82,7 +82,7 @@ pub fn onWriteFail( js_err.ensureStillAlive(); const vm = jsc.VirtualMachine.get(); const function = vm.rareData().mysql_context.onQueryRejectFn.get() orelse return; - bun.assertf(function.isCallable(), "onQueryRejectFn is not callable"); + bun.assertf(function.isCallable(), "onQueryRejectFn is not callable", .{}); const event_loop = vm.eventLoop(); const js_array = if (queries_array == .zero) .js_undefined else queries_array; js_array.ensureStillAlive(); From a39179a109cac278fd45a1978fab43b0bffa26fe Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 21:36:11 -0700 Subject: [PATCH 50/59] remove allowGC --- src/sql/mysql/MySQLQuery.zig | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index 4621acc36dc4..a09cc4f7e305 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -191,17 +191,6 @@ fn consumePendingValue(thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject return pending_value; } -pub fn allowGC(thisValue: jsc.JSValue, globalObject: *jsc.JSGlobalObject) void { - if (thisValue == .zero) { - return; - } - - defer thisValue.ensureStillAlive(); - js.bindingSetCached(thisValue, globalObject, .zero); - js.pendingValueSetCached(thisValue, globalObject, .zero); - js.targetSetCached(thisValue, globalObject, .zero); -} - fn u64ToJSValue(value: u64) JSValue { if (value <= jsc.MAX_SAFE_INTEGER) { return JSValue.jsNumber(value); @@ -221,7 +210,6 @@ pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalOb const thisValue = this.thisValue.tryGet() orelse return; defer if (is_last) { - allowGC(thisValue, globalObject); this.thisValue.downgrade(); }; const targetValue = this.getTarget(globalObject, is_last) orelse return; From 2b66c6f4a429e384d56d7ceb79aa1438a0afc080 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 22:01:12 -0700 Subject: [PATCH 51/59] opsie --- src/sql/postgres/PostgresSQLQuery.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sql/postgres/PostgresSQLQuery.zig b/src/sql/postgres/PostgresSQLQuery.zig index a8a399362f9c..1adc71356dd0 100644 --- a/src/sql/postgres/PostgresSQLQuery.zig +++ b/src/sql/postgres/PostgresSQLQuery.zig @@ -62,7 +62,7 @@ pub fn deinit(this: *@This()) void { pub fn finalize(this: *@This()) void { debug("PostgresSQLQuery finalize", .{}); - this.finalize(); + this.thisValue.finalize(); this.deref(); } From ca80e070deee47ae544a67a7621123d803058b51 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 22:05:27 -0700 Subject: [PATCH 52/59] remove .zero from JSref --- src/bun.js/bindings/JSRef.zig | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/bun.js/bindings/JSRef.zig b/src/bun.js/bindings/JSRef.zig index ee8f697f388c..c76a4056eb65 100644 --- a/src/bun.js/bindings/JSRef.zig +++ b/src/bun.js/bindings/JSRef.zig @@ -4,26 +4,28 @@ pub const JSRef = union(enum) { finalized: void, pub fn initWeak(value: jsc.JSValue) @This() { + bun.assert(!value.isEmptyOrUndefinedOrNull()); return .{ .weak = value }; } pub fn initStrong(value: jsc.JSValue, globalThis: *jsc.JSGlobalObject) @This() { - bun.assert(value != .zero); + bun.assert(!value.isEmptyOrUndefinedOrNull()); return .{ .strong = .create(value, globalThis) }; } pub fn empty() @This() { - return .{ .weak = .zero }; + return .{ .weak = .js_undefined }; } pub fn tryGet(this: *const @This()) ?jsc.JSValue { return switch (this.*) { - .weak => if (this.weak != .zero) this.weak else null, + .weak => if (this.weak.isEmptyOrUndefinedOrNull()) null else this.weak, .strong => this.strong.get(), .finalized => null, }; } pub fn setWeak(this: *@This(), value: jsc.JSValue) void { + bun.assert(!value.isEmptyOrUndefinedOrNull()); switch (this.*) { .weak => {}, .strong => { @@ -37,7 +39,7 @@ pub const JSRef = union(enum) { } pub fn setStrong(this: *@This(), value: jsc.JSValue, globalThis: *jsc.JSGlobalObject) void { - bun.assert(value != .zero); + bun.assert(!value.isEmptyOrUndefinedOrNull()); if (this.* == .strong) { this.strong.set(globalThis, value); return; @@ -48,7 +50,7 @@ pub const JSRef = union(enum) { pub fn upgrade(this: *@This(), globalThis: *jsc.JSGlobalObject) void { switch (this.*) { .weak => { - bun.assert(this.weak != .zero); + bun.assert(!this.weak.isEmptyOrUndefinedOrNull()); this.* = .{ .strong = .create(this.weak, globalThis) }; }, .strong => {}, @@ -62,7 +64,7 @@ pub const JSRef = union(enum) { switch (this.*) { .weak => {}, .strong => |*strong| { - const value = strong.get() orelse .zero; + const value = strong.trySwap() orelse .js_undefined; value.ensureStillAlive(); strong.deinit(); this.* = .{ .weak = value }; @@ -75,7 +77,7 @@ pub const JSRef = union(enum) { pub fn isEmpty(this: *const @This()) bool { return switch (this.*) { - .weak => this.weak == .zero, + .weak => this.weak.isEmptyOrUndefinedOrNull(), .strong => !this.strong.has(), .finalized => true, }; @@ -83,7 +85,7 @@ pub const JSRef = union(enum) { pub fn isNotEmpty(this: *const @This()) bool { return switch (this.*) { - .weak => this.weak != .zero, + .weak => !this.weak.isEmptyOrUndefinedOrNull(), .strong => this.strong.has(), .finalized => false, }; @@ -92,7 +94,7 @@ pub const JSRef = union(enum) { pub fn deinit(this: *@This()) void { switch (this.*) { .weak => { - this.weak = .zero; + this.weak = .js_undefined; }, .strong => { this.strong.deinit(); From b4a9f5f0ffcda0bf9adaf5a3368b7098f4cf3ec4 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 22:15:18 -0700 Subject: [PATCH 53/59] no need to use tryGet if we have the callframe this value --- src/sql/mysql/MySQLQuery.zig | 4 ++-- src/sql/postgres/PostgresSQLQuery.zig | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index a09cc4f7e305..aef4e22edefb 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -312,9 +312,9 @@ pub fn call(globalThis: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSEr return this_value; } -pub fn setPendingValue(this: *@This(), globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { +pub fn setPendingValue(_: *@This(), globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const result = callframe.argument(0); - const thisValue = this.thisValue.tryGet() orelse return .js_undefined; + const thisValue = callframe.this(); js.pendingValueSetCached(thisValue, globalObject, result); return .js_undefined; } diff --git a/src/sql/postgres/PostgresSQLQuery.zig b/src/sql/postgres/PostgresSQLQuery.zig index 1adc71356dd0..5d4a16c4b92e 100644 --- a/src/sql/postgres/PostgresSQLQuery.zig +++ b/src/sql/postgres/PostgresSQLQuery.zig @@ -238,9 +238,9 @@ pub fn doDone(this: *@This(), globalObject: *jsc.JSGlobalObject, _: *jsc.CallFra this.flags.is_done = true; return .js_undefined; } -pub fn setPendingValue(this: *PostgresSQLQuery, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { +pub fn setPendingValue(_: *PostgresSQLQuery, globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JSError!JSValue { const result = callframe.argument(0); - const thisValue = this.thisValue.tryGet() orelse return .js_undefined; + const thisValue = callframe.this(); js.pendingValueSetCached(thisValue, globalObject, result); return .js_undefined; } From b616fe1db65bd1b98cd76a32ce06ef34fe721cf1 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 22:42:14 -0700 Subject: [PATCH 54/59] wip --- src/sql/mysql/MySQLConnection.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 8dddb303e867..04296e36a45d 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -373,6 +373,7 @@ pub fn failWithJSValue(this: *MySQLConnection, value: JSValue) void { } this.status = .failed; + if (this.vm.isShuttingDown()) return; const on_close = this.consumeOnCloseCallback(this.globalObject) orelse return; on_close.ensureStillAlive(); From 2bd01af7e84d939be66a202f347e742254dac5d5 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 22:46:25 -0700 Subject: [PATCH 55/59] fix js tag --- src/sql/postgres/CommandTag.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sql/postgres/CommandTag.zig b/src/sql/postgres/CommandTag.zig index 47f70048c2ae..43ee3d6abe84 100644 --- a/src/sql/postgres/CommandTag.zig +++ b/src/sql/postgres/CommandTag.zig @@ -39,7 +39,7 @@ pub const CommandTag = union(enum) { .MOVE => JSValue.jsNumber(6), .FETCH => JSValue.jsNumber(7), .COPY => JSValue.jsNumber(8), - .other => |tag| jsc.ZigString.init(tag).toJS(globalObject), + .other => |tag| bun.String.createUTF8ForJS(globalObject, tag), }; } From 4400f39b308767e76801c330e3c69b33227b4a59 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 22:47:57 -0700 Subject: [PATCH 56/59] dont do weird stuff --- src/sql/mysql/MySQLConnection.zig | 2 +- src/sql/mysql/MySQLQuery.zig | 8 +------- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index 04296e36a45d..e18cce87160c 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -1790,7 +1790,7 @@ fn handleResultSetOK(this: *MySQLConnection, request: *MySQLQuery, statement: *M request.onResult( statement.result_count, this.globalObject, - this.js_value.tryGet() orelse .js_undefined, + this.getQueriesArray(), this.flags.is_ready_for_query, last_insert_id, affected_rows, diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index aef4e22edefb..18eef13b746a 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -198,7 +198,7 @@ fn u64ToJSValue(value: u64) JSValue { return JSValue.jsBigInt(value); } -pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalObject, connection: jsc.JSValue, is_last: bool, last_insert_id: u64, affected_rows: u64) void { +pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalObject, queries_array: jsc.JSValue, is_last: bool, last_insert_id: u64, affected_rows: u64) void { this.ref(); defer this.deref(); @@ -220,12 +220,6 @@ pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalOb const event_loop = vm.eventLoop(); const tag: CommandTag = .{ .SELECT = result_count }; - var queries_array = if (connection == .zero) .js_undefined else MySQLConnection.js.queriesGetCached(connection) orelse .js_undefined; - if (queries_array == .zero) { - queries_array = .js_undefined; - } else { - queries_array.ensureStillAlive(); - } event_loop.runCallback(function, globalObject, thisValue, &.{ targetValue, From d83103fe496678806a43ccada6a8d2d49d83618e Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 23:15:39 -0700 Subject: [PATCH 57/59] actually handle the exceptions here --- src/sql/mysql/MySQLQuery.zig | 4 ++-- src/sql/postgres/CommandTag.zig | 2 +- src/sql/postgres/PostgresSQLQuery.zig | 5 +++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index 18eef13b746a..fc5978972242 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -220,11 +220,11 @@ pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalOb const event_loop = vm.eventLoop(); const tag: CommandTag = .{ .SELECT = result_count }; - + const js_tag = tag.toJSTag(globalObject) catch |e| return globalObject.reportActiveExceptionAsUnhandled(e); event_loop.runCallback(function, globalObject, thisValue, &.{ targetValue, consumePendingValue(thisValue, globalObject) orelse .js_undefined, - tag.toJSTag(globalObject), + js_tag, tag.toJSNumber(), queries_array, JSValue.jsBoolean(is_last), diff --git a/src/sql/postgres/CommandTag.zig b/src/sql/postgres/CommandTag.zig index 43ee3d6abe84..2fd987ab2cec 100644 --- a/src/sql/postgres/CommandTag.zig +++ b/src/sql/postgres/CommandTag.zig @@ -29,7 +29,7 @@ pub const CommandTag = union(enum) { other: []const u8, - pub fn toJSTag(this: CommandTag, globalObject: *jsc.JSGlobalObject) JSValue { + pub fn toJSTag(this: CommandTag, globalObject: *jsc.JSGlobalObject) bun.JSError!jsc.JSValue { return switch (this) { .INSERT => JSValue.jsNumber(1), .DELETE => JSValue.jsNumber(2), diff --git a/src/sql/postgres/PostgresSQLQuery.zig b/src/sql/postgres/PostgresSQLQuery.zig index 5d4a16c4b92e..92b822ca6753 100644 --- a/src/sql/postgres/PostgresSQLQuery.zig +++ b/src/sql/postgres/PostgresSQLQuery.zig @@ -146,11 +146,12 @@ pub fn onResult(this: *@This(), command_tag_str: []const u8, globalObject: *jsc. const function = vm.rareData().postgresql_context.onQueryResolveFn.get().?; const event_loop = vm.eventLoop(); const tag = CommandTag.init(command_tag_str); - + const js_tag = tag.toJSTag(globalObject) catch |e| return globalObject.reportActiveExceptionAsUnhandled(e); + js_tag.ensureStillAlive(); event_loop.runCallback(function, globalObject, thisValue, &.{ targetValue, consumePendingValue(thisValue, globalObject) orelse .js_undefined, - tag.toJSTag(globalObject), + js_tag, tag.toJSNumber(), if (connection == .zero) .js_undefined else PostgresSQLConnection.js.queriesGetCached(connection) orelse .js_undefined, JSValue.jsBoolean(is_last), From a6d749276c1b84bffcc127d8d881a70d88765782 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Wed, 10 Sep 2025 23:18:49 -0700 Subject: [PATCH 58/59] dont make it an impossible to catch error --- src/sql/mysql/MySQLQuery.zig | 8 ++++++-- src/sql/postgres/PostgresSQLQuery.zig | 8 +++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/sql/mysql/MySQLQuery.zig b/src/sql/mysql/MySQLQuery.zig index fc5978972242..2d68784085c2 100644 --- a/src/sql/mysql/MySQLQuery.zig +++ b/src/sql/mysql/MySQLQuery.zig @@ -207,6 +207,11 @@ pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalOb } else { this.status = .partial_response; } + + const tag: CommandTag = .{ .SELECT = result_count }; + const js_tag = tag.toJSTag(globalObject) catch |e| return this.onJSError(globalObject.takeException(e), globalObject); + js_tag.ensureStillAlive(); + const thisValue = this.thisValue.tryGet() orelse return; defer if (is_last) { @@ -219,8 +224,7 @@ pub fn onResult(this: *@This(), result_count: u64, globalObject: *jsc.JSGlobalOb bun.assertf(function.isCallable(), "onQueryResolveFn is not callable", .{}); const event_loop = vm.eventLoop(); - const tag: CommandTag = .{ .SELECT = result_count }; - const js_tag = tag.toJSTag(globalObject) catch |e| return globalObject.reportActiveExceptionAsUnhandled(e); + event_loop.runCallback(function, globalObject, thisValue, &.{ targetValue, consumePendingValue(thisValue, globalObject) orelse .js_undefined, diff --git a/src/sql/postgres/PostgresSQLQuery.zig b/src/sql/postgres/PostgresSQLQuery.zig index 92b822ca6753..ed398d3fba45 100644 --- a/src/sql/postgres/PostgresSQLQuery.zig +++ b/src/sql/postgres/PostgresSQLQuery.zig @@ -135,6 +135,10 @@ pub fn onResult(this: *@This(), command_tag_str: []const u8, globalObject: *jsc. } else { this.status = .partial_response; } + const tag = CommandTag.init(command_tag_str); + const js_tag = tag.toJSTag(globalObject) catch |e| return this.onJSError(globalObject.takeException(e), globalObject); + js_tag.ensureStillAlive(); + const thisValue = this.thisValue.tryGet() orelse return; defer if (is_last) { allowGC(thisValue, globalObject); @@ -145,9 +149,7 @@ pub fn onResult(this: *@This(), command_tag_str: []const u8, globalObject: *jsc. const vm = jsc.VirtualMachine.get(); const function = vm.rareData().postgresql_context.onQueryResolveFn.get().?; const event_loop = vm.eventLoop(); - const tag = CommandTag.init(command_tag_str); - const js_tag = tag.toJSTag(globalObject) catch |e| return globalObject.reportActiveExceptionAsUnhandled(e); - js_tag.ensureStillAlive(); + event_loop.runCallback(function, globalObject, thisValue, &.{ targetValue, consumePendingValue(thisValue, globalObject) orelse .js_undefined, From c226a947c97e20045099c450d0acb852985330b6 Mon Sep 17 00:00:00 2001 From: Ciro Spaciari Date: Thu, 11 Sep 2025 17:10:54 -0700 Subject: [PATCH 59/59] dont touch JS in the finalizer --- src/sql/mysql/MySQLConnection.zig | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/sql/mysql/MySQLConnection.zig b/src/sql/mysql/MySQLConnection.zig index e18cce87160c..f819b9aad3de 100644 --- a/src/sql/mysql/MySQLConnection.zig +++ b/src/sql/mysql/MySQLConnection.zig @@ -962,7 +962,6 @@ pub fn call(globalObject: *jsc.JSGlobalObject, callframe: *jsc.CallFrame) bun.JS } pub fn deinit(this: *MySQLConnection) void { - this.disconnect(); this.stopTimers(); debug("MySQLConnection deinit", .{}); @@ -973,10 +972,7 @@ pub fn deinit(this: *MySQLConnection) void { // Clear any pending requests first for (requests.readableSlice(0)) |request| { this.finishRequest(request); - request.onError(.{ - .error_code = 2013, - .error_message = .{ .temporary = "Connection closed" }, - }, this.globalObject); + request.deref(); } this.write_buffer.deinit(bun.default_allocator); this.read_buffer.deinit(bun.default_allocator);