Skip to content

Commit

Permalink
Add PessimisticallyCalculateMaxWritableSpace
Browse files Browse the repository at this point in the history
Signed-off-by: Andre Kurait <[email protected]>
  • Loading branch information
AndreKurait committed May 3, 2024
1 parent 1b66165 commit 0325b24
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,14 @@ public static int calculateMaxWritableSpace(int totalAvailableSpace, int request
return Math.min(maxWriteBytesSpace, requestedWriteableSpace);
}

// Similar to calculateMaxWritableSpace but perform pessimistic calculation with fewer operations. In some cases returns
// up to 1 byte fewer than what could be written out of the available space.
public static int pessimisticallyCalculateMaxWritableSpace(int totalAvailableSpace, int requestedWriteableSpace) {
final int pessimisticLengthFieldSpace = CodedOutputStream.computeUInt32SizeNoTag(totalAvailableSpace);
int maxWriteBytesSpace = totalAvailableSpace - pessimisticLengthFieldSpace;
return Math.min(maxWriteBytesSpace, requestedWriteableSpace);
}

private void readByteBufIntoCurrentStream(int fieldNum, ByteBuf buf) throws IOException {
var codedOutputStream = getOrCreateCodedOutputStream();
if (buf.readableBytes() > 0) {
Expand Down Expand Up @@ -346,7 +354,7 @@ private void addDataMessage(int captureFieldNumber, int dataFieldNumber, Instant
while(readBuffer.readableBytes() > 0) {
// addSubstreamMessage will write until COS limit and flush prior if needed
spaceLeft = currentOutputStreamWriteableSpaceLeft();
var bytesToRead = calculateMaxWritableSpace(spaceLeft - trafficStreamOverhead, readBuffer.readableBytes());
var bytesToRead = pessimisticallyCalculateMaxWritableSpace(spaceLeft - trafficStreamOverhead, readBuffer.readableBytes());
if (bytesToRead <= 0) {
throw new IllegalStateException("Stream space is not allowing forward progress on byteBuf reading");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,15 @@ public void testCalculateMaxWritableSpace(int totalAvailableSpace, int requested
- (calculatedMaxWritableSpace + 1);
Assertions.assertTrue(expectedSpaceLeftAfterWriteIfOneMoreByteWrote < 0, "expected no space to write one more byte");
}

// Test that when PessimisticallyCalculateMaxWritableSpace != calculatedMaxWritableSpace, then
// it is positive and equal to calculateMaxWritableSpace - 1
var pessimisticWriteableSpace = StreamChannelConnectionCaptureSerializer.pessimisticallyCalculateMaxWritableSpace(totalAvailableSpace,
requestedWriteableSpace);
if (pessimisticWriteableSpace != calculatedMaxWritableSpace) {
Assertions.assertTrue(pessimisticWriteableSpace > 0);
Assertions.assertEquals(calculatedMaxWritableSpace - 1, pessimisticWriteableSpace);
}
}

@Test
Expand Down

0 comments on commit 0325b24

Please sign in to comment.