Skip to content

Commit ac7045b

Browse files
committed
fix: WebSocketOutputStream wait to write until WebSocket queue is released
Signed-off-by: Daniel Arteaga Barba <[email protected]>
1 parent 6d39601 commit ac7045b

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

util/src/main/java/io/kubernetes/client/util/WebSocketStreamHandler.java

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,13 @@ private synchronized OutputStream getSocketInputOutputStream(int stream) {
209209
}
210210

211211
private class WebSocketOutputStream extends OutputStream {
212+
213+
private static final long WEB_SOCKET_MAX_QUEUE_SIZE = 16L * 1024 * 1024;
214+
215+
private static final int WEB_SOCKET_MAX_QUEUE_SIZE_MAX_ATTEMPTS = 15;
216+
217+
private static final int WEB_SOCKET_MAX_QUEUE_SIZE_WAIT_MILLISECONDS = 1000;
218+
212219
private final byte stream;
213220

214221
public WebSocketOutputStream(int stream) {
@@ -265,10 +272,25 @@ public void write(byte[] b, int offset, int length) throws IOException {
265272
int bufferSize = Math.min(remaining, 15 * 1024 * 1024);
266273
byte[] buffer = new byte[bufferSize + 1];
267274
buffer[0] = stream;
275+
268276
System.arraycopy(b, offset + bytesWritten, buffer, 1, bufferSize);
269-
if (!WebSocketStreamHandler.this.socket.send(ByteString.of(buffer))) {
277+
ByteString byteString = ByteString.of(buffer);
278+
279+
int attempts = 0;
280+
while (WebSocketStreamHandler.this.socket.queueSize() + byteString.size() > WEB_SOCKET_MAX_QUEUE_SIZE
281+
&& attempts < WEB_SOCKET_MAX_QUEUE_SIZE_MAX_ATTEMPTS) {
282+
try {
283+
Thread.sleep(WEB_SOCKET_MAX_QUEUE_SIZE_WAIT_MILLISECONDS);
284+
attempts ++;
285+
} catch (InterruptedException e) {
286+
throw new IOException("Error waiting web socket queue", e);
287+
}
288+
}
289+
290+
if (!WebSocketStreamHandler.this.socket.send(byteString)) {
270291
throw new IOException("WebSocket has closed.");
271292
}
293+
272294
bytesWritten += bufferSize;
273295
remaining -= bufferSize;
274296
}

0 commit comments

Comments
 (0)