From bd77afb2df0ef0a44192c5dcc625f719e948d5be Mon Sep 17 00:00:00 2001 From: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com> Date: Fri, 16 Sep 2022 22:36:06 -0700 Subject: [PATCH] Fix issue with server not starting before exiting --- src/bun.js/api/server.zig | 2 ++ src/bun.js/event_loop.zig | 6 ++++-- src/bun.js/javascript.zig | 4 ++++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index 55b829caa3..8381a15bd6 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -2053,6 +2053,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type { if (this.keeping_js_alive) return; this.vm.us_loop_reference_count +|= 1; + this.vm.eventLoop().start_server_on_next_tick = true; this.keeping_js_alive = true; } @@ -2060,6 +2061,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type { if (!this.keeping_js_alive) return; this.vm.us_loop_reference_count -|= 1; + this.vm.eventLoop().start_server_on_next_tick = false; this.keeping_js_alive = false; } diff --git a/src/bun.js/event_loop.zig b/src/bun.js/event_loop.zig index 6a6107b05a..1907838d02 100644 --- a/src/bun.js/event_loop.zig +++ b/src/bun.js/event_loop.zig @@ -209,6 +209,7 @@ pub const EventLoop = struct { global: *JSGlobalObject = undefined, virtual_machine: *VirtualMachine = undefined, waker: ?AsyncIO.Waker = null, + start_server_on_next_tick: bool = false, defer_count: std.atomic.Atomic(usize) = std.atomic.Atomic(usize).init(0), pub const Queue = std.fifo.LinearFifo(Task, .Dynamic); @@ -353,16 +354,17 @@ pub const EventLoop = struct { ctx.global.vm().releaseWeakRefs(); ctx.global.vm().drainMicrotasks(); - if (ctx.us_loop_reference_count > 0 and !ctx.is_us_loop_entered) { + if (ctx.us_loop_reference_count > 0 and !ctx.is_us_loop_entered and (ctx.uws_event_loop.?.num_polls > 0 or this.start_server_on_next_tick)) { if (this.tickConcurrentWithCount() > 0) { this.tick(); - } else if (ctx.uws_event_loop.?.num_polls > 0) { + } else { if ((@intCast(c_ulonglong, ctx.uws_event_loop.?.internal_loop_data.iteration_nr) % 1_000) == 1) { _ = ctx.global.vm().runGC(true); } } ctx.is_us_loop_entered = true; + this.start_server_on_next_tick = false; ctx.enterUWSLoop(); ctx.is_us_loop_entered = false; } diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig index 5a085af013..d52a864a91 100644 --- a/src/bun.js/javascript.zig +++ b/src/bun.js/javascript.zig @@ -1456,6 +1456,10 @@ pub const VirtualMachine = struct { this.waitForPromise(promise); + if (this.eventLoop().start_server_on_next_tick) { + this.enterUWSLoop(); + } + return promise; }