Skip to content
Closed
Show file tree
Hide file tree
Changes from 52 commits
Commits
Show all changes
64 commits
Select commit Hold shift + click to select a range
4654a8a
dont override this let it use binded value
cirospaciari Sep 8, 2025
8bf8b8e
test
cirospaciari Sep 9, 2025
3be8796
wip
cirospaciari Sep 9, 2025
edec93a
test
cirospaciari Sep 9, 2025
6f125e0
toError
cirospaciari Sep 9, 2025
b809cd2
test
cirospaciari Sep 9, 2025
7eecefe
test
cirospaciari Sep 9, 2025
413dd86
test
cirospaciari Sep 9, 2025
becf777
test
cirospaciari Sep 9, 2025
07ca61f
a
cirospaciari Sep 9, 2025
f424308
fix disconnect inside finalie
cirospaciari Sep 9, 2025
edeca46
dont pass zero
cirospaciari Sep 9, 2025
b3d46fa
check that
cirospaciari Sep 9, 2025
173309b
fix test
cirospaciari Sep 9, 2025
3d05371
more consistent
cirospaciari Sep 9, 2025
60d4f92
enable more
cirospaciari Sep 9, 2025
7c30edd
opsie
cirospaciari Sep 9, 2025
c5fbe10
opsie
cirospaciari Sep 9, 2025
b79f0d1
tst
cirospaciari Sep 9, 2025
7753820
delay clos
cirospaciari Sep 9, 2025
3e84a29
ensureStillAlive
cirospaciari Sep 9, 2025
b778121
ok
cirospaciari Sep 9, 2025
f1a5263
opsie
cirospaciari Sep 9, 2025
fa0febc
opsie
cirospaciari Sep 10, 2025
c4996b2
more
cirospaciari Sep 10, 2025
08f3270
dont timeout when disconnected
cirospaciari Sep 10, 2025
f763180
test
cirospaciari Sep 10, 2025
38a798b
maybe
cirospaciari Sep 10, 2025
054de55
maybe2
cirospaciari Sep 10, 2025
ec1fc80
use bool instead of i32 here
cirospaciari Sep 10, 2025
1c0ae14
lets go back and test it again
cirospaciari Sep 10, 2025
09099b3
test without microtask
cirospaciari Sep 10, 2025
6d789e2
opsie
cirospaciari Sep 10, 2025
75fde6c
more
cirospaciari Sep 10, 2025
bca76bf
opsie
cirospaciari Sep 10, 2025
32d5797
opsie
cirospaciari Sep 10, 2025
e557195
opsie
cirospaciari Sep 10, 2025
7d7c3da
more
cirospaciari Sep 10, 2025
2cc90a7
more
cirospaciari Sep 10, 2025
8eb6b93
revert this
cirospaciari Sep 10, 2025
1a5660b
Merge branch 'main' into ciro/fix-onclose
Jarred-Sumner Sep 10, 2025
477aa56
Ciro/fix onclose refactor (#22556)
cirospaciari Sep 10, 2025
a9a56e6
Merge branch 'main' into ciro/fix-onclose
cirospaciari Sep 10, 2025
8a64dd8
more
cirospaciari Sep 11, 2025
61bd3e6
Merge branch 'main' into ciro/fix-onclose
cirospaciari Sep 11, 2025
155f0a8
Merge branch 'main' into ciro/fix-onclose
cirospaciari Sep 11, 2025
07631e0
test
cirospaciari Sep 11, 2025
00ce084
opsie
cirospaciari Sep 11, 2025
bb85cc4
allow no asyncContext
cirospaciari Sep 11, 2025
e5cc5d5
fix test-queue-microtask
cirospaciari Sep 11, 2025
6cc1e75
Merge branch 'main' into ciro/fix-onclose
cirospaciari Sep 11, 2025
019ccc3
queueMicrotask again
cirospaciari Sep 11, 2025
324c72c
more
cirospaciari Sep 11, 2025
5ddc772
opsie
cirospaciari Sep 11, 2025
a39179a
remove allowGC
cirospaciari Sep 11, 2025
2b66c6f
opsie
cirospaciari Sep 11, 2025
ca80e07
remove .zero from JSref
cirospaciari Sep 11, 2025
b4a9f5f
no need to use tryGet if we have the callframe this value
cirospaciari Sep 11, 2025
b616fe1
wip
cirospaciari Sep 11, 2025
2bd01af
fix js tag
cirospaciari Sep 11, 2025
4400f39
dont do weird stuff
cirospaciari Sep 11, 2025
d83103f
actually handle the exceptions here
cirospaciari Sep 11, 2025
a6d7492
dont make it an impossible to catch error
cirospaciari Sep 11, 2025
c226a94
dont touch JS in the finalizer
cirospaciari Sep 12, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions src/bun.js/api/server.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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| {
Expand Down
2 changes: 1 addition & 1 deletion src/bun.js/api/server/RequestContext.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
3 changes: 1 addition & 2 deletions src/bun.js/api/sql.classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ for (const type of types) {
construct: true,
finalize: true,
configurable: false,
hasPendingActivity: true,
hasPendingActivity: type === "PostgresSQL",
klass: {
// escapeString: {
// fn: "escapeString",
Expand Down Expand Up @@ -60,7 +60,6 @@ for (const type of types) {
construct: true,
finalize: true,
configurable: false,

JSType: "0b11101110",
klass: {},
proto: {
Expand Down
43 changes: 34 additions & 9 deletions src/bun.js/bindings/JSRef.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,15 @@ pub const JSRef = union(enum) {
}

pub fn initStrong(value: jsc.JSValue, globalThis: *jsc.JSGlobalObject) @This() {
bun.assert(value != .zero);
return .{ .strong = .create(value, globalThis) };
}

pub fn empty() @This() {
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(),
Expand All @@ -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;
Expand All @@ -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);
},
}
}
Comment thread
cirospaciari marked this conversation as resolved.
Resolved

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 => {
Expand Down
17 changes: 16 additions & 1 deletion src/bun.js/bindings/ZigGlobalObject.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1548,9 +1548,18 @@ 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(!callback.isEmpty(), "Invalid microtask callback");
#endif

if (asyncContext.isEmpty()) {
asyncContext = JSC::jsUndefined();
}

// This is a JSC builtin function
lexicalGlobalObject->queueMicrotask(globalObject->performMicrotaskFunction(), callback, asyncContext,
lexicalGlobalObject->queueMicrotask(function, callback, asyncContext,
JSC::JSValue {}, JSC::JSValue {});

return JSC::JSValue::encode(JSC::jsUndefined());
Expand Down Expand Up @@ -4147,6 +4156,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<double>(reinterpret_cast<uintptr_t>(ptr))), JSValue(std::bit_cast<double>(reinterpret_cast<uintptr_t>(callback))), jsUndefined(), jsUndefined());
}
Expand Down
29 changes: 25 additions & 4 deletions src/bun.js/bindings/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -3463,10 +3464,28 @@ 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<Zig::GlobalObject*>(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(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);
Expand Down Expand Up @@ -6121,8 +6140,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());
Expand All @@ -6139,10 +6159,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]),
Expand Down
12 changes: 10 additions & 2 deletions src/codegen/bundle-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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(
Expand Down
30 changes: 15 additions & 15 deletions src/js/bun/sql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
};
Comment thread
cirospaciari marked this conversation as resolved.
Resolved
Expand Down Expand Up @@ -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;

Expand All @@ -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;
Expand All @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
Expand All @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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;

Expand All @@ -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;
Expand All @@ -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()) {
Expand Down
Loading