Skip to content

Commit 312dfac

Browse files
committed
Backport bd6152f5967107d7b32db9bcfa224fc07314f098
1 parent 4addb57 commit 312dfac

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

Lines changed: 58 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,10 @@ class Stream<T> extends ExchangeImpl<T> {
157157

158158
// send lock: prevent sending DataFrames after reset occurred.
159159
private final Object sendLock = new Object();
160+
// inputQ lock: methods that take from the inputQ
161+
// must not run concurrently.
162+
private final Lock inputQLock = new ReentrantLock();
163+
160164
/**
161165
* A reference to this Stream's connection Send Window controller. The
162166
* stream MUST acquire the appropriate amount of Send Window before
@@ -177,6 +181,8 @@ HttpConnection connection() {
177181
private void schedule() {
178182
boolean onCompleteCalled = false;
179183
HttpResponse.BodySubscriber<T> subscriber = responseSubscriber;
184+
// prevents drainInputQueue() from running concurrently
185+
inputQLock.lock();
180186
try {
181187
if (subscriber == null) {
182188
subscriber = responseSubscriber = pendingResponseSubscriber;
@@ -194,7 +200,7 @@ private void schedule() {
194200
handleReset(rf, subscriber);
195201
return;
196202
}
197-
DataFrame df = (DataFrame)frame;
203+
DataFrame df = (DataFrame) frame;
198204
boolean finished = df.getFlag(DataFrame.END_STREAM);
199205

200206
List<ByteBuffer> buffers = df.getData();
@@ -244,6 +250,7 @@ private void schedule() {
244250
} catch (Throwable throwable) {
245251
errorRef.compareAndSet(null, throwable);
246252
} finally {
253+
inputQLock.unlock();
247254
if (sched.isStopped()) drainInputQueue();
248255
}
249256

@@ -262,26 +269,36 @@ private void schedule() {
262269
} catch (Throwable x) {
263270
Log.logError("Subscriber::onError threw exception: {0}", t);
264271
} finally {
272+
// cancelImpl will eventually call drainInputQueue();
265273
cancelImpl(t);
266-
drainInputQueue();
267274
}
268275
}
269276
}
270277

271-
// must only be called from the scheduler schedule() loop.
272-
// ensure that all received data frames are accounted for
278+
// Called from the scheduler schedule() loop,
279+
// or after resetting the stream.
280+
// Ensures that all received data frames are accounted for
273281
// in the connection window flow control if the scheduler
274282
// is stopped before all the data is consumed.
283+
// The inputQLock is used to prevent concurrently taking
284+
// from the queue.
275285
private void drainInputQueue() {
276286
Http2Frame frame;
277-
while ((frame = inputQ.poll()) != null) {
278-
if (frame instanceof DataFrame df) {
279-
// Data frames that have been added to the inputQ
280-
// must be released using releaseUnconsumed() to
281-
// account for the amount of unprocessed bytes
282-
// tracked by the connection.windowUpdater.
283-
connection.releaseUnconsumed(df);
287+
// will wait until schedule() has finished taking
288+
// from the queue, if needed.
289+
inputQLock.lock();
290+
try {
291+
while ((frame = inputQ.poll()) != null) {
292+
if (frame instanceof DataFrame df) {
293+
// Data frames that have been added to the inputQ
294+
// must be released using releaseUnconsumed() to
295+
// account for the amount of unprocessed bytes
296+
// tracked by the connection.windowUpdater.
297+
connection.releaseUnconsumed(df);
298+
}
284299
}
300+
} finally {
301+
inputQLock.unlock();
285302
}
286303
}
287304

@@ -393,12 +410,38 @@ private void receiveDataFrame(DataFrame df) {
393410
return;
394411
}
395412
}
396-
inputQ.add(df);
413+
pushDataFrame(len, df);
397414
} finally {
398415
sched.runOrSchedule();
399416
}
400417
}
401418

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

@@ -1700,7 +1745,7 @@ String dbgString() {
17001745
@Override
17011746
protected boolean windowSizeExceeded(long received) {
17021747
onProtocolError(new ProtocolException("stream %s flow control window exceeded"
1703-
.formatted(streamid)), ResetFrame.FLOW_CONTROL_ERROR);
1748+
.formatted(streamid)), ResetFrame.FLOW_CONTROL_ERROR);
17041749
return true;
17051750
}
17061751
}

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,11 @@ void test(String uri) throws Exception {
175175
var response = responses.get(keys[i]);
176176
String ckey = response.headers().firstValue("X-Connection-Key").get();
177177
if (label == null) label = ckey;
178-
assertEquals(ckey, label, "Unexpected key for " + query);
178+
if (i < max - 1) {
179+
// the connection window might be exceeded at i == max - 2, which
180+
// means that the last request could go on a new connection.
181+
assertEquals(ckey, label, "Unexpected key for " + query);
182+
}
179183
int wait = uri.startsWith("https://") ? 500 : 250;
180184
try (InputStream is = response.body()) {
181185
Thread.sleep(Utils.adjustTimeout(wait));

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

Lines changed: 56 additions & 16 deletions
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
* jdk.httpclient.test.lib.common.TestServerConfigurator
@@ -41,7 +41,6 @@
4141
import java.net.http.HttpClient;
4242
import java.net.http.HttpHeaders;
4343
import java.net.http.HttpRequest;
44-
import java.net.http.HttpRequest.BodyPublishers;
4544
import java.net.http.HttpResponse;
4645
import java.net.http.HttpResponse.BodyHandlers;
4746
import java.nio.charset.StandardCharsets;
@@ -56,6 +55,7 @@
5655
import javax.net.ssl.SSLContext;
5756
import javax.net.ssl.SSLSession;
5857

58+
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpHeadOrGetHandler;
5959
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestServer;
6060
import jdk.httpclient.test.lib.http2.BodyOutputStream;
6161
import jdk.httpclient.test.lib.http2.Http2Handler;
@@ -72,6 +72,7 @@
7272
import org.testng.annotations.DataProvider;
7373
import org.testng.annotations.Test;
7474

75+
import static java.util.concurrent.TimeUnit.NANOSECONDS;
7576
import static org.testng.Assert.assertEquals;
7677
import static org.testng.Assert.fail;
7778

@@ -95,6 +96,19 @@ public Object[][] variants() {
9596
};
9697
}
9798

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

99113
@Test(dataProvider = "variants")
100114
void test(String uri,
@@ -121,7 +135,7 @@ void test(String uri,
121135
CompletableFuture<String> sent = new CompletableFuture<>();
122136
responseSent.put(query, sent);
123137
HttpRequest request = HttpRequest.newBuilder(uriWithQuery)
124-
.POST(BodyPublishers.ofString("Hello there!"))
138+
.GET()
125139
.build();
126140
System.out.println("\nSending request:" + uriWithQuery);
127141
final HttpClient cc = client;
@@ -136,9 +150,9 @@ void test(String uri,
136150
// we have to pull to get the exception, but slow enough
137151
// so that DataFrames are buffered up to the point that
138152
// the window is exceeded...
139-
int wait = uri.startsWith("https://") ? 500 : 350;
153+
long wait = uri.startsWith("https://") ? 800 : 350;
140154
try (InputStream is = response.body()) {
141-
Thread.sleep(Utils.adjustTimeout(wait));
155+
sleep(wait);
142156
is.readAllBytes();
143157
}
144158
// we could fail here if we haven't waited long enough
@@ -187,7 +201,7 @@ void testAsync(String uri,
187201
CompletableFuture<String> sent = new CompletableFuture<>();
188202
responseSent.put(query, sent);
189203
HttpRequest request = HttpRequest.newBuilder(uriWithQuery)
190-
.POST(BodyPublishers.ofString("Hello there!"))
204+
.GET()
191205
.build();
192206
System.out.println("\nSending request:" + uriWithQuery);
193207
final HttpClient cc = client;
@@ -201,9 +215,9 @@ void testAsync(String uri,
201215
assertEquals(key, label, "Unexpected key for " + query);
202216
}
203217
sent.join();
204-
int wait = uri.startsWith("https://") ? 600 : 300;
218+
long wait = uri.startsWith("https://") ? 800 : 350;
205219
try (InputStream is = response.body()) {
206-
Thread.sleep(Utils.adjustTimeout(wait));
220+
sleep(wait);
207221
is.readAllBytes();
208222
}
209223
// we could fail here if we haven't waited long enough
@@ -269,7 +283,9 @@ public void setup() throws Exception {
269283
var https2TestServer = new Http2TestServer("localhost", true, sslContext);
270284
https2TestServer.addHandler(new Http2TestHandler(), "/https2/");
271285
this.https2TestServer = HttpTestServer.of(https2TestServer);
286+
this.https2TestServer.addHandler(new HttpHeadOrGetHandler(), "/https2/head/");
272287
https2URI = "https://" + this.https2TestServer.serverAuthority() + "/https2/x";
288+
String h2Head = "https://" + this.https2TestServer.serverAuthority() + "/https2/head/z";
273289

274290
// Override the default exchange supplier with a custom one to enable
275291
// particular test scenarios
@@ -278,6 +294,13 @@ public void setup() throws Exception {
278294

279295
this.http2TestServer.start();
280296
this.https2TestServer.start();
297+
298+
// warmup to eliminate delay due to SSL class loading and initialization.
299+
try (var client = HttpClient.newBuilder().sslContext(sslContext).build()) {
300+
var request = HttpRequest.newBuilder(URI.create(h2Head)).HEAD().build();
301+
var resp = client.send(request, BodyHandlers.discarding());
302+
assertEquals(resp.statusCode(), 200);
303+
}
281304
}
282305

283306
@AfterTest
@@ -296,11 +319,19 @@ public void handle(Http2TestExchange t) throws IOException {
296319
OutputStream os = t.getResponseBody()) {
297320

298321
byte[] bytes = is.readAllBytes();
299-
System.out.println("Server " + t.getLocalAddress() + " received:\n"
300-
+ t.getRequestURI() + ": " + new String(bytes, StandardCharsets.UTF_8));
322+
if (bytes.length != 0) {
323+
System.out.println("Server " + t.getLocalAddress() + " received:\n"
324+
+ t.getRequestURI() + ": " + new String(bytes, StandardCharsets.UTF_8));
325+
} else {
326+
System.out.println("No request body for " + t.getRequestMethod());
327+
}
328+
301329
t.getResponseHeaders().setHeader("X-Connection-Key", t.getConnectionKey());
302330

303-
if (bytes.length == 0) bytes = "no request body!".getBytes(StandardCharsets.UTF_8);
331+
if (bytes.length == 0) {
332+
bytes = "no request body!"
333+
.repeat(100).getBytes(StandardCharsets.UTF_8);
334+
}
304335
int window = Integer.getInteger("jdk.httpclient.windowsize", 2 * 16 * 1024);
305336
final int maxChunkSize;
306337
if (t instanceof FCHttp2TestExchange fct) {
@@ -324,13 +355,22 @@ public void handle(Http2TestExchange t) throws IOException {
324355
// ignore and continue...
325356
}
326357
}
327-
((BodyOutputStream) os).writeUncontrolled(resp, 0, resp.length);
358+
try {
359+
((BodyOutputStream) os).writeUncontrolled(resp, 0, resp.length);
360+
} catch (IOException x) {
361+
if (t instanceof FCHttp2TestExchange fct) {
362+
fct.conn.updateConnectionWindow(resp.length);
363+
}
364+
}
365+
}
366+
} finally {
367+
if (t instanceof FCHttp2TestExchange fct) {
368+
fct.responseSent(query);
369+
} else {
370+
fail("Exchange is not %s but %s"
371+
.formatted(FCHttp2TestExchange.class.getName(), t.getClass().getName()));
328372
}
329373
}
330-
if (t instanceof FCHttp2TestExchange fct) {
331-
fct.responseSent(query);
332-
} else fail("Exchange is not %s but %s"
333-
.formatted(FCHttp2TestExchange.class.getName(), t.getClass().getName()));
334374
}
335375
}
336376

0 commit comments

Comments
 (0)