This commit is contained in:
Alistair Smith
2025-05-30 15:09:56 -07:00
parent 53958f369d
commit c663ccd83b
3 changed files with 31 additions and 0 deletions

View File

@@ -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<uint32_t>(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();

View File

@@ -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<bool isSSL>
us_socket_context_t* webSocketContext()
{

View File

@@ -184,6 +184,16 @@ ExceptionOr<void> 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 {};
}