Skip to content

Commit 5675b62

Browse files
author
Paul Hohensee
committed
8343855: HTTP/2 ConnectionWindowUpdateSender may miss some unprocessed DataFrames from closed streams
Reviewed-by: rkennke Backport-of: bd6152f5967107d7b32db9bcfa224fc07314f098
1 parent 67c4a08 commit 5675b62

File tree

5 files changed

+179
-39
lines changed

5 files changed

+179
-39
lines changed

src/java.net.http/share/classes/jdk/internal/net/http/Stream.java

+58-13
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,10 @@ class Stream<T> extends ExchangeImpl<T> {
160160
// send lock: prevent sending DataFrames after reset occurred.
161161
private final Lock sendLock = new ReentrantLock();
162162
private final Lock stateLock = new ReentrantLock();
163+
// inputQ lock: methods that take from the inputQ
164+
// must not run concurrently.
165+
private final Lock inputQLock = new ReentrantLock();
166+
163167
/**
164168
* A reference to this Stream's connection Send Window controller. The
165169
* stream MUST acquire the appropriate amount of Send Window before
@@ -180,6 +184,8 @@ HttpConnection connection() {
180184
private void schedule() {
181185
boolean onCompleteCalled = false;
182186
HttpResponse.BodySubscriber<T> subscriber = responseSubscriber;
187+
// prevents drainInputQueue() from running concurrently
188+
inputQLock.lock();
183189
try {
184190
if (subscriber == null) {
185191
subscriber = responseSubscriber = pendingResponseSubscriber;
@@ -197,7 +203,7 @@ private void schedule() {
197203
handleReset(rf, subscriber);
198204
return;
199205
}
200-
DataFrame df = (DataFrame)frame;
206+
DataFrame df = (DataFrame) frame;
201207
boolean finished = df.getFlag(DataFrame.END_STREAM);
202208

203209
List<ByteBuffer> buffers = df.getData();
@@ -247,6 +253,7 @@ private void schedule() {
247253
} catch (Throwable throwable) {
248254
errorRef.compareAndSet(null, throwable);
249255
} finally {
256+
inputQLock.unlock();
250257
if (sched.isStopped()) drainInputQueue();
251258
}
252259

@@ -265,26 +272,36 @@ private void schedule() {
265272
} catch (Throwable x) {
266273
Log.logError("Subscriber::onError threw exception: {0}", t);
267274
} finally {
275+
// cancelImpl will eventually call drainInputQueue();
268276
cancelImpl(t);
269-
drainInputQueue();
270277
}
271278
}
272279
}
273280

274-
// must only be called from the scheduler schedule() loop.
275-
// ensure that all received data frames are accounted for
281+
// Called from the scheduler schedule() loop,
282+
// or after resetting the stream.
283+
// Ensures that all received data frames are accounted for
276284
// in the connection window flow control if the scheduler
277285
// is stopped before all the data is consumed.
286+
// The inputQLock is used to prevent concurrently taking
287+
// from the queue.
278288
private void drainInputQueue() {
279289
Http2Frame frame;
280-
while ((frame = inputQ.poll()) != null) {
281-
if (frame instanceof DataFrame df) {
282-
// Data frames that have been added to the inputQ
283-
// must be released using releaseUnconsumed() to
284-
// account for the amount of unprocessed bytes
285-
// tracked by the connection.windowUpdater.
286-
connection.releaseUnconsumed(df);
290+
// will wait until schedule() has finished taking
291+
// from the queue, if needed.
292+
inputQLock.lock();
293+
try {
294+
while ((frame = inputQ.poll()) != null) {
295+
if (frame instanceof DataFrame df) {
296+
// Data frames that have been added to the inputQ
297+
// must be released using releaseUnconsumed() to
298+
// account for the amount of unprocessed bytes
299+
// tracked by the connection.windowUpdater.
300+
connection.releaseUnconsumed(df);
301+
}
287302
}
303+
} finally {
304+
inputQLock.unlock();
288305
}
289306
}
290307

@@ -396,12 +413,38 @@ private void receiveDataFrame(DataFrame df) {
396413
return;
397414
}
398415
}
399-
inputQ.add(df);
416+
pushDataFrame(len, df);
400417
} finally {
401418
sched.runOrSchedule();
402419
}
403420
}
404421

422+
// Ensures that no data frame is pushed on the inputQ
423+
// after the stream is closed.
424+
// Changes to the `closed` boolean are guarded by the
425+
// stateLock. Contention should be low as only one
426+
// thread at a time adds to the inputQ, and
427+
// we can only contend when closing the stream.
428+
// Note that this method can run concurrently with
429+
// methods holding the inputQLock: that is OK.
430+
// The inputQLock is there to ensure that methods
431+
// taking from the queue are not running concurrently
432+
// with each others, but concurrently adding at the
433+
// end of the queue while peeking/polling at the head
434+
// is OK.
435+
private void pushDataFrame(int len, DataFrame df) {
436+
boolean closed = false;
437+
stateLock.lock();
438+
try {
439+
if (!(closed = this.closed)) {
440+
inputQ.add(df);
441+
}
442+
} finally {
443+
stateLock.unlock();
444+
}
445+
if (closed && len > 0) connection.releaseUnconsumed(df);
446+
}
447+
405448
/** Handles a RESET frame. RESET is always handled inline in the queue. */
406449
private void receiveResetFrame(ResetFrame frame) {
407450
inputQ.add(frame);
@@ -1510,6 +1553,8 @@ void cancelImpl(final Throwable e, final int resetFrameErrCode) {
15101553
}
15111554
} catch (Throwable ex) {
15121555
Log.logError(ex);
1556+
} finally {
1557+
drainInputQueue();
15131558
}
15141559
}
15151560

