From c663ccd83bd2dad8c54151d64831ebbb368f77cb Mon Sep 17 00:00:00 2001 From: Alistair Smith Date: Fri, 30 May 2025 15:09:56 -0700 Subject: [PATCH] 1 --- .../bindings/ScriptExecutionContext.cpp | 19 +++++++++++++++++++ src/bun.js/bindings/ScriptExecutionContext.h | 2 ++ src/bun.js/bindings/webcore/MessagePort.cpp | 10 ++++++++++ 3 files changed, 31 insertions(+) diff --git a/src/bun.js/bindings/ScriptExecutionContext.cpp b/src/bun.js/bindings/ScriptExecutionContext.cpp index fbd519eada..0c573408af 100644 --- a/src/bun.js/bindings/ScriptExecutionContext.cpp +++ b/src/bun.js/bindings/ScriptExecutionContext.cpp @@ -122,6 +122,25 @@ void ScriptExecutionContext::unrefEventLoop() Bun__eventLoop__incrementRefConcurrently(WebCore::clientData(vm())->bunVM, -1); } +bool ScriptExecutionContext::canSendMessage() +{ + us_loop_t* loop = (us_loop_t*)uws_get_loop(); + uint32_t currentTickNr = static_cast(us_loop_iteration_number(loop)); + + if (lastSendTickNr != currentTickNr) { + messagesSentThisTick = 0; + lastSendTickNr = currentTickNr; + } + + constexpr uint32_t MAX_MESSAGES_PER_TICK = 1000; + if (messagesSentThisTick >= MAX_MESSAGES_PER_TICK) { + return false; + } + + messagesSentThisTick++; + return true; +} + ScriptExecutionContext::~ScriptExecutionContext() { checkConsistency(); diff --git a/src/bun.js/bindings/ScriptExecutionContext.h b/src/bun.js/bindings/ScriptExecutionContext.h index 874f3a3892..4d36305f2a 100644 --- a/src/bun.js/bindings/ScriptExecutionContext.h +++ b/src/bun.js/bindings/ScriptExecutionContext.h @@ -63,6 +63,8 @@ public: uint32_t lastSendTickNr = -1; // Will be updated to the us_loop_t->data.iteration_nr every tick we send a message in // https://github.com/oven-sh/bun/blob/d7a517cdfc31705a6b4fb696dc834ba8d98d5d3a/packages/bun-usockets/src/internal/loop_data.h#L58 + bool canSendMessage(); + template us_socket_context_t* webSocketContext() { diff --git a/src/bun.js/bindings/webcore/MessagePort.cpp b/src/bun.js/bindings/webcore/MessagePort.cpp index f70a7b5bdf..f0973054c2 100644 --- a/src/bun.js/bindings/webcore/MessagePort.cpp +++ b/src/bun.js/bindings/webcore/MessagePort.cpp @@ -184,6 +184,16 @@ ExceptionOr MessagePort::postMessage(JSC::JSGlobalObject& state, JSC::JSVa MessageWithMessagePorts message { messageData.releaseReturnValue(), WTFMove(transferredPorts) }; + auto* context = scriptExecutionContext(); + if (!context->canSendMessage()) { + context->postImmediateCppTask([protectedThis = Ref { *this }, message = WTFMove(message)](ScriptExecutionContext& ctx) mutable { + if (protectedThis->isEntangled()) { + MessagePortChannelProvider::fromContext(ctx).postMessageToRemote(WTFMove(message), protectedThis->m_remoteIdentifier); + } + }); + return {}; + } + MessagePortChannelProvider::fromContext(*protectedScriptExecutionContext()).postMessageToRemote(WTFMove(message), m_remoteIdentifier); return {}; }