GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — netty: create adaptive cumulator · grpc/grpc-java@0be7b25

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • netty/src
    • main/java/io/grpc/netty
      • GrpcHttp2ConnectionHandler.java
      • NettyAdaptiveCumulator.java
    • test/java/io/grpc/netty
      • NettyAdaptiveCumulatorTest.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎netty/src/main/java/io/grpc/netty/GrpcHttp2ConnectionHandler.java‎

Copy file name to clipboardExpand all lines: netty/src/main/java/io/grpc/netty/GrpcHttp2ConnectionHandler.java
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
*/
3232
@Internal
3333
public abstract class GrpcHttp2ConnectionHandler extends Http2ConnectionHandler {
34+
protected static final int CUMULATOR_COMPOSE_MIN_SIZE = 1024;
3435

3536
@Nullable
3637
protected final ChannelPromise channelUnused;
@@ -42,6 +43,7 @@ protected GrpcHttp2ConnectionHandler(
4243
Http2Settings initialSettings) {
4344
super(decoder, encoder, initialSettings);
4445
this.channelUnused = channelUnused;
46+
setCumulator(new NettyAdaptiveCumulator(CUMULATOR_COMPOSE_MIN_SIZE));
4547
}
4648

4749
/**
Collapse file

‎netty/src/main/java/io/grpc/netty/NettyAdaptiveCumulator.java‎

Copy file name to clipboard
+177Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
/*
2+
* Copyright 2020 The gRPC Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package io.grpc.netty;
18+
19+
import com.google.common.annotations.VisibleForTesting;
20+
import com.google.common.base.Preconditions;
21+
import io.netty.buffer.ByteBuf;
22+
import io.netty.buffer.ByteBufAllocator;
23+
import io.netty.buffer.CompositeByteBuf;
24+
25+
class NettyAdaptiveCumulator implements io.netty.handler.codec.ByteToMessageDecoder.Cumulator {
26+
private final int composeMinSize;
27+
28+
NettyAdaptiveCumulator(int composeMinSize) {
29+
Preconditions.checkArgument(composeMinSize >= 0, "composeMinSize must be non-negative");
30+
this.composeMinSize = composeMinSize;
31+
}
32+
33+
/**
34+
* "Adaptive" cumulator: cumulate {@link ByteBuf}s by dynamically switching between merge and
35+
* compose strategies.
36+
*
37+
* <p>This cumulator applies a heuristic to make a decision whether to track a reference to the
38+
* buffer with bytes received from the network stack in an array ("zero-copy"), or to merge it
39+
* with merge into the last component (the tail) and appending the incoming buffer by performing
40+
* memory copy.
41+
*
42+
* <p>It is necessary as a protection from a potential attack on the COMPOSITE_CUMULATOR.
43+
* Consider a pathological case when an attacker sends TCP packages containing a single byte of
44+
* data, and forcing to track each one in a separate buffer. In this case we'll be paying a memory
45+
* overhead for each buffer, as well as extra compute to read the cumulation.
46+
*
47+
* <p>Implemented heuristic establishes minimal threshold for the total size of the tail and
48+
* incoming buffer, below which they are merged. The sum of the tail and the incoming buffer is
49+
* used to avoid a case where attacker alternates the size of data packets to trick the cumulator
50+
* into always selecting compose strategy.
51+
*/
52+
@Override
53+
@SuppressWarnings("ReferenceEquality")
54+
public final ByteBuf cumulate(ByteBufAllocator alloc, ByteBuf cumulation, ByteBuf in) {
55+
if (!cumulation.isReadable()) {
56+
cumulation.release();
57+
return in;
58+
}
59+
CompositeByteBuf composite = null;
60+
try {
61+
if (cumulation instanceof CompositeByteBuf && cumulation.refCnt() == 1) {
62+
composite = (CompositeByteBuf) cumulation;
63+
// Writer index must equal capacity if we are going to "write"
64+
// new components to the end
65+
if (composite.writerIndex() != composite.capacity()) {
66+
composite.capacity(composite.writerIndex());
67+
}
68+
} else {
69+
composite = alloc.compositeBuffer(Integer.MAX_VALUE)
70+
.addFlattenedComponents(true, cumulation);
71+
}
72+
addInput(alloc, composite, in);
73+
in = null;
74+
return composite;
75+
} finally {
76+
if (in != null) {
77+
// We must release if the ownership was not transferred as otherwise it may produce a leak
78+
in.release();
79+
// Also release any new buffer allocated if we're not returning it
80+
if (composite != null && composite != cumulation) {
81+
composite.release();
82+
}
83+
}
84+
}
85+
}
86+
87+
@VisibleForTesting
88+
void addInput(ByteBufAllocator alloc, CompositeByteBuf composite, ByteBuf in) {
89+
if (shouldCompose(composite, in, composeMinSize)) {
90+
composite.addFlattenedComponents(true, in);
91+
} else {
92+
// The total size of the new data and the last component are below the threshold. Merge them.
93+
mergeWithCompositeTail(alloc, composite, in);
94+
}
95+
}
96+
97+
@VisibleForTesting
98+
static boolean shouldCompose(CompositeByteBuf composite, ByteBuf in, int composeMinSize) {
99+
int componentCount = composite.numComponents();
100+
if (composite.numComponents() == 0) {
101+
return true;
102+
}
103+
int tailSize = composite.capacity() - composite.toByteIndex(componentCount - 1);
104+
return tailSize + in.readableBytes() >= composeMinSize;
105+
}
106+
107+
/**
108+
* Append the given {@link ByteBuf} {@code in} to {@link CompositeByteBuf} {@code composite} by
109+
* expanding or replacing the tail component of the {@link CompositeByteBuf}.
110+
*
111+
* <p>The goal is to prevent {@code O(n^2)} runtime in a pathological case, that forces copying
112+
* the tail component into a new buffer, for each incoming single-byte buffer. We append the new
113+
* bytes to the tail, when a write (or a fast write) is possible.
114+
*
115+
* <p>Otherwise, the tail is replaced with a new buffer, with the capacity increased enough to
116+
* achieve runtime amortization.
117+
*
118+
* <p>We assume that implementations of {@link ByteBufAllocator#calculateNewCapacity(int, int)},
119+
* are similar to {@link io.netty.buffer.AbstractByteBufAllocator#calculateNewCapacity(int, int)},
120+
* which doubles buffer capacity by normalizing it to the closest power of two. This assumption
121+
* is verified in unit tests for this method.
122+
*/
123+
@VisibleForTesting
124+
static void mergeWithCompositeTail(ByteBufAllocator alloc, CompositeByteBuf composite,
125+
ByteBuf in) {
126+
127+
int newBytes = in.readableBytes();
128+
int tailIndex = composite.numComponents() - 1;
129+
int tailStart = composite.toByteIndex(tailIndex);
130+
int tailBytes = composite.capacity() - tailStart;
131+
int totalBytes = newBytes + tailBytes;
132+
133+
ByteBuf tail = composite.component(tailIndex);
134+
ByteBuf merged = null;
135+
136+
try {
137+
if (tail.refCnt() == 1 && !tail.isReadOnly() && totalBytes <= tail.maxCapacity()) {
138+
// Ideal case: the tail isn't shared, and can be expanded to the required capacity.
139+
// Take ownership of the tail.
140+
merged = tail.retainedDuplicate();
141+
merged = merged.unwrap();
142+
// The tail is a readable non-composite buffer, so writeBytes() handles everything for us.
143+
// - ensureWritable() performs a fast resize when possible (f.e. PooledByteBuf's simply
144+
// updates its boundary to the end of consecutive memory run assigned to this buffer)
145+
// - when the required size doesn't fit into maxFastWritableBytes(), a new buffer is
146+
// allocated, and the capacity calculated with alloc.calculateNewCapacity()
147+
merged.writeBytes(in);
148+
} else {
149+
// The tail is shared, or not expandable. Replace it with a new buffer of desired capacity.
150+
merged = alloc.buffer(alloc.calculateNewCapacity(totalBytes, Integer.MAX_VALUE));
151+
merged.setBytes(0, composite, tailStart, tailBytes)
152+
.setBytes(tailBytes, in, in.readerIndex(), newBytes)
153+
.writerIndex(totalBytes);
154+
in.readerIndex(in.writerIndex());
155+
}
156+
// Store readerIndex to avoid out of bounds writerIndex during component replacement.
157+
int prevReader = composite.readerIndex();
158+
// Remove the tail, reset writer index, add merged component.
159+
composite.removeComponent(tailIndex).setIndex(0, tailStart)
160+
.addFlattenedComponents(true, merged);
161+
merged = null;
162+
in.release();
163+
in = null;
164+
// Restore the reader.
165+
composite.readerIndex(prevReader);
166+
} finally {
167+
// Input buffer was merged with the tail.
168+
if (in != null) {
169+
in.release();
170+
}
171+
// If merge's ownership isn't transferred to the composite buf, release it to prevent a leak.
172+
if (merged != null) {
173+
merged.release();
174+
}
175+
}
176+
}
177+
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.