Skip to content

Commit fe335db

Browse files
committed
fix: empty macroTask
1 parent 9597e5c commit fe335db

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

src/proxy.ts

+15-3
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ const useMicrotask = true
3333
// Client to relay socket data
3434
export type C2RSocketData = {
3535
connId: number // 连接 ID,连接建立时随机分配,用于日志
36+
hasPendingMacroTask: boolean, // 是否有未完成的宏任务
3637
sendBuffer: ArrayBufferSink // 发送缓冲区
3738
ppStream: ProxyProtocolPacketStream // Proxy Protocol v2 解包流
3839
C2RStream: MinecraftPacketStream // 用于解包握手和登录包
@@ -53,6 +54,7 @@ export type C2RSocketData = {
5354
// Relay to server socket data
5455
type R2SSocketData = {
5556
client: Bun.Socket<C2RSocketData> | null // 客户端连接
57+
hasPendingMacroTask: boolean, // 是否有未完成的宏任务
5658
sendBuffer: ArrayBufferSink // 发送缓冲区
5759
timeouts: NodeJS.Timer[] // 存储所有的 timeout
5860
}
@@ -62,20 +64,28 @@ const writeToBuffer = (
6264
buffer: Buffer,
6365
) => {
6466
socket.data.sendBuffer.write(buffer)
65-
if (useMicrotask) queueMicrotask(() => sendBuffer(socket))
66-
else sendBuffer(socket)
67+
if (useMicrotask) {
68+
if (!socket.data.hasPendingMacroTask) {
69+
socket.data.hasPendingMacroTask = true
70+
queueMicrotask(() => sendBuffer(socket))
71+
}
72+
} else sendBuffer(socket)
6773
}
6874

6975
const sendBuffer = (
7076
socket: Bun.Socket<C2RSocketData> | Bun.Socket<R2SSocketData>,
7177
) => {
7278
if (socket.data.sendBuffer) {
7379
const data = socket.data.sendBuffer.flush() as Uint8Array
74-
if (!data) return
80+
if (!data) {
81+
socket.data.hasPendingMacroTask = false
82+
return
83+
}
7584
const written = socket.write(data)
7685
if (written < data.byteLength) {
7786
socket.data.sendBuffer.write(data.subarray(written))
7887
}
88+
socket.data.hasPendingMacroTask = false
7989
}
8090
}
8191

@@ -147,6 +157,7 @@ export class MinecraftProxy {
147157
open: async remoteSocket => {
148158
remoteSocket.data = {
149159
client: clientSocket,
160+
hasPendingMacroTask: false,
150161
sendBuffer: new ArrayBufferSink(),
151162
timeouts: [],
152163
}
@@ -223,6 +234,7 @@ export class MinecraftProxy {
223234
open: clientSocket => {
224235
clientSocket.data = {
225236
connId: Math.floor(Math.random() * 100000),
237+
hasPendingMacroTask: false,
226238
sendBuffer: new ArrayBufferSink(),
227239
ppStream: new ProxyProtocolPacketStream(),
228240
C2RStream: new MinecraftPacketStream(),

0 commit comments

Comments
 (0)