@@ -1733,7 +1778,7 @@ String dbgString() {
17331778
@Override
17341779
protected boolean windowSizeExceeded(long received) {
17351780
onProtocolError(new ProtocolException("stream %s flow control window exceeded"
1736-
.formatted(streamid)), ResetFrame.FLOW_CONTROL_ERROR);
1781+
.formatted(streamid)), ResetFrame.FLOW_CONTROL_ERROR);
17371782
return true;
17381783
}
17391784
}

test/jdk/java/net/httpclient/http2/ConnectionFlowControlTest.java

+5-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,11 @@ void test(String uri) throws Exception {
171171
var response = responses.get(keys[i]);
172172
String ckey = response.headers().firstValue("X-Connection-Key").get();
173173
if (label == null) label = ckey;
174-
assertEquals(ckey, label, "Unexpected key for " + query);
174+
if (i < max - 1) {
175+
// the connection window might be exceeded at i == max - 2, which
176+
// means that the last request could go on a new connection.
177+
assertEquals(ckey, label, "Unexpected key for " + query);
178+
}
175179
int wait = uri.startsWith("https://") ? 500 : 250;
176180
try (InputStream is = response.body()) {
177181
Thread.sleep(Utils.adjustTimeout(wait));

test/jdk/java/net/httpclient/http2/StreamFlowControlTest.java

+56-16
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
/*
2525
* @test
26-
* @bug 8342075
26+
* @bug 8342075 8343855
2727
* @library /test/lib /test/jdk/java/net/httpclient/lib
2828
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
2929
* @run testng/othervm -Djdk.internal.httpclient.debug=true
@@ -40,7 +40,6 @@
4040
import java.net.http.HttpClient;
4141
import java.net.http.HttpHeaders;
4242
import java.net.http.HttpRequest;
43-
import java.net.http.HttpRequest.BodyPublishers;
4443
import java.net.http.HttpResponse;
4544
import java.net.http.HttpResponse.BodyHandlers;
4645
import java.nio.charset.StandardCharsets;
@@ -53,6 +52,7 @@
5352
import javax.net.ssl.SSLContext;
5453
import javax.net.ssl.SSLSession;
5554

55+
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpHeadOrGetHandler;
5656
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestServer;
5757
import jdk.httpclient.test.lib.http2.BodyOutputStream;
5858
import jdk.httpclient.test.lib.http2.Http2Handler;
@@ -69,6 +69,7 @@
6969
import org.testng.annotations.DataProvider;
7070
import org.testng.annotations.Test;
7171

72+
import static java.util.concurrent.TimeUnit.NANOSECONDS;
7273
import static org.testng.Assert.assertEquals;
7374
import static org.testng.Assert.fail;
7475

@@ -92,6 +93,19 @@ public Object[][] variants() {
9293
};
9394
}
9495

96+
static void sleep(long wait) throws InterruptedException {
97+
if (wait <= 0) return;
98+
long remaining = Utils.adjustTimeout(wait);
99+
long start = System.nanoTime();
100+
while (remaining > 0) {
101+
Thread.sleep(remaining);
102+
long end = System.nanoTime();
103+
remaining = remaining - NANOSECONDS.toMillis(end - start);
104+
}
105+
System.out.printf("Waited %s ms%n",
106+
NANOSECONDS.toMillis(System.nanoTime() - start));
107+
}
108+
95109

96110
@Test(dataProvider = "variants")
97111
void test(String uri,
@@ -115,7 +129,7 @@ void test(String uri,
115129
CompletableFuture<String> sent = new CompletableFuture<>();
116130
responseSent.put(query, sent);
117131
HttpRequest request = HttpRequest.newBuilder(uriWithQuery)
118-
.POST(BodyPublishers.ofString("Hello there!"))
132+
.GET()
119133
.build();
120134
System.out.println("\nSending request:" + uriWithQuery);
121135
final HttpClient cc = client;
@@ -130,9 +144,9 @@ void test(String uri,
130144
// we have to pull to get the exception, but slow enough
131145
// so that DataFrames are buffered up to the point that
132146
// the window is exceeded...
133-
int wait = uri.startsWith("https://") ? 500 : 350;
147+
long wait = uri.startsWith("https://") ? 800 : 350;
134148
try (InputStream is = response.body()) {
135-
Thread.sleep(Utils.adjustTimeout(wait));
149+
sleep(wait);
136150
is.readAllBytes();
137151
}
138152
// we could fail here if we haven't waited long enough
@@ -174,7 +188,7 @@ void testAsync(String uri,
174188
CompletableFuture<String> sent = new CompletableFuture<>();
175189
responseSent.put(query, sent);
176190
HttpRequest request = HttpRequest.newBuilder(uriWithQuery)
177-
.POST(BodyPublishers.ofString("Hello there!"))
191+
.GET()
178192
.build();
179193
System.out.println("\nSending request:" + uriWithQuery);
180194
final HttpClient cc = client;
@@ -188,9 +202,9 @@ void testAsync(String uri,
188202
assertEquals(key, label, "Unexpected key for " + query);
189203
}
190204
sent.join();
191-
int wait = uri.startsWith("https://") ? 600 : 300;
205+
long wait = uri.startsWith("https://") ? 800 : 350;
192206
try (InputStream is = response.body()) {
193-
Thread.sleep(Utils.adjustTimeout(wait));
207+
sleep(wait);
194208
is.readAllBytes();
195209
}
196210
// we could fail here if we haven't waited long enough
@@ -252,7 +266,9 @@ public void setup() throws Exception {
252266
var https2TestServer = new Http2TestServer("localhost", true, sslContext);
253267
https2TestServer.addHandler(new Http2TestHandler(), "/https2/");
254268
this.https2TestServer = HttpTestServer.of(https2TestServer);
269+
this.https2TestServer.addHandler(new HttpHeadOrGetHandler(), "/https2/head/");
255270
https2URI = "https://" + this.https2TestServer.serverAuthority() + "/https2/x";
271+
String h2Head = "https://" + this.https2TestServer.serverAuthority() + "/https2/head/z";
256272

257273
// Override the default exchange supplier with a custom one to enable
258274
// particular test scenarios
@@ -261,6 +277,13 @@ public void setup() throws Exception {
261277

262278
this.http2TestServer.start();
263279
this.https2TestServer.start();
280+
281+
// warmup to eliminate delay due to SSL class loading and initialization.
282+
try (var client = HttpClient.newBuilder().sslContext(sslContext).build()) {
283+
var request = HttpRequest.newBuilder(URI.create(h2Head)).HEAD().build();
284+
var resp = client.send(request, BodyHandlers.discarding());
285+
assertEquals(resp.statusCode(), 200);
286+
}
264287
}
265288

266289
@AfterTest
@@ -279,11 +302,19 @@ public void handle(Http2TestExchange t) throws IOException {
279302
OutputStream os = t.getResponseBody()) {
280303

281304
byte[] bytes = is.readAllBytes();
282-
System.out.println("Server " + t.getLocalAddress() + " received:\n"
283-
+ t.getRequestURI() + ": " + new String(bytes, StandardCharsets.UTF_8));
305+
if (bytes.length != 0) {
306+
System.out.println("Server " + t.getLocalAddress() + " received:\n"
307+
+ t.getRequestURI() + ": " + new String(bytes, StandardCharsets.UTF_8));
308+
} else {
309+
System.out.println("No request body for " + t.getRequestMethod());
310+
}
311+
284312
t.getResponseHeaders().setHeader("X-Connection-Key", t.getConnectionKey());
285313

286-
if (bytes.length == 0) bytes = "no request body!".getBytes(StandardCharsets.UTF_8);
314+
if (bytes.length == 0) {
315+
bytes = "no request body!"
316+
.repeat(100).getBytes(StandardCharsets.UTF_8);
317+
}
287318
int window = Integer.getInteger("jdk.httpclient.windowsize", 2 * 16 * 1024);
288319
final int maxChunkSize;
289320
if (t instanceof FCHttp2TestExchange fct) {
@@ -307,13 +338,22 @@ public void handle(Http2TestExchange t) throws IOException {
307338
// ignore and continue...
308339
}
309340
}
310-
((BodyOutputStream) os).writeUncontrolled(resp, 0, resp.length);
341+
try {
342+
((BodyOutputStream) os).writeUncontrolled(resp, 0, resp.length);
343+
} catch (IOException x) {
344+
if (t instanceof FCHttp2TestExchange fct) {
345+
fct.conn.updateConnectionWindow(resp.length);
346+
}
347+
}
348+
}
349+
} finally {
350+
if (t instanceof FCHttp2TestExchange fct) {
351+
fct.responseSent(query);
352+
} else {
353+
fail("Exchange is not %s but %s"
354+
.formatted(FCHttp2TestExchange.class.getName(), t.getClass().getName()));
311355
}
312356
}
313-
if (t instanceof FCHttp2TestExchange fct) {
314-
fct.responseSent(query);
315-
} else fail("Exchange is not %s but %s"
316-
.formatted(FCHttp2TestExchange.class.getName(), t.getClass().getName()));
317357
}
318358
}
319359

0 commit comments

Comments
 (0